TimedeltaArray ============== .. cpp:class:: numpy::TimedeltaArray numpy C++ class. Example ------- .. code-block:: cpp #include using namespace numpy; // Use TimedeltaArray TimedeltaArray obj; // ... operations ... Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``TimedeltaArray(const numpy::NDArray& data, const numpy::NDArray& mask, bool copy = false)`` - df_timedelta_array.h:151 - * - ``explicit TimedeltaArray(const numpy::NDArray& data)`` - df_timedelta_array.h:166 - * - ``explicit TimedeltaArray(const std::vector>& values)`` - df_timedelta_array.h:207 - * - ``explicit TimedeltaArray(const std::vector& duration_strings)`` - df_timedelta_array.h:227 - Construction ------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``static TimedeltaArray from_sequence(const std::vector>& scalars)`` - static TimedeltaArray - df_timedelta_array.h:437 - Array Creation -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool empty() const`` - bool - df_timedelta_array.h:292 - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::timedelta64 at(size_t index) const`` - numpy::timedelta64 - df_timedelta_array.h:344 - :ref:`View ` * - ``TimedeltaArray take(const std::vector& indices, bool allow_fill = false, std::optional fill_value = std::nullopt) const`` - TimedeltaArray - df_timedelta_array.h:391 - :ref:`View ` Statistics ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional max() const`` - std::optional - df_timedelta_array.h:817 - :ref:`View ` * - ``std::optional min() const`` - std::optional - df_timedelta_array.h:808 - :ref:`View ` * - ``IntegerArray nanoseconds() const`` - IntegerArray - df_timedelta_array.h:896 - :ref:`View ` Sorting ------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::NDArray argsort(bool ascending = true, const std::string& na_position = "last") const`` - numpy::NDArray - df_timedelta_array.h:737 - :ref:`View ` Math Operations --------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``TimedeltaArray abs() const`` - TimedeltaArray - df_timedelta_array.h:1255 - :ref:`View ` * - ``TimedeltaArray ceil(const std::string& freq) const`` - TimedeltaArray - df_timedelta_array.h:1303 - :ref:`View ` * - ``TimedeltaArray floor(const std::string& freq) const`` - TimedeltaArray - df_timedelta_array.h:1278 - :ref:`View ` * - ``TimedeltaArray round(const std::string& freq) const`` - TimedeltaArray - df_timedelta_array.h:1328 - :ref:`View ` Linear Algebra -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``void detect_unit()`` - void - df_timedelta_array.h:1405 - Set Operations -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``TimedeltaArray unique() const`` - TimedeltaArray - df_timedelta_array.h:675 - :ref:`View ` I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::NDArray to_numpy(const numpy::timedelta64& na_value = numpy::timedelta64::NaT()) const`` - numpy::NDArray - df_timedelta_array.h:500 - :ref:`View ` * - ``std::vector> to_pytimedelta() const`` - std::vector> - df_timedelta_array.h:961 - * - ``std::string to_string() const`` - std::string - df_timedelta_array.h:1357 - :ref:`View ` Type Handling ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``TimedeltaArray copy() const`` - TimedeltaArray - df_timedelta_array.h:384 - :ref:`View ` Type Checking ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool is_na(size_t index) const`` - bool - df_timedelta_array.h:355 - * - ``BooleanArray is_negative() const`` - BooleanArray - df_timedelta_array.h:1075 - * - ``BooleanArray is_positive() const`` - BooleanArray - df_timedelta_array.h:1056 - * - ``BooleanArray is_zero() const`` - BooleanArray - df_timedelta_array.h:1094 - :ref:`View ` Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional argmax() const`` - std::optional - df_timedelta_array.h:788 - :ref:`View ` * - ``std::optional argmin() const`` - std::optional - df_timedelta_array.h:768 - :ref:`View ` * - ``static TimedeltaArray concat(const std::vector& arrays)`` - static TimedeltaArray - df_timedelta_array.h:444 - * - ``size_t count() const`` - size_t - df_timedelta_array.h:513 - :ref:`View ` * - ``const numpy::NDArray& data() const`` - const numpy::NDArray& - df_timedelta_array.h:317 - :ref:`View ` * - ``IntegerArray days() const`` - IntegerArray - df_timedelta_array.h:830 - :ref:`View ` * - ``TimedeltaArray dropna() const`` - TimedeltaArray - df_timedelta_array.h:487 - * - ``dtype_type dtype() const`` - dtype_type - df_timedelta_array.h:257 - :ref:`View ` * - ``std::pair, TimedeltaArray> factorize() const`` - std::pair, TimedeltaArray> - df_timedelta_array.h:701 - * - ``TimedeltaArray fillna(const numpy::timedelta64& value) const`` - TimedeltaArray - df_timedelta_array.h:473 - * - ``bool has_na() const`` - bool - df_timedelta_array.h:526 - * - ``numpy::NDArray isna() const`` - numpy::NDArray - df_timedelta_array.h:366 - * - ``size_t len() const`` - size_t - df_timedelta_array.h:299 - * - ``const numpy::NDArray& mask() const`` - const numpy::NDArray& - df_timedelta_array.h:324 - :ref:`View ` * - ``IntegerArray microseconds() const`` - IntegerArray - df_timedelta_array.h:873 - :ref:`View ` * - ``size_t nbytes() const`` - size_t - df_timedelta_array.h:271 - :ref:`View ` * - ``constexpr int ndim() const`` - constexpr int - df_timedelta_array.h:278 - :ref:`View ` * - ``numpy::NDArray notna() const`` - numpy::NDArray - df_timedelta_array.h:373 - * - ``static int64_t parse_freq_to_seconds(const std::string& freq)`` - static int64_t - df_timedelta_array.h:1415 - * - ``std::string repr() const`` - std::string - df_timedelta_array.h:1374 - * - ``IntegerArray seconds() const`` - IntegerArray - df_timedelta_array.h:849 - :ref:`View ` * - ``std::vector shape() const`` - std::vector - df_timedelta_array.h:285 - :ref:`View ` * - ``size_t size() const`` - size_t - df_timedelta_array.h:264 - :ref:`View ` * - ``numpy::timedelta64 td(duration_strings[i])`` - numpy::timedelta64 - df_timedelta_array.h:238 - :ref:`View ` * - ``FloatingArray total_seconds() const`` - FloatingArray - df_timedelta_array.h:934 - :ref:`View ` * - ``numpy::DateTimeUnit unit() const`` - numpy::DateTimeUnit - df_timedelta_array.h:306 - * - ``void validate_arrays()`` - void - df_timedelta_array.h:1387 - Code Examples ------------- The following examples are extracted from the test suite. .. _example-timedeltaarray-empty-0: .. dropdown:: empty (np_test_1_all.cpp:6316) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6306 :emphasize-lines: 11 } void test_data_generator_emptyBenchmarkSorting() { std::cout << "========= test_data_generator_empty ======================="; DataGenerator gen(42); // Test empty data generation std::vector data = gen.generate(0, DataPattern::RANDOM); if (!(data.empty())) { std::string description = std::string("test_data_generator_emptyBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.empty())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Empty data generation test passed" << std::endl; std::cout << " -> tests passed" << std::endl; } .. _example-timedeltaarray-at-1: .. dropdown:: at (np_test_1_all.cpp:144) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 134 :emphasize-lines: 11 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}); std::cout << " -> tests passed" << std::endl; } void testArithmetic() { std::cout << "========= testArithmeticOperations ======================="; auto array1 = createFloat32Array({2, 2}, 5.0f); auto array2 = createFloat32Array({2, 2}, 3.0f); .. _example-timedeltaarray-take-2: .. dropdown:: take (np_test_5_all.cpp:4313) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4303 :emphasize-lines: 11 for (size_t i = 0; i < 6; ++i) { arr.setElementAt({ i }, static_cast(i * 10)); // [0, 10, 20, 30, 40, 50] } // Take specific indices numpy::NDArray indices({ 3 }); indices.setElementAt({ 0 }, 5); // 50 indices.setElementAt({ 1 }, 2); // 20 indices.setElementAt({ 2 }, 0); // 0 auto result = numpy::take(arr, indices); if (result.getSize() != 3) { std::cout << " [FAIL] : in np_test_take_basic() : Wrong result size"; throw std::runtime_error("Test failed"); } if (result.getElementAt({ 0 }) != 50 || result.getElementAt({ 1 }) != 20 || result.getElementAt({ 2 }) != 0) { std::cout << " [FAIL] : in np_test_take_basic() : Wrong values extracted"; throw std::runtime_error("Test failed"); } .. _example-timedeltaarray-max-3: .. dropdown:: max (np_test_1_all.cpp:7274) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7264 :emphasize-lines: 11 if (sizeof(uintp) == sizeof(void*)) { // std::cout << " -> uintp size matches pointer size"; } else { // std::cout << " ✗ uintp size doesn't match pointer size" << std::endl; } // Test range limits // std::cout << "Range Information:" << std::endl; // std::cout << " intp min: " << std::numeric_limits::min() << std::endl; // std::cout << " intp max: " << std::numeric_limits::max() << std::endl; // std::cout << " uintp max: " << std::numeric_limits::max() << std::endl; // std::cout << " longdouble digits: " << std::numeric_limits::digits << std::endl; std::cout << " -> tests passed" << std::endl; } void testComplexArithmeticExtendedTypes() { std::cout << "========= testComplexArithmeticExtendedTypes ======================="; clongdouble c1(3.0L, 4.0L); // 3 + 4i .. _example-timedeltaarray-min-4: .. dropdown:: min (np_test_1_all.cpp:2350) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2340 :emphasize-lines: 11 if (i % 3 == 0) { large_array.setElementAt({i}, object_(static_cast(i))); } else if (i % 3 == 1) { large_array.setElementAt({i}, object_(static_cast(i) * 0.5)); } else { large_array.setElementAt({i}, object_(std::string("str") + std::to_string(i))); } } // Verify pattern for (size_t i = 0; i < std::min(large_size, size_t(100)); ++i) { // Check first 100 object_ obj = large_array.getElementAt({i}); if (i % 3 == 0) { if (!(obj.is_type())) { std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(obj.is_type())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } } else if (i % 3 == 1) { if (!(obj.is_type())) { std::string description = std::string("unknown_function():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(obj.is_type())"; .. _example-timedeltaarray-nanoseconds-5: .. dropdown:: nanoseconds (np_test_5_all.cpp:21255) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21245 :emphasize-lines: 11 errors++; } } if (errors == 0) { std::cout << "np_test_timedelta_constructors -> tests passed" << std::endl; } return errors; } // ============================================================================= // Test 2: Static Factory Methods // ============================================================================= int np_test_timedelta_static_factories() { int errors = 0; // NaT() { numpy::Timedelta nat = numpy::Timedelta::NaT(); if (!nat.isNaT()) { std::cout << "[FAIL] np_test_timedelta_static_factories: NaT().isNaT() should be true" .. _example-timedeltaarray-argsort-6: .. dropdown:: argsort (np_test_1_all.cpp:16841) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16831 :emphasize-lines: 11 std::cout << "========= test_argsort ======================="; // Test 1D array argsort NDArray arr1d({ 5 }); arr1d.setElementAt({ 0 }, 30); // index 0 arr1d.setElementAt({ 1 }, 10); // index 1 arr1d.setElementAt({ 2 }, 40); // index 2 arr1d.setElementAt({ 3 }, 20); // index 3 arr1d.setElementAt({ 4 }, 50); // index 4 auto indices = argsort(arr1d); // Expected order: 10(idx1), 20(idx3), 30(idx0), 40(idx2), 50(idx4) if (!(indices.getElementAt({ 0 }) == 1)) { std::string description = std::string("test_argsort():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(indices.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(indices.getElementAt({ 1 }) == 3)) { std::string description = std::string("test_argsort():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(indices.getElementAt({ 1 }) == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-timedeltaarray-abs-7: .. dropdown:: abs (np_test_1_all.cpp:101) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 91 :emphasize-lines: 11 if (arr.getShape().size() == 1 && arr.getShape()[0] <= 10) { for (size_t i = 0; i < arr.getShape()[0]; ++i) { // std::cout << static_cast(arr.getElementAt({i})) << " "; } } // std::cout << std::endl; } // Helper function for core array extensions tests bool isApproxEqualExt(double a, double b, double tolerance = 1e-10) { return std::abs(a - b) < tolerance; } } void f_nothing() { // This function does nothing and tests nothing // It's a placeholder test function } // ------ merging np_test_advanced_indexing.cpp -- number of functions merged=16 -------------------------------- .. _example-timedeltaarray-ceil-8: .. dropdown:: ceil (np_test_2_all.cpp:5735) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5725 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] floor function works correctly\n"; // Test ceil auto ceil_result = ceil(values); if (!(approx_equal(ceil_result.getElementAt({ 0 }), std::ceil(-2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(ceil_result.getElementAt({ 0 }), std::ceil(-2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(approx_equal(ceil_result.getElementAt({ 5 }), std::ceil(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(ceil_result.getElementAt({ 5 }), std::ceil(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaarray-floor-9: .. dropdown:: floor (np_test_2_all.cpp:5721) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 5711 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(approx_equal(round_result.getElementAt({ 5 }), std::round(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(round_result.getElementAt({ 5 }), std::round(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] round function works correctly\n"; // Test floor auto floor_result = floor(values); if (!(approx_equal(floor_result.getElementAt({ 0 }), std::floor(-2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(floor_result.getElementAt({ 0 }), std::floor(-2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))) { std::string description = std::string("testRoundingFunctions():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(floor_result.getElementAt({ 5 }), std::floor(2.7)))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaarray-round-10: .. dropdown:: round (np_test_1_all.cpp:23769) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 23759 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(power_scalar_result.getShape() == array.getShape())) { std::string description = std::string("testMathFunctionSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(power_scalar_result.getShape() == array.getShape())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Power functions have correct signatures\n"; // Test rounding functions with new decimals parameter auto round_result = round(array); // Default decimals=0 auto round_decimals_result = round(array, 2); // With decimals if (!(round_result.getShape() == array.getShape())) { std::string description = std::string("testMathFunctionSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(round_result.getShape() == array.getShape())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(round_decimals_result.getShape() == array.getShape())) { std::string description = std::string("testMathFunctionSignatures():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(round_decimals_result.getShape() == array.getShape())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-timedeltaarray-unique-11: .. dropdown:: unique (np_test_1_all.cpp:6259) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6249 :emphasize-lines: 11 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); } // std::cout << "Few unique data generation test passed. Unique values: " << unique_count << std::endl; .. _example-timedeltaarray-to_numpy-12: .. dropdown:: to_numpy (np_test_5_all.cpp:21373) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21363 :emphasize-lines: 11 if (errors == 0) { std::cout << "np_test_timedelta_components -> tests passed" << std::endl; } return errors; } // ============================================================================= // Test 4: Total Conversion Properties // ============================================================================= int np_test_timedelta_total_conversions() { int errors = 0; numpy::Timedelta td(1, 12, 0); // 1 day 12 hours = 1.5 days = 36 hours // total_seconds { double secs = td.total_seconds(); double expected = (24 + 12) * 3600.0; if (std::abs(secs - expected) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_total_conversions: total_seconds expected " << expected << ", got " << secs << std::endl; .. _example-timedeltaarray-to_string-13: .. dropdown:: to_string (np_test_1_all.cpp:454) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 444 :emphasize-lines: 11 // Modify through different views view1.setElementAt({0, 0}, 100); view2.setElementAt({2, 1}, 200); // This is (1, 2) in original view3.setElementAt({0, 0}, 300); // This is (1, 1) in original // std::cout << "After modifications through multiple views:" << std::endl; //original.printArray(); // Verify all changes are reflected if (!(original.getElementAt({0, 0}) == 100)) { std::string description = std::string("testAdvancedViewLifecycle():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({0, 0}) == 100)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(original.getElementAt({1, 2}) == 200)) { std::string description = std::string("testAdvancedViewLifecycle():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({1, 2}) == 200)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(original.getElementAt({1, 1}) == 300)) { std::string description = std::string("testAdvancedViewLifecycle():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({1, 1}) == 300)"; .. _example-timedeltaarray-copy-14: .. dropdown:: copy (np_test_1_all.cpp:9812) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 9802 :emphasize-lines: 11 //original.printArray(); // The modification should be at position (1,1) in original if (!(original.getElementAt({1, 1}) == 9999)) { std::string description = std::string("testSliceCopyVsViewMemoryOwnership():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(original.getElementAt({1, 1}) == 9999)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Slice view shares memory with original"; // Test slice copy (should be independent) auto slice_copy = original.sliceArray({{2, 4}, {2, 4}}); // std::cout << "Slice copy [2:4, 2:4]:"; //slice_copy.printArray(); slice_copy.setElementAt({0, 0}, 7777); // std::cout << "After modifying slice copy at (0,0):" << std::endl; // std::cout << "Original array:" << std::endl; //original.printArray(); // std::cout << "Slice copy:" << std::endl; .. _example-timedeltaarray-is_zero-15: .. dropdown:: is_zero (np_test_2_all.cpp:7329) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7319 :emphasize-lines: 11 // Test machine epsilon auto eps_double = machine_epsilon(); if (!(eps_double > 0)) { std::string description = std::string("test_basic_utilities():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(eps_double > 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Machine epsilon (double): " << eps_double << std::endl; // Test zero check bool is_zero_result = is_zero(1e-16); if (!(is_zero_result == true)) { std::string description = std::string("test_basic_utilities():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(is_zero_result == true)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Is 1e-16 zero? " << (is_zero_result ? "Yes" : "No") << std::endl; // Test safe divide double safe_result = safe_divide(1.0, 2.0); if (!(safe_result == 0.5)) { .. _example-timedeltaarray-argmax-16: .. dropdown:: argmax (np_test_3_all.cpp:20521) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20511 :emphasize-lines: 11 auto result = numpy::argmin(arr); // Should return 1 (index of (1,5)) if (result.getElementAt({0}) != 1) { throw std::runtime_error("argmin() failed: expected index 1"); } std::cout << "PASSED\n"; } void test_argmax_complex128() { std::cout << " Testing argmax() with complex128... "; numpy::NDArray arr({3}); arr.setElementAt({0}, complex128(3.0, 1.0)); // index 0 - largest arr.setElementAt({1}, complex128(1.0, 5.0)); // index 1 arr.setElementAt({2}, complex128(2.0, 2.0)); // index 2 auto result = numpy::argmax(arr); // Should return 0 (index of (3,1)) if (result.getElementAt({0}) != 0) { throw std::runtime_error("argmax() failed: expected index 0"); } .. _example-timedeltaarray-argmin-17: .. dropdown:: argmin (np_test_3_all.cpp:20506) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20496 :emphasize-lines: 11 if (min_result.getElementAt({0}).real() != 2.0 || min_result.getElementAt({0}).imag() != 1.0) { throw std::runtime_error("min() tie-breaking failed: expected (2,1)"); } if (max_result.getElementAt({0}).real() != 2.0 || max_result.getElementAt({0}).imag() != 5.0) { throw std::runtime_error("max() tie-breaking failed: expected (2,5)"); } std::cout << "PASSED\n"; } void test_argmin_complex128() { std::cout << " Testing argmin() with complex128... "; numpy::NDArray arr({3}); arr.setElementAt({0}, complex128(3.0, 1.0)); // index 0 arr.setElementAt({1}, complex128(1.0, 5.0)); // index 1 - smallest arr.setElementAt({2}, complex128(2.0, 2.0)); // index 2 auto result = numpy::argmin(arr); // Should return 1 (index of (1,5)) if (result.getElementAt({0}) != 1) { throw std::runtime_error("argmin() failed: expected index 1"); } .. _example-timedeltaarray-count-18: .. dropdown:: count (np_test_1_all.cpp:3616) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3606 :emphasize-lines: 11 // Create larger arrays for performance testing auto large_arr = NDArray::createOnes({100, 100}); auto broadcast_arr = NDArray::createOnes({1, 100}); // Time the operation (basic timing) auto start = std::chrono::high_resolution_clock::now(); auto result = large_arr.addArrays(broadcast_arr); auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end - start); // std::cout << "Large array broadcasting took " << duration.count() << " microseconds" << std::endl; // Verify result shape if (!((result.getShape() == std::vector{100, 100}))) { std::string description = std::string("test_broadcasting_performance():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !((result.getShape() == std::vector{100, 100}))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.getElementAt({50, 50}) == 2.0)) { std::string description = std::string("test_broadcasting_performance():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({50, 50}) == 2.0)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-timedeltaarray-data-19: .. 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-timedeltaarray-days-20: .. dropdown:: days (np_test_1_all.cpp:28638) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 28628 :emphasize-lines: 11 } void np_test_datetime_business_date_range() { std::cout << "========= businessDateRange: business days only ======================="; // Get business days in first week of January 2024 auto start_dt = numpy::datetime64("2024-01-01"); auto end_dt = numpy::datetime64("2024-01-07"); auto biz_dates = numpy::datetime_utils::businessDateRange(start_dt, end_dt); // Should have between 3-5 business days (accounting for holidays) bool passed = (biz_dates.size() >= 3 && biz_dates.size() <= 5); if (!passed) { std::cout << " [FAIL] : in np_test_datetime_business_date_range() : Got " << biz_dates.size() << " business days"; throw std::runtime_error("np_test_datetime_business_date_range failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-timedeltaarray-dtype-21: .. dropdown:: dtype (np_test_3_all.cpp:7942) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7932 :emphasize-lines: 11 if (info.max != expected_max) { std::cerr << "[FAIL] IInfo::max mismatch"; throw std::runtime_error("IInfo uint64 max test failed"); } // std::cout << "[OK] IInfo::max = " << info.max << std::endl; std::cout << " -> tests passed" << std::endl; } // ============================================================================ // dtype() Tests - DType descriptor creation // ============================================================================ void np_test_dtype_from_string_integers() { std::cout << "========= np_test_dtype_from_string_integers ======================="; // Test integer type strings if (dtype("int8") != DType::INT8) { std::cerr << "[FAIL] dtype(\"int8\") should return INT8"; throw std::runtime_error("dtype string test failed"); } .. _example-timedeltaarray-mask-22: .. dropdown:: mask (np_test_1_all.cpp:27691) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27681 :emphasize-lines: 11 void test_mask_rows_cols() { std::cout << "========= ma::mask_rows() and ma::mask_cols(): mask operations ==="; auto data = numpy::array({ {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0} }); auto mask = numpy::array({ {false, true, false}, {false, false, false} }); auto ma = numpy::ma::masked_array(data, mask); auto result_rows = numpy::ma::mask_rows(ma); auto result_cols = numpy::ma::mask_cols(ma); // std::cout << " ma::mask_rows(): row 0 fully masked: " << (result_rows.mask().getElementAt({ 0, 0 }) ? "true" : "false") << std::endl; // std::cout << " ma::mask_cols(): column 1 fully masked: " << (result_cols.mask().getElementAt({ 1, 1 }) ? "true" : "false"); std::cout << " -> tests passed"; } void test_compress_rowcols() { std::cout << "========= ma::compress_rowcols(): remove masked rows/columns ==="; auto data = numpy::array({ {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0} }); auto mask = numpy::array({ {false, false, false}, {false, true, false}, {false, false, false} }); auto ma = numpy::ma::masked_array(data, mask); .. _example-timedeltaarray-microseconds-23: .. dropdown:: microseconds (np_test_2_all.cpp:4731) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4721 :emphasize-lines: 11 } // Write thread-specific pattern for (size_t j = 0; j < size; ++j) { ptr[j] = thread_id * 1000 + static_cast(j); } allocations.push_back({ ptr, size }); // Small delay to increase chance of concurrent access std::this_thread::sleep_for(std::chrono::microseconds(1)); } // Verify data integrity for (auto& alloc : allocations) { for (size_t j = 0; j < alloc.second; ++j) { if (!(alloc.first[j] == thread_id * 1000 + static_cast(j))) { std::string description = std::string("test_concurrent_allocations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(alloc.first[j] == thread_id * 1000 + static_cast(j))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaarray-nbytes-24: .. dropdown:: nbytes (np_test_2_all.cpp:3547) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3537 :emphasize-lines: 11 } // Test itemsize if (!(itemsize(arr) == sizeof(double))) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(itemsize(arr) == sizeof(double))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test nbytes if (!(nbytes(arr) == 24 * sizeof(double))) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(nbytes(arr) == 24 * sizeof(double))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test flags auto flags_info = flags(arr); if (!(flags_info.owndata == true)) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(flags_info.owndata == true)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-timedeltaarray-ndim-25: .. dropdown:: ndim (np_test_2_all.cpp:3526) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3516 :emphasize-lines: 11 void testArrayInfo() { std::cout << "Testing array information functions...\n"; // Test basic info functions auto arr = createFloat64Array({ 2, 3, 4 }); for (size_t i = 0; i < arr.getSize(); ++i) { arr.setElementAt({ i / 12, (i / 4) % 3, i % 4 }, static_cast(i)); } // Test ndim if (!(ndim(arr) == 3)) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(ndim(arr) == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test size if (!(size(arr) == 24)) { std::string description = std::string("testArrayInfo():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(size(arr) == 24)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-timedeltaarray-seconds-26: .. dropdown:: seconds (np_test_5_all.cpp:21240) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21230 :emphasize-lines: 11 // From value and unit - static factory for fractional values { numpy::Timedelta td_frac = numpy::Timedelta::from_value(1.5, "h"); // 1.5 hours = 90 minutes std::cout << " Timedelta::from_value(1.5, 'h') = " << td_frac.total_minutes() << " minutes" << std::endl; if (std::abs(td_frac.total_minutes() - 90.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from_value(1.5, 'h') expected 90 minutes, got " << td_frac.total_minutes() << std::endl; errors++; } numpy::Timedelta td_frac2 = numpy::Timedelta::from_value(0.5, "D"); // 0.5 days = 12 hours std::cout << " Timedelta::from_value(0.5, 'D') = " << td_frac2.total_hours() << " hours" << std::endl; if (std::abs(td_frac2.total_hours() - 12.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from_value(0.5, 'D') expected 12 hours, got " << td_frac2.total_hours() << std::endl; errors++; } } if (errors == 0) { std::cout << "np_test_timedelta_constructors -> tests passed" << std::endl; .. _example-timedeltaarray-shape-27: .. dropdown:: shape (np_test_1_all.cpp:3751) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 3741 :emphasize-lines: 11 } for (size_t j = 0; j < 3; ++j) { arr3.setElementAt({0, j}, static_cast((j + 1) * 100)); // [100, 200, 300] } // Broadcast all arrays together std::vector> arrays = {arr1, arr2, arr3}; auto broadcasted = broadcast_arrays(arrays); // All should have shape (2, 3) for (const auto& arr : broadcasted) { if (!((arr.getShape() == std::vector{2, 3}))) { std::string description = std::string("test_broadcast_arrays():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !((arr.getShape() == std::vector{2, 3}))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } } // Check values if (!(broadcasted[0].getElementAt({0, 1}) == 2.0)) { .. _example-timedeltaarray-size-28: .. dropdown:: size (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-timedeltaarray-td-29: .. dropdown:: td (np_test_2_all.cpp:21974) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21964 :emphasize-lines: 11 {numpy::DateTimeUnit::Hour, "h"}, {numpy::DateTimeUnit::Minute, "m"}, {numpy::DateTimeUnit::Second, "s"}, {numpy::DateTimeUnit::Millisecond, "ms"}, {numpy::DateTimeUnit::Microsecond, "us"}, {numpy::DateTimeUnit::Nanosecond, "ns"} }; // Test all timedelta64 units for (const auto& test : tests) { numpy::timedelta64 td(1, test.unit); auto [unit_str, count] = numpy::datetime_utils::datetime_data(td); if (unit_str != test.expected_str || count != 1) { std::cout << " [FAIL] : in np_test_datetime_data_timedelta() : timedelta64 unit test failed for " << test.expected_str << ": got ('" << unit_str << "', " << count << ")" << std::endl; throw std::runtime_error("np_test_datetime_data_timedelta failed: timedelta64 unit mismatch"); } } std::cout << " -> tests passed" << std::endl; .. _example-timedeltaarray-total_seconds-30: .. dropdown:: total_seconds (np_test_5_all.cpp:21288) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21278 :emphasize-lines: 11 } } // max() { numpy::Timedelta max_td = numpy::Timedelta::max(); if (max_td.value() != INT64_MAX) { std::cout << "[FAIL] np_test_timedelta_static_factories: max() expected INT64_MAX" << std::endl; errors++; } } // resolution() { numpy::Timedelta res = numpy::Timedelta::resolution(); if (res.value() != 1) { std::cout << "[FAIL] np_test_timedelta_static_factories: resolution() expected 1 ns" << std::endl; errors++; }