NDArray ======= .. cpp:class:: numpy::NDArray Core array class in the numpy namespace. Example ------- .. code-block:: cpp #include using namespace numpy; // Create NDArray NDArray arr = np::zeros({3, 4}); NDArray ones = np::ones({2, 2}); // Access data auto shape = arr.shape(); double val = arr(0, 1); // Operations auto result = arr + 1.0; auto mean_val = np::mean(arr); Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``NDArray(const std::vector&shape, const T &fill_value = T{})`` - NP_NDARRAY.H:50 - :ref:`View ` * - ``NDArray(T \*external_data, const std::vector&shape, std::shared_ptrowner = nullptr)`` - NP_NDARRAY.H:54 - :ref:`View ` * - ``NDArray(T \*data_ptr, size_toffset, const std::vector&shape, const std::vector&strides, std::shared_ptrowner)`` - NP_NDARRAY.H:58 - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``DType getDType()`` - DType - NP_NDARRAY.H:115 - :ref:`View ` * - ``T getElementAt(const std::vector&indices)`` - T - NP_NDARRAY.H:72 - :ref:`View ` * - ``size_t getOffset()`` - size_t - NP_NDARRAY.H:113 - * - ``const std::vector& getShape()`` - const std::vector& - NP_NDARRAY.H:110 - :ref:`View ` * - ``size_t getSize()`` - size_t - NP_NDARRAY.H:112 - :ref:`View ` * - ``const std::vector& getStrides()`` - const std::vector& - NP_NDARRAY.H:111 - :ref:`View ` * - ``std::string getTypeName()`` - std::string - NP_NDARRAY.H:116 - :ref:`View ` * - ``T item()`` - T - NP_NDARRAY.H:203 - :ref:`View ` * - ``T item(size_tflat_index)`` - T - NP_NDARRAY.H:211 - :ref:`View ` * - ``void itemset(const T &value)`` - void - NP_NDARRAY.H:219 - :ref:`View ` * - ``void itemset(size_tflat_index, const T &value)`` - void - NP_NDARRAY.H:227 - :ref:`View ` * - ``std::vector> nonzero()`` - std::vector> - NP_NDARRAY.H:174 - :ref:`View ` Statistics ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``T maxArray()`` - T - NP_NDARRAY.H:100 - :ref:`View ` * - ``double meanArray()`` - double - NP_NDARRAY.H:98 - :ref:`View ` * - ``T minArray()`` - T - NP_NDARRAY.H:99 - :ref:`View ` * - ``T sumArray()`` - T - NP_NDARRAY.H:97 - :ref:`View ` Sorting ------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``void sort(std::optionalaxis = std::nullopt, SortKindkind = static_cast(0), boolstable = false)`` - void - NP_NDARRAY.H:106 - :ref:`View ` I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::string tolist()`` - std::string - NP_NDARRAY.H:188 - :ref:`View ` Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``T \* data()`` - T \* - NP_NDARRAY.H:121 - :ref:`View ` * - ``const T \* data()`` - const T \* - NP_NDARRAY.H:130 - :ref:`View ` * - ``void dump(const std::string &filename)`` - void - NP_NDARRAY.H:289 - :ref:`View ` * - ``void fill(const T &value)`` - void - NP_NDARRAY.H:195 - :ref:`View ` * - ``T & flat(size_tflat_index)`` - T & - NP_NDARRAY.H:235 - :ref:`View ` * - ``const T & flat(size_tflat_index)`` - const T & - NP_NDARRAY.H:243 - :ref:`View ` * - ``bool isAligned()`` - bool - NP_NDARRAY.H:337 - :ref:`View ` * - ``bool isCContiguous()`` - bool - NP_NDARRAY.H:152 - :ref:`View ` * - ``bool isContiguous()`` - bool - NP_NDARRAY.H:151 - :ref:`View ` * - ``bool isFContiguous()`` - bool - NP_NDARRAY.H:153 - :ref:`View ` * - ``bool isWriteable()`` - bool - NP_NDARRAY.H:331 - :ref:`View ` * - ``bool ownsData()`` - bool - NP_NDARRAY.H:114 - :ref:`View ` * - ``void printArray(const std::string &title = "")`` - void - NP_NDARRAY.H:103 - :ref:`View ` * - ``void setElementAt(const std::vector&indices, const T &value)`` - void - NP_NDARRAY.H:73 - :ref:`View ` * - ``void setElementAt(std::initializer_listindices, const T &value)`` - void - NP_NDARRAY.H:74 - :ref:`View ` * - ``void setflags(boolwrite = true, boolalign = false, booluic = false)`` - void - NP_NDARRAY.H:325 - :ref:`View ` * - ``std::string toString(const std::string &title = "")`` - std::string - NP_NDARRAY.H:102 - :ref:`View ` * - ``T \* unsafe_data()`` - T \* - NP_NDARRAY.H:142 - * - ``const T \* unsafe_data()`` - const T \* - NP_NDARRAY.H:146 - Code Examples ------------- The following examples are extracted from the test suite. .. _example-ndarray-ndarray-0: .. dropdown:: NDArray (np_test_1_all.cpp:890) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 880 :emphasize-lines: 11 } // std::cout << "[OK] array == scalar"; std::cout << " -> tests passed" << std::endl; } void testLogicalOperations() { std::cout << "========= testLogicalOperations ======================="; // Create boolean arrays auto a = NDArray({3}); a.setElementAt({0}, true); a.setElementAt({1}, false); a.setElementAt({2}, true); auto b = NDArray({3}); b.setElementAt({0}, false); b.setElementAt({1}, false); b.setElementAt({2}, true); // Test logical_and .. _example-ndarray-ndarray-1: .. dropdown:: NDArray (np_test_1_all.cpp:890) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 880 :emphasize-lines: 11 } // std::cout << "[OK] array == scalar"; std::cout << " -> tests passed" << std::endl; } void testLogicalOperations() { std::cout << "========= testLogicalOperations ======================="; // Create boolean arrays auto a = NDArray({3}); a.setElementAt({0}, true); a.setElementAt({1}, false); a.setElementAt({2}, true); auto b = NDArray({3}); b.setElementAt({0}, false); b.setElementAt({1}, false); b.setElementAt({2}, true); // Test logical_and .. _example-ndarray-ndarray-2: .. dropdown:: NDArray (np_test_1_all.cpp:890) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 880 :emphasize-lines: 11 } // std::cout << "[OK] array == scalar"; std::cout << " -> tests passed" << std::endl; } void testLogicalOperations() { std::cout << "========= testLogicalOperations ======================="; // Create boolean arrays auto a = NDArray({3}); a.setElementAt({0}, true); a.setElementAt({1}, false); a.setElementAt({2}, true); auto b = NDArray({3}); b.setElementAt({0}, false); b.setElementAt({1}, false); b.setElementAt({2}, true); // Test logical_and .. _example-ndarray-getdtype-3: .. dropdown:: getDType (np_test_1_all.cpp:7238) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7228 :emphasize-lines: 11 // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " clongdouble: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " intp: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " uintp: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " bytes: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // Test getDType() // std::cout << "DType Enums:" << std::endl; // std::cout << " longdouble DType: " << static_cast(TypeTraits::getDType()) << std::endl; // std::cout << " clongdouble DType: " << static_cast(TypeTraits::getDType()) << std::endl; // std::cout << " intp DType: " << static_cast(TypeTraits::getDType()) << std::endl; // std::cout << " uintp DType: " << static_cast(TypeTraits::getDType()) << std::endl; // std::cout << " bytes DType: " << static_cast(TypeTraits::getDType()) << std::endl; std::cout << " -> tests passed" << std::endl; } .. _example-ndarray-getelementat-4: .. dropdown:: getElementAt (np_test_1_all.cpp:49) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 39 :emphasize-lines: 11 using namespace numpy::benchmark; using namespace numpy::char_; // Helper functions for array comparison tests namespace { const double TOLERANCE = 1e-10; bool allTrue(const NDArray& arr) { std::vector indices(arr.getShape().size(), 0); do { if (!arr.getElementAt(indices)) { return false; } } while (incrementIndices(indices, arr.getShape())); return true; } bool allFalse(const NDArray& arr) { std::vector indices(arr.getShape().size(), 0); do { if (arr.getElementAt(indices)) { .. _example-ndarray-getshape-5: .. dropdown:: getShape (np_test_1_all.cpp:47) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 37 :emphasize-lines: 11 using namespace numpy; using namespace numpy::benchmark; using namespace numpy::char_; // Helper functions for array comparison tests namespace { const double TOLERANCE = 1e-10; bool allTrue(const NDArray& arr) { std::vector indices(arr.getShape().size(), 0); do { if (!arr.getElementAt(indices)) { return false; } } while (incrementIndices(indices, arr.getShape())); return true; } bool allFalse(const NDArray& arr) { std::vector indices(arr.getShape().size(), 0); .. _example-ndarray-getsize-6: .. dropdown:: getSize (np_test_1_all.cpp:2172) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2162 :emphasize-lines: 11 } std::cout << " -> tests passed" << std::endl; } void testArrayEdgeCases() { std::cout << "========= testArrayEdgeCases ======================="; // Test 1: Empty arrays NDArray empty_array = createObjectZeros({0}); if (!(empty_array.getSize() == 0)) { std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(empty_array.getSize() == 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(empty_array.getShape() == std::vector{0})) { std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(empty_array.getShape() == std::vector{0})"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-ndarray-getstrides-7: .. dropdown:: getStrides (np_test_1_all.cpp:13373) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 13363 :emphasize-lines: 11 namespace numpy_tests { using namespace numpy; void testBasicStrides() { std::cout << "========= testBasicStrides ======================="; // Test 1D array auto array1d = createInt32Array({ 5 }, 10); const auto& strides1d = array1d.getStrides(); // std::cout << "1D array shape: (" << array1d.getShape()[0] << ")" << std::endl; // std::cout << "1D array strides: (" << strides1d[0] << ")" << std::endl; if (!(strides1d.size() == 1)) { std::string description = std::string("testBasicStrides():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(strides1d.size() == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(strides1d[0] == 1)) { .. _example-ndarray-gettypename-8: .. dropdown:: getTypeName (np_test_1_all.cpp:7227) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7217 :emphasize-lines: 11 // std::cout << "Min: " << ip_array.minArray() << std::endl; // std::cout << "Max: " << ip_array.maxArray() << std::endl; std::cout << " -> tests passed" << std::endl; } void testTypeTraitsExtendedTypes() { std::cout << "========= testTypeTraitsExtendedTypes ======================="; // std::cout << "Type Information:" << std::endl; // std::cout << " longdouble: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " clongdouble: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " intp: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " uintp: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; // std::cout << " bytes: " << TypeTraits::getTypeName() // << ", size: " << TypeTraits::getTypeSize() << " bytes" << std::endl; .. _example-ndarray-item-9: .. dropdown:: item (np_test_4_all.cpp:20048) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20038 :emphasize-lines: 11 /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" #include "../numpy/np_masked_array.h" #include .. _example-ndarray-item-10: .. dropdown:: item (np_test_4_all.cpp:20048) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20038 :emphasize-lines: 11 /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" #include "../numpy/np_masked_array.h" #include .. _example-ndarray-itemset-11: .. dropdown:: itemset (np_test_4_all.cpp:20049) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20039 :emphasize-lines: 11 /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" #include "../numpy/np_masked_array.h" #include #include .. _example-ndarray-itemset-12: .. dropdown:: itemset (np_test_4_all.cpp:20049) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20039 :emphasize-lines: 11 /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" #include "../numpy/np_masked_array.h" #include #include .. _example-ndarray-nonzero-13: .. dropdown:: nonzero (np_test_4_all.cpp:18465) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18455 :emphasize-lines: 11 } std::cout << " -> tests passed\n"; } void np_test_phase1_nonzero() { std::cout << "========= nonzero: find nonzero indices ===="; // Test 1D array auto arr1d = numpy::array({0, 2, 0, 4, 5, 0, 7}); auto indices1d = numpy::nonzero(arr1d); // Should return vector with 1 array (for 1D input) if (indices1d.size() != 1) { std::cout << " [FAIL] : nonzero 1D returned " << indices1d.size() << " arrays, expected 1\n"; throw std::runtime_error("nonzero failed: wrong number of arrays for 1D"); } // Should find 4 nonzero elements if (indices1d[0].getSize() != 4) { std::cout << " [FAIL] : nonzero 1D found " << indices1d[0].getSize() << " elements, expected 4\n"; .. _example-ndarray-maxarray-14: .. dropdown:: maxArray (np_test_1_all.cpp:234) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 224 :emphasize-lines: 11 array.setElementAt({1, 0}, -1.0); array.setElementAt({1, 1}, 0.0); array.setElementAt({1, 2}, 4.5); // std::cout << "Test array:" << std::endl; //array.printArray(); // std::cout << "Sum: " << array.sumArray() << std::endl; // std::cout << "Mean: " << array.meanArray() << std::endl; // std::cout << "Min: " << array.minArray() << std::endl; // std::cout << "Max: " << array.maxArray() << std::endl; std::cout << " -> tests passed" << std::endl; } void testReshapeAndFlatten() { std::cout << "========= testReshapeAndFlatten ======================="; auto range_array = NDArray::createRange(0, 12, 1); // std::cout << "Range array (0-11):" << std::endl; //range_array.printArray(); .. _example-ndarray-meanarray-15: .. dropdown:: meanArray (np_test_1_all.cpp:232) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 222 :emphasize-lines: 11 array.setElementAt({0, 1}, 2.5); array.setElementAt({0, 2}, 3.5); array.setElementAt({1, 0}, -1.0); array.setElementAt({1, 1}, 0.0); array.setElementAt({1, 2}, 4.5); // std::cout << "Test array:" << std::endl; //array.printArray(); // std::cout << "Sum: " << array.sumArray() << std::endl; // std::cout << "Mean: " << array.meanArray() << std::endl; // std::cout << "Min: " << array.minArray() << std::endl; // std::cout << "Max: " << array.maxArray() << std::endl; std::cout << " -> tests passed" << std::endl; } void testReshapeAndFlatten() { std::cout << "========= testReshapeAndFlatten ======================="; auto range_array = NDArray::createRange(0, 12, 1); .. _example-ndarray-minarray-16: .. dropdown:: minArray (np_test_1_all.cpp:233) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 223 :emphasize-lines: 11 array.setElementAt({0, 2}, 3.5); array.setElementAt({1, 0}, -1.0); array.setElementAt({1, 1}, 0.0); array.setElementAt({1, 2}, 4.5); // std::cout << "Test array:" << std::endl; //array.printArray(); // std::cout << "Sum: " << array.sumArray() << std::endl; // std::cout << "Mean: " << array.meanArray() << std::endl; // std::cout << "Min: " << array.minArray() << std::endl; // std::cout << "Max: " << array.maxArray() << std::endl; std::cout << " -> tests passed" << std::endl; } void testReshapeAndFlatten() { std::cout << "========= testReshapeAndFlatten ======================="; auto range_array = NDArray::createRange(0, 12, 1); // std::cout << "Range array (0-11):" << std::endl; .. _example-ndarray-sumarray-17: .. dropdown:: sumArray (np_test_1_all.cpp:231) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 221 :emphasize-lines: 11 array.setElementAt({0, 0}, 1.5); array.setElementAt({0, 1}, 2.5); array.setElementAt({0, 2}, 3.5); array.setElementAt({1, 0}, -1.0); array.setElementAt({1, 1}, 0.0); array.setElementAt({1, 2}, 4.5); // std::cout << "Test array:" << std::endl; //array.printArray(); // std::cout << "Sum: " << array.sumArray() << std::endl; // std::cout << "Mean: " << array.meanArray() << std::endl; // std::cout << "Min: " << array.minArray() << std::endl; // std::cout << "Max: " << array.maxArray() << std::endl; std::cout << " -> tests passed" << std::endl; } void testReshapeAndFlatten() { std::cout << "========= testReshapeAndFlatten ======================="; .. _example-ndarray-sort-18: .. dropdown:: sort (np_test_1_all.cpp:6258) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6248 :emphasize-lines: 11 std::vector data = gen.generate(100, DataPattern::FEW_UNIQUE); if (!(data.size() == 100)) { std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 100)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Count unique values std::vector sorted_copy = data; std::sort(sorted_copy.begin(), sorted_copy.end()); auto unique_end = std::unique(sorted_copy.begin(), sorted_copy.end()); size_t unique_count = std::distance(sorted_copy.begin(), unique_end); // Should have significantly fewer unique values than total elements if (!(unique_count < data.size() / 2)) { std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(unique_count < data.size() / 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-ndarray-tolist-19: .. dropdown:: tolist (np_test_4_all.cpp:20046) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20036 :emphasize-lines: 11 } // namespace numpy_tests /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" .. _example-ndarray-data-20: .. dropdown:: data (np_test_1_all.cpp:2084) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2074 :emphasize-lines: 11 } if (!(derived_ptr->extra == 2)) { std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(derived_ptr->extra == 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test 6: Large object handling struct LargeObject { std::vector data; LargeObject() : data(10000, 3.14159) {} // Large object }; LargeObject large; object_ large_obj(large); // Should handle large objects if (!(!large_obj.is_null())) { std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(!large_obj.is_null())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(large_obj.is_type())) { .. _example-ndarray-data-21: .. dropdown:: data (np_test_1_all.cpp:2084) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2074 :emphasize-lines: 11 } if (!(derived_ptr->extra == 2)) { std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(derived_ptr->extra == 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test 6: Large object handling struct LargeObject { std::vector data; LargeObject() : data(10000, 3.14159) {} // Large object }; LargeObject large; object_ large_obj(large); // Should handle large objects if (!(!large_obj.is_null())) { std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(!large_obj.is_null())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(large_obj.is_type())) { .. _example-ndarray-dump-22: .. dropdown:: dump (np_test_4_all.cpp:22039) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22029 :emphasize-lines: 11 return 1; } } } // namespace numpy_tests // Comprehensive test suite for Phase 6 NDArray Methods // // This file tests the Phase 6 LOW priority NDArray methods: // - byteswap() - Swap byte order for endianness conversion // - dump() - Serialize array to binary file // - dumps() - Serialize array to byte vector // - setflags() - Set array metadata flags #include #include #include #include #include #include #include "../numpy/np_ndarray.h" .. _example-ndarray-fill-23: .. dropdown:: fill (np_test_4_all.cpp:20047) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20037 :emphasize-lines: 11 } // namespace numpy_tests /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" #include "../numpy/np_masked_array.h" .. _example-ndarray-flat-24: .. dropdown:: flat (np_test_5_all.cpp:11172) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11162 :emphasize-lines: 11 // ============================================================================ // NDITER TESTS // ============================================================================ void np_test_nditer_basic() { std::cout << "========= NDIter: basic C-order iteration ======================="; // Create 2D array numpy::NDArray arr({ 3, 4 }); for (size_t i = 0; i < 12; ++i) { arr.flat(i) = static_cast(i); } // Test C-order iteration auto it = numpy::nditer(arr, true); int count = 0; while (!it.is_finished()) { int value = *it; auto indices = it.indices(); size_t flat_idx = it.flat_index(); .. _example-ndarray-flat-25: .. dropdown:: flat (np_test_5_all.cpp:11172) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11162 :emphasize-lines: 11 // ============================================================================ // NDITER TESTS // ============================================================================ void np_test_nditer_basic() { std::cout << "========= NDIter: basic C-order iteration ======================="; // Create 2D array numpy::NDArray arr({ 3, 4 }); for (size_t i = 0; i < 12; ++i) { arr.flat(i) = static_cast(i); } // Test C-order iteration auto it = numpy::nditer(arr, true); int count = 0; while (!it.is_finished()) { int value = *it; auto indices = it.indices(); size_t flat_idx = it.flat_index(); .. _example-ndarray-isaligned-26: .. dropdown:: isAligned (np_test_4_all.cpp:22313) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22303 :emphasize-lines: 11 void np_test_phase6_setflags_basic() { std::cout << "========= setflags basic functionality ======================="; numpy::NDArray arr({5}); // Check defaults if (!arr.isWriteable()) { std::cout << " [FAIL] : Default writeable should be true"; throw std::runtime_error("default writeable test failed"); } if (!arr.isAligned()) { std::cout << " [FAIL] : Default aligned should be true"; throw std::runtime_error("default aligned test failed"); } // Set writeable to false arr.setflags(false); if (arr.isWriteable()) { std::cout << " [FAIL] : Writeable should be false"; throw std::runtime_error("setflags writeable test failed"); } .. _example-ndarray-isccontiguous-27: .. dropdown:: isCContiguous (np_test_1_all.cpp:393) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 383 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void testMemoryLayoutQueries() { std::cout << "========= testMemoryLayoutQueries ======================="; auto array = createFloat64Array({2, 3}); // std::cout << "Array contiguous: " << (array.isContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Array C-contiguous: " << (array.isCContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Array F-contiguous: " << (array.isFContiguous() ? "Yes" : "No") << std::endl; // Test with a transposed view auto transposed = array.transposeView(); // std::cout << "Transposed contiguous: " << (transposed.isContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Transposed C-contiguous: " << (transposed.isCContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Transposed F-contiguous: " << (transposed.isFContiguous() ? "Yes" : "No") << std::endl; std::cout << " -> tests passed" << std::endl; } .. _example-ndarray-iscontiguous-28: .. dropdown:: isContiguous (np_test_1_all.cpp:392) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 382 :emphasize-lines: 11 //array.printArray(); std::cout << " -> tests passed" << std::endl; } void testMemoryLayoutQueries() { std::cout << "========= testMemoryLayoutQueries ======================="; auto array = createFloat64Array({2, 3}); // std::cout << "Array contiguous: " << (array.isContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Array C-contiguous: " << (array.isCContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Array F-contiguous: " << (array.isFContiguous() ? "Yes" : "No") << std::endl; // Test with a transposed view auto transposed = array.transposeView(); // std::cout << "Transposed contiguous: " << (transposed.isContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Transposed C-contiguous: " << (transposed.isCContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Transposed F-contiguous: " << (transposed.isFContiguous() ? "Yes" : "No") << std::endl; std::cout << " -> tests passed" << std::endl; .. _example-ndarray-isfcontiguous-29: .. dropdown:: isFContiguous (np_test_1_all.cpp:394) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 384 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void testMemoryLayoutQueries() { std::cout << "========= testMemoryLayoutQueries ======================="; auto array = createFloat64Array({2, 3}); // std::cout << "Array contiguous: " << (array.isContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Array C-contiguous: " << (array.isCContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Array F-contiguous: " << (array.isFContiguous() ? "Yes" : "No") << std::endl; // Test with a transposed view auto transposed = array.transposeView(); // std::cout << "Transposed contiguous: " << (transposed.isContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Transposed C-contiguous: " << (transposed.isCContiguous() ? "Yes" : "No") << std::endl; // std::cout << "Transposed F-contiguous: " << (transposed.isFContiguous() ? "Yes" : "No") << std::endl; std::cout << " -> tests passed" << std::endl; } .. _example-ndarray-iswriteable-30: .. dropdown:: isWriteable (np_test_4_all.cpp:22309) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22299 :emphasize-lines: 11 // ============================================================================ // SETFLAGS TESTS // ============================================================================ void np_test_phase6_setflags_basic() { std::cout << "========= setflags basic functionality ======================="; numpy::NDArray arr({5}); // Check defaults if (!arr.isWriteable()) { std::cout << " [FAIL] : Default writeable should be true"; throw std::runtime_error("default writeable test failed"); } if (!arr.isAligned()) { std::cout << " [FAIL] : Default aligned should be true"; throw std::runtime_error("default aligned test failed"); } // Set writeable to false arr.setflags(false); .. _example-ndarray-ownsdata-31: .. dropdown:: ownsData (np_test_1_all.cpp:577) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 567 :emphasize-lines: 11 std::cout << "========= testViewMemoryProperties ======================="; auto original = createFloat64Array({3, 4}, 2.5); // Test various view properties auto basic_view = original.view(); auto transpose_view = original.transposeView(); auto slice_view = original.sliceView({{0, 2}, {1, 3}}); // Check ownership flags bool orig_owns = original.ownsData(); if (orig_owns != true) { std::cout << "[FAIL] in testViewMemoryProperties(): original.ownsData() = " << orig_owns << ", expected true" << std::endl; throw std::runtime_error("testViewMemoryProperties(): original ownership flag incorrect"); } bool basic_owns = basic_view.ownsData(); if (basic_owns != false) { std::cout << "[FAIL] in testViewMemoryProperties(): basic_view.ownsData() = " << basic_owns << ", expected false" << std::endl; throw std::runtime_error("testViewMemoryProperties(): basic_view ownership flag incorrect"); } bool transpose_owns = transpose_view.ownsData(); .. _example-ndarray-printarray-32: .. dropdown:: printArray (np_test_1_all.cpp:67) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 57 :emphasize-lines: 11 std::vector indices(arr.getShape().size(), 0); do { if (arr.getElementAt(indices)) { return false; } } while (incrementIndices(indices, arr.getShape())); return true; } template void printArray(const NDArray& arr, const std::string& name) { std::cout << name << ": "; if (arr.getShape().size() == 1) { for (size_t i = 0; i < arr.getShape()[0]; ++i) { // std::cout << arr.getElementAt({i}) << " "; } } // std::cout << std::endl; } // Helper functions for bitwise operations tests .. _example-ndarray-setelementat-33: .. dropdown:: setElementAt (np_test_1_all.cpp:135) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 125 :emphasize-lines: 11 //ones_array.printArray(); std::cout << " -> tests passed" << std::endl; } void testElementAccess() { std::cout << "========= testElementAccess ======================="; auto array = createInt32Array({3, 3}, 0); array.setElementAt({0, 0}, 1); array.setElementAt({0, 1}, 2); array.setElementAt({0, 2}, 3); array.setElementAt({1, 1}, 5); array.setElementAt({2, 2}, 9); // std::cout << "Array after setting elements:" << std::endl; //array.printArray(); // std::cout << "Element at (1,1): " << array.getElementAt({1, 1}) << std::endl; // std::cout << "Element at (2,2): " << array.getElementAt({2, 2}); .. _example-ndarray-setelementat-34: .. dropdown:: setElementAt (np_test_1_all.cpp:135) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 125 :emphasize-lines: 11 //ones_array.printArray(); std::cout << " -> tests passed" << std::endl; } void testElementAccess() { std::cout << "========= testElementAccess ======================="; auto array = createInt32Array({3, 3}, 0); array.setElementAt({0, 0}, 1); array.setElementAt({0, 1}, 2); array.setElementAt({0, 2}, 3); array.setElementAt({1, 1}, 5); array.setElementAt({2, 2}, 9); // std::cout << "Array after setting elements:" << std::endl; //array.printArray(); // std::cout << "Element at (1,1): " << array.getElementAt({1, 1}) << std::endl; // std::cout << "Element at (2,2): " << array.getElementAt({2, 2}); .. _example-ndarray-setflags-35: .. dropdown:: setflags (np_test_4_all.cpp:22041) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22031 :emphasize-lines: 11 } } // namespace numpy_tests // Comprehensive test suite for Phase 6 NDArray Methods // // This file tests the Phase 6 LOW priority NDArray methods: // - byteswap() - Swap byte order for endianness conversion // - dump() - Serialize array to binary file // - dumps() - Serialize array to byte vector // - setflags() - Set array metadata flags #include #include #include #include #include #include #include "../numpy/np_ndarray.h" // IMPORTANT: No using namespace directives to avoid name clashes .. _example-ndarray-tostring-36: .. dropdown:: toString (np_test_1_all.cpp:6826) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6816 :emphasize-lines: 11 void testDatetime64CreationDateTime() { std::cout << "========= testDatetime64CreationDateTime ======================="; // Test default constructor datetime64 default_dt; if (!(default_dt.isNaT())) { std::string description = std::string("testDatetime64CreationDateTime():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(default_dt.isNaT())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Default datetime64 is NaT: " << default_dt.toString() << std::endl; // Test value constructor datetime64 epoch_day(0, DateTimeUnit::Day); // std::cout << "Epoch day: " << epoch_day.toString() << std::endl; // Test string constructor datetime64 date_from_string("2024-01-15"); // std::cout << "Date from string '2024-01-15': " << date_from_string.toString() << std::endl; datetime64 datetime_from_string("2024-01-15T10:30:45");