NDArray#
- class NDArray#
N-dimensional array class from numpyCore Python, providing NumPy-compatible array functionality with high-performance C++ implementation.
Example#
import numpycore as np
# Create array from list
arr = np.array([1, 2, 3, 4, 5])
print(arr.shape) # (5,)
print(arr.dtype) # int64
# Create 2D array
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(mat.shape) # (2, 3)
# Mathematical operations
result = arr * 2 + 1
print(result.sum()) # 35
# Reshape and transpose
reshaped = mat.reshape((3, 2))
transposed = mat.T
Attributes#
Attribute |
Description |
Example |
|---|---|---|
|
View of the transposed array. |
|
|
Base object if memory is from some other object. |
|
|
An object to simplify the interaction of the array with the ctypes … |
|
|
Python buffer object pointing to the start of the array’s data. |
|
|
Data-type of the array’s elements. |
|
|
Information about the memory layout of the array. |
|
|
A 1-D iterator over the array. |
|
|
The imaginary part of the array. |
|
|
Length of one array element in bytes. |
|
|
Total bytes consumed by the elements of the array. |
|
|
Number of array dimensions. |
|
|
The real part of the array. |
|
|
Tuple of array dimensions. |
|
|
Number of elements in the array. |
|
|
Tuple of bytes to step in each dimension when traversing an array. |
Construction#
Method |
Description |
Example |
|---|---|---|
|
Initialize self. See help(type(self)) for accurate signature. |
Shape Manipulation#
Indexing / Slicing#
Method |
Description |
Example |
|---|---|---|
|
Return self[key]. |
|
|
Set self[key] to value. |
|
|
a.choose(choices, out=None, mode=’raise’) |
|
|
a.compress(condition, axis=None, out=None) |
|
|
a.diagonal(offset=0, axis1=0, axis2=1) |
|
|
a.nonzero() |
|
|
a.put(indices, values, mode=’raise’) |
|
|
a.searchsorted(v, side=’left’, sorter=None) |
|
|
a.take(indices, axis=None, out=None, mode=’raise’) |
Joining / Splitting#
Method |
Description |
Example |
|---|---|---|
|
a.repeat(repeats, axis=None) |
Mathematical Operations#
Statistics#
Method |
Description |
Example |
|---|---|---|
|
a.argmax(axis=None, out=None, *, keepdims=False) |
|
|
a.argmin(axis=None, out=None, *, keepdims=False) |
|
|
a.max(axis=None, out=None, keepdims=False, initial=<no value>, wher… |
|
|
a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True) |
|
|
a.min(axis=None, out=None, keepdims=False, initial=<no value>, wher… |
|
|
a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, … |
|
|
a.ptp(axis=None, out=None, keepdims=False) |
|
|
a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, w… |
|
|
a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, w… |
|
|
a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, w… |
Sorting / Searching#
Method |
Description |
Example |
|---|---|---|
|
a.argpartition(kth, axis=-1, kind=’introselect’, order=None) |
|
|
a.argsort(axis=-1, kind=None, order=None) |
|
|
a.partition(kth, axis=-1, kind=’introselect’, order=None) |
|
|
a.sort(axis=-1, kind=None, order=None) |
Comparison / Logic#
Method |
Description |
Example |
|---|---|---|
|
Return self==value. |
|
|
Return self>=value. |
|
|
Return self>value. |
|
|
Return self<=value. |
|
|
Return self<value. |
|
|
Return self!=value. |
|
|
a.all(axis=None, out=None, keepdims=False, *, where=True) |
|
|
a.any(axis=None, out=None, keepdims=False, *, where=True) |
Linear Algebra#
Method |
Description |
Example |
|---|---|---|
|
Return self@value. |
|
|
||
|
a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) |
I/O#
Method |
Description |
Example |
|---|---|---|
|
a.astype(dtype, order=’K’, casting=’unsafe’, subok=True, copy=True) |
|
|
a.byteswap(inplace=False) |
|
|
a.copy(order=’C’) |
|
|
a.tobytes(order=’C’) |
|
|
a.tofile(fid, sep=””, format=”%s”) |
|
|
a.tolist() |
|
|
a.view([dtype][, type]) |
Arithmetic Operators#
Method |
Description |
Example |
|---|---|---|
|
||
|
Return self+value. |
|
|
Return bool(key in self). |
|
|
Return self//value. |
|
|
||
|
Implement iter(self). |
|
|
Return len(self). |
|
|
Return self%value. |
|
|
Return self*value. |
|
|
-self |
|
|
+self |
|
|
Return pow(self, value, mod). |
|
|
Return value+self. |
|
|
Return repr(self). |
|
|
Return value@self. |
|
|
Return value*self. |
|
|
Return value-self. |
|
|
Return value/self. |
|
|
Return str(self). |
|
|
Return self-value. |
|
|
Return self/value. |
Other Methods#
Method |
Description |
Example |
|---|---|---|
|
a.conj() |
|
|
a.conjugate() |
|
|
a.cumprod(axis=None, dtype=None, out=None) |
|
|
a.cumsum(axis=None, dtype=None, out=None) |
|
|
a.dump(file) |
|
|
a.dumps() |
|
|
a.fill(value) |
|
|
a.getfield(dtype, offset=0) |
|
|
a.item(*args) |
|
|
a.itemset(*args) |
|
|
arr.newbyteorder(new_order=’S’, /) |
|
|
a.round(decimals=0, out=None) |
|
|
a.setfield(val, dtype, offset=0) |
|
|
a.setflags(write=None, align=None, uic=None) |
|
|
a.tostring(order=’C’) |
Code Examples#
The following examples are extracted from the test suite.
T (test_array_methods.py:132)
122 assert_arrays_equal(np_result, nc_result, "reshape_with_minus_one")
123
124
125# ============================================================================
126# TRANSPOSE TESTS
127# ============================================================================
128
129def test_transpose_2d():
130 """Test transpose of 2D array"""
131 np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
132 np_result = np_arr.T
133
134 # Create equivalent numpycore array
135 nc_base = test_bind.numpycore.arange(1, 7, 1)
136 nc_arr = nc_base.reshape(2, 3)
137 nc_result = nc_arr.T
138
139 assert_arrays_equal(np_result, nc_result, "transpose_2d")
140
141
142def test_transpose_method():
data (test_masked_array_wrappers.py:72)
62 print("Testing MaskedArray.clip()")
63 print("="*70)
64
65 # data = [1, 5, 3, 8, 2], mask = [F, F, T, F, F]
66 # clip to [2, 6]: unmasked [2, 5, -, 6, 2], masked value unchanged
67 ma = create_masked_array([1.0, 5.0, 3.0, 8.0, 2.0], [False, False, True, False, False])
68
69 result = ma.clip(2.0, 6.0)
70
71 # Verify unmasked values are clipped
72 result_data = test_bind.np.asarray(result.data)
73 assert_array_equal(result_data[0], 2.0, "clip lower bound") # 1 -> 2
74 assert_array_equal(result_data[1], 5.0, "clip middle unchanged") # 5 stays 5
75 assert_array_equal(result_data[3], 6.0, "clip upper bound") # 8 -> 6
76
77 # Verify masked element NOT touched
78 assert_array_equal(result_data[2], 3.0, "clip masked element unchanged")
79
80 print(f"[OK] ma.clip(): PASSED")
81 return True
dtype (test_abs_types.py:13)
3Test abs() function for all supported types comparing NumpyCore vs NumPy.
4Covers: float64, float32, int64, int32, int16, int8, uint64, uint32, uint16, uint8, bool, complex64, complex128
5"""
6import sys
7import test_bind
8
9def assert_arrays_equal(np_result, nc_result, test_name, rtol=1e-10, atol=1e-10):
10 np = test_bind.np
11 np_arr = np.asarray(np_result)
12 nc_arr = np.asarray(nc_result)
13 if np_arr.dtype != nc_arr.dtype:
14 print(f"[FAIL] {test_name}: dtype mismatch - np:{np_arr.dtype} vs nc:{nc_arr.dtype}")
15 return False
16 if np_arr.shape != nc_arr.shape:
17 print(f"[FAIL] {test_name}: shape mismatch - np:{np_arr.shape} vs nc:{nc_arr.shape}")
18 return False
19 if not np.allclose(np_arr, nc_arr, rtol=rtol, atol=atol, equal_nan=True):
20 print(f"[FAIL] {test_name}: values mismatch")
21 print(f" np: {np_arr}")
22 print(f" nc: {nc_arr}")
23 return False
flags (test_array_conversion.py:124)
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}"
133 print(" [OK] ascontiguousarray with dtype")
itemsize (test_array_properties.py:199)
189 tests_failed += 1
190
191
192# ============================================================================
193# ITEMSIZE AND NBYTES TESTS
194# ============================================================================
195
196def test_itemsize_float64():
197 """Test itemsize for float64 (should be 8 bytes)"""
198 arr = test_bind.numpycore.ones([2, 2])
199 assert_equal(arr.itemsize, 8, "itemsize_float64")
200
201
202def test_itemsize_float32():
203 """Test itemsize for float32 (should be 4 bytes)"""
204 arr = test_bind.numpycore.ones([2, 2], dtype='float32')
205 assert_equal(arr.itemsize, 4, "itemsize_float32")
206
207
208def test_itemsize_int32():
209 """Test itemsize for int32 (should be 4 bytes)"""
nbytes (test_array_properties.py:228)
218def test_nbytes():
219 """Test nbytes (size * itemsize)"""
220 global tests_run, tests_passed, tests_failed
221 tests_run += 1
222
223 arr = test_bind.numpycore.zeros([3, 4]) # 12 elements * 8 bytes = 96
224 expected_nbytes = arr.size * arr.itemsize
225
226 if arr.nbytes == expected_nbytes and expected_nbytes == 96:
227 f_print_success(f"nbytes: PASS (nbytes={arr.nbytes})")
228 tests_passed += 1
229 else:
230 f_print_error(f"nbytes: FAIL - expected {expected_nbytes}, got {arr.nbytes}")
231 tests_failed += 1
232
233
234# ============================================================================
235# MAIN TEST RUNNER
236# ============================================================================
ndim (test_array_properties.py:76)
66 assert_equal(arr.shape, (7, 3), "shape_rectangular")
67
68
69# ============================================================================
70# NDIM PROPERTY TESTS
71# ============================================================================
72
73def test_ndim_1d():
74 """Test ndim property for 1D array"""
75 arr = test_bind.numpycore.arange(0, 10, 1)
76 assert_equal(arr.ndim, 1, "ndim_1d")
77
78
79def test_ndim_2d():
80 """Test ndim property for 2D array"""
81 arr = test_bind.numpycore.zeros([3, 4])
82 assert_equal(arr.ndim, 2, "ndim_2d")
83
84
85def test_ndim_3d():
86 """Test ndim property for 3D array"""
shape (test_abs_types.py:16)
6import sys
7import test_bind
8
9def assert_arrays_equal(np_result, nc_result, test_name, rtol=1e-10, atol=1e-10):
10 np = test_bind.np
11 np_arr = np.asarray(np_result)
12 nc_arr = np.asarray(nc_result)
13 if np_arr.dtype != nc_arr.dtype:
14 print(f"[FAIL] {test_name}: dtype mismatch - np:{np_arr.dtype} vs nc:{nc_arr.dtype}")
15 return False
16 if np_arr.shape != nc_arr.shape:
17 print(f"[FAIL] {test_name}: shape mismatch - np:{np_arr.shape} vs nc:{nc_arr.shape}")
18 return False
19 if not np.allclose(np_arr, nc_arr, rtol=rtol, atol=atol, equal_nan=True):
20 print(f"[FAIL] {test_name}: values mismatch")
21 print(f" np: {np_arr}")
22 print(f" nc: {nc_arr}")
23 return False
24 print(f"[OK] {test_name}")
25 return True
size (test_array_properties.py:98)
88 assert_equal(arr.ndim, 3, "ndim_3d")
89
90
91# ============================================================================
92# SIZE PROPERTY TESTS
93# ============================================================================
94
95def test_size_1d():
96 """Test size property for 1D array"""
97 arr = test_bind.numpycore.zeros([10])
98 assert_equal(arr.size, 10, "size_1d")
99
100
101def test_size_2d():
102 """Test size property for 2D array"""
103 arr = test_bind.numpycore.ones([3, 4])
104 assert_equal(arr.size, 12, "size_2d")
105
106
107def test_size_3d():
108 """Test size property for 3D array"""
flatten (test_array_methods.py:171)
161 assert_arrays_equal(np_result, nc_result, "transpose_rectangular")
162
163
164# ============================================================================
165# FLATTEN TESTS
166# ============================================================================
167
168def test_flatten_2d():
169 """Test flatten of 2D array"""
170 np_arr = test_bind.np.array([[1.0, 2.0], [3.0, 4.0]])
171 np_result = np_arr.flatten()
172
173 # Create equivalent numpycore array
174 nc_base = test_bind.numpycore.arange(1, 5, 1)
175 nc_arr = nc_base.reshape(2, 2)
176 nc_result = nc_arr.flatten()
177
178 assert_arrays_equal(np_result, nc_result, "flatten_2d")
179
180
181def test_flatten_3d():
ravel (test_array_methods.py:199)
189 assert_arrays_equal(np_result, nc_result, "flatten_3d")
190
191
192# ============================================================================
193# RAVEL TESTS
194# ============================================================================
195
196def test_ravel_2d():
197 """Test ravel of 2D array"""
198 np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
199 np_result = np_arr.ravel()
200
201 nc_base = test_bind.numpycore.arange(1, 7, 1)
202 nc_arr = nc_base.reshape(2, 3)
203 nc_result = nc_arr.ravel()
204
205 assert_arrays_equal(np_result, nc_result, "ravel_2d")
206
207
208def test_ravel_3d():
209 """Test ravel of 3D array"""
reshape (test_array_methods.py:84)
74 return False
75
76
77# ============================================================================
78# RESHAPE TESTS
79# ============================================================================
80
81def test_reshape_1d_to_2d():
82 """Test reshape from 1D to 2D"""
83 np_arr = test_bind.np.arange(0, 6, 1, dtype='float64')
84 np_result = np_arr.reshape(2, 3)
85
86 nc_arr = test_bind.numpycore.arange(0, 6, 1)
87 nc_result = nc_arr.reshape(2, 3)
88
89 assert_arrays_equal(np_result, nc_result, "reshape_1d_to_2d")
90
91
92def test_reshape_2d_to_1d():
93 """Test reshape from 2D to 1D"""
94 np_arr = test_bind.np.ones([2, 3])
resize (test_type_conversion.py:274)
264# ============================================================================
265
266def test_resize_grow():
267 """Test resize to larger size"""
268
269 np_arr = test_bind.np.array([1.0, 2.0, 3.0])
270 # pybind11 arrays don't own data, so use .copy() to get owned array for .resize()
271 nc_arr = test_bind.numpycore.arange(1.0, 4.0, 1.0).copy()
272
273 # Resize to larger
274 np_arr.resize([5], refcheck=False)
275 nc_arr.resize([5], refcheck=False)
276
277 assert_arrays_equal(np_arr, nc_arr, "resize_grow")
278
279
280def test_resize_shrink():
281 """Test resize to smaller size"""
282
283 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0])
284 # pybind11 arrays don't own data, so use .copy() to get owned array for .resize()
swapaxes (test_set_operations.py:253)
243 nc_result = test_bind.np.squeeze(nc_arr)
244
245 assert_arrays_equal(np_result, nc_result, "squeeze")
246
247
248def test_swapaxes():
249 """Test swapaxes (interchange two axes)"""
250 np_arr = test_bind.np.arange(12, dtype='float64').reshape(3, 4)
251 nc_arr = test_bind.numpycore.arange(0.0, 12.0, 1.0).reshape(3, 4)
252
253 np_result = np_arr.swapaxes(0, 1)
254 nc_result = nc_arr.swapaxes(0, 1)
255
256 assert_arrays_equal(np_result, nc_result, "swapaxes")
257
258
259def test_choose():
260 """Test choose (construct array from index array)"""
261 np_choices = [
262 test_bind.np.array([0.0, 1.0, 2.0]),
263 test_bind.np.array([10.0, 11.0, 12.0]),
transpose (test_array_methods.py:145)
135 nc_base = test_bind.numpycore.arange(1, 7, 1)
136 nc_arr = nc_base.reshape(2, 3)
137 nc_result = nc_arr.T
138
139 assert_arrays_equal(np_result, nc_result, "transpose_2d")
140
141
142def test_transpose_method():
143 """Test transpose() method"""
144 np_arr = test_bind.np.ones([3, 4])
145 np_result = np_arr.transpose()
146
147 nc_arr = test_bind.numpycore.ones([3, 4])
148 nc_result = nc_arr.transpose()
149
150 assert_arrays_equal(np_result, nc_result, "transpose_method")
151
152
153def test_transpose_rectangular():
154 """Test transpose of non-square matrix"""
155 np_arr = test_bind.np.full([5, 2], 7.0)
compress (test_advanced_operations.py:300)
290 assert_arrays_equal(np_result, nc_result, "clip")
291
292
293def test_compress():
294 """Test compress (select elements based on condition)"""
295 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0])
296 np_condition = test_bind.np.array([True, False, True, False, True])
297
298 nc_arr = test_bind.numpycore.arange(1.0, 6.0, 1.0)
299
300 np_result = np_arr.compress(np_condition)
301 nc_result = nc_arr.compress(np_condition)
302
303 assert_arrays_equal(np_result, nc_result, "compress")
304
305
306def test_take():
307 """Test take (select elements by indices)"""
308 np_arr = test_bind.np.array([10.0, 20.0, 30.0, 40.0, 50.0])
309 np_indices = test_bind.np.array([0, 2, 4])
diagonal (test_advanced_operations.py:194)
184 nc_result = nc_arr.trace()
185
186 assert_scalars_equal(np_result, nc_result, "trace")
187
188
189def test_diagonal():
190 """Test extracting diagonal"""
191 np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
192 nc_arr = test_bind.numpycore.arange(1.0, 10.0, 1.0).reshape(3, 3)
193
194 np_result = np_arr.diagonal()
195 nc_result = nc_arr.diagonal()
196
197 assert_arrays_equal(np_result, nc_result, "diagonal")
198
199
200# ============================================================================
201# Logical Operations Tests
202# ============================================================================
203
204def test_all():
nonzero (test_advanced_operations.py:272)
262def test_nonzero():
263 """Test nonzero (indices of nonzero elements)"""
264 np_arr = test_bind.np.array([0.0, 1.0, 0.0, 3.0, 0.0, 5.0])
265
266 nc_arr = test_bind.numpycore.zeros([6])
267 nc_arr.itemset(1, 1.0)
268 nc_arr.itemset(3, 3.0)
269 nc_arr.itemset(5, 5.0)
270
271 np_result = np_arr.nonzero()[0] # Get first tuple element
272 nc_result = nc_arr.nonzero()[0]
273
274 assert_arrays_equal(np_result, nc_result, "nonzero", atol=0)
275
276
277# ============================================================================
278# Element Selection Tests
279# ============================================================================
280
281def test_clip():
put (test_set_operations.py:338)
328 nc_arr.fill(3.14)
329
330 assert_arrays_equal(np_arr, nc_arr, "fill")
331
332
333def test_put():
334 """Test put (replace specified elements)"""
335 np_arr = test_bind.np.zeros(5, dtype='float64')
336 nc_arr = test_bind.numpycore.zeros([5])
337
338 np_arr.put([0, 2, 4], [1.0, 2.0, 3.0])
339 nc_arr.put([0, 2, 4], [1.0, 2.0, 3.0])
340
341 assert_arrays_equal(np_arr, nc_arr, "put")
342
343
344# ============================================================================
345# Sorting Variants Tests
346# ============================================================================
347
348def test_partition():
searchsorted (test_advanced_operations.py:329)
319# ============================================================================
320# Searching Tests
321# ============================================================================
322
323def test_searchsorted():
324 """Test searchsorted (find indices where elements should be inserted)"""
325 np_arr = test_bind.np.array([1.0, 3.0, 5.0, 7.0, 9.0])
326 nc_arr = test_bind.numpycore.linspace(1.0, 9.0, 5)
327
328 # Search for single value
329 np_result = np_arr.searchsorted(4.0)
330 nc_result = nc_arr.searchsorted(4.0)
331
332 assert_scalars_equal(np_result, nc_result, "searchsorted_single", atol=0)
333
334
335def test_searchsorted_multiple():
336 """Test searchsorted with multiple values"""
337 np_arr = test_bind.np.array([1.0, 3.0, 5.0, 7.0, 9.0])
338 np_values = test_bind.np.array([2.0, 6.0, 8.0])
take (test_advanced_operations.py:313)
303 assert_arrays_equal(np_result, nc_result, "compress")
304
305
306def test_take():
307 """Test take (select elements by indices)"""
308 np_arr = test_bind.np.array([10.0, 20.0, 30.0, 40.0, 50.0])
309 np_indices = test_bind.np.array([0, 2, 4])
310
311 nc_arr = test_bind.numpycore.linspace(10.0, 50.0, 5)
312
313 np_result = np_arr.take(np_indices)
314 nc_result = nc_arr.take(np_indices)
315
316 assert_arrays_equal(np_result, nc_result, "take")
317
318
319# ============================================================================
320# Searching Tests
321# ============================================================================
322
323def test_searchsorted():
clip (test_advanced_operations.py:287)
277# ============================================================================
278# Element Selection Tests
279# ============================================================================
280
281def test_clip():
282 """Test clip (limit values to range)"""
283 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0])
284 nc_arr = test_bind.numpycore.arange(1.0, 6.0, 1.0)
285
286 np_result = np_arr.clip(2.0, 4.0)
287 nc_result = nc_arr.clip(2.0, 4.0)
288
289 assert_arrays_equal(np_result, nc_result, "clip")
290
291
292def test_compress():
293 """Test compress (select elements based on condition)"""
294 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0])
295 np_condition = test_bind.np.array([True, False, True, False, True])
max (test_array_methods.py:319)
309 nc_base = test_bind.numpycore.full([5], 5.0)
310 nc_arr = nc_base + test_bind.np.array([0, -3, 3, -4, 4])
311 nc_result = nc_arr.min()
312
313 assert_scalar_equal(np_result, nc_result, "min_1d")
314
315
316def test_max_1d():
317 """Test max() on 1D array"""
318 np_arr = test_bind.np.array([5.0, 2.0, 8.0, 1.0, 9.0])
319 np_result = np_arr.max()
320
321 nc_base = test_bind.numpycore.full([5], 5.0)
322 nc_arr = nc_base + test_bind.np.array([0, -3, 3, -4, 4])
323 nc_result = nc_arr.max()
324
325 assert_scalar_equal(np_result, nc_result, "max_1d")
326
327
328def test_min_2d():
329 """Test min() on 2D array"""
mean (test_array_methods.py:284)
274 nc_arr = test_bind.numpycore.ones([3, 4])
275 nc_result = nc_arr.sum()
276
277 assert_scalar_equal(np_result, nc_result, "sum_2d")
278
279
280def test_mean_1d():
281 """Test mean() on 1D array"""
282 np_arr = test_bind.np.array([2.0, 4.0, 6.0, 8.0])
283 np_result = np_arr.mean()
284
285 nc_base = test_bind.numpycore.full([4], 2.0)
286 nc_arr = nc_base + test_bind.np.array([0, 2, 4, 6])
287 nc_result = nc_arr.mean()
288
289 assert_scalar_equal(np_result, nc_result, "mean_1d")
290
291
292def test_mean_2d():
293 """Test mean() on 2D array"""
min (test_array_methods.py:307)
297 nc_arr = test_bind.numpycore.full([3, 3], 5.0)
298 nc_result = nc_arr.mean()
299
300 assert_scalar_equal(np_result, nc_result, "mean_2d")
301
302
303def test_min_1d():
304 """Test min() on 1D array"""
305 np_arr = test_bind.np.array([5.0, 2.0, 8.0, 1.0, 9.0])
306 np_result = np_arr.min()
307
308 nc_base = test_bind.numpycore.full([5], 5.0)
309 nc_arr = nc_base + test_bind.np.array([0, -3, 3, -4, 4])
310 nc_result = nc_arr.min()
311
312 assert_scalar_equal(np_result, nc_result, "min_1d")
313
314
315def test_max_1d():
316 """Test max() on 1D array"""
prod (test_set_operations.py:288)
278# ============================================================================
279# Reduction Operations Tests
280# ============================================================================
281
282def test_prod():
283 """Test prod (product of array elements)"""
284 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0])
285 nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0)
286
287 np_result = np_arr.prod()
288 nc_result = nc_arr.prod()
289
290 assert_scalars_equal(np_result, nc_result, "prod")
291
292
293def test_ptp():
294 """Test ptp (peak to peak / range of values)"""
295 np_arr = test_bind.np.array([1.0, 5.0, 3.0, 9.0, 2.0])
296 nc_arr = test_bind.numpycore.zeros([5])
297 for i, val in enumerate([1.0, 5.0, 3.0, 9.0, 2.0]):
ptp (test_set_operations.py:301)
291 assert_scalars_equal(np_result, nc_result, "prod")
292
293
294def test_ptp():
295 """Test ptp (peak to peak / range of values)"""
296 np_arr = test_bind.np.array([1.0, 5.0, 3.0, 9.0, 2.0])
297 nc_arr = test_bind.numpycore.zeros([5])
298 for i, val in enumerate([1.0, 5.0, 3.0, 9.0, 2.0]):
299 nc_arr.itemset(i, val)
300
301 np_result = np_arr.ptp()
302 nc_result = nc_arr.ptp()
303
304 assert_scalars_equal(np_result, nc_result, "ptp")
305
306
307# ============================================================================
308# Element Access Tests
309# ============================================================================
310
311def test_item():
sum (test_array_methods.py:262)
252 assert_arrays_equal(np_copy, nc_copy, "copy_preserves_values")
253
254
255# ============================================================================
256# REDUCTION METHOD TESTS (sum, mean, min, max)
257# ============================================================================
258
259def test_sum_1d():
260 """Test sum() on 1D array"""
261 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0])
262 np_result = np_arr.sum()
263
264 nc_arr = test_bind.numpycore.arange(1, 6, 1)
265 nc_result = nc_arr.sum()
266
267 assert_scalar_equal(np_result, nc_result, "sum_1d")
268
269
270def test_sum_2d():
271 """Test sum() on 2D array"""
272 np_arr = test_bind.np.ones([3, 4])
sort (test_ndarray_sort.py:8)
1#!/usr/bin/env python3
2"""
3ndarray.sort() Method Parity Tests
4Tests the in-place sorting method for numpycore arrays
5Compares behavior against official NumPy
6
7The ndarray.sort() method sorts an array in-place. Unlike np.sort(), which returns
8a sorted copy, arr.sort() modifies the original array and returns None.
9"""
10
11import sys
12import os
13
14# Add the build directory to path
15sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'x64', 'Debug'))
16
17import test_bind
18from test_bind import (
trace (test_advanced_operations.py:183)
173 nc_result = nc_a.dot(nc_b)
174
175 assert_arrays_equal(np_result, nc_result, "dot_matrix_matrix")
176
177
178def test_trace():
179 """Test trace (sum of diagonal elements)"""
180 np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
181 nc_arr = test_bind.numpycore.arange(1.0, 10.0, 1.0).reshape(3, 3)
182
183 np_result = np_arr.trace()
184 nc_result = nc_arr.trace()
185
186 assert_scalars_equal(np_result, nc_result, "trace")
187
188
189def test_diagonal():
190 """Test extracting diagonal"""
191 np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
192 nc_arr = test_bind.numpycore.arange(1.0, 10.0, 1.0).reshape(3, 3)
astype (test_type_conversion.py:104)
94# Type Conversion Tests
95# ============================================================================
96
97def test_astype_int_to_float():
98 """Test type conversion from int to float"""
99
100 np_arr = test_bind.np.array([1, 2, 3, 4, 5])
101
102 nc_arr = test_bind.numpycore.arange(1, 6, 1)
103
104 np_result = np_arr.astype(test_bind.np.float64)
105 nc_result = nc_arr.astype(test_bind.np.float64)
106
107 assert_arrays_equal(np_result, nc_result, "astype_int_to_float")
108
109
110def test_astype_float_to_int():
111 """Test type conversion from float to int"""
112
113 np_arr = test_bind.np.array([1.7, 2.3, 3.9, 4.1, 5.5])
copy (test_array_methods.py:247)
237 f_print_success("copy_basic: PASS (copy is independent)")
238 tests_passed += 1
239 else:
240 f_print_error(f"copy_basic: FAIL - copy was affected by original modification")
241 tests_failed += 1
242
243
244def test_copy_preserves_values():
245 """Test copy preserves array values"""
246 np_arr = test_bind.np.arange(0, 10, 1, dtype='float64')
247 np_copy = np_arr.copy()
248
249 nc_arr = test_bind.numpycore.arange(0, 10, 1)
250 nc_copy = nc_arr.copy()
251
252 assert_arrays_equal(np_copy, nc_copy, "copy_preserves_values")
253
254
255# ============================================================================
256# REDUCTION METHOD TESTS (sum, mean, min, max)
257# ============================================================================
tobytes (test_type_conversion.py:222)
212 assert_values_equal(np_result, nc_result, "tolist_3d")
213
214
215def test_tobytes_1d():
216 """Test conversion to bytes (1D)"""
217
218 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0], dtype=test_bind.np.float64)
219
220 nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0)
221
222 np_result = np_arr.tobytes()
223 nc_result = nc_arr.tobytes()
224
225 assert_values_equal(np_result, nc_result, "tobytes_1d")
226
227
228def test_tobytes_2d():
229 """Test conversion to bytes (2D)"""
230
231 np_arr = test_bind.np.array([[1.0, 2.0], [3.0, 4.0]], dtype=test_bind.np.float64)
tolist (test_eig_reenable.py:52)
42 print("[PASS] Basic symmetric test passed")
43
44
45def test_basic_general():
46 """Test 2: Basic general (non-symmetric) matrix"""
47 print("\n=== Test 2: Basic general matrix ===")
48 a = np.array([[1.0, 2.0], [3.0, 4.0]])
49
50 w, v = np.linalg.eig(a)
51
52 print(f"Matrix: {a.tolist()}")
53 print(f"Eigenvalues: {w}")
54 print(f"Eigenvectors:\n{v}")
55
56 # Verify eigenvalue equation
57 for i in range(2):
58 left = a @ v[:, i]
59 right = w[i] * v[:, i]
60 assert np.allclose(left, right, atol=1e-10), f"Eigenvalue equation failed for index {i}"
61
62 print("[PASS]Basic general test passed")
view (test_type_conversion.py:390)
380# ============================================================================
381# Array View Tests
382# ============================================================================
383
384def test_view_same_dtype():
385 """Test view with same dtype"""
386
387 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0])
388 nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0)
389
390 np_view = np_arr.view(test_bind.np.float64)
391 nc_view = nc_arr.view(test_bind.np.float64)
392
393 assert_arrays_equal(np_view, nc_view, "view_same_dtype")
394
395
396def test_view_float64_as_int64():
397 """Test view float64 as int64"""
398
399 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0], dtype=test_bind.np.float64)
400 nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0)
fill (test_set_operations.py:327)
317 nc_result = nc_arr.item(2)
318
319 assert_scalars_equal(np_result, nc_result, "item")
320
321
322def test_fill():
323 """Test fill (fill array with scalar value)"""
324 np_arr = test_bind.np.zeros(5, dtype='float64')
325 nc_arr = test_bind.numpycore.zeros([5])
326
327 np_arr.fill(3.14)
328 nc_arr.fill(3.14)
329
330 assert_arrays_equal(np_arr, nc_arr, "fill")
331
332
333def test_put():
334 """Test put (replace specified elements)"""
335 np_arr = test_bind.np.zeros(5, dtype='float64')
336 nc_arr = test_bind.numpycore.zeros([5])
item (test_set_operations.py:316)
306# ============================================================================
307# Element Access Tests
308# ============================================================================
309
310def test_item():
311 """Test item (copy element to standard Python scalar)"""
312 np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0])
313 nc_arr = test_bind.numpycore.arange(1.0, 6.0, 1.0)
314
315 np_result = np_arr.item(2)
316 nc_result = nc_arr.item(2)
317
318 assert_scalars_equal(np_result, nc_result, "item")
319
320
321def test_fill():
322 """Test fill (fill array with scalar value)"""
323 np_arr = test_bind.np.zeros(5, dtype='float64')
324 nc_arr = test_bind.numpycore.zeros([5])