Timedelta ========= .. cpp:class:: numpy::Timedelta numpy C++ class. Example ------- .. code-block:: cpp #include using namespace numpy; // Use Timedelta Timedelta obj; // ... operations ... Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``Timedelta(int64_tnanoseconds)`` - NP_TIMEDELTA.H:233 - :ref:`View ` * - ``Timedelta(int64_tdays, int64_thours, int64_tminutes = 0, int64_tseconds = 0, int64_tmilliseconds = 0, int64_tmicroseconds = 0, int64_tnanoseconds = 0)`` - NP_TIMEDELTA.H:238 - :ref:`View ` * - ``Timedelta(const std::string &duration_string)`` - NP_TIMEDELTA.H:253 - :ref:`View ` * - ``Timedelta(int64_tvalue, const std::string &unit)`` - NP_TIMEDELTA.H:261 - :ref:`View ` * - ``Timedelta(const timedelta64 &td)`` - NP_TIMEDELTA.H:273 - :ref:`View ` * - ``Timedelta(const std::chrono::duration&dur)`` - NP_TIMEDELTA.H:308 - :ref:`View ` Operators --------- .. list-table:: :widths: 40 25 15 20 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Timedelta operator+(const Timedelta &other)`` - Timedelta - NP_TIMEDELTA.H:680 - * - ``Timedelta operator-(const Timedelta &other)`` - Timedelta - NP_TIMEDELTA.H:685 - * - ``Timedelta & operator+=(const Timedelta &other)`` - Timedelta & - NP_TIMEDELTA.H:690 - * - ``Timedelta & operator-=(const Timedelta &other)`` - Timedelta & - NP_TIMEDELTA.H:700 - * - ``Timedelta operator-()`` - Timedelta - NP_TIMEDELTA.H:711 - * - ``Timedelta operator\*(int64_tscalar)`` - Timedelta - NP_TIMEDELTA.H:717 - * - ``Timedelta operator\*(intscalar)`` - Timedelta - NP_TIMEDELTA.H:722 - * - ``Timedelta operator\*(doublescalar)`` - Timedelta - NP_TIMEDELTA.H:726 - * - ``Timedelta & operator\*=(int64_tscalar)`` - Timedelta & - NP_TIMEDELTA.H:731 - * - ``Timedelta & operator\*=(intscalar)`` - Timedelta & - NP_TIMEDELTA.H:739 - * - ``Timedelta & operator\*=(doublescalar)`` - Timedelta & - NP_TIMEDELTA.H:743 - * - ``Timedelta operator/(int64_tscalar)`` - Timedelta - NP_TIMEDELTA.H:752 - * - ``Timedelta operator/(intscalar)`` - Timedelta - NP_TIMEDELTA.H:757 - * - ``Timedelta operator/(doublescalar)`` - Timedelta - NP_TIMEDELTA.H:761 - * - ``Timedelta & operator/=(int64_tscalar)`` - Timedelta & - NP_TIMEDELTA.H:766 - * - ``Timedelta & operator/=(intscalar)`` - Timedelta & - NP_TIMEDELTA.H:776 - * - ``Timedelta & operator/=(doublescalar)`` - Timedelta & - NP_TIMEDELTA.H:780 - * - ``double operator/(const Timedelta &other)`` - double - NP_TIMEDELTA.H:791 - * - ``Timedelta operator%(const Timedelta &other)`` - Timedelta - NP_TIMEDELTA.H:799 - * - ``Timedelta operator+(const timedelta64 &td)`` - Timedelta - NP_TIMEDELTA.H:829 - * - ``Timedelta operator-(const timedelta64 &td)`` - Timedelta - NP_TIMEDELTA.H:834 - * - ``bool operator==(const Timedelta &other)`` - bool - NP_TIMEDELTA.H:843 - * - ``bool operator!=(const Timedelta &other)`` - bool - NP_TIMEDELTA.H:849 - * - ``bool operator<(const Timedelta &other)`` - bool - NP_TIMEDELTA.H:855 - * - ``bool operator<=(const Timedelta &other)`` - bool - NP_TIMEDELTA.H:860 - * - ``bool operator>(const Timedelta &other)`` - bool - NP_TIMEDELTA.H:865 - * - ``bool operator>=(const Timedelta &other)`` - bool - NP_TIMEDELTA.H:870 - Construction ------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Timedelta from_value(doublevalue, const std::string &unit)`` - Timedelta - NP_TIMEDELTA.H:268 - :ref:`View ` Statistics ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Timedelta max()`` - Timedelta - NP_TIMEDELTA.H:328 - :ref:`View ` * - ``Timedelta min()`` - Timedelta - NP_TIMEDELTA.H:324 - :ref:`View ` * - ``int32_t minutes()`` - int32_t - NP_TIMEDELTA.H:371 - :ref:`View ` * - ``int32_t nanoseconds()`` - int32_t - NP_TIMEDELTA.H:395 - :ref:`View ` Math Operations --------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Timedelta abs()`` - Timedelta - NP_TIMEDELTA.H:807 - :ref:`View ` * - ``Timedelta ceil(const std::string &freq, const std::string &ambiguous = "raise", const std::string &nonexistent = "raise")`` - Timedelta - NP_TIMEDELTA.H:603 - :ref:`View ` * - ``Timedelta floor(const std::string &freq, const std::string &ambiguous = "raise", const std::string &nonexistent = "raise")`` - Timedelta - NP_TIMEDELTA.H:585 - :ref:`View ` * - ``Timedelta round(const std::string &freq, const std::string &ambiguous = "raise", const std::string &nonexistent = "raise")`` - Timedelta - NP_TIMEDELTA.H:624 - :ref:`View ` Linear Algebra -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``void invalidateCache()`` - void - NP_TIMEDELTA.H:62 - I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::chrono::nanoseconds to_chrono()`` - std::chrono::nanoseconds - NP_TIMEDELTA.H:476 - :ref:`View ` * - ``Duration to_chrono_duration()`` - Duration - NP_TIMEDELTA.H:484 - :ref:`View ` * - ``int64_t to_numpy(const std::string &dtype = "timedelta64[ns]", boolcopy = false)`` - int64_t - NP_TIMEDELTA.H:469 - :ref:`View ` * - ``timedelta64 to_timedelta64(DateTimeUnitunit = DateTimeUnit::Nanosecond)`` - timedelta64 - NP_TIMEDELTA.H:438 - :ref:`View ` Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``Timedelta NaT()`` - Timedelta - NP_TIMEDELTA.H:318 - :ref:`View ` * - ``Timedelta as_unit(const std::string &unit, boolround_ok = true)`` - Timedelta - NP_TIMEDELTA.H:656 - :ref:`View ` * - ``int64_t components_days()`` - int64_t - NP_TIMEDELTA.H:402 - :ref:`View ` * - ``std::string components_str()`` - std::string - NP_TIMEDELTA.H:566 - :ref:`View ` * - ``void computeComponents()`` - void - NP_TIMEDELTA.H:66 - * - ``int64_t days()`` - int64_t - NP_TIMEDELTA.H:359 - :ref:`View ` * - ``int64_t delta()`` - int64_t - NP_TIMEDELTA.H:354 - :ref:`View ` * - ``int32_t hours()`` - int32_t - NP_TIMEDELTA.H:365 - :ref:`View ` * - ``bool isNaT()`` - bool - NP_TIMEDELTA.H:340 - :ref:`View ` * - ``std::string isoformat()`` - std::string - NP_TIMEDELTA.H:529 - :ref:`View ` * - ``int32_t microseconds()`` - int32_t - NP_TIMEDELTA.H:389 - :ref:`View ` * - ``int32_t milliseconds()`` - int32_t - NP_TIMEDELTA.H:383 - :ref:`View ` * - ``int64_t parseDurationString(const std::string &s)`` - int64_t - NP_TIMEDELTA.H:112 - * - ``int64_t parseFrequencyToNanos(const std::string &freq)`` - int64_t - NP_TIMEDELTA.H:99 - * - ``Timedelta resolution()`` - Timedelta - NP_TIMEDELTA.H:332 - :ref:`View ` * - ``int32_t seconds()`` - int32_t - NP_TIMEDELTA.H:377 - :ref:`View ` * - ``std::string toString()`` - std::string - NP_TIMEDELTA.H:497 - :ref:`View ` * - ``double total_days()`` - double - NP_TIMEDELTA.H:423 - :ref:`View ` * - ``double total_hours()`` - double - NP_TIMEDELTA.H:418 - :ref:`View ` * - ``double total_minutes()`` - double - NP_TIMEDELTA.H:413 - :ref:`View ` * - ``double total_nanoseconds()`` - double - NP_TIMEDELTA.H:428 - * - ``double total_seconds()`` - double - NP_TIMEDELTA.H:408 - :ref:`View ` * - ``int64_t value()`` - int64_t - NP_TIMEDELTA.H:349 - :ref:`View ` Code Examples ------------- The following examples are extracted from the test suite. .. _example-timedelta-timedelta-0: .. dropdown:: Timedelta (np_test_5_all.cpp:21164) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21154 :emphasize-lines: 11 if (std::abs(td.total_hours() - 2.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from chrono expected 2 hours, got " << td.total_hours() << std::endl; errors++; } } // From value and unit (pandas-style) - int64_t version { numpy::Timedelta td_hours(5, "h"); // 5 hours std::cout << " Timedelta(5, 'h') = " << td_hours.total_hours() << " hours" << std::endl; if (std::abs(td_hours.total_hours() - 5.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(5, 'h') expected 5 hours, got " << td_hours.total_hours() << std::endl; errors++; } numpy::Timedelta td_days(3, "D"); // 3 days std::cout << " Timedelta(3, 'D') = " << td_days.days() << " days" << std::endl; if (td_days.days() != 3) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(3, 'D') expected 3 days, got " .. _example-timedelta-timedelta-1: .. dropdown:: Timedelta (np_test_5_all.cpp:21164) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21154 :emphasize-lines: 11 if (std::abs(td.total_hours() - 2.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from chrono expected 2 hours, got " << td.total_hours() << std::endl; errors++; } } // From value and unit (pandas-style) - int64_t version { numpy::Timedelta td_hours(5, "h"); // 5 hours std::cout << " Timedelta(5, 'h') = " << td_hours.total_hours() << " hours" << std::endl; if (std::abs(td_hours.total_hours() - 5.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(5, 'h') expected 5 hours, got " << td_hours.total_hours() << std::endl; errors++; } numpy::Timedelta td_days(3, "D"); // 3 days std::cout << " Timedelta(3, 'D') = " << td_days.days() << " days" << std::endl; if (td_days.days() != 3) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(3, 'D') expected 3 days, got " .. _example-timedelta-timedelta-2: .. dropdown:: Timedelta (np_test_5_all.cpp:21164) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21154 :emphasize-lines: 11 if (std::abs(td.total_hours() - 2.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from chrono expected 2 hours, got " << td.total_hours() << std::endl; errors++; } } // From value and unit (pandas-style) - int64_t version { numpy::Timedelta td_hours(5, "h"); // 5 hours std::cout << " Timedelta(5, 'h') = " << td_hours.total_hours() << " hours" << std::endl; if (std::abs(td_hours.total_hours() - 5.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(5, 'h') expected 5 hours, got " << td_hours.total_hours() << std::endl; errors++; } numpy::Timedelta td_days(3, "D"); // 3 days std::cout << " Timedelta(3, 'D') = " << td_days.days() << " days" << std::endl; if (td_days.days() != 3) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(3, 'D') expected 3 days, got " .. _example-timedelta-timedelta-3: .. dropdown:: Timedelta (np_test_5_all.cpp:21164) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21154 :emphasize-lines: 11 if (std::abs(td.total_hours() - 2.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from chrono expected 2 hours, got " << td.total_hours() << std::endl; errors++; } } // From value and unit (pandas-style) - int64_t version { numpy::Timedelta td_hours(5, "h"); // 5 hours std::cout << " Timedelta(5, 'h') = " << td_hours.total_hours() << " hours" << std::endl; if (std::abs(td_hours.total_hours() - 5.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(5, 'h') expected 5 hours, got " << td_hours.total_hours() << std::endl; errors++; } numpy::Timedelta td_days(3, "D"); // 3 days std::cout << " Timedelta(3, 'D') = " << td_days.days() << " days" << std::endl; if (td_days.days() != 3) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(3, 'D') expected 3 days, got " .. _example-timedelta-timedelta-4: .. dropdown:: Timedelta (np_test_5_all.cpp:21164) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21154 :emphasize-lines: 11 if (std::abs(td.total_hours() - 2.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from chrono expected 2 hours, got " << td.total_hours() << std::endl; errors++; } } // From value and unit (pandas-style) - int64_t version { numpy::Timedelta td_hours(5, "h"); // 5 hours std::cout << " Timedelta(5, 'h') = " << td_hours.total_hours() << " hours" << std::endl; if (std::abs(td_hours.total_hours() - 5.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(5, 'h') expected 5 hours, got " << td_hours.total_hours() << std::endl; errors++; } numpy::Timedelta td_days(3, "D"); // 3 days std::cout << " Timedelta(3, 'D') = " << td_days.days() << " days" << std::endl; if (td_days.days() != 3) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(3, 'D') expected 3 days, got " .. _example-timedelta-timedelta-5: .. dropdown:: Timedelta (np_test_5_all.cpp:21164) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21154 :emphasize-lines: 11 if (std::abs(td.total_hours() - 2.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from chrono expected 2 hours, got " << td.total_hours() << std::endl; errors++; } } // From value and unit (pandas-style) - int64_t version { numpy::Timedelta td_hours(5, "h"); // 5 hours std::cout << " Timedelta(5, 'h') = " << td_hours.total_hours() << " hours" << std::endl; if (std::abs(td_hours.total_hours() - 5.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(5, 'h') expected 5 hours, got " << td_hours.total_hours() << std::endl; errors++; } numpy::Timedelta td_days(3, "D"); // 3 days std::cout << " Timedelta(3, 'D') = " << td_days.days() << " days" << std::endl; if (td_days.days() != 3) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(3, 'D') expected 3 days, got " .. _example-timedelta-from_value-6: .. dropdown:: from_value (np_test_5_all.cpp:21232) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21222 :emphasize-lines: 11 std::cout << " Timedelta(2, 'W') = " << td_week.days() << " days" << std::endl; if (td_week.days() != 14) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(2, 'W') expected 14 days, got " << td_week.days() << std::endl; errors++; } } // 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) { .. _example-timedelta-max-7: .. 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-timedelta-min-8: .. 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-timedelta-minutes-9: .. dropdown:: minutes (np_test_5_all.cpp:21131) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21121 :emphasize-lines: 11 if (td.value() != expected) { std::cout << "[FAIL] np_test_timedelta_constructors: from components expected " << expected << ", got " << td.value() << std::endl; errors++; } } // From string "1 days 02:30:00" { numpy::Timedelta td("1 days 02:30:00"); if (td.days() != 1 || td.hours() != 2 || td.minutes() != 30) { std::cout << "[FAIL] np_test_timedelta_constructors: from string '1 days 02:30:00' " << "got days=" << td.days() << " hours=" << td.hours() << " minutes=" << td.minutes() << std::endl; errors++; } } // From timedelta64 { numpy::timedelta64 td64(3600, numpy::DateTimeUnit::Second); // 1 hour .. _example-timedelta-nanoseconds-10: .. dropdown:: nanoseconds (np_test_5_all.cpp:21346) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21336 :emphasize-lines: 11 if (td.milliseconds() != 100) { std::cout << "[FAIL] np_test_timedelta_components: milliseconds() expected 100, got " << td.milliseconds() << std::endl; errors++; } if (td.microseconds() != 200) { std::cout << "[FAIL] np_test_timedelta_components: microseconds() expected 200, got " << td.microseconds() << std::endl; errors++; } if (td.nanoseconds() != 300) { std::cout << "[FAIL] np_test_timedelta_components: nanoseconds() expected 300, got " << td.nanoseconds() << std::endl; errors++; } } // Components alias { numpy::Timedelta td(5, 0, 0); if (td.components_days() != 5) { .. _example-timedelta-abs-11: .. 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-timedelta-ceil-12: .. 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-timedelta-floor-13: .. 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-timedelta-round-14: .. 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-timedelta-to_chrono-15: .. dropdown:: to_chrono (np_test_5_all.cpp:21474) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21464 :emphasize-lines: 11 int64_t nanos = td.to_numpy(); if (nanos != numpy::Timedelta::NANOS_PER_DAY) { std::cout << "[FAIL] np_test_timedelta_conversions: to_numpy expected " << numpy::Timedelta::NANOS_PER_DAY << ", got " << nanos << std::endl; errors++; } } // to_chrono { std::chrono::nanoseconds dur = td.to_chrono(); if (dur.count() != numpy::Timedelta::NANOS_PER_DAY) { std::cout << "[FAIL] np_test_timedelta_conversions: to_chrono expected " << numpy::Timedelta::NANOS_PER_DAY << ", got " << dur.count() << std::endl; errors++; } } // to_chrono_duration { auto hrs = td.to_chrono_duration(); .. _example-timedelta-to_chrono_duration-16: .. dropdown:: to_chrono_duration (np_test_5_all.cpp:21484) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21474 :emphasize-lines: 11 std::chrono::nanoseconds dur = td.to_chrono(); if (dur.count() != numpy::Timedelta::NANOS_PER_DAY) { std::cout << "[FAIL] np_test_timedelta_conversions: to_chrono expected " << numpy::Timedelta::NANOS_PER_DAY << ", got " << dur.count() << std::endl; errors++; } } // to_chrono_duration { auto hrs = td.to_chrono_duration(); if (hrs.count() != 24) { std::cout << "[FAIL] np_test_timedelta_conversions: to_chrono_duration expected 24, got " << hrs.count() << std::endl; errors++; } } if (errors == 0) { std::cout << "np_test_timedelta_conversions -> tests passed" << std::endl; } .. _example-timedelta-to_numpy-17: .. dropdown:: to_numpy (np_test_5_all.cpp:21464) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21454 :emphasize-lines: 11 numpy::timedelta64 td64 = td.to_timedelta64(numpy::DateTimeUnit::Hour); if (td64.getValue() != 24) { std::cout << "[FAIL] np_test_timedelta_conversions: to_timedelta64(Hour) expected 24, got " << td64.getValue() << std::endl; errors++; } } // to_numpy { int64_t nanos = td.to_numpy(); if (nanos != numpy::Timedelta::NANOS_PER_DAY) { std::cout << "[FAIL] np_test_timedelta_conversions: to_numpy expected " << numpy::Timedelta::NANOS_PER_DAY << ", got " << nanos << std::endl; errors++; } } // to_chrono { std::chrono::nanoseconds dur = td.to_chrono(); .. _example-timedelta-to_timedelta64-18: .. dropdown:: to_timedelta64 (np_test_5_all.cpp:21444) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21434 :emphasize-lines: 11 // ============================================================================= // Test 5: Conversion Methods // ============================================================================= int np_test_timedelta_conversions() { int errors = 0; numpy::Timedelta td(1, 0, 0); // 1 day // to_timedelta64 with Day unit { numpy::timedelta64 td64 = td.to_timedelta64(numpy::DateTimeUnit::Day); if (td64.getValue() != 1) { std::cout << "[FAIL] np_test_timedelta_conversions: to_timedelta64(Day) expected 1, got " << td64.getValue() << std::endl; errors++; } } // to_timedelta64 with Hour unit { numpy::timedelta64 td64 = td.to_timedelta64(numpy::DateTimeUnit::Hour); .. _example-timedelta-nat-19: .. dropdown:: NaT (np_test_1_all.cpp:7020) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7010 :emphasize-lines: 11 // std::cout << april_2024.getElementAt({i}).toString() << " "; } // std::cout << std::endl; std::cout << " -> tests passed" << std::endl; } void testNaTHandlingDateTime() { std::cout << "========= testNaTHandlingDateTime ======================="; datetime64 nat_dt = datetime64::NaT(); timedelta64 nat_td = timedelta64::NaT(); // std::cout << "NaT datetime: " << nat_dt.toString() << std::endl; // std::cout << "NaT timedelta: " << nat_td.toString() << std::endl; datetime64 valid_date("2024-01-01"); // NaT arithmetic datetime64 result1 = valid_date + nat_td; datetime64 result2 = nat_dt + timedelta64(1, DateTimeUnit::Day); .. _example-timedelta-as_unit-20: .. dropdown:: as_unit (np_test_5_all.cpp:22957) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22947 :emphasize-lines: 11 } // Replace multiple numpy::Timestamp multi = ts.replace(2025, 7, 20, 14); if (multi.year() != 2025 || multi.month() != 7 || multi.day() != 20 || multi.hour() != 14) { pass = false; fail_msg = "Replace multiple values failed"; } // as_unit numpy::Timestamp as_unit_ts = ts.as_unit("ns"); if (as_unit_ts.isNaT()) { pass = false; fail_msg = "as_unit should not return NaT"; } if (!pass) { std::cout << " [FAIL] : in np_test_timestamp_replace() : " << fail_msg; throw std::runtime_error("np_test_timestamp_replace failed: " + fail_msg); } .. _example-timedelta-components_days-21: .. dropdown:: components_days (np_test_5_all.cpp:21356) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21346 :emphasize-lines: 11 if (td.nanoseconds() != 300) { std::cout << "[FAIL] np_test_timedelta_components: nanoseconds() expected 300, got " << td.nanoseconds() << std::endl; errors++; } } // Components alias { numpy::Timedelta td(5, 0, 0); if (td.components_days() != 5) { std::cout << "[FAIL] np_test_timedelta_components: components_days() expected 5, got " << td.components_days() << std::endl; errors++; } } if (errors == 0) { std::cout << "np_test_timedelta_components -> tests passed" << std::endl; } return errors; .. _example-timedelta-components_str-22: .. dropdown:: components_str (np_test_5_all.cpp:21550) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21540 :emphasize-lines: 11 if (iso.find("P1D") == std::string::npos) { std::cout << "[FAIL] np_test_timedelta_strings: isoformat expected 'P1D...', got '" << iso << "'" << std::endl; errors++; } } // components_str { numpy::Timedelta td(1, 2, 30, 45, 100, 200, 300); std::string comp = td.components_str(); if (comp.find("days=1") == std::string::npos) { std::cout << "[FAIL] np_test_timedelta_strings: components_str missing days=1, got '" << comp << "'" << std::endl; errors++; } } if (errors == 0) { std::cout << "np_test_timedelta_strings -> tests passed" << std::endl; } .. _example-timedelta-days-23: .. 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-timedelta-delta-24: .. dropdown:: delta (np_test_5_all.cpp:21419) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21409 :emphasize-lines: 11 // total_days { double days = td.total_days(); if (std::abs(days - 1.5) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_total_conversions: total_days expected 1.5, got " << days << std::endl; errors++; } } // value() and delta() { if (td.value() != td.delta()) { std::cout << "[FAIL] np_test_timedelta_total_conversions: value() != delta()" << std::endl; errors++; } } if (errors == 0) { std::cout << "np_test_timedelta_total_conversions -> tests passed" << std::endl; .. _example-timedelta-hours-25: .. dropdown:: hours (np_test_5_all.cpp:21131) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21121 :emphasize-lines: 11 if (td.value() != expected) { std::cout << "[FAIL] np_test_timedelta_constructors: from components expected " << expected << ", got " << td.value() << std::endl; errors++; } } // From string "1 days 02:30:00" { numpy::Timedelta td("1 days 02:30:00"); if (td.days() != 1 || td.hours() != 2 || td.minutes() != 30) { std::cout << "[FAIL] np_test_timedelta_constructors: from string '1 days 02:30:00' " << "got days=" << td.days() << " hours=" << td.hours() << " minutes=" << td.minutes() << std::endl; errors++; } } // From timedelta64 { numpy::timedelta64 td64(3600, numpy::DateTimeUnit::Second); // 1 hour .. _example-timedelta-isnat-26: .. dropdown:: isNaT (np_test_1_all.cpp:6821) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6811 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } // DateTime Functions (merged from np_test_datetime.cpp) 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; .. _example-timedelta-isoformat-27: .. dropdown:: isoformat (np_test_5_all.cpp:21539) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21529 :emphasize-lines: 11 if (nat.toString() != "NaT") { std::cout << "[FAIL] np_test_timedelta_strings: toString(NaT) expected 'NaT', got '" << nat.toString() << "'" << std::endl; errors++; } } // isoformat { numpy::Timedelta td(1, 2, 30); std::string iso = td.isoformat(); if (iso.find("P1D") == std::string::npos) { std::cout << "[FAIL] np_test_timedelta_strings: isoformat expected 'P1D...', got '" << iso << "'" << std::endl; errors++; } } // components_str { numpy::Timedelta td(1, 2, 30, 45, 100, 200, 300); .. _example-timedelta-microseconds-28: .. 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-timedelta-milliseconds-29: .. dropdown:: milliseconds (np_test_1_all.cpp:6046) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6036 :emphasize-lines: 11 // ------ merging np_test_benchmark_sorting.cpp -- number of functions merged= 11 -------------------------------- void test_timer_accuracyBenchmarkSorting() { std::cout << "========= test_timer_accuracy ======================="; Timer timer; timer.start(); // Sleep for a known duration (10ms) std::this_thread::sleep_for(std::chrono::milliseconds(10)); double elapsed = timer.elapsed_milliseconds(); // Timer should be approximately 10ms (allow 5ms tolerance for system variance) if (!(elapsed >= 3.0 && elapsed <= 105.0)) { std::string description = std::string("test_timer_accuracyBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(elapsed >= 3.0 && elapsed <= 105.0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Timer accuracy test passed. Elapsed: " << elapsed << " ms" << std::endl; .. _example-timedelta-resolution-30: .. dropdown:: resolution (np_test_5_all.cpp:21291) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21281 :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++; } } if (errors == 0) { .. _example-timedelta-seconds-31: .. dropdown:: seconds (np_test_5_all.cpp:21331) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21321 :emphasize-lines: 11 if (td.hours() != 2) { std::cout << "[FAIL] np_test_timedelta_components: hours() expected 2, got " << td.hours() << std::endl; errors++; } if (td.minutes() != 30) { std::cout << "[FAIL] np_test_timedelta_components: minutes() expected 30, got " << td.minutes() << std::endl; errors++; } if (td.seconds() != 45) { std::cout << "[FAIL] np_test_timedelta_components: seconds() expected 45, got " << td.seconds() << std::endl; errors++; } if (td.milliseconds() != 100) { std::cout << "[FAIL] np_test_timedelta_components: milliseconds() expected 100, got " << td.milliseconds() << std::endl; errors++; } if (td.microseconds() != 200) { .. _example-timedelta-tostring-32: .. 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"); .. _example-timedelta-total_days-33: .. dropdown:: total_days (np_test_5_all.cpp:21411) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21401 :emphasize-lines: 11 double hrs = td.total_hours(); if (std::abs(hrs - 36.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_total_conversions: total_hours expected 36, got " << hrs << std::endl; errors++; } } // total_days { double days = td.total_days(); if (std::abs(days - 1.5) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_total_conversions: total_days expected 1.5, got " << days << std::endl; errors++; } } // value() and delta() { if (td.value() != td.delta()) { .. _example-timedelta-total_hours-34: .. dropdown:: total_hours (np_test_5_all.cpp:21143) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21133 :emphasize-lines: 11 << "got days=" << td.days() << " hours=" << td.hours() << " minutes=" << td.minutes() << std::endl; errors++; } } // From timedelta64 { numpy::timedelta64 td64(3600, numpy::DateTimeUnit::Second); // 1 hour numpy::Timedelta td(td64); if (std::abs(td.total_hours() - 1.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: from timedelta64 expected 1 hour, got " << td.total_hours() << std::endl; errors++; } } // From std::chrono::duration { std::chrono::hours h(2); numpy::Timedelta td(h); .. _example-timedelta-total_minutes-35: .. dropdown:: total_minutes (np_test_5_all.cpp:21180) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21170 :emphasize-lines: 11 numpy::Timedelta td_days(3, "D"); // 3 days std::cout << " Timedelta(3, 'D') = " << td_days.days() << " days" << std::endl; if (td_days.days() != 3) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(3, 'D') expected 3 days, got " << td_days.days() << std::endl; errors++; } numpy::Timedelta td_min(90, "min"); // 90 minutes = 1.5 hours std::cout << " Timedelta(90, 'min') = " << td_min.total_minutes() << " minutes" << std::endl; if (std::abs(td_min.total_minutes() - 90.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(90, 'min') expected 90 minutes, got " << td_min.total_minutes() << std::endl; errors++; } numpy::Timedelta td_sec(30, "s"); // 30 seconds std::cout << " Timedelta(30, 's') = " << td_sec.total_seconds() << " seconds" << std::endl; if (std::abs(td_sec.total_seconds() - 30.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(30, 's') expected 30 seconds, got " .. _example-timedelta-total_seconds-36: .. dropdown:: total_seconds (np_test_5_all.cpp:21188) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 21178 :emphasize-lines: 11 numpy::Timedelta td_min(90, "min"); // 90 minutes = 1.5 hours std::cout << " Timedelta(90, 'min') = " << td_min.total_minutes() << " minutes" << std::endl; if (std::abs(td_min.total_minutes() - 90.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(90, 'min') expected 90 minutes, got " << td_min.total_minutes() << std::endl; errors++; } numpy::Timedelta td_sec(30, "s"); // 30 seconds std::cout << " Timedelta(30, 's') = " << td_sec.total_seconds() << " seconds" << std::endl; if (std::abs(td_sec.total_seconds() - 30.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_constructors: Timedelta(30, 's') expected 30 seconds, got " << td_sec.total_seconds() << std::endl; errors++; } numpy::Timedelta td_ms(500, "ms"); // 500 milliseconds std::cout << " Timedelta(500, 'ms') = " << td_ms.value() << " nanoseconds" << std::endl; int64_t expected_ms = 500 * numpy::Timedelta::NANOS_PER_MILLISECOND; if (td_ms.value() != expected_ms) { .. _example-timedelta-value-37: .. dropdown:: value (np_test_1_all.cpp:7786) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7776 :emphasize-lines: 11 } void testFloat16PrecisionFloat16() { std::cout << "========= testFloat16PrecisionFloat16 ======================="; // Test precision limits float16 small_val(0.0001f); float16 large_val(30000.0f); float16 very_small(1e-8f); // This might underflow to zero // std::cout << "Small value (0.0001): " << small_val << std::endl; // std::cout << "Large value (30000): " << large_val << std::endl; // std::cout << "Very small value (1e-8): " << very_small << std::endl; // Test conversion accuracy float original = 1.234f; float16 converted(original); float back_converted = static_cast(converted); // std::cout << "Original float: " << std::setprecision(10) << original << std::endl; // std::cout << "Float16 version: " << converted << std::endl;