Array Creation Functions ======================== .. currentmodule:: numpycore Functions for creating arrays. Example ------- .. code-block:: python 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 --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Function - Description - Example * - array(object, dtype) - Create array from list/tuple/array - * - asarray(a) - Convert input to array - :ref:`View ` * - asanyarray(a) - Convert to array (pass through subclasses) - :ref:`View ` * - ascontiguousarray(a) - Return contiguous array - :ref:`View ` * - copy(a) - Return array copy - Zeros and Ones -------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Function - Description - Example * - zeros(shape, dtype) - Array of zeros - :ref:`View ` * - ones(shape, dtype) - Array of ones - :ref:`View ` * - empty(shape, dtype) - Uninitialized array - :ref:`View ` * - full(shape, fill_value) - Array filled with value - :ref:`View ` * - zeros_like(a) - Zeros with same shape as a - :ref:`View ` * - ones_like(a) - Ones with same shape as a - :ref:`View ` * - empty_like(a) - Empty with same shape as a - :ref:`View ` * - full_like(a, fill_value) - Filled with same shape as a - :ref:`View ` Numerical Ranges ---------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Function - Description - Example * - arange(start, stop, step) - Evenly spaced values within interval - :ref:`View ` * - linspace(start, stop, num) - Evenly spaced numbers over interval - :ref:`View ` * - logspace(start, stop, num) - Numbers spaced evenly on log scale - * - geomspace(start, stop, num) - Numbers spaced evenly on geometric scale - Matrix Creation --------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Function - Description - Example * - eye(N, M, k) - 2-D array with ones on diagonal - :ref:`View ` * - identity(n) - Identity matrix - :ref:`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 ------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Function - Description - Example * - meshgrid(*xi) - Coordinate matrices from vectors - :ref:`View ` * - mgrid - Dense multi-dimensional meshgrid - * - ogrid - Open multi-dimensional meshgrid - * - indices(dimensions) - Grid of indices - :ref:`View ` Code Examples ------------- The following examples are extracted from the test suite. .. _example-creation-from-data-asarray-0: .. dropdown:: asarray (test_array_conversion.py:35) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 25 :emphasize-lines: 11 print("Warning: NumPy not available. Skipping comparison tests.") def test_asarray(): """Test asarray function with various input types""" print("="*70) print("Testing asarray()") print("="*70) # Test 1: Python list print("\n[Test 1] asarray from Python list") result = numpycore.asarray([1, 2, 3, 4, 5]) print(f" numpycore.asarray([1, 2, 3, 4, 5]): {result}") print(f" Shape: {result.shape}, dtype: {result.dtype}") assert result.shape == (5,), f"Expected shape (5,), got {result.shape}" if HAS_NUMPY: np_result = np.asarray([1, 2, 3, 4, 5]) assert np.allclose(result, np_result), "Results don't match NumPy" print(" [OK] Python list") # Test 2: 2D Python list print("\n[Test 2] asarray from 2D Python list") .. _example-creation-from-data-asanyarray-1: .. dropdown:: asanyarray (test_array_conversion.py:98) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 88 :emphasize-lines: 11 print("="*70) def test_asanyarray(): """Test asanyarray function""" print("\n" + "="*70) print("Testing asanyarray()") print("="*70) # Test 1: Basic array print("\n[Test 1] asanyarray from list") result = numpycore.asanyarray([1, 2, 3, 4]) print(f" numpycore.asanyarray([1, 2, 3, 4]): {result}") assert result.shape == (4,), f"Expected shape (4,), got {result.shape}" print(" [OK] asanyarray from list") # Test 2: 2D array print("\n[Test 2] asanyarray from 2D list") result = numpycore.asanyarray([[1, 2], [3, 4], [5, 6]]) print(f" numpycore.asanyarray([[1, 2], [3, 4], [5, 6]]): shape={result.shape}") assert result.shape == (3, 2), f"Expected shape (3, 2), got {result.shape}" print(" [OK] asanyarray from 2D list") .. _example-creation-from-data-ascontiguousarray-2: .. dropdown:: ascontiguousarray (test_array_conversion.py:122) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 112 :emphasize-lines: 11 print("="*70) 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}" .. _example-creation-zeros-ones-zeros-3: .. dropdown:: zeros (test_advanced_linalg_and_numerical.py:63) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 53 :emphasize-lines: 11 # ============================================================================ # Linear Algebra Tests # ============================================================================ def test_solve(): """Test np.linalg.solve() for solving linear systems Ax = b""" # Create a simple 2x2 system: [[2, 1], [1, 3]] @ x = [1, 2] np_A = test_bind.np.array([[2.0, 1.0], [1.0, 3.0]]) np_b = test_bind.np.array([1.0, 2.0]) nc_A = test_bind.numpycore.zeros([2, 2]) nc_A.itemset(0, 2.0) nc_A.itemset(1, 1.0) nc_A.itemset(2, 1.0) nc_A.itemset(3, 3.0) nc_b = test_bind.numpycore.zeros([2]) nc_b.itemset(0, 1.0) nc_b.itemset(1, 2.0) np_result = test_bind.np.linalg.solve(np_A, np_b) .. _example-creation-zeros-ones-ones-4: .. dropdown:: ones (test_2d_3d_operations.py:15) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 5 :emphasize-lines: 11 def assert_arrays_equal(np_result, nc_result, test_name): 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): print(f"[FAIL] {test_name}"); sys.exit(1) print(f"[OK] {test_name}: PASSED") def 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") def 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") def 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") def 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") def 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") def 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") def f_main(): if test_bind.f_setup_test_environment() != 0: return 1 print("="*70); print("Additional 2D/3D Operations Tests"); print("="*70); print() test_rot90_k2(); test_fliplr(); test_flipud(); test_roll_2d(); test_rollaxis(); test_transpose_axes() print(); print("[OK] All 6 2D/3D operations tests passed!") return 0 if __name__ == "__main__": sys.exit(f_main()) .. _example-creation-zeros-ones-empty-5: .. dropdown:: empty (test_array_creation_complete.py:67) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 57 :emphasize-lines: 11 assert np.allclose(arr, np.zeros((2, 3))), "zeros() 2D values incorrect" f_print_success("zeros() tests passed") def test_empty(): """Test empty() - create uninitialized array""" f_print_info("Testing empty()") # Test shape creation arr = test_bind.numpycore.empty([2, 3]) assert arr.shape == (2, 3), f"Expected shape (2, 3), got {arr.shape}" assert arr.dtype == np.float64, f"Expected dtype float64, got {arr.dtype}" f_print_success("empty() tests passed") def test_full(): """Test full() - create array filled with specific value""" f_print_info("Testing full()") .. _example-creation-zeros-ones-full-6: .. dropdown:: full (test_array_creation_complete.py:79) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 69 :emphasize-lines: 11 assert arr.dtype == np.float64, f"Expected dtype float64, got {arr.dtype}" f_print_success("empty() tests passed") def test_full(): """Test full() - create array filled with specific value""" f_print_info("Testing full()") # Test with scalar value arr = test_bind.numpycore.full([2, 3], 7.5) assert arr.shape == (2, 3), f"Expected shape (2, 3), got {arr.shape}" assert np.allclose(arr, np.full((2, 3), 7.5)), "full() values incorrect" f_print_success("full() tests passed") def test_identity(): """Test identity() - create identity matrix""" f_print_info("Testing identity()") .. _example-creation-zeros-ones-zeros_like-7: .. dropdown:: zeros_like (test_array_creation_complete.py:163) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 153 :emphasize-lines: 11 assert np.allclose(arr, np.ones_like(prototype)), "ones_like() values incorrect" f_print_success("ones_like() tests passed") def test_zeros_like(): """Test zeros_like() - create array of zeros with shape from prototype""" f_print_info("Testing zeros_like()") prototype = np.array([[1, 2], [3, 4]]) arr = test_bind.numpycore.zeros_like(prototype) assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}" assert np.allclose(arr, np.zeros_like(prototype)), "zeros_like() values incorrect" f_print_success("zeros_like() tests passed") def test_empty_like(): """Test empty_like() - create uninitialized array with shape from prototype""" f_print_info("Testing empty_like()") .. _example-creation-zeros-ones-ones_like-8: .. dropdown:: ones_like (test_array_creation_complete.py:151) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 141 :emphasize-lines: 11 # ============================================================================ # LIKE FUNCTIONS TESTS # ============================================================================ def test_ones_like(): """Test ones_like() - create array of ones with shape from prototype""" f_print_info("Testing ones_like()") prototype = np.array([[1, 2], [3, 4]]) arr = test_bind.numpycore.ones_like(prototype) assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}" assert np.allclose(arr, np.ones_like(prototype)), "ones_like() values incorrect" f_print_success("ones_like() tests passed") def test_zeros_like(): """Test zeros_like() - create array of zeros with shape from prototype""" f_print_info("Testing zeros_like()") .. _example-creation-zeros-ones-empty_like-9: .. dropdown:: empty_like (test_array_creation_complete.py:175) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 165 :emphasize-lines: 11 assert np.allclose(arr, np.zeros_like(prototype)), "zeros_like() values incorrect" f_print_success("zeros_like() tests passed") def test_empty_like(): """Test empty_like() - create uninitialized array with shape from prototype""" f_print_info("Testing empty_like()") prototype = np.array([[1, 2], [3, 4]]) arr = test_bind.numpycore.empty_like(prototype) assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}" assert arr.dtype == prototype.dtype, f"Expected dtype {prototype.dtype}, got {arr.dtype}" f_print_success("empty_like() tests passed") def test_full_like(): """Test full_like() - create filled array with shape from prototype""" f_print_info("Testing full_like()") .. _example-creation-zeros-ones-full_like-10: .. dropdown:: full_like (test_array_creation_complete.py:187) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 177 :emphasize-lines: 11 assert arr.dtype == prototype.dtype, f"Expected dtype {prototype.dtype}, got {arr.dtype}" f_print_success("empty_like() tests passed") def test_full_like(): """Test full_like() - create filled array with shape from prototype""" f_print_info("Testing full_like()") prototype = np.array([[1, 2], [3, 4]]) arr = test_bind.numpycore.full_like(prototype, 7.5) assert arr.shape == prototype.shape, f"Expected shape {prototype.shape}, got {arr.shape}" assert np.allclose(arr, np.full_like(prototype, 7.5)), "full_like() values incorrect" f_print_success("full_like() tests passed") # ============================================================================ # CONVERSION FUNCTIONS TESTS # ============================================================================ .. _example-creation-ranges-arange-11: .. dropdown:: arange (test_2d_3d_operations.py:11) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 1 :emphasize-lines: 11 #!/usr/bin/env python3 """Phase 28: Additional 2D/3D Operations Tests""" import sys import test_bind def assert_arrays_equal(np_result, nc_result, test_name): 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): print(f"[FAIL] {test_name}"); sys.exit(1) print(f"[OK] {test_name}: PASSED") def 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") def 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") def 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") def 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") def 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") def 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") def f_main(): if test_bind.f_setup_test_environment() != 0: return 1 print("="*70); print("Additional 2D/3D Operations Tests"); print("="*70); print() test_rot90_k2(); test_fliplr(); test_flipud(); test_roll_2d(); test_rollaxis(); test_transpose_axes() .. _example-creation-ranges-linspace-12: .. dropdown:: linspace (test_advanced_operations.py:75) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 65 :emphasize-lines: 11 return False # ============================================================================ # Sorting Tests # ============================================================================ def test_sort_1d(): """Test sorting 1D array""" np_arr = test_bind.np.array([3.0, 1.0, 4.0, 1.0, 5.0, 9.0]) nc_arr = test_bind.numpycore.linspace(3.0, 9.0, 6) # Will need to shuffle or use explicit values # Use explicit construction nc_values = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0] nc_arr = test_bind.numpycore.zeros([6]) for i, val in enumerate(nc_values): nc_arr.itemset(i, val) np_sorted = test_bind.np.sort(np_arr) nc_sorted = test_bind.np.sort(nc_arr) .. _example-creation-matrix-eye-13: .. dropdown:: eye (test_array_creation_complete.py:102) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 92 :emphasize-lines: 11 assert np.allclose(arr, np.identity(3)), "identity() values incorrect" f_print_success("identity() tests passed") def test_eye(): """Test eye() - create matrix with ones on diagonal""" f_print_info("Testing eye()") # Square matrix arr = test_bind.numpycore.eye(3, 3, 0) assert arr.shape == (3, 3), f"Expected shape (3, 3), got {arr.shape}" assert np.allclose(arr, np.eye(3)), "eye() values incorrect" # Rectangular matrix arr = test_bind.numpycore.eye(3, 4, 1) assert arr.shape == (3, 4), f"Expected shape (3, 4), got {arr.shape}" assert np.allclose(arr, np.eye(3, 4, 1)), "eye() with offset values incorrect" f_print_success("eye() tests passed") .. _example-creation-matrix-identity-14: .. dropdown:: identity (test_array_creation_complete.py:90) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 80 :emphasize-lines: 11 assert arr.shape == (2, 3), f"Expected shape (2, 3), got {arr.shape}" assert np.allclose(arr, np.full((2, 3), 7.5)), "full() values incorrect" f_print_success("full() tests passed") def test_identity(): """Test identity() - create identity matrix""" f_print_info("Testing identity()") arr = test_bind.numpycore.identity(3) assert arr.shape == (3, 3), f"Expected shape (3, 3), got {arr.shape}" assert np.allclose(arr, np.identity(3)), "identity() values incorrect" f_print_success("identity() tests passed") def test_eye(): """Test eye() - create matrix with ones on diagonal""" f_print_info("Testing eye()") .. _example-creation-grid-meshgrid-15: .. dropdown:: meshgrid (test_array_creation_extended.py:464) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 454 :emphasize-lines: 11 np_arr = test_bind.np.arange(0, 24, 1, dtype='float64').reshape(2, 3, 4) nc_arr = test_bind.numpycore.arange(0.0, 24.0, 1.0).reshape(2, 3, 4) np_result = test_bind.np.ravel(np_arr) nc_result = test_bind.numpycore.ravel(nc_arr) assert_arrays_equal(np_result, nc_result, "ravel_numpycore_3d") def test_meshgrid_numpycore_2d_xy(): """Test numpycore.meshgrid() with 2 vectors, xy indexing""" np_x = test_bind.np.array([1.0, 2.0, 3.0]) np_y = test_bind.np.array([4.0, 5.0]) nc_x = test_bind.numpycore.array([1.0, 2.0, 3.0]) nc_y = test_bind.numpycore.array([4.0, 5.0]) np_xv, np_yv = test_bind.np.meshgrid(np_x, np_y, indexing='xy') nc_xv, nc_yv = test_bind.numpycore.meshgrid(nc_x, nc_y, indexing='xy') assert_arrays_equal(np_xv, nc_xv, "meshgrid_numpycore_2d_xy_xv") .. _example-creation-grid-indices-16: .. dropdown:: indices (test_phase11_array_generation.py:36) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 26 :emphasize-lines: 11 # and all elements after should be >= element at index 3 partitioned_nc = arr_nc[result_nc] partitioned_np = arr_np[result_np] assert test_bind.np.all(partitioned_nc[:4] <= partitioned_nc[3]), "Partition property failed for numpycore" assert test_bind.np.all(partitioned_nc[4:] >= partitioned_nc[3]), "Partition property failed for numpycore" print("[OK] test_argpartition_basic: argpartition(arr, 3) works correctly") def test_indices_2d_dense(): """Test indices() - 2D dense mode""" grid_nc = test_bind.numpycore.indices((2, 3)) grid_np = test_bind.np.indices((2, 3)) assert len(grid_nc) == 2, f"Expected 2 arrays, got {len(grid_nc)}" assert test_bind.np.allclose(grid_nc[0], grid_np[0]), "Row indices don't match" assert test_bind.np.allclose(grid_nc[1], grid_np[1]), "Column indices don't match" print("[OK] test_indices_2d_dense: indices((2, 3)) dense mode matches NumPy") def test_indices_2d_sparse(): """Test indices() - 2D sparse mode""" grid_nc = test_bind.numpycore.indices((2, 3), sparse=True)