Array Creation Functions#

Functions for creating arrays.

Example#

import numpycore as np

# From data
arr = np.array([1, 2, 3])
mat = np.array([[1, 2], [3, 4]])

# Zeros and ones
zeros = np.zeros((3, 3))
ones = np.ones((2, 4))
full = np.full((2, 3), 7)

# Ranges
arange = np.arange(0, 10, 2)
linspace = np.linspace(0, 1, 100)

From Data#

Function

Description

Example

array(object, dtype)

Create array from list/tuple/array

asarray(a)

Convert input to array

View

asanyarray(a)

Convert to array (pass through subclasses)

View

ascontiguousarray(a)

Return contiguous array

View

copy(a)

Return array copy

Zeros and Ones#

Function

Description

Example

zeros(shape, dtype)

Array of zeros

View

ones(shape, dtype)

Array of ones

View

empty(shape, dtype)

Uninitialized array

View

full(shape, fill_value)

Array filled with value

View

zeros_like(a)

Zeros with same shape as a

View

ones_like(a)

Ones with same shape as a

View

empty_like(a)

Empty with same shape as a

View

full_like(a, fill_value)

Filled with same shape as a

View

Numerical Ranges#

Function

Description

Example

arange(start, stop, step)

Evenly spaced values within interval

View

linspace(start, stop, num)

Evenly spaced numbers over interval

View

logspace(start, stop, num)

Numbers spaced evenly on log scale

geomspace(start, stop, num)

Numbers spaced evenly on geometric scale

Matrix Creation#

Function

Description

Example

eye(N, M, k)

2-D array with ones on diagonal

View

identity(n)

Identity matrix

View

diag(v, k)

Diagonal array or extract diagonal

diagflat(v, k)

Create 2-D array with diagonal

tri(N, M, k)

Array with ones at and below diagonal

tril(m, k)

Lower triangle of array

triu(m, k)

Upper triangle of array

vander(x, N)

Vandermonde matrix

Grid Creation#

Function

Description

Example

meshgrid(*xi)

Coordinate matrices from vectors

View

mgrid

Dense multi-dimensional meshgrid

ogrid

Open multi-dimensional meshgrid

indices(dimensions)

Grid of indices

View

Code Examples#

The following examples are extracted from the test suite.

asarray (test_array_conversion.py:35)
25    print("Warning: NumPy not available. Skipping comparison tests.")
26
27def test_asarray():
28    """Test asarray function with various input types"""
29    print("="*70)
30    print("Testing asarray()")
31    print("="*70)
32
33    # Test 1: Python list
34    print("\n[Test 1] asarray from Python list")
35    result = numpycore.asarray([1, 2, 3, 4, 5])
36    print(f"  numpycore.asarray([1, 2, 3, 4, 5]): {result}")
37    print(f"  Shape: {result.shape}, dtype: {result.dtype}")
38    assert result.shape == (5,), f"Expected shape (5,), got {result.shape}"
39    if HAS_NUMPY:
40        np_result = np.asarray([1, 2, 3, 4, 5])
41        assert np.allclose(result, np_result), "Results don't match NumPy"
42    print("  [OK] Python list")
43
44    # Test 2: 2D Python list
45    print("\n[Test 2] asarray from 2D Python list")
asanyarray (test_array_conversion.py:98)
 88    print("="*70)
 89
 90def test_asanyarray():
 91    """Test asanyarray function"""
 92    print("\n" + "="*70)
 93    print("Testing asanyarray()")
 94    print("="*70)
 95
 96    # Test 1: Basic array
 97    print("\n[Test 1] asanyarray from list")
 98    result = numpycore.asanyarray([1, 2, 3, 4])
 99    print(f"  numpycore.asanyarray([1, 2, 3, 4]): {result}")
100    assert result.shape == (4,), f"Expected shape (4,), got {result.shape}"
101    print("  [OK] asanyarray from list")
102
103    # Test 2: 2D array
104    print("\n[Test 2] asanyarray from 2D list")
105    result = numpycore.asanyarray([[1, 2], [3, 4], [5, 6]])
106    print(f"  numpycore.asanyarray([[1, 2], [3, 4], [5, 6]]): shape={result.shape}")
107    assert result.shape == (3, 2), f"Expected shape (3, 2), got {result.shape}"
108    print("  [OK] asanyarray from 2D list")
ascontiguousarray (test_array_conversion.py:122)
112    print("="*70)
113
114def test_ascontiguousarray():
115    """Test ascontiguousarray function"""
116    print("\n" + "="*70)
117    print("Testing ascontiguousarray()")
118    print("="*70)
119
120    # Test 1: Basic array
121    print("\n[Test 1] ascontiguousarray from list")
122    result = numpycore.ascontiguousarray([[1, 2, 3], [4, 5, 6]])
123    print(f"  numpycore.ascontiguousarray([[1, 2, 3], [4, 5, 6]]): shape={result.shape}")
124    print(f"  Result is C-contiguous: {result.flags['C_CONTIGUOUS']}")
125    assert result.flags['C_CONTIGUOUS'], "Result should be C-contiguous"
126    print("  [OK] C-contiguous array")
127
128    # Test 2: With dtype
129    print("\n[Test 2] ascontiguousarray with dtype")
130    result = numpycore.ascontiguousarray([1, 2, 3, 4], dtype='float64')
131    print(f"  numpycore.ascontiguousarray([1, 2, 3, 4], dtype='float64'): {result}")
132    assert result.dtype == np.float64, f"Expected float64, got {result.dtype}"
zeros (test_advanced_linalg_and_numerical.py:63)
53# ============================================================================
54# Linear Algebra Tests
55# ============================================================================
56
57def test_solve():
58    """Test np.linalg.solve() for solving linear systems Ax = b"""
59    # Create a simple 2x2 system: [[2, 1], [1, 3]] @ x = [1, 2]
60    np_A = test_bind.np.array([[2.0, 1.0], [1.0, 3.0]])
61    np_b = test_bind.np.array([1.0, 2.0])
62
63    nc_A = test_bind.numpycore.zeros([2, 2])
64    nc_A.itemset(0, 2.0)
65    nc_A.itemset(1, 1.0)
66    nc_A.itemset(2, 1.0)
67    nc_A.itemset(3, 3.0)
68
69    nc_b = test_bind.numpycore.zeros([2])
70    nc_b.itemset(0, 1.0)
71    nc_b.itemset(1, 2.0)
72
73    np_result = test_bind.np.linalg.solve(np_A, np_b)
ones (test_2d_3d_operations.py:15)
 5def assert_arrays_equal(np_result, nc_result, test_name):
 6    if not test_bind.np.allclose(test_bind.np.asarray(np_result), test_bind.np.asarray(nc_result), rtol=1e-10, atol=1e-10, equal_nan=True):
 7        print(f"[FAIL] {test_name}"); sys.exit(1)
 8    print(f"[OK] {test_name}: PASSED")
 9
10def test_rot90_k2(): assert_arrays_equal(test_bind.np.rot90(test_bind.np.array([[1,2],[3,4]]),k=2), test_bind.np.rot90(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2]),k=2), "rot90_k2")
11def test_fliplr(): assert_arrays_equal(test_bind.np.fliplr(test_bind.np.array([[1,2],[3,4]])), test_bind.np.fliplr(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2])), "fliplr")
12def test_flipud(): assert_arrays_equal(test_bind.np.flipud(test_bind.np.array([[1,2],[3,4]])), test_bind.np.flipud(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2])), "flipud")
13def test_roll_2d(): assert_arrays_equal(test_bind.np.roll(test_bind.np.array([[1,2],[3,4]]),1,axis=0), test_bind.np.roll(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2]),1,axis=0), "roll_2d")
14def test_rollaxis(): assert_arrays_equal(test_bind.np.rollaxis(test_bind.np.ones((3,4,5)),2), test_bind.np.rollaxis(test_bind.numpycore.ones([3,4,5]),2), "rollaxis")
15def test_transpose_axes(): assert_arrays_equal(test_bind.np.transpose(test_bind.np.ones((2,3,4)),(2,0,1)), test_bind.np.transpose(test_bind.numpycore.ones([2,3,4]),(2,0,1)), "transpose_axes")
16
17def f_main():
18    if test_bind.f_setup_test_environment() != 0: return 1
19    print("="*70); print("Additional 2D/3D Operations Tests"); print("="*70); print()
20    test_rot90_k2(); test_fliplr(); test_flipud(); test_roll_2d(); test_rollaxis(); test_transpose_axes()
21    print(); print("[OK] All 6 2D/3D operations tests passed!")
22    return 0
23
24if __name__ == "__main__": sys.exit(f_main())
empty (test_array_creation_complete.py:67)
57    assert np.allclose(arr, np.zeros((2, 3))), "zeros() 2D values incorrect"
58
59    f_print_success("zeros() tests passed")
60
61
62def test_empty():
63    """Test empty() - create uninitialized array"""
64    f_print_info("Testing empty()")
65
66    # Test shape creation
67    arr = test_bind.numpycore.empty([2, 3])
68    assert arr.shape == (2, 3), f"Expected shape (2, 3), got {arr.shape}"
69    assert arr.dtype == np.float64, f"Expected dtype float64, got {arr.dtype}"
70
71    f_print_success("empty() tests passed")
72
73
74def test_full():
75    """Test full() - create array filled with specific value"""
76    f_print_info("Testing full()")
full (test_array_creation_complete.py:79)
69    assert arr.dtype == np.float64, f"Expected dtype float64, got {arr.dtype}"
70
71    f_print_success("empty() tests passed")
72
73
74def test_full():
75    """Test full() - create array filled with specific value"""
76    f_print_info("Testing full()")
77
78    # Test with scalar value
79    arr = test_bind.numpycore.full([2, 3], 7.5)
80    assert arr.shape == (2, 3), f"Expected shape (2, 3), got {arr.shape}"
81    assert np.allclose(arr, np.full((2, 3), 7.5)), "full() values incorrect"
82
83    f_print_success("full() tests passed")
84
85
86def test_identity():
87    """Test identity() - create identity matrix"""
88    f_print_info("Testing identity()")
zeros_like (test_array_creation_complete.py:163)
153    assert np.allclose(arr, np.ones_like(prototype)), "ones_like() values incorrect"
154
155    f_print_success("ones_like() tests passed")
156
157
158def test_zeros_like():
159    """Test zeros_like() - create array of zeros with shape from prototype"""
160    f_print_info("Testing zeros_like()")
161
162    prototype = np.array([[1, 2], [3, 4]])
163    arr = test_bind.numpycore.zeros_like(prototype)
164    assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}"
165    assert np.allclose(arr, np.zeros_like(prototype)), "zeros_like() values incorrect"
166
167    f_print_success("zeros_like() tests passed")
168
169
170def test_empty_like():
171    """Test empty_like() - create uninitialized array with shape from prototype"""
172    f_print_info("Testing empty_like()")
ones_like (test_array_creation_complete.py:151)
141# ============================================================================
142# LIKE FUNCTIONS TESTS
143# ============================================================================
144
145def test_ones_like():
146    """Test ones_like() - create array of ones with shape from prototype"""
147    f_print_info("Testing ones_like()")
148
149    prototype = np.array([[1, 2], [3, 4]])
150    arr = test_bind.numpycore.ones_like(prototype)
151    assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}"
152    assert np.allclose(arr, np.ones_like(prototype)), "ones_like() values incorrect"
153
154    f_print_success("ones_like() tests passed")
155
156
157def test_zeros_like():
158    """Test zeros_like() - create array of zeros with shape from prototype"""
159    f_print_info("Testing zeros_like()")
empty_like (test_array_creation_complete.py:175)
165    assert np.allclose(arr, np.zeros_like(prototype)), "zeros_like() values incorrect"
166
167    f_print_success("zeros_like() tests passed")
168
169
170def test_empty_like():
171    """Test empty_like() - create uninitialized array with shape from prototype"""
172    f_print_info("Testing empty_like()")
173
174    prototype = np.array([[1, 2], [3, 4]])
175    arr = test_bind.numpycore.empty_like(prototype)
176    assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}"
177    assert arr.dtype == prototype.dtype, f"Expected dtype {prototype.dtype}, got {arr.dtype}"
178
179    f_print_success("empty_like() tests passed")
180
181
182def test_full_like():
183    """Test full_like() - create filled array with shape from prototype"""
184    f_print_info("Testing full_like()")
full_like (test_array_creation_complete.py:187)
177    assert arr.dtype == prototype.dtype, f"Expected dtype {prototype.dtype}, got {arr.dtype}"
178
179    f_print_success("empty_like() tests passed")
180
181
182def test_full_like():
183    """Test full_like() - create filled array with shape from prototype"""
184    f_print_info("Testing full_like()")
185
186    prototype = np.array([[1, 2], [3, 4]])
187    arr = test_bind.numpycore.full_like(prototype, 7.5)
188    assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}"
189    assert np.allclose(arr, np.full_like(prototype, 7.5)), "full_like() values incorrect"
190
191    f_print_success("full_like() tests passed")
192
193
194# ============================================================================
195# CONVERSION FUNCTIONS TESTS
196# ============================================================================
arange (test_2d_3d_operations.py:11)
 1#!/usr/bin/env python3
 2"""Phase 28: Additional 2D/3D Operations Tests"""
 3import sys
 4import test_bind
 5
 6def assert_arrays_equal(np_result, nc_result, test_name):
 7    if not test_bind.np.allclose(test_bind.np.asarray(np_result), test_bind.np.asarray(nc_result), rtol=1e-10, atol=1e-10, equal_nan=True):
 8        print(f"[FAIL] {test_name}"); sys.exit(1)
 9    print(f"[OK] {test_name}: PASSED")
10
11def test_rot90_k2(): assert_arrays_equal(test_bind.np.rot90(test_bind.np.array([[1,2],[3,4]]),k=2), test_bind.np.rot90(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2]),k=2), "rot90_k2")
12def test_fliplr(): assert_arrays_equal(test_bind.np.fliplr(test_bind.np.array([[1,2],[3,4]])), test_bind.np.fliplr(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2])), "fliplr")
13def test_flipud(): assert_arrays_equal(test_bind.np.flipud(test_bind.np.array([[1,2],[3,4]])), test_bind.np.flipud(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2])), "flipud")
14def test_roll_2d(): assert_arrays_equal(test_bind.np.roll(test_bind.np.array([[1,2],[3,4]]),1,axis=0), test_bind.np.roll(test_bind.numpycore.arange(1.,5.,1.).reshape([2,2]),1,axis=0), "roll_2d")
15def test_rollaxis(): assert_arrays_equal(test_bind.np.rollaxis(test_bind.np.ones((3,4,5)),2), test_bind.np.rollaxis(test_bind.numpycore.ones([3,4,5]),2), "rollaxis")
16def test_transpose_axes(): assert_arrays_equal(test_bind.np.transpose(test_bind.np.ones((2,3,4)),(2,0,1)), test_bind.np.transpose(test_bind.numpycore.ones([2,3,4]),(2,0,1)), "transpose_axes")
17
18def f_main():
19    if test_bind.f_setup_test_environment() != 0: return 1
20    print("="*70); print("Additional 2D/3D Operations Tests"); print("="*70); print()
21    test_rot90_k2(); test_fliplr(); test_flipud(); test_roll_2d(); test_rollaxis(); test_transpose_axes()
linspace (test_advanced_operations.py:75)
65        return False
66
67
68# ============================================================================
69# Sorting Tests
70# ============================================================================
71
72def test_sort_1d():
73    """Test sorting 1D array"""
74    np_arr = test_bind.np.array([3.0, 1.0, 4.0, 1.0, 5.0, 9.0])
75    nc_arr = test_bind.numpycore.linspace(3.0, 9.0, 6)  # Will need to shuffle or use explicit values
76
77    # Use explicit construction
78    nc_values = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0]
79    nc_arr = test_bind.numpycore.zeros([6])
80    for i, val in enumerate(nc_values):
81        nc_arr.itemset(i, val)
82
83    np_sorted = test_bind.np.sort(np_arr)
84    nc_sorted = test_bind.np.sort(nc_arr)
eye (test_array_creation_complete.py:102)
 92    assert np.allclose(arr, np.identity(3)), "identity() values incorrect"
 93
 94    f_print_success("identity() tests passed")
 95
 96
 97def test_eye():
 98    """Test eye() - create matrix with ones on diagonal"""
 99    f_print_info("Testing eye()")
100
101    # Square matrix
102    arr = test_bind.numpycore.eye(3, 3, 0)
103    assert arr.shape == (3, 3), f"Expected shape (3, 3), got {arr.shape}"
104    assert np.allclose(arr, np.eye(3)), "eye() values incorrect"
105
106    # Rectangular matrix
107    arr = test_bind.numpycore.eye(3, 4, 1)
108    assert arr.shape == (3, 4), f"Expected shape (3, 4), got {arr.shape}"
109    assert np.allclose(arr, np.eye(3, 4, 1)), "eye() with offset values incorrect"
110
111    f_print_success("eye() tests passed")
identity (test_array_creation_complete.py:90)
80    assert arr.shape == (2, 3), f"Expected shape (2, 3), got {arr.shape}"
81    assert np.allclose(arr, np.full((2, 3), 7.5)), "full() values incorrect"
82
83    f_print_success("full() tests passed")
84
85
86def test_identity():
87    """Test identity() - create identity matrix"""
88    f_print_info("Testing identity()")
89
90    arr = test_bind.numpycore.identity(3)
91    assert arr.shape == (3, 3), f"Expected shape (3, 3), got {arr.shape}"
92    assert np.allclose(arr, np.identity(3)), "identity() values incorrect"
93
94    f_print_success("identity() tests passed")
95
96
97def test_eye():
98    """Test eye() - create matrix with ones on diagonal"""
99    f_print_info("Testing eye()")
meshgrid (test_array_creation_extended.py:464)
454    np_arr = test_bind.np.arange(0, 24, 1, dtype='float64').reshape(2, 3, 4)
455    nc_arr = test_bind.numpycore.arange(0.0, 24.0, 1.0).reshape(2, 3, 4)
456
457    np_result = test_bind.np.ravel(np_arr)
458    nc_result = test_bind.numpycore.ravel(nc_arr)
459
460    assert_arrays_equal(np_result, nc_result, "ravel_numpycore_3d")
461
462
463def test_meshgrid_numpycore_2d_xy():
464    """Test numpycore.meshgrid() with 2 vectors, xy indexing"""
465    np_x = test_bind.np.array([1.0, 2.0, 3.0])
466    np_y = test_bind.np.array([4.0, 5.0])
467
468    nc_x = test_bind.numpycore.array([1.0, 2.0, 3.0])
469    nc_y = test_bind.numpycore.array([4.0, 5.0])
470
471    np_xv, np_yv = test_bind.np.meshgrid(np_x, np_y, indexing='xy')
472    nc_xv, nc_yv = test_bind.numpycore.meshgrid(nc_x, nc_y, indexing='xy')
473
474    assert_arrays_equal(np_xv, nc_xv, "meshgrid_numpycore_2d_xy_xv")
indices (test_phase11_array_generation.py:36)
26    # and all elements after should be >= element at index 3
27    partitioned_nc = arr_nc[result_nc]
28    partitioned_np = arr_np[result_np]
29
30    assert test_bind.np.all(partitioned_nc[:4] <= partitioned_nc[3]), "Partition property failed for numpycore"
31    assert test_bind.np.all(partitioned_nc[4:] >= partitioned_nc[3]), "Partition property failed for numpycore"
32    print("[OK] test_argpartition_basic: argpartition(arr, 3) works correctly")
33
34def test_indices_2d_dense():
35    """Test indices() - 2D dense mode"""
36    grid_nc = test_bind.numpycore.indices((2, 3))
37    grid_np = test_bind.np.indices((2, 3))
38
39    assert len(grid_nc) == 2, f"Expected 2 arrays, got {len(grid_nc)}"
40    assert test_bind.np.allclose(grid_nc[0], grid_np[0]), "Row indices don't match"
41    assert test_bind.np.allclose(grid_nc[1], grid_np[1]), "Column indices don't match"
42    print("[OK] test_indices_2d_dense: indices((2, 3)) dense mode matches NumPy")
43
44def test_indices_2d_sparse():
45    """Test indices() - 2D sparse mode"""
46    grid_nc = test_bind.numpycore.indices((2, 3), sparse=True)