NDArray ======= .. currentmodule:: numpycore .. class:: NDArray N-dimensional array class from numpyCore Python, providing NumPy-compatible array functionality with high-performance C++ implementation. Example ------- .. code-block:: python 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 ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Attribute - Description - Example * - :attr:`~NDArray.T` - View of the transposed array. - :ref:`View ` * - :attr:`~NDArray.base` - Base object if memory is from some other object. - * - :attr:`~NDArray.ctypes` - An object to simplify the interaction of the array with the ctypes ... - * - :attr:`~NDArray.data` - Python buffer object pointing to the start of the array's data. - :ref:`View ` * - :attr:`~NDArray.dtype` - Data-type of the array's elements. - :ref:`View ` * - :attr:`~NDArray.flags` - Information about the memory layout of the array. - :ref:`View ` * - :attr:`~NDArray.flat` - A 1-D iterator over the array. - * - :attr:`~NDArray.imag` - The imaginary part of the array. - * - :attr:`~NDArray.itemsize` - Length of one array element in bytes. - :ref:`View ` * - :attr:`~NDArray.nbytes` - Total bytes consumed by the elements of the array. - :ref:`View ` * - :attr:`~NDArray.ndim` - Number of array dimensions. - :ref:`View ` * - :attr:`~NDArray.real` - The real part of the array. - * - :attr:`~NDArray.shape` - Tuple of array dimensions. - :ref:`View ` * - :attr:`~NDArray.size` - Number of elements in the array. - :ref:`View ` * - :attr:`~NDArray.strides` - Tuple of bytes to step in each dimension when traversing an array. - Construction ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.__init__` ``(self, /, *args, **kwargs)`` - Initialize self. See help(type(self)) for accurate signature. - Shape Manipulation ------------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.flatten` - a.flatten(order='C') - :ref:`View ` * - :meth:`~NDArray.ravel` - a.ravel([order]) - :ref:`View ` * - :meth:`~NDArray.reshape` - a.reshape(shape, order='C') - :ref:`View ` * - :meth:`~NDArray.resize` - a.resize(new_shape, refcheck=True) - :ref:`View ` * - :meth:`~NDArray.squeeze` - a.squeeze(axis=None) - * - :meth:`~NDArray.swapaxes` - a.swapaxes(axis1, axis2) - :ref:`View ` * - :meth:`~NDArray.transpose` - a.transpose(*axes) - :ref:`View ` Indexing / Slicing ------------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.__getitem__` ``(self, key, /)`` - Return self[key]. - * - :meth:`~NDArray.__setitem__` ``(self, key, value, /)`` - Set self[key] to value. - * - :meth:`~NDArray.choose` - a.choose(choices, out=None, mode='raise') - * - :meth:`~NDArray.compress` - a.compress(condition, axis=None, out=None) - :ref:`View ` * - :meth:`~NDArray.diagonal` - a.diagonal(offset=0, axis1=0, axis2=1) - :ref:`View ` * - :meth:`~NDArray.nonzero` - a.nonzero() - :ref:`View ` * - :meth:`~NDArray.put` - a.put(indices, values, mode='raise') - :ref:`View ` * - :meth:`~NDArray.searchsorted` - a.searchsorted(v, side='left', sorter=None) - :ref:`View ` * - :meth:`~NDArray.take` - a.take(indices, axis=None, out=None, mode='raise') - :ref:`View ` Joining / Splitting ------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.repeat` - a.repeat(repeats, axis=None) - Mathematical Operations ----------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.clip` - a.clip(min=None, max=None, out=None, **kwargs) - :ref:`View ` Statistics ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.argmax` - a.argmax(axis=None, out=None, *, keepdims=False) - * - :meth:`~NDArray.argmin` - a.argmin(axis=None, out=None, *, keepdims=False) - * - :meth:`~NDArray.max` - a.max(axis=None, out=None, keepdims=False, initial=, wher... - :ref:`View ` * - :meth:`~NDArray.mean` - a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True) - :ref:`View ` * - :meth:`~NDArray.min` - a.min(axis=None, out=None, keepdims=False, initial=, wher... - :ref:`View ` * - :meth:`~NDArray.prod` - a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, ... - :ref:`View ` * - :meth:`~NDArray.ptp` - a.ptp(axis=None, out=None, keepdims=False) - :ref:`View ` * - :meth:`~NDArray.std` - a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, w... - * - :meth:`~NDArray.sum` - a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, w... - :ref:`View ` * - :meth:`~NDArray.var` - a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, w... - Sorting / Searching ------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.argpartition` - a.argpartition(kth, axis=-1, kind='introselect', order=None) - * - :meth:`~NDArray.argsort` - a.argsort(axis=-1, kind=None, order=None) - * - :meth:`~NDArray.partition` - a.partition(kth, axis=-1, kind='introselect', order=None) - * - :meth:`~NDArray.sort` - a.sort(axis=-1, kind=None, order=None) - :ref:`View ` Comparison / Logic ------------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.__eq__` ``(self, value, /)`` - Return self==value. - * - :meth:`~NDArray.__ge__` ``(self, value, /)`` - Return self>=value. - * - :meth:`~NDArray.__gt__` ``(self, value, /)`` - Return self>value. - * - :meth:`~NDArray.__le__` ``(self, value, /)`` - Return self<=value. - * - :meth:`~NDArray.__lt__` ``(self, value, /)`` - Return self` I/O --- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.astype` - a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) - :ref:`View ` * - :meth:`~NDArray.byteswap` - a.byteswap(inplace=False) - * - :meth:`~NDArray.copy` - a.copy(order='C') - :ref:`View ` * - :meth:`~NDArray.tobytes` - a.tobytes(order='C') - :ref:`View ` * - :meth:`~NDArray.tofile` - a.tofile(fid, sep="", format="%s") - * - :meth:`~NDArray.tolist` - a.tolist() - :ref:`View ` * - :meth:`~NDArray.view` - a.view([dtype][, type]) - :ref:`View ` Arithmetic Operators -------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.__abs__` ``(self, /)`` - - * - :meth:`~NDArray.__add__` ``(self, value, /)`` - Return self+value. - * - :meth:`~NDArray.__contains__` ``(self, key, /)`` - Return bool(key in self). - * - :meth:`~NDArray.__floordiv__` ``(self, value, /)`` - Return self//value. - * - :meth:`~NDArray.__hash__` - - * - :meth:`~NDArray.__iter__` ``(self, /)`` - Implement iter(self). - * - :meth:`~NDArray.__len__` ``(self, /)`` - Return len(self). - * - :meth:`~NDArray.__mod__` ``(self, value, /)`` - Return self%value. - * - :meth:`~NDArray.__mul__` ``(self, value, /)`` - Return self*value. - * - :meth:`~NDArray.__neg__` ``(self, /)`` - -self - * - :meth:`~NDArray.__pos__` ``(self, /)`` - +self - * - :meth:`~NDArray.__pow__` ``(self, value, mod=None, /)`` - Return pow(self, value, mod). - * - :meth:`~NDArray.__radd__` ``(self, value, /)`` - Return value+self. - * - :meth:`~NDArray.__repr__` ``(self, /)`` - Return repr(self). - * - :meth:`~NDArray.__rmatmul__` ``(self, value, /)`` - Return value@self. - * - :meth:`~NDArray.__rmul__` ``(self, value, /)`` - Return value*self. - * - :meth:`~NDArray.__rsub__` ``(self, value, /)`` - Return value-self. - * - :meth:`~NDArray.__rtruediv__` ``(self, value, /)`` - Return value/self. - * - :meth:`~NDArray.__str__` ``(self, /)`` - Return str(self). - * - :meth:`~NDArray.__sub__` ``(self, value, /)`` - Return self-value. - * - :meth:`~NDArray.__truediv__` ``(self, value, /)`` - Return self/value. - Other Methods ------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~NDArray.conj` - a.conj() - * - :meth:`~NDArray.conjugate` - a.conjugate() - * - :meth:`~NDArray.cumprod` - a.cumprod(axis=None, dtype=None, out=None) - * - :meth:`~NDArray.cumsum` - a.cumsum(axis=None, dtype=None, out=None) - * - :meth:`~NDArray.dump` - a.dump(file) - * - :meth:`~NDArray.dumps` - a.dumps() - * - :meth:`~NDArray.fill` ``([0, 0])`` - a.fill(value) - :ref:`View ` * - :meth:`~NDArray.getfield` - a.getfield(dtype, offset=0) - * - :meth:`~NDArray.item` - a.item(*args) - :ref:`View ` * - :meth:`~NDArray.itemset` - a.itemset(*args) - * - :meth:`~NDArray.newbyteorder` - arr.newbyteorder(new_order='S', /) - * - :meth:`~NDArray.round` - a.round(decimals=0, out=None) - * - :meth:`~NDArray.setfield` - a.setfield(val, dtype, offset=0) - * - :meth:`~NDArray.setflags` - a.setflags(write=None, align=None, uic=None) - * - :meth:`~NDArray.tostring` - a.tostring(order='C') - Code Examples ------------- The following examples are extracted from the test suite. .. _example-ndarray-t-0: .. dropdown:: T (test_array_methods.py:132) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 122 :emphasize-lines: 11 assert_arrays_equal(np_result, nc_result, "reshape_with_minus_one") # ============================================================================ # TRANSPOSE TESTS # ============================================================================ def test_transpose_2d(): """Test transpose of 2D array""" np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) np_result = np_arr.T # Create equivalent numpycore array nc_base = test_bind.numpycore.arange(1, 7, 1) nc_arr = nc_base.reshape(2, 3) nc_result = nc_arr.T assert_arrays_equal(np_result, nc_result, "transpose_2d") def test_transpose_method(): .. _example-ndarray-data-1: .. dropdown:: data (test_masked_array_wrappers.py:72) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 62 :emphasize-lines: 11 print("Testing MaskedArray.clip()") print("="*70) # data = [1, 5, 3, 8, 2], mask = [F, F, T, F, F] # clip to [2, 6]: unmasked [2, 5, -, 6, 2], masked value unchanged ma = create_masked_array([1.0, 5.0, 3.0, 8.0, 2.0], [False, False, True, False, False]) result = ma.clip(2.0, 6.0) # Verify unmasked values are clipped result_data = test_bind.np.asarray(result.data) assert_array_equal(result_data[0], 2.0, "clip lower bound") # 1 -> 2 assert_array_equal(result_data[1], 5.0, "clip middle unchanged") # 5 stays 5 assert_array_equal(result_data[3], 6.0, "clip upper bound") # 8 -> 6 # Verify masked element NOT touched assert_array_equal(result_data[2], 3.0, "clip masked element unchanged") print(f"[OK] ma.clip(): PASSED") return True .. _example-ndarray-dtype-2: .. dropdown:: dtype (test_abs_types.py:13) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 3 :emphasize-lines: 11 Test abs() function for all supported types comparing NumpyCore vs NumPy. Covers: float64, float32, int64, int32, int16, int8, uint64, uint32, uint16, uint8, bool, complex64, complex128 """ import sys import test_bind def assert_arrays_equal(np_result, nc_result, test_name, rtol=1e-10, atol=1e-10): np = test_bind.np np_arr = np.asarray(np_result) nc_arr = np.asarray(nc_result) if np_arr.dtype != nc_arr.dtype: print(f"[FAIL] {test_name}: dtype mismatch - np:{np_arr.dtype} vs nc:{nc_arr.dtype}") return False if np_arr.shape != nc_arr.shape: print(f"[FAIL] {test_name}: shape mismatch - np:{np_arr.shape} vs nc:{nc_arr.shape}") return False if not np.allclose(np_arr, nc_arr, rtol=rtol, atol=atol, equal_nan=True): print(f"[FAIL] {test_name}: values mismatch") print(f" np: {np_arr}") print(f" nc: {nc_arr}") return False .. _example-ndarray-flags-3: .. dropdown:: flags (test_array_conversion.py:124) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 114 :emphasize-lines: 11 def test_ascontiguousarray(): """Test ascontiguousarray function""" print("\n" + "="*70) print("Testing ascontiguousarray()") print("="*70) # Test 1: Basic array print("\n[Test 1] ascontiguousarray from list") result = numpycore.ascontiguousarray([[1, 2, 3], [4, 5, 6]]) print(f" numpycore.ascontiguousarray([[1, 2, 3], [4, 5, 6]]): shape={result.shape}") print(f" Result is C-contiguous: {result.flags['C_CONTIGUOUS']}") assert result.flags['C_CONTIGUOUS'], "Result should be C-contiguous" print(" [OK] C-contiguous array") # Test 2: With dtype print("\n[Test 2] ascontiguousarray with dtype") result = numpycore.ascontiguousarray([1, 2, 3, 4], dtype='float64') print(f" numpycore.ascontiguousarray([1, 2, 3, 4], dtype='float64'): {result}") assert result.dtype == np.float64, f"Expected float64, got {result.dtype}" print(" [OK] ascontiguousarray with dtype") .. _example-ndarray-itemsize-4: .. dropdown:: itemsize (test_array_properties.py:199) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 189 :emphasize-lines: 11 tests_failed += 1 # ============================================================================ # ITEMSIZE AND NBYTES TESTS # ============================================================================ def test_itemsize_float64(): """Test itemsize for float64 (should be 8 bytes)""" arr = test_bind.numpycore.ones([2, 2]) assert_equal(arr.itemsize, 8, "itemsize_float64") def test_itemsize_float32(): """Test itemsize for float32 (should be 4 bytes)""" arr = test_bind.numpycore.ones([2, 2], dtype='float32') assert_equal(arr.itemsize, 4, "itemsize_float32") def test_itemsize_int32(): """Test itemsize for int32 (should be 4 bytes)""" .. _example-ndarray-nbytes-5: .. dropdown:: nbytes (test_array_properties.py:228) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 218 :emphasize-lines: 11 def test_nbytes(): """Test nbytes (size * itemsize)""" global tests_run, tests_passed, tests_failed tests_run += 1 arr = test_bind.numpycore.zeros([3, 4]) # 12 elements * 8 bytes = 96 expected_nbytes = arr.size * arr.itemsize if arr.nbytes == expected_nbytes and expected_nbytes == 96: f_print_success(f"nbytes: PASS (nbytes={arr.nbytes})") tests_passed += 1 else: f_print_error(f"nbytes: FAIL - expected {expected_nbytes}, got {arr.nbytes}") tests_failed += 1 # ============================================================================ # MAIN TEST RUNNER # ============================================================================ .. _example-ndarray-ndim-6: .. dropdown:: ndim (test_array_properties.py:76) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 66 :emphasize-lines: 11 assert_equal(arr.shape, (7, 3), "shape_rectangular") # ============================================================================ # NDIM PROPERTY TESTS # ============================================================================ def test_ndim_1d(): """Test ndim property for 1D array""" arr = test_bind.numpycore.arange(0, 10, 1) assert_equal(arr.ndim, 1, "ndim_1d") def test_ndim_2d(): """Test ndim property for 2D array""" arr = test_bind.numpycore.zeros([3, 4]) assert_equal(arr.ndim, 2, "ndim_2d") def test_ndim_3d(): """Test ndim property for 3D array""" .. _example-ndarray-shape-7: .. dropdown:: shape (test_abs_types.py:16) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 6 :emphasize-lines: 11 import sys import test_bind def assert_arrays_equal(np_result, nc_result, test_name, rtol=1e-10, atol=1e-10): np = test_bind.np np_arr = np.asarray(np_result) nc_arr = np.asarray(nc_result) if np_arr.dtype != nc_arr.dtype: print(f"[FAIL] {test_name}: dtype mismatch - np:{np_arr.dtype} vs nc:{nc_arr.dtype}") return False if np_arr.shape != nc_arr.shape: print(f"[FAIL] {test_name}: shape mismatch - np:{np_arr.shape} vs nc:{nc_arr.shape}") return False if not np.allclose(np_arr, nc_arr, rtol=rtol, atol=atol, equal_nan=True): print(f"[FAIL] {test_name}: values mismatch") print(f" np: {np_arr}") print(f" nc: {nc_arr}") return False print(f"[OK] {test_name}") return True .. _example-ndarray-size-8: .. dropdown:: size (test_array_properties.py:98) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 88 :emphasize-lines: 11 assert_equal(arr.ndim, 3, "ndim_3d") # ============================================================================ # SIZE PROPERTY TESTS # ============================================================================ def test_size_1d(): """Test size property for 1D array""" arr = test_bind.numpycore.zeros([10]) assert_equal(arr.size, 10, "size_1d") def test_size_2d(): """Test size property for 2D array""" arr = test_bind.numpycore.ones([3, 4]) assert_equal(arr.size, 12, "size_2d") def test_size_3d(): """Test size property for 3D array""" .. _example-ndarray-flatten-9: .. dropdown:: flatten (test_array_methods.py:171) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 161 :emphasize-lines: 11 assert_arrays_equal(np_result, nc_result, "transpose_rectangular") # ============================================================================ # FLATTEN TESTS # ============================================================================ def test_flatten_2d(): """Test flatten of 2D array""" np_arr = test_bind.np.array([[1.0, 2.0], [3.0, 4.0]]) np_result = np_arr.flatten() # Create equivalent numpycore array nc_base = test_bind.numpycore.arange(1, 5, 1) nc_arr = nc_base.reshape(2, 2) nc_result = nc_arr.flatten() assert_arrays_equal(np_result, nc_result, "flatten_2d") def test_flatten_3d(): .. _example-ndarray-ravel-10: .. dropdown:: ravel (test_array_methods.py:199) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 189 :emphasize-lines: 11 assert_arrays_equal(np_result, nc_result, "flatten_3d") # ============================================================================ # RAVEL TESTS # ============================================================================ def test_ravel_2d(): """Test ravel of 2D array""" np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) np_result = np_arr.ravel() nc_base = test_bind.numpycore.arange(1, 7, 1) nc_arr = nc_base.reshape(2, 3) nc_result = nc_arr.ravel() assert_arrays_equal(np_result, nc_result, "ravel_2d") def test_ravel_3d(): """Test ravel of 3D array""" .. _example-ndarray-reshape-11: .. dropdown:: reshape (test_array_methods.py:84) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 74 :emphasize-lines: 11 return False # ============================================================================ # RESHAPE TESTS # ============================================================================ def test_reshape_1d_to_2d(): """Test reshape from 1D to 2D""" np_arr = test_bind.np.arange(0, 6, 1, dtype='float64') np_result = np_arr.reshape(2, 3) nc_arr = test_bind.numpycore.arange(0, 6, 1) nc_result = nc_arr.reshape(2, 3) assert_arrays_equal(np_result, nc_result, "reshape_1d_to_2d") def test_reshape_2d_to_1d(): """Test reshape from 2D to 1D""" np_arr = test_bind.np.ones([2, 3]) .. _example-ndarray-resize-12: .. dropdown:: resize (test_type_conversion.py:274) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 264 :emphasize-lines: 11 # ============================================================================ def test_resize_grow(): """Test resize to larger size""" np_arr = test_bind.np.array([1.0, 2.0, 3.0]) # pybind11 arrays don't own data, so use .copy() to get owned array for .resize() nc_arr = test_bind.numpycore.arange(1.0, 4.0, 1.0).copy() # Resize to larger np_arr.resize([5], refcheck=False) nc_arr.resize([5], refcheck=False) assert_arrays_equal(np_arr, nc_arr, "resize_grow") def test_resize_shrink(): """Test resize to smaller size""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0]) # pybind11 arrays don't own data, so use .copy() to get owned array for .resize() .. _example-ndarray-swapaxes-13: .. dropdown:: swapaxes (test_set_operations.py:253) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 243 :emphasize-lines: 11 nc_result = test_bind.np.squeeze(nc_arr) assert_arrays_equal(np_result, nc_result, "squeeze") def test_swapaxes(): """Test swapaxes (interchange two axes)""" np_arr = test_bind.np.arange(12, dtype='float64').reshape(3, 4) nc_arr = test_bind.numpycore.arange(0.0, 12.0, 1.0).reshape(3, 4) np_result = np_arr.swapaxes(0, 1) nc_result = nc_arr.swapaxes(0, 1) assert_arrays_equal(np_result, nc_result, "swapaxes") def test_choose(): """Test choose (construct array from index array)""" np_choices = [ test_bind.np.array([0.0, 1.0, 2.0]), test_bind.np.array([10.0, 11.0, 12.0]), .. _example-ndarray-transpose-14: .. dropdown:: transpose (test_array_methods.py:145) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 135 :emphasize-lines: 11 nc_base = test_bind.numpycore.arange(1, 7, 1) nc_arr = nc_base.reshape(2, 3) nc_result = nc_arr.T assert_arrays_equal(np_result, nc_result, "transpose_2d") def test_transpose_method(): """Test transpose() method""" np_arr = test_bind.np.ones([3, 4]) np_result = np_arr.transpose() nc_arr = test_bind.numpycore.ones([3, 4]) nc_result = nc_arr.transpose() assert_arrays_equal(np_result, nc_result, "transpose_method") def test_transpose_rectangular(): """Test transpose of non-square matrix""" np_arr = test_bind.np.full([5, 2], 7.0) .. _example-ndarray-compress-15: .. dropdown:: compress (test_advanced_operations.py:300) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 290 :emphasize-lines: 11 assert_arrays_equal(np_result, nc_result, "clip") def test_compress(): """Test compress (select elements based on condition)""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0]) np_condition = test_bind.np.array([True, False, True, False, True]) nc_arr = test_bind.numpycore.arange(1.0, 6.0, 1.0) np_result = np_arr.compress(np_condition) nc_result = nc_arr.compress(np_condition) assert_arrays_equal(np_result, nc_result, "compress") def test_take(): """Test take (select elements by indices)""" np_arr = test_bind.np.array([10.0, 20.0, 30.0, 40.0, 50.0]) np_indices = test_bind.np.array([0, 2, 4]) .. _example-ndarray-diagonal-16: .. dropdown:: diagonal (test_advanced_operations.py:194) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 184 :emphasize-lines: 11 nc_result = nc_arr.trace() assert_scalars_equal(np_result, nc_result, "trace") def test_diagonal(): """Test extracting diagonal""" np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) nc_arr = test_bind.numpycore.arange(1.0, 10.0, 1.0).reshape(3, 3) np_result = np_arr.diagonal() nc_result = nc_arr.diagonal() assert_arrays_equal(np_result, nc_result, "diagonal") # ============================================================================ # Logical Operations Tests # ============================================================================ def test_all(): .. _example-ndarray-nonzero-17: .. dropdown:: nonzero (test_advanced_operations.py:272) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 262 :emphasize-lines: 11 def test_nonzero(): """Test nonzero (indices of nonzero elements)""" np_arr = test_bind.np.array([0.0, 1.0, 0.0, 3.0, 0.0, 5.0]) nc_arr = test_bind.numpycore.zeros([6]) nc_arr.itemset(1, 1.0) nc_arr.itemset(3, 3.0) nc_arr.itemset(5, 5.0) np_result = np_arr.nonzero()[0] # Get first tuple element nc_result = nc_arr.nonzero()[0] assert_arrays_equal(np_result, nc_result, "nonzero", atol=0) # ============================================================================ # Element Selection Tests # ============================================================================ def test_clip(): .. _example-ndarray-put-18: .. dropdown:: put (test_set_operations.py:338) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 328 :emphasize-lines: 11 nc_arr.fill(3.14) assert_arrays_equal(np_arr, nc_arr, "fill") def test_put(): """Test put (replace specified elements)""" np_arr = test_bind.np.zeros(5, dtype='float64') nc_arr = test_bind.numpycore.zeros([5]) np_arr.put([0, 2, 4], [1.0, 2.0, 3.0]) nc_arr.put([0, 2, 4], [1.0, 2.0, 3.0]) assert_arrays_equal(np_arr, nc_arr, "put") # ============================================================================ # Sorting Variants Tests # ============================================================================ def test_partition(): .. _example-ndarray-searchsorted-19: .. dropdown:: searchsorted (test_advanced_operations.py:329) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 319 :emphasize-lines: 11 # ============================================================================ # Searching Tests # ============================================================================ def test_searchsorted(): """Test searchsorted (find indices where elements should be inserted)""" np_arr = test_bind.np.array([1.0, 3.0, 5.0, 7.0, 9.0]) nc_arr = test_bind.numpycore.linspace(1.0, 9.0, 5) # Search for single value np_result = np_arr.searchsorted(4.0) nc_result = nc_arr.searchsorted(4.0) assert_scalars_equal(np_result, nc_result, "searchsorted_single", atol=0) def test_searchsorted_multiple(): """Test searchsorted with multiple values""" np_arr = test_bind.np.array([1.0, 3.0, 5.0, 7.0, 9.0]) np_values = test_bind.np.array([2.0, 6.0, 8.0]) .. _example-ndarray-take-20: .. dropdown:: take (test_advanced_operations.py:313) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 303 :emphasize-lines: 11 assert_arrays_equal(np_result, nc_result, "compress") def test_take(): """Test take (select elements by indices)""" np_arr = test_bind.np.array([10.0, 20.0, 30.0, 40.0, 50.0]) np_indices = test_bind.np.array([0, 2, 4]) nc_arr = test_bind.numpycore.linspace(10.0, 50.0, 5) np_result = np_arr.take(np_indices) nc_result = nc_arr.take(np_indices) assert_arrays_equal(np_result, nc_result, "take") # ============================================================================ # Searching Tests # ============================================================================ def test_searchsorted(): .. _example-ndarray-clip-21: .. dropdown:: clip (test_advanced_operations.py:287) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 277 :emphasize-lines: 11 # ============================================================================ # Element Selection Tests # ============================================================================ def test_clip(): """Test clip (limit values to range)""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0]) nc_arr = test_bind.numpycore.arange(1.0, 6.0, 1.0) np_result = np_arr.clip(2.0, 4.0) nc_result = nc_arr.clip(2.0, 4.0) assert_arrays_equal(np_result, nc_result, "clip") def test_compress(): """Test compress (select elements based on condition)""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0]) np_condition = test_bind.np.array([True, False, True, False, True]) .. _example-ndarray-max-22: .. dropdown:: max (test_array_methods.py:319) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 309 :emphasize-lines: 11 nc_base = test_bind.numpycore.full([5], 5.0) nc_arr = nc_base + test_bind.np.array([0, -3, 3, -4, 4]) nc_result = nc_arr.min() assert_scalar_equal(np_result, nc_result, "min_1d") def test_max_1d(): """Test max() on 1D array""" np_arr = test_bind.np.array([5.0, 2.0, 8.0, 1.0, 9.0]) np_result = np_arr.max() nc_base = test_bind.numpycore.full([5], 5.0) nc_arr = nc_base + test_bind.np.array([0, -3, 3, -4, 4]) nc_result = nc_arr.max() assert_scalar_equal(np_result, nc_result, "max_1d") def test_min_2d(): """Test min() on 2D array""" .. _example-ndarray-mean-23: .. dropdown:: mean (test_array_methods.py:284) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 274 :emphasize-lines: 11 nc_arr = test_bind.numpycore.ones([3, 4]) nc_result = nc_arr.sum() assert_scalar_equal(np_result, nc_result, "sum_2d") def test_mean_1d(): """Test mean() on 1D array""" np_arr = test_bind.np.array([2.0, 4.0, 6.0, 8.0]) np_result = np_arr.mean() nc_base = test_bind.numpycore.full([4], 2.0) nc_arr = nc_base + test_bind.np.array([0, 2, 4, 6]) nc_result = nc_arr.mean() assert_scalar_equal(np_result, nc_result, "mean_1d") def test_mean_2d(): """Test mean() on 2D array""" .. _example-ndarray-min-24: .. dropdown:: min (test_array_methods.py:307) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 297 :emphasize-lines: 11 nc_arr = test_bind.numpycore.full([3, 3], 5.0) nc_result = nc_arr.mean() assert_scalar_equal(np_result, nc_result, "mean_2d") def test_min_1d(): """Test min() on 1D array""" np_arr = test_bind.np.array([5.0, 2.0, 8.0, 1.0, 9.0]) np_result = np_arr.min() nc_base = test_bind.numpycore.full([5], 5.0) nc_arr = nc_base + test_bind.np.array([0, -3, 3, -4, 4]) nc_result = nc_arr.min() assert_scalar_equal(np_result, nc_result, "min_1d") def test_max_1d(): """Test max() on 1D array""" .. _example-ndarray-prod-25: .. dropdown:: prod (test_set_operations.py:288) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 278 :emphasize-lines: 11 # ============================================================================ # Reduction Operations Tests # ============================================================================ def test_prod(): """Test prod (product of array elements)""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0]) nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0) np_result = np_arr.prod() nc_result = nc_arr.prod() assert_scalars_equal(np_result, nc_result, "prod") def test_ptp(): """Test ptp (peak to peak / range of values)""" np_arr = test_bind.np.array([1.0, 5.0, 3.0, 9.0, 2.0]) nc_arr = test_bind.numpycore.zeros([5]) for i, val in enumerate([1.0, 5.0, 3.0, 9.0, 2.0]): .. _example-ndarray-ptp-26: .. dropdown:: ptp (test_set_operations.py:301) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 291 :emphasize-lines: 11 assert_scalars_equal(np_result, nc_result, "prod") def test_ptp(): """Test ptp (peak to peak / range of values)""" np_arr = test_bind.np.array([1.0, 5.0, 3.0, 9.0, 2.0]) nc_arr = test_bind.numpycore.zeros([5]) for i, val in enumerate([1.0, 5.0, 3.0, 9.0, 2.0]): nc_arr.itemset(i, val) np_result = np_arr.ptp() nc_result = nc_arr.ptp() assert_scalars_equal(np_result, nc_result, "ptp") # ============================================================================ # Element Access Tests # ============================================================================ def test_item(): .. _example-ndarray-sum-27: .. dropdown:: sum (test_array_methods.py:262) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 252 :emphasize-lines: 11 assert_arrays_equal(np_copy, nc_copy, "copy_preserves_values") # ============================================================================ # REDUCTION METHOD TESTS (sum, mean, min, max) # ============================================================================ def test_sum_1d(): """Test sum() on 1D array""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0]) np_result = np_arr.sum() nc_arr = test_bind.numpycore.arange(1, 6, 1) nc_result = nc_arr.sum() assert_scalar_equal(np_result, nc_result, "sum_1d") def test_sum_2d(): """Test sum() on 2D array""" np_arr = test_bind.np.ones([3, 4]) .. _example-ndarray-sort-28: .. dropdown:: sort (test_ndarray_sort.py:8) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 1 :emphasize-lines: 8 #!/usr/bin/env python3 """ ndarray.sort() Method Parity Tests Tests the in-place sorting method for numpycore arrays Compares behavior against official NumPy The ndarray.sort() method sorts an array in-place. Unlike np.sort(), which returns a sorted copy, arr.sort() modifies the original array and returns None. """ import sys import os # Add the build directory to path sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'x64', 'Debug')) import test_bind from test_bind import ( .. _example-ndarray-trace-29: .. dropdown:: trace (test_advanced_operations.py:183) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 173 :emphasize-lines: 11 nc_result = nc_a.dot(nc_b) assert_arrays_equal(np_result, nc_result, "dot_matrix_matrix") def test_trace(): """Test trace (sum of diagonal elements)""" np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) nc_arr = test_bind.numpycore.arange(1.0, 10.0, 1.0).reshape(3, 3) np_result = np_arr.trace() nc_result = nc_arr.trace() assert_scalars_equal(np_result, nc_result, "trace") def test_diagonal(): """Test extracting diagonal""" np_arr = test_bind.np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) nc_arr = test_bind.numpycore.arange(1.0, 10.0, 1.0).reshape(3, 3) .. _example-ndarray-astype-30: .. dropdown:: astype (test_type_conversion.py:104) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 94 :emphasize-lines: 11 # Type Conversion Tests # ============================================================================ def test_astype_int_to_float(): """Test type conversion from int to float""" np_arr = test_bind.np.array([1, 2, 3, 4, 5]) nc_arr = test_bind.numpycore.arange(1, 6, 1) np_result = np_arr.astype(test_bind.np.float64) nc_result = nc_arr.astype(test_bind.np.float64) assert_arrays_equal(np_result, nc_result, "astype_int_to_float") def test_astype_float_to_int(): """Test type conversion from float to int""" np_arr = test_bind.np.array([1.7, 2.3, 3.9, 4.1, 5.5]) .. _example-ndarray-copy-31: .. dropdown:: copy (test_array_methods.py:247) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 237 :emphasize-lines: 11 f_print_success("copy_basic: PASS (copy is independent)") tests_passed += 1 else: f_print_error(f"copy_basic: FAIL - copy was affected by original modification") tests_failed += 1 def test_copy_preserves_values(): """Test copy preserves array values""" np_arr = test_bind.np.arange(0, 10, 1, dtype='float64') np_copy = np_arr.copy() nc_arr = test_bind.numpycore.arange(0, 10, 1) nc_copy = nc_arr.copy() assert_arrays_equal(np_copy, nc_copy, "copy_preserves_values") # ============================================================================ # REDUCTION METHOD TESTS (sum, mean, min, max) # ============================================================================ .. _example-ndarray-tobytes-32: .. dropdown:: tobytes (test_type_conversion.py:222) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 212 :emphasize-lines: 11 assert_values_equal(np_result, nc_result, "tolist_3d") def test_tobytes_1d(): """Test conversion to bytes (1D)""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0], dtype=test_bind.np.float64) nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0) np_result = np_arr.tobytes() nc_result = nc_arr.tobytes() assert_values_equal(np_result, nc_result, "tobytes_1d") def test_tobytes_2d(): """Test conversion to bytes (2D)""" np_arr = test_bind.np.array([[1.0, 2.0], [3.0, 4.0]], dtype=test_bind.np.float64) .. _example-ndarray-tolist-33: .. dropdown:: tolist (test_eig_reenable.py:52) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 42 :emphasize-lines: 11 print("[PASS] Basic symmetric test passed") def test_basic_general(): """Test 2: Basic general (non-symmetric) matrix""" print("\n=== Test 2: Basic general matrix ===") a = np.array([[1.0, 2.0], [3.0, 4.0]]) w, v = np.linalg.eig(a) print(f"Matrix: {a.tolist()}") print(f"Eigenvalues: {w}") print(f"Eigenvectors:\n{v}") # Verify eigenvalue equation for i in range(2): left = a @ v[:, i] right = w[i] * v[:, i] assert np.allclose(left, right, atol=1e-10), f"Eigenvalue equation failed for index {i}" print("[PASS]Basic general test passed") .. _example-ndarray-view-34: .. dropdown:: view (test_type_conversion.py:390) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 380 :emphasize-lines: 11 # ============================================================================ # Array View Tests # ============================================================================ def test_view_same_dtype(): """Test view with same dtype""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0]) nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0) np_view = np_arr.view(test_bind.np.float64) nc_view = nc_arr.view(test_bind.np.float64) assert_arrays_equal(np_view, nc_view, "view_same_dtype") def test_view_float64_as_int64(): """Test view float64 as int64""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0], dtype=test_bind.np.float64) nc_arr = test_bind.numpycore.arange(1.0, 5.0, 1.0) .. _example-ndarray-fill-35: .. dropdown:: fill (test_set_operations.py:327) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 317 :emphasize-lines: 11 nc_result = nc_arr.item(2) assert_scalars_equal(np_result, nc_result, "item") def test_fill(): """Test fill (fill array with scalar value)""" np_arr = test_bind.np.zeros(5, dtype='float64') nc_arr = test_bind.numpycore.zeros([5]) np_arr.fill(3.14) nc_arr.fill(3.14) assert_arrays_equal(np_arr, nc_arr, "fill") def test_put(): """Test put (replace specified elements)""" np_arr = test_bind.np.zeros(5, dtype='float64') nc_arr = test_bind.numpycore.zeros([5]) .. _example-ndarray-item-36: .. dropdown:: item (test_set_operations.py:316) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 306 :emphasize-lines: 11 # ============================================================================ # Element Access Tests # ============================================================================ def test_item(): """Test item (copy element to standard Python scalar)""" np_arr = test_bind.np.array([1.0, 2.0, 3.0, 4.0, 5.0]) nc_arr = test_bind.numpycore.arange(1.0, 6.0, 1.0) np_result = np_arr.item(2) nc_result = nc_arr.item(2) assert_scalars_equal(np_result, nc_result, "item") def test_fill(): """Test fill (fill array with scalar value)""" np_arr = test_bind.np.zeros(5, dtype='float64') nc_arr = test_bind.numpycore.zeros([5])