PeriodArray =========== .. cpp:class:: numpy::PeriodArray numpy C++ class. Example ------- .. code-block:: cpp #include using namespace numpy; // Use PeriodArray PeriodArray obj; // ... operations ... Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``PeriodArray(const numpy::NDArray& data, const numpy::NDArray& mask, const std::string& freq, bool copy = false)`` - df_period_array.h:583 - * - ``PeriodArray(const numpy::NDArray& data, const std::string& freq)`` - df_period_array.h:599 - * - ``PeriodArray(const std::vector>& values, const std::string& freq)`` - df_period_array.h:641 - * - ``PeriodArray(const std::vector& period_strings, const std::string& freq)`` - df_period_array.h:661 - Construction ------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``static PeriodArray from_sequence(const std::vector>& scalars, const std::string& freq)`` - static PeriodArray - df_period_array.h:1536 - Array Creation -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool empty() const`` - bool - df_period_array.h:721 - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::int64 at(size_t index) const`` - numpy::int64 - df_period_array.h:780 - :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_period_array.h:1461 - :ref:`View ` * - ``std::optional min() const`` - std::optional - df_period_array.h:1452 - :ref:`View ` * - ``IntegerArray minute() const`` - IntegerArray - df_period_array.h:1040 - :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_period_array.h:1382 - :ref:`View ` Set Operations -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``PeriodArray unique() const`` - PeriodArray - df_period_array.h:1474 - :ref:`View ` I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::string to_string() const`` - std::string - df_period_array.h:1581 - :ref:`View ` * - ``DatetimeArray to_timestamp(const std::string& how = "start") const`` - DatetimeArray - df_period_array.h:1119 - Type Handling ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``PeriodArray copy() const`` - PeriodArray - df_period_array.h:827 - :ref:`View ` Type Checking ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``BooleanArray is_leap_year() const`` - BooleanArray - df_period_array.h:1096 - :ref:`View ` * - ``bool is_na(size_t index) const`` - bool - df_period_array.h:791 - Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional argmax() const`` - std::optional - df_period_array.h:1433 - :ref:`View ` * - ``std::optional argmin() const`` - std::optional - df_period_array.h:1414 - :ref:`View ` * - ``PeriodArray asfreq(const std::string& new_freq, const std::string& how = "end") const`` - PeriodArray - df_period_array.h:1152 - * - ``static PeriodArray concat(const std::vector& arrays)`` - static PeriodArray - df_period_array.h:1544 - * - ``size_t count() const`` - size_t - df_period_array.h:834 - :ref:`View ` * - ``const numpy::NDArray& data() const`` - const numpy::NDArray& - df_period_array.h:753 - :ref:`View ` * - ``IntegerArray day() const`` - IntegerArray - df_period_array.h:965 - :ref:`View ` * - ``IntegerArray dayofweek() const`` - IntegerArray - df_period_array.h:982 - :ref:`View ` * - ``IntegerArray dayofyear() const`` - IntegerArray - df_period_array.h:1006 - :ref:`View ` * - ``IntegerArray days_in_month() const`` - IntegerArray - df_period_array.h:1074 - :ref:`View ` * - ``days_since_epoch_to_date(days, year, month, day)`` - - df_period_array.h:1174 - * - ``PeriodArray dropna() const`` - PeriodArray - df_period_array.h:873 - * - ``dtype_type dtype() const`` - dtype_type - df_period_array.h:686 - :ref:`View ` * - ``DatetimeArray end_time() const`` - DatetimeArray - df_period_array.h:1143 - * - ``std::pair, PeriodArray> factorize() const`` - std::pair, PeriodArray> - df_period_array.h:1500 - * - ``PeriodArray fillna(numpy::int64 value) const`` - PeriodArray - df_period_array.h:859 - * - ``PeriodFrequency freq() const`` - PeriodFrequency - df_period_array.h:735 - * - ``std::string freqstr() const`` - std::string - df_period_array.h:742 - * - ``bool has_na() const`` - bool - df_period_array.h:847 - * - ``IntegerArray hour() const`` - IntegerArray - df_period_array.h:1023 - :ref:`View ` * - ``numpy::NDArray isna() const`` - numpy::NDArray - df_period_array.h:809 - * - ``size_t len() const`` - size_t - df_period_array.h:728 - * - ``const numpy::NDArray& mask() const`` - const numpy::NDArray& - df_period_array.h:760 - :ref:`View ` * - ``IntegerArray month() const`` - IntegerArray - df_period_array.h:924 - :ref:`View ` * - ``size_t nbytes() const`` - size_t - df_period_array.h:700 - :ref:`View ` * - ``constexpr int ndim() const`` - constexpr int - df_period_array.h:707 - :ref:`View ` * - ``numpy::NDArray notna() const`` - numpy::NDArray - df_period_array.h:816 - * - ``numpy::int64 ordinal(size_t index) const`` - numpy::int64 - df_period_array.h:798 - * - ``ordinal_to_day(data\_.getElementAt(`` - - df_period_array.h:973 - * - ``ordinal_to_dayofweek(data\_.getElementAt(`` - - df_period_array.h:990 - * - ``ordinal_to_dayofyear(data\_.getElementAt(`` - - df_period_array.h:1014 - * - ``ordinal_to_hour(data\_.getElementAt(`` - - df_period_array.h:1031 - * - ``ordinal_to_minute(data\_.getElementAt(`` - - df_period_array.h:1048 - * - ``ordinal_to_month(data\_.getElementAt(`` - - df_period_array.h:932 - * - ``ordinal_to_quarter(data\_.getElementAt(`` - - df_period_array.h:915 - * - ``ordinal_to_second(data\_.getElementAt(`` - - df_period_array.h:1065 - * - ``ordinal_to_week(data\_.getElementAt(`` - - df_period_array.h:949 - * - ``ordinal_to_year(data\_.getElementAt(`` - - df_period_array.h:898 - * - ``IntegerArray quarter() const`` - IntegerArray - df_period_array.h:907 - :ref:`View ` * - ``std::string repr() const`` - std::string - df_period_array.h:1603 - * - ``IntegerArray second() const`` - IntegerArray - df_period_array.h:1057 - :ref:`View ` * - ``std::vector shape() const`` - std::vector - df_period_array.h:714 - :ref:`View ` * - ``size_t size() const`` - size_t - df_period_array.h:693 - :ref:`View ` * - ``DatetimeArray start_time() const`` - DatetimeArray - df_period_array.h:1136 - * - ``void validate_arrays()`` - void - df_period_array.h:543 - * - ``IntegerArray week() const`` - IntegerArray - df_period_array.h:941 - :ref:`View ` * - ``IntegerArray weekday() const`` - IntegerArray - df_period_array.h:999 - :ref:`View ` * - ``IntegerArray weekofyear() const`` - IntegerArray - df_period_array.h:958 - * - ``IntegerArray year() const`` - IntegerArray - df_period_array.h:890 - :ref:`View ` Code Examples ------------- The following examples are extracted from the test suite. .. _example-periodarray-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-periodarray-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-periodarray-max-2: .. 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-periodarray-min-3: .. 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-periodarray-minute-4: .. dropdown:: minute (np_test_5_all.cpp:22186) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22176 :emphasize-lines: 11 errors++; } numpy::Timedelta td3("45s"); if (std::abs(td3.total_seconds() - 45.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_edge_cases: '45s' expected 45 sec" << std::endl; errors++; } numpy::Timedelta td4("NaT"); if (!td4.isNaT()) { std::cout << "[FAIL] np_test_timedelta_edge_cases: 'NaT' should parse to NaT" << std::endl; errors++; } } // Stream operator { numpy::Timedelta td(1, 2, 30); .. _example-periodarray-argsort-5: .. 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-periodarray-unique-6: .. 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-periodarray-to_string-7: .. 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-periodarray-copy-8: .. 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-periodarray-is_leap_year-9: .. dropdown:: is_leap_year (np_test_5_all.cpp:22577) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22567 :emphasize-lines: 11 numpy::Timestamp::strptime("", "%Y-%m-%d"); } catch (const std::invalid_argument&) { threw = true; } if (!threw) { throw std::runtime_error("strptime failed: should throw for empty string"); } // Test 9: Empty format should throw threw = false; try { numpy::Timestamp::strptime("2024-03-15", ""); } catch (const std::invalid_argument&) { threw = true; } if (!threw) { throw std::runtime_error("strptime failed: should throw for empty format"); } // Test 10: Literal percent numpy::Timestamp ts10 = numpy::Timestamp::strptime("100%2024-03-15", "100%%%Y-%m-%d"); .. _example-periodarray-argmax-10: .. 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-periodarray-argmin-11: .. 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-periodarray-count-12: .. 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-periodarray-data-13: .. 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-periodarray-day-14: .. dropdown:: day (np_test_5_all.cpp:22185) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22175 :emphasize-lines: 11 << std::endl; errors++; } numpy::Timedelta td3("45s"); if (std::abs(td3.total_seconds() - 45.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_edge_cases: '45s' expected 45 sec" << std::endl; errors++; } numpy::Timedelta td4("NaT"); if (!td4.isNaT()) { std::cout << "[FAIL] np_test_timedelta_edge_cases: 'NaT' should parse to NaT" << std::endl; errors++; } } // Stream operator { .. _example-periodarray-dayofweek-15: .. dropdown:: dayofweek (np_test_5_all.cpp:22547) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22537 :emphasize-lines: 11 throw std::runtime_error("strptime failed: American format parsing"); } // Test 4: 2-digit year numpy::Timestamp ts4 = numpy::Timestamp::strptime("03/15/24", "%m/%d/%y"); if (ts4.year() != 2024) { throw std::runtime_error("strptime failed: 2-digit year parsing"); } // Test 5: With microseconds numpy::Timestamp ts5 = numpy::Timestamp::strptime("2024-03-15 14:30:45.123456", "%Y-%m-%d %H:%M:%S.%f"); if (ts5.microsecond() != 123456) { throw std::runtime_error("strptime failed: microseconds parsing"); } // Test 6: 12-hour format with AM/PM numpy::Timestamp ts6 = numpy::Timestamp::strptime("03/15/2024 02:30:00 PM", "%m/%d/%Y %I:%M:%S %p"); if (ts6.hour() != 14) { throw std::runtime_error("strptime failed: 12-hour format parsing"); } .. _example-periodarray-dayofyear-16: .. dropdown:: dayofyear (np_test_5_all.cpp:22549) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22539 :emphasize-lines: 11 // Test 4: 2-digit year numpy::Timestamp ts4 = numpy::Timestamp::strptime("03/15/24", "%m/%d/%y"); if (ts4.year() != 2024) { throw std::runtime_error("strptime failed: 2-digit year parsing"); } // Test 5: With microseconds numpy::Timestamp ts5 = numpy::Timestamp::strptime("2024-03-15 14:30:45.123456", "%Y-%m-%d %H:%M:%S.%f"); if (ts5.microsecond() != 123456) { throw std::runtime_error("strptime failed: microseconds parsing"); } // Test 6: 12-hour format with AM/PM numpy::Timestamp ts6 = numpy::Timestamp::strptime("03/15/2024 02:30:00 PM", "%m/%d/%Y %I:%M:%S %p"); if (ts6.hour() != 14) { throw std::runtime_error("strptime failed: 12-hour format parsing"); } // Test 7: Day of year format numpy::Timestamp ts7 = numpy::Timestamp::strptime("2024-075", "%Y-%j"); .. _example-periodarray-days_in_month-17: .. dropdown:: days_in_month (np_test_5_all.cpp:22552) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22542 :emphasize-lines: 11 if (ts4.year() != 2024) { throw std::runtime_error("strptime failed: 2-digit year parsing"); } // Test 5: With microseconds numpy::Timestamp ts5 = numpy::Timestamp::strptime("2024-03-15 14:30:45.123456", "%Y-%m-%d %H:%M:%S.%f"); if (ts5.microsecond() != 123456) { throw std::runtime_error("strptime failed: microseconds parsing"); } // Test 6: 12-hour format with AM/PM numpy::Timestamp ts6 = numpy::Timestamp::strptime("03/15/2024 02:30:00 PM", "%m/%d/%Y %I:%M:%S %p"); if (ts6.hour() != 14) { throw std::runtime_error("strptime failed: 12-hour format parsing"); } // Test 7: Day of year format numpy::Timestamp ts7 = numpy::Timestamp::strptime("2024-075", "%Y-%j"); if (ts7.month() != 3 || ts7.day() != 15) { // Day 75 of 2024 is March 15 throw std::runtime_error("strptime failed: day of year parsing"); } .. _example-periodarray-dtype-18: .. 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-periodarray-hour-19: .. dropdown:: hour (np_test_5_all.cpp:22186) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22176 :emphasize-lines: 11 errors++; } numpy::Timedelta td3("45s"); if (std::abs(td3.total_seconds() - 45.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_edge_cases: '45s' expected 45 sec" << std::endl; errors++; } numpy::Timedelta td4("NaT"); if (!td4.isNaT()) { std::cout << "[FAIL] np_test_timedelta_edge_cases: 'NaT' should parse to NaT" << std::endl; errors++; } } // Stream operator { numpy::Timedelta td(1, 2, 30); .. _example-periodarray-mask-20: .. 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-periodarray-month-21: .. dropdown:: month (np_test_5_all.cpp:22185) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22175 :emphasize-lines: 11 << std::endl; errors++; } numpy::Timedelta td3("45s"); if (std::abs(td3.total_seconds() - 45.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_edge_cases: '45s' expected 45 sec" << std::endl; errors++; } numpy::Timedelta td4("NaT"); if (!td4.isNaT()) { std::cout << "[FAIL] np_test_timedelta_edge_cases: 'NaT' should parse to NaT" << std::endl; errors++; } } // Stream operator { .. _example-periodarray-nbytes-22: .. 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-periodarray-ndim-23: .. 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-periodarray-quarter-24: .. dropdown:: quarter (np_test_5_all.cpp:22551) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22541 :emphasize-lines: 11 numpy::Timestamp ts4 = numpy::Timestamp::strptime("03/15/24", "%m/%d/%y"); if (ts4.year() != 2024) { throw std::runtime_error("strptime failed: 2-digit year parsing"); } // Test 5: With microseconds numpy::Timestamp ts5 = numpy::Timestamp::strptime("2024-03-15 14:30:45.123456", "%Y-%m-%d %H:%M:%S.%f"); if (ts5.microsecond() != 123456) { throw std::runtime_error("strptime failed: microseconds parsing"); } // Test 6: 12-hour format with AM/PM numpy::Timestamp ts6 = numpy::Timestamp::strptime("03/15/2024 02:30:00 PM", "%m/%d/%Y %I:%M:%S %p"); if (ts6.hour() != 14) { throw std::runtime_error("strptime failed: 12-hour format parsing"); } // Test 7: Day of year format numpy::Timestamp ts7 = numpy::Timestamp::strptime("2024-075", "%Y-%j"); if (ts7.month() != 3 || ts7.day() != 15) { // Day 75 of 2024 is March 15 throw std::runtime_error("strptime failed: day of year parsing"); .. _example-periodarray-second-25: .. dropdown:: second (np_test_5_all.cpp:22186) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22176 :emphasize-lines: 11 errors++; } numpy::Timedelta td3("45s"); if (std::abs(td3.total_seconds() - 45.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_edge_cases: '45s' expected 45 sec" << std::endl; errors++; } numpy::Timedelta td4("NaT"); if (!td4.isNaT()) { std::cout << "[FAIL] np_test_timedelta_edge_cases: 'NaT' should parse to NaT" << std::endl; errors++; } } // Stream operator { numpy::Timedelta td(1, 2, 30); .. _example-periodarray-shape-26: .. 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-periodarray-size-27: .. 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-periodarray-week-28: .. dropdown:: week (np_test_1_all.cpp:27347) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27337 :emphasize-lines: 11 std::cout << "========= busday_offset: forward offset ======================="; // Start on Monday, offset by 5 business days -> should be next Monday NDArray dates({ 1 }); NDArray offsets({ 1 }); dates.setElementAt({ 0 }, datetime64(19723, DateTimeUnit::Day)); // 2024-01-01 (Monday) offsets.setElementAt({ 0 }, int64_t(5)); auto result = busday_offset(dates, offsets); // Expected: Monday + 5 business days = Monday next week (skipping weekend) datetime64 expected(19730, DateTimeUnit::Day); // 2024-01-08 (Monday) if (result.getElementAt({ 0 }) != expected) { std::cout << " [FAIL] : in test_busday_offset_forward() : incorrect offset result"; throw std::runtime_error("busday_offset forward test failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-periodarray-weekday-29: .. dropdown:: weekday (np_test_5_all.cpp:22772) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22762 :emphasize-lines: 11 // timestamp double posix = ts.timestamp(); if (posix <= 0) { pass = false; fail_msg = "POSIX timestamp should be positive"; } // timetuple auto [y, mo, d, h, mi, s] = ts.timetuple(); if (y != 2024 || mo != 6) { pass = false; fail_msg = "timetuple values incorrect"; } // date/time tuples auto [dy, dm, dd] = ts.date(); if (dy != 2024) { pass = false; fail_msg = "date tuple year"; } auto [th, tmi, ts2, tus] = ts.time(); if (th != 12) { pass = false; fail_msg = "time tuple hour"; } // Julian date double jd = ts.to_julian_date(); if (jd < 2400000) { pass = false; fail_msg = "Julian date should be reasonable"; } // Ordinal int ord = ts.toordinal(); .. _example-periodarray-year-30: .. dropdown:: year (np_test_5_all.cpp:22185) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22175 :emphasize-lines: 11 << std::endl; errors++; } numpy::Timedelta td3("45s"); if (std::abs(td3.total_seconds() - 45.0) > 0.0001) { std::cout << "[FAIL] np_test_timedelta_edge_cases: '45s' expected 45 sec" << std::endl; errors++; } numpy::Timedelta td4("NaT"); if (!td4.isNaT()) { std::cout << "[FAIL] np_test_timedelta_edge_cases: 'NaT' should parse to NaT" << std::endl; errors++; } } // Stream operator {