TimedeltaIndex ============== .. cpp:class:: numpy::TimedeltaIndex numpy C++ class. Example ------- .. code-block:: cpp #include using namespace numpy; // Use TimedeltaIndex TimedeltaIndex obj; // ... operations ... Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``explicit TimedeltaIndex(const TimedeltaArray& arr, const std::optional& name = std::nullopt)`` - df_timedelta_index.h:111 - * - ``explicit TimedeltaIndex(TimedeltaArray&& arr, const std::optional& name = std::nullopt)`` - df_timedelta_index.h:121 - * - ``explicit TimedeltaIndex(const std::vector& values, const std::optional& name = std::nullopt)`` - df_timedelta_index.h:131 - * - ``explicit TimedeltaIndex(const std::vector>& values, const std::optional& name = std::nullopt)`` - df_timedelta_index.h:149 - * - ``TimedeltaIndex(const TimedeltaIndex& other)`` - df_timedelta_index.h:160 - * - ``TimedeltaIndex(TimedeltaIndex&& other) noexcept`` - df_timedelta_index.h:167 - Indexing / Selection -------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::NDArray get_indexer(const TimedeltaIndex& target) const`` - numpy::NDArray - df_timedelta_index.h:1382 - * - ``numpy::NDArray get_indexer_for(const std::vector& values) const`` - numpy::NDArray - df_timedelta_index.h:1426 - * - ``get_indexer_non_unique(const TimedeltaIndex& target) const`` - - df_timedelta_index.h:1459 - * - ``TimedeltaIndex get_level_values(int level = 0) const`` - TimedeltaIndex - df_timedelta_index.h:1521 - * - ``int64_t get_loc(int64_t key) const`` - int64_t - df_timedelta_index.h:1534 - * - ``size_t get_slice_bound(int64_t label, const std::string& side) const`` - size_t - df_timedelta_index.h:1557 - * - ``numpy::timedelta64 item() const`` - numpy::timedelta64 - df_timedelta_index.h:1879 - :ref:`View ` * - ``TimedeltaIndex putmask(const BooleanArray& mask, const numpy::timedelta64& value) const`` - TimedeltaIndex - df_timedelta_index.h:2043 - :ref:`View ` * - ``size_t searchsorted(int64_t value, const std::string& side = "left") const`` - size_t - df_timedelta_index.h:2168 - :ref:`View ` * - ``TimedeltaIndex take(const std::vector& indices) const`` - TimedeltaIndex - df_timedelta_index.h:2377 - :ref:`View ` * - ``TimedeltaIndex where(const BooleanArray& cond, const numpy::timedelta64& other) const`` - TimedeltaIndex - df_timedelta_index.h:2736 - :ref:`View ` * - ``TimedeltaIndex where(const BooleanArray& cond) const`` - TimedeltaIndex - df_timedelta_index.h:2761 - :ref:`View ` Shape Manipulation ------------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``TimedeltaIndex T() const`` - TimedeltaIndex - df_timedelta_index.h:2612 - :ref:`View ` * - ``std::vector> ravel() const`` - std::vector> - df_timedelta_index.h:2071 - :ref:`View ` * - ``TimedeltaIndex transpose() const`` - TimedeltaIndex - df_timedelta_index.h:2605 - :ref:`View ` Statistics ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional max(bool skipna = true) const`` - std::optional - df_timedelta_index.h:462 - :ref:`View ` * - ``std::optional median(bool skipna = true) const`` - std::optional - df_timedelta_index.h:1956 - :ref:`View ` * - ``std::optional min(bool skipna = true) const`` - std::optional - df_timedelta_index.h:431 - :ref:`View ` * - ``IntegerArray nanoseconds() const`` - IntegerArray - df_timedelta_index.h:243 - :ref:`View ` * - ``std::optional std(bool skipna = true) const`` - std::optional - df_timedelta_index.h:577 - :ref:`View ` * - ``std::optional sum(bool skipna = true) const`` - std::optional - df_timedelta_index.h:493 - :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_index.h:809 - :ref:`View ` * - ``TimedeltaIndex sort(bool ascending = true) const`` - TimedeltaIndex - df_timedelta_index.h:2299 - :ref:`View ` * - ``TimedeltaIndex sort_values(bool ascending = true, const std::string& na_position = "last") const`` - TimedeltaIndex - df_timedelta_index.h:2309 - * - ``sortlevel(int level = 0, bool ascending = true) const`` - - df_timedelta_index.h:2328 - Math Operations --------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``TimedeltaIndex ceil(const std::string& freq) const`` - TimedeltaIndex - df_timedelta_index.h:395 - :ref:`View ` * - ``TimedeltaIndex floor(const std::string& freq) const`` - TimedeltaIndex - df_timedelta_index.h:385 - :ref:`View ` * - ``TimedeltaIndex round(const std::string& freq) const`` - TimedeltaIndex - df_timedelta_index.h:375 - :ref:`View ` Comparison ---------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool equals(const TimedeltaIndex& other) const`` - bool - df_timedelta_index.h:1309 - Logical ------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool all(bool skipna = true) const`` - bool - df_timedelta_index.h:713 - :ref:`View ` * - ``bool any(bool skipna = true) const`` - bool - df_timedelta_index.h:735 - :ref:`View ` Set Operations -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``BooleanArray isin(const std::vector& values) const`` - BooleanArray - df_timedelta_index.h:1803 - :ref:`View ` * - ``TimedeltaIndex unique() const`` - TimedeltaIndex - df_timedelta_index.h:2672 - :ref:`View ` I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``TimedeltaIndex to_flat_index() const`` - TimedeltaIndex - df_timedelta_index.h:2400 - * - ``FrameData to_frame(bool index = true, const std::optional& name = std::nullopt) const`` - FrameData - df_timedelta_index.h:2514 - * - ``std::vector to_frame_values(bool index = true) const`` - std::vector - df_timedelta_index.h:2414 - * - ``std::vector> to_list() const`` - std::vector> - df_timedelta_index.h:2437 - * - ``numpy::NDArray to_numpy() const`` - numpy::NDArray - df_timedelta_index.h:2456 - :ref:`View ` * - ``std::vector> to_pytimedelta() const`` - std::vector> - df_timedelta_index.h:362 - * - ``SeriesData to_series(const std::optional& index = std::nullopt, const std::optional& name = std::nullopt) const`` - SeriesData - df_timedelta_index.h:2573 - * - ``std::vector> to_series_values() const`` - std::vector> - df_timedelta_index.h:2468 - * - ``std::string to_string() const override`` - std::string - df_timedelta_index.h:655 - :ref:`View ` * - ``std::vector> tolist() const`` - std::vector> - df_timedelta_index.h:2444 - :ref:`View ` Joining / Splitting ------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``TimedeltaIndex append(const TimedeltaIndex& other) const`` - TimedeltaIndex - df_timedelta_index.h:780 - :ref:`View ` * - ``TimedeltaIndex append(const std::vector& others) const`` - TimedeltaIndex - df_timedelta_index.h:789 - :ref:`View ` * - ``TimedeltaIndex delete\_(size_t loc) const`` - TimedeltaIndex - df_timedelta_index.h:992 - :ref:`View ` * - ``TimedeltaIndex delete\_(const std::vector& locs) const`` - TimedeltaIndex - df_timedelta_index.h:1011 - :ref:`View ` * - ``TimedeltaIndex insert(size_t loc, const numpy::timedelta64& item) const`` - TimedeltaIndex - df_timedelta_index.h:1655 - :ref:`View ` * - ``TimedeltaIndex repeat(size_t repeats) const`` - TimedeltaIndex - df_timedelta_index.h:2120 - :ref:`View ` * - ``TimedeltaIndex repeat(const std::vector& repeats) const`` - TimedeltaIndex - df_timedelta_index.h:2138 - :ref:`View ` Type Handling ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``AsTypeResult astype(const std::string& dtype, bool copy_data = true) const`` - AsTypeResult - df_timedelta_index.h:921 - :ref:`View ` * - ``numpy::NDArray astype_int64() const`` - numpy::NDArray - df_timedelta_index.h:871 - * - ``TimedeltaIndex copy(const std::optional& name = std::nullopt) const`` - TimedeltaIndex - df_timedelta_index.h:631 - :ref:`View ` * - ``TimedeltaIndex view() const`` - TimedeltaIndex - df_timedelta_index.h:2722 - :ref:`View ` Type Checking ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool is\_(const TimedeltaIndex& other) const`` - bool - df_timedelta_index.h:1730 - * - ``bool is_boolean() const`` - bool - df_timedelta_index.h:1742 - * - ``bool is_categorical() const`` - bool - df_timedelta_index.h:1750 - * - ``bool is_floating() const`` - bool - df_timedelta_index.h:1758 - * - ``bool is_integer() const`` - bool - df_timedelta_index.h:1766 - * - ``bool is_interval() const`` - bool - df_timedelta_index.h:1774 - * - ``bool is_numeric() const`` - bool - df_timedelta_index.h:1782 - :ref:`View ` * - ``bool is_object() const`` - bool - df_timedelta_index.h:1790 - Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``int64_t argmax() const`` - int64_t - df_timedelta_index.h:552 - :ref:`View ` * - ``int64_t argmin() const`` - int64_t - df_timedelta_index.h:528 - :ref:`View ` * - ``TimedeltaArray arr(opt_values)`` - TimedeltaArray - df_timedelta_index.h:140 - :ref:`View ` * - ``TimedeltaArray arr(values)`` - TimedeltaArray - df_timedelta_index.h:153 - :ref:`View ` * - ``TimedeltaIndex as_unit(const std::string& target_unit) const`` - TimedeltaIndex - df_timedelta_index.h:405 - :ref:`View ` * - ``int64_t asof(int64_t label) const`` - int64_t - df_timedelta_index.h:829 - * - ``std::vector asof_locs(const std::vector& labels) const`` - std::vector - df_timedelta_index.h:854 - * - ``std::unique_ptr clone() const override`` - std::unique_ptr - df_timedelta_index.h:622 - :ref:`View ` * - ``TimedeltaComponents components() const`` - TimedeltaComponents - df_timedelta_index.h:251 - :ref:`View ` * - ``static TimedeltaIndex concat(const std::vector& indexes)`` - static TimedeltaIndex - df_timedelta_index.h:760 - * - ``IntegerArray days() const`` - IntegerArray - df_timedelta_index.h:219 - :ref:`View ` * - ``TimedeltaIndex diff(int64_t periods = 1) const`` - TimedeltaIndex - df_timedelta_index.h:1031 - :ref:`View ` * - ``TimedeltaIndex diff_idx(TimedeltaArray(result), this->name())`` - TimedeltaIndex - df_timedelta_index.h:1108 - * - ``TimedeltaIndex difference(const TimedeltaIndex& other, bool sort = true) const`` - TimedeltaIndex - df_timedelta_index.h:1079 - :ref:`View ` * - ``TimedeltaIndex drop(const std::vector& labels) const`` - TimedeltaIndex - df_timedelta_index.h:1124 - * - ``TimedeltaIndex drop_duplicates(const std::string& keep = "first") const`` - TimedeltaIndex - df_timedelta_index.h:1151 - * - ``TimedeltaIndex droplevel(int level = 0) const`` - TimedeltaIndex - df_timedelta_index.h:1222 - * - ``TimedeltaIndex dropna() const`` - TimedeltaIndex - df_timedelta_index.h:1234 - * - ``std::string dtype_str() const`` - std::string - df_timedelta_index.h:207 - * - ``BooleanArray duplicated(const std::string& keep = "first") const`` - BooleanArray - df_timedelta_index.h:1248 - * - ``std::pair, TimedeltaIndex> factorize() const`` - std::pair, TimedeltaIndex> - df_timedelta_index.h:1336 - * - ``TimedeltaIndex fillna(const numpy::timedelta64& value) const`` - TimedeltaIndex - df_timedelta_index.h:1350 - * - ``numpy::NDArray float_arr(std::vector`` - numpy::NDArray - df_timedelta_index.h:949 - :ref:`View ` * - ``std::vector format(const std::string& formatter = "") const`` - std::vector - df_timedelta_index.h:1364 - :ref:`View ` * - ``std::unordered_map> groupby(KeyFunc key_func) const`` - std::unordered_map> - df_timedelta_index.h:1593 - * - ``bool holds_integer() const`` - bool - df_timedelta_index.h:1616 - * - ``bool identical(const TimedeltaIndex& other) const`` - bool - df_timedelta_index.h:1629 - * - ``\* TimedeltaIndex idx(`` - \* TimedeltaIndex - df_timedelta_index.h:916 - :ref:`View ` * - ``\* TimedeltaIndex idx(`` - \* TimedeltaIndex - df_timedelta_index.h:2503 - :ref:`View ` * - ``\* TimedeltaIndex idx(`` - \* TimedeltaIndex - df_timedelta_index.h:2566 - :ref:`View ` * - ``numpy::NDArray indexer_arr(std::vector`` - numpy::NDArray - df_timedelta_index.h:1499 - * - ``TimedeltaIndex infer_objects() const`` - TimedeltaIndex - df_timedelta_index.h:1641 - * - ``std::string inferred_type() const override`` - std::string - df_timedelta_index.h:199 - * - ``numpy::NDArray int_arr(std::vector`` - numpy::NDArray - df_timedelta_index.h:937 - :ref:`View ` * - ``numpy::NDArray int_result(std::vector`` - numpy::NDArray - df_timedelta_index.h:813 - * - ``TimedeltaIndex inter_idx(TimedeltaArray(result), this->name())`` - TimedeltaIndex - df_timedelta_index.h:1714 - * - ``TimedeltaIndex intersection(const TimedeltaIndex& other, bool sort = false) const`` - TimedeltaIndex - df_timedelta_index.h:1685 - * - ``BooleanArray isna() const`` - BooleanArray - df_timedelta_index.h:1833 - * - ``BooleanArray isnull() const`` - BooleanArray - df_timedelta_index.h:1846 - * - ``TimedeltaIndex join(const TimedeltaIndex& other, const std::string& how = "left") const`` - TimedeltaIndex - df_timedelta_index.h:1904 - :ref:`View ` * - ``TimedeltaIndex map(std::function func) const`` - TimedeltaIndex - df_timedelta_index.h:1926 - * - ``size_t memory_usage(bool deep = true) const`` - size_t - df_timedelta_index.h:1997 - * - ``IntegerArray microseconds() const`` - IntegerArray - df_timedelta_index.h:235 - :ref:`View ` * - ``numpy::NDArray missing_arr(std::vector`` - numpy::NDArray - df_timedelta_index.h:1504 - * - ``BooleanArray notna() const`` - BooleanArray - df_timedelta_index.h:1854 - * - ``BooleanArray notnull() const`` - BooleanArray - df_timedelta_index.h:1867 - * - ``size_t nunique(bool dropna = true) const`` - size_t - df_timedelta_index.h:2010 - * - ``reindex(const TimedeltaIndex& target, const std::string& method = "") const`` - - df_timedelta_index.h:2092 - * - ``TimedeltaIndex rename(const std::optional& new_name) const`` - TimedeltaIndex - df_timedelta_index.h:643 - * - ``std::string repr() const`` - std::string - df_timedelta_index.h:696 - * - ``std::vector> result(this->size(), false)`` - std::vector> - df_timedelta_index.h:1250 - :ref:`View ` * - ``IntegerArray seconds() const`` - IntegerArray - df_timedelta_index.h:227 - :ref:`View ` * - ``TimedeltaIndex set_names(const std::string& names) const`` - TimedeltaIndex - df_timedelta_index.h:2212 - * - ``TimedeltaIndex set_names() const`` - TimedeltaIndex - df_timedelta_index.h:2220 - * - ``TimedeltaIndex shift(int64_t periods, const std::optional& freq = std::nullopt) const`` - TimedeltaIndex - df_timedelta_index.h:416 - :ref:`View ` * - ``TimedeltaIndex slice(size_t start, size_t stop, size_t step = 1) const`` - TimedeltaIndex - df_timedelta_index.h:2235 - :ref:`View ` * - ``std::vector slice_indexer( const std::optional& start = std::nullopt, const std::optional& stop = std::nullopt, size_t step = 1) const`` - std::vector - df_timedelta_index.h:2276 - * - ``std::pair slice_locs( const std::optional& start = std::nullopt, const std::optional& stop = std::nullopt) const`` - std::pair - df_timedelta_index.h:2252 - * - ``TimedeltaIndex symmetric_difference(const TimedeltaIndex& other, bool sort = true) const`` - TimedeltaIndex - df_timedelta_index.h:2358 - * - ``TimedeltaIndex union\_(const TimedeltaIndex& other, bool sort = true) const`` - TimedeltaIndex - df_timedelta_index.h:2626 - * - ``TimedeltaIndex union_idx(TimedeltaArray(result), this->name())`` - TimedeltaIndex - df_timedelta_index.h:2657 - * - ``value_counts(bool dropna = true) const`` - - df_timedelta_index.h:2687 - Code Examples ------------- The following examples are extracted from the test suite. .. _example-timedeltaindex-item-0: .. dropdown:: item (np_test_4_all.cpp:20048) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20038 :emphasize-lines: 11 /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" #include "../numpy/np_masked_array.h" #include .. _example-timedeltaindex-putmask-1: .. dropdown:: putmask (np_test_5_all.cpp:4659) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4649 :emphasize-lines: 11 mask.setElementAt({ 1 }, false); mask.setElementAt({ 2 }, true); mask.setElementAt({ 3 }, false); mask.setElementAt({ 4 }, true); // Create value array numpy::NDArray values({ 1 }); values.setElementAt({ 0 }, 99); // Apply putmask numpy::putmask(arr, mask, values); // Expected: [99, 2, 99, 4, 99] if (arr.getElementAt({ 0 }) != 99 || arr.getElementAt({ 1 }) != 2 || arr.getElementAt({ 2 }) != 99 || arr.getElementAt({ 3 }) != 4 || arr.getElementAt({ 4 }) != 99) { std::cout << " [FAIL] : in np_test_putmask() : Incorrect result"; throw std::runtime_error("Test failed"); } // Test with multiple values .. _example-timedeltaindex-searchsorted-2: .. dropdown:: searchsorted (np_test_2_all.cpp:8204) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 8194 :emphasize-lines: 11 // Test missing NumPy functions void test_numpy_functions() { std::cout << "========= NumPy Functions Test =========================="; // Test searchsorted { std::vector sorted_arr = { 1, 3, 5, 7, 9 }; std::vector values = { 2, 6, 8 }; auto result = numpy::searchsorted(sorted_arr, values, "left"); std::vector expected = { 1, 3, 4 }; if (result != expected) { std::cout << " searchsorted (left): -> [FAIL]"; throw std::runtime_error("searchsorted (left): FAILED - incorrect result indices"); } // std::cout << "[OK] searchsorted (left): PASSED" << std::endl; auto result_right = numpy::searchsorted(sorted_arr, values, "right"); std::vector expected_right = { 1, 3, 4 }; .. _example-timedeltaindex-take-3: .. 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-timedeltaindex-where-4: .. dropdown:: where (np_test_3_all.cpp:15253) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15243 :emphasize-lines: 11 auto y_data = createInt32Array({ 4 }, 0); y_data.setElementAt({ 0 }, 100); y_data.setElementAt({ 1 }, 200); y_data.setElementAt({ 2 }, 300); y_data.setElementAt({ 3 }, 400); auto y_mask = createBoolArray({ 4 }, false); MaskedArray y(y_data, y_mask, -999); // Test where() selection auto result = where(condition, x, y); if (!(result.getElementAt({ 0 }) == 10)) { std::string description = std::string("test_where_selection():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 0 }) == 10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.getElementAt({ 1 }) == 200)) { std::string description = std::string("test_where_selection():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 1 }) == 200)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-timedeltaindex-where-5: .. dropdown:: where (np_test_3_all.cpp:15253) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 15243 :emphasize-lines: 11 auto y_data = createInt32Array({ 4 }, 0); y_data.setElementAt({ 0 }, 100); y_data.setElementAt({ 1 }, 200); y_data.setElementAt({ 2 }, 300); y_data.setElementAt({ 3 }, 400); auto y_mask = createBoolArray({ 4 }, false); MaskedArray y(y_data, y_mask, -999); // Test where() selection auto result = where(condition, x, y); if (!(result.getElementAt({ 0 }) == 10)) { std::string description = std::string("test_where_selection():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 0 }) == 10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.getElementAt({ 1 }) == 200)) { std::string description = std::string("test_where_selection():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.getElementAt({ 1 }) == 200)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-timedeltaindex-t-6: .. dropdown:: T (np_test_1_all.cpp:20062) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20052 :emphasize-lines: 11 std::mt19937 gen; public: MatrixGenerator(unsigned seed = 12345) : gen(seed) {} // Generate real matrix with known real eigenvalues NDArray real_matrix_real_eigenvalues(size_t n) { // Create diagonal matrix with known eigenvalues NDArray D = NDArray::createZeros({ n, n }); for (size_t i = 0; i < n; ++i) { D.setElementAt({ i, i }, T(i + 1)); // Eigenvalues 1, 2, 3, ... } // Create random orthogonal transformation auto Q = random_orthogonal_matrix(n); auto QT = Q.transposeArray(); // A = Q * D * Q^T return matmul(matmul(Q, D), QT); } .. _example-timedeltaindex-ravel-7: .. dropdown:: ravel (np_test_1_all.cpp:4082) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4072 :emphasize-lines: 11 std::cout << "Testing ravel function...\n"; // Test with 2-D array auto arr_2d = createFloat64Array({ 2, 3 }); for (size_t i = 0; i < 2; ++i) { for (size_t j = 0; j < 3; ++j) { arr_2d.setElementAt({ i, j }, static_cast(i * 3 + j)); } } auto raveled = ravel(arr_2d); if (!(raveled.getShape() == std::vector({ 6 }))) { std::string description = std::string("testRavelFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(raveled.getShape() == std::vector({ 6 }))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } for (size_t i = 0; i < 6; ++i) { if (!(isApproxEqualExt(raveled.getElementAt({ i }), static_cast(i)))) { std::string description = std::string("testRavelFunction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(isApproxEqualExt(raveled.getElementAt({ i }), static_cast(i)))"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-timedeltaindex-transpose-8: .. dropdown:: transpose (np_test_2_all.cpp:4973) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4963 :emphasize-lines: 11 } /** * Test matrix properties and methods */ void testMatrixProperties() { std::cout << "========= testMatrixProperties ======================="; // Test transpose numpy::Matrix m("1 2 3; 4 5 6"); auto mt = m.transpose(); assert_test(mt.rows() == 3, "Transpose rows"); assert_test(mt.cols() == 2, "Transpose cols"); assert_test(std::abs(mt(0, 1) - 4.0) < 1e-10, "Transpose element"); assert_test(std::abs(mt(2, 0) - 3.0) < 1e-10, "Transpose element"); // Test trace for square matrix numpy::Matrix square("1 2; 3 4"); double tr = square.trace(); assert_test(std::abs(tr - 5.0) < 1e-10, "Matrix trace"); .. _example-timedeltaindex-max-9: .. 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-timedeltaindex-median-10: .. dropdown:: median (np_test_1_all.cpp:11882) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11872 :emphasize-lines: 11 std::cout << "========= testMedianAndPercentiles ======================="; // Test median with odd number of elements auto odd_array = createInt32Array({ 5 }, 0); odd_array.setElementAt({ 0 }, 1); odd_array.setElementAt({ 1 }, 3); odd_array.setElementAt({ 2 }, 5); odd_array.setElementAt({ 3 }, 7); odd_array.setElementAt({ 4 }, 9); auto median_odd = median(odd_array); if (!(approx_equal(median_odd.getElementAt({ 0 }), 5.0, 1e-10))) { std::string description = std::string("testMedianAndPercentiles():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(median_odd.getElementAt({ 0 }), 5.0, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Median with odd count works correctly\n"; // Test median with even number of elements auto even_array = createInt32Array({ 4 }, 0); even_array.setElementAt({ 0 }, 1); .. _example-timedeltaindex-min-11: .. 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-timedeltaindex-nanoseconds-12: .. 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-timedeltaindex-std-13: .. dropdown:: std (np_test_1_all.cpp:11836) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11826 :emphasize-lines: 11 auto var_sample = var(array, std::nullopt, 1); // ddof=1 for sample variance double expected_sample_var = 1.25 * 4.0 / 3.0; // Bessel's correction if (!(approx_equal(var_sample.getElementAt({ 0 }), expected_sample_var, 1e-10))) { std::string description = std::string("testVarianceAndStandardDeviation():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(var_sample.getElementAt({ 0 }), expected_sample_var, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Sample variance works correctly\n"; // Test standard deviation auto std_result = numpy::std(array, std::nullopt, 0); if (!(approx_equal(std_result.getElementAt({ 0 }), std::sqrt(expected_var), 1e-10))) { std::string description = std::string("testVarianceAndStandardDeviation():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(std_result.getElementAt({ 0 }), std::sqrt(expected_var), 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Standard deviation works correctly\n"; // Test along axis auto array2d = createFloat64Array({ 2, 2 }, 0); array2d.setElementAt({ 0, 0 }, 1.0); .. _example-timedeltaindex-sum-14: .. dropdown:: sum (np_test_1_all.cpp:11766) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 11756 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(approx_equal(mean_axis1.getElementAt({ 1 }), 5.0, 1e-10))) { std::string description = std::string("testBasicStatistics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(mean_axis1.getElementAt({ 1 }), 5.0, 1e-10))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] mean along axis 1 works correctly\n"; // Test sum auto sum_all = sum(array); if (!(sum_all.getElementAt({ 0 }) == 21)) { std::string description = std::string("testBasicStatistics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(sum_all.getElementAt({ 0 }) == 21)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] sum works correctly\n"; // Test min and max auto min_all = min(array); auto max_all = max(array); .. _example-timedeltaindex-argsort-15: .. 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-timedeltaindex-sort-16: .. dropdown:: sort (np_test_1_all.cpp:6258) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6248 :emphasize-lines: 11 std::vector data = gen.generate(100, DataPattern::FEW_UNIQUE); if (!(data.size() == 100)) { std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 100)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Count unique values std::vector sorted_copy = data; std::sort(sorted_copy.begin(), sorted_copy.end()); auto unique_end = std::unique(sorted_copy.begin(), sorted_copy.end()); size_t unique_count = std::distance(sorted_copy.begin(), unique_end); // Should have significantly fewer unique values than total elements if (!(unique_count < data.size() / 2)) { std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(unique_count < data.size() / 2)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaindex-ceil-17: .. 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-timedeltaindex-floor-18: .. 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-timedeltaindex-round-19: .. 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-timedeltaindex-all-20: .. dropdown:: all (np_test_4_all.cpp:23928) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 23918 :emphasize-lines: 11 } } } auto result = numpy::einsum("ijk->ik", {A}); if (result.getShape()[0] != 2 || result.getShape()[1] != 2) { throw std::runtime_error("einsum partial sum shape wrong"); } // Sum over j: 1+2+3 = 6 for all (i,k) positions if (std::abs(result.getElementAt({0, 0}) - 6.0) > 1e-10 || std::abs(result.getElementAt({1, 1}) - 6.0) > 1e-10) { throw std::runtime_error("einsum partial sum values wrong"); } // std::cout << " OK: Partial sum: 'ijk->ik'\n"; } // Test 5: Size-1 dimension handling { .. _example-timedeltaindex-any-21: .. dropdown:: any (np_test_2_all.cpp:16758) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 16748 :emphasize-lines: 11 // ANY() TESTS - SCALAR RESULT // ============================================================================ void np_test_logic_any_scalar_all_false() { std::cout << "========= any: all false elements ======================="; // Create array with all false/zero elements std::vector data = { 0.0, 0.0, 0.0 }; numpy::NDArray arr = numpy::createArrayFromVector({ 3 }, data); bool result = numpy::any(arr); if (result != false) { std::cout << " [FAIL] : in np_test_logic_any_scalar_all_false() : expected false for all-zero array"; throw std::runtime_error("np_test_logic_any_scalar_all_false failed: expected false"); } std::cout << " -> tests passed" << std::endl; } void np_test_logic_any_scalar_all_true() { .. _example-timedeltaindex-isin-22: .. dropdown:: isin (np_test_1_all.cpp:19434) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 19424 :emphasize-lines: 11 std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(membership.getElementAt({ 5 }) == false)) { std::string description = std::string("testMembershipOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(membership.getElementAt({ 5 }) == false)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Membership testing (in1d) works correctly\n"; // Test isin (alias for in1d) auto isin_result = isin(test_array, test_values); // Should be identical to in1d result for (size_t i = 0; i < membership.getSize(); ++i) { if (!(isin_result.getElementAt({ i }) == membership.getElementAt({ i }))) { std::string description = std::string("testMembershipOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(isin_result.getElementAt({ i }) == membership.getElementAt({ i }))"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } } .. _example-timedeltaindex-unique-23: .. 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-timedeltaindex-to_numpy-24: .. 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-timedeltaindex-to_string-25: .. 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-timedeltaindex-tolist-26: .. dropdown:: tolist (np_test_4_all.cpp:20046) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 20036 :emphasize-lines: 11 } // namespace numpy_tests /** * @file np_test_phase6.cpp * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities * * Tests: * - ndarray.nonzero() - Return indices of non-zero elements * - ndarray.tobytes() - Convert to bytes representation * - ndarray.tolist() - Convert to nested list string * - ndarray.fill() - Fill with scalar value (in-place) * - ndarray.item() - Get single element as scalar * - ndarray.itemset() - Set single element value * - ma.masked_all_like() - Create masked array with all elements masked * * Created: 2025-10-28 * Status: Phase 6A Implementation - HIGH PRIORITY functions */ #include "../numpy/np_ndarray.h" .. _example-timedeltaindex-append-27: .. dropdown:: append (np_test_2_all.cpp:7028) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7018 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(deleted_dups.getElementAt({ 2 }) == 3)) { std::string description = std::string("testModificationOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(deleted_dups.getElementAt({ 2 }) == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Delete with duplicate indices works correctly\n"; // Test append auto appended = append(array, 100); if (!(appended.getSize() == array.getSize() + 1)) { std::string description = std::string("testModificationOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(appended.getSize() == array.getSize() + 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(appended.getElementAt({ appended.getSize() - 1 }) == 100)) { std::string description = std::string("testModificationOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(appended.getElementAt({ appended.getSize() - 1 }) == 100)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaindex-append-28: .. dropdown:: append (np_test_2_all.cpp:7028) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7018 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(deleted_dups.getElementAt({ 2 }) == 3)) { std::string description = std::string("testModificationOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(deleted_dups.getElementAt({ 2 }) == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Delete with duplicate indices works correctly\n"; // Test append auto appended = append(array, 100); if (!(appended.getSize() == array.getSize() + 1)) { std::string description = std::string("testModificationOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(appended.getSize() == array.getSize() + 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(appended.getElementAt({ appended.getSize() - 1 }) == 100)) { std::string description = std::string("testModificationOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(appended.getElementAt({ appended.getSize() - 1 }) == 100)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaindex-delete_-29: .. dropdown:: delete_ (np_test_4_all.cpp:18411) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18401 :emphasize-lines: 11 } // ============================================================================ // SPRINT 1.2: ESSENTIAL OPERATIONS TESTS // ============================================================================ void np_test_phase1_delete() { std::cout << "========= delete_: element deletion ===="; auto arr = numpy::array({10, 20, 30, 40, 50}); auto result = numpy::delete_(arr, 2); // Delete index 2 (value 30) // Verify size reduced if (result.getSize() != 4) { std::cout << " [FAIL] : delete_ result size is " << result.getSize() << ", expected 4\n"; throw std::runtime_error("delete_ failed: wrong size"); } // Verify correct element was removed if (result.getElementAt({0}) != 10 || result.getElementAt({1}) != 20 || result.getElementAt({2}) != 40 || result.getElementAt({3}) != 50) { .. _example-timedeltaindex-delete_-30: .. dropdown:: delete_ (np_test_4_all.cpp:18411) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18401 :emphasize-lines: 11 } // ============================================================================ // SPRINT 1.2: ESSENTIAL OPERATIONS TESTS // ============================================================================ void np_test_phase1_delete() { std::cout << "========= delete_: element deletion ===="; auto arr = numpy::array({10, 20, 30, 40, 50}); auto result = numpy::delete_(arr, 2); // Delete index 2 (value 30) // Verify size reduced if (result.getSize() != 4) { std::cout << " [FAIL] : delete_ result size is " << result.getSize() << ", expected 4\n"; throw std::runtime_error("delete_ failed: wrong size"); } // Verify correct element was removed if (result.getElementAt({0}) != 10 || result.getElementAt({1}) != 20 || result.getElementAt({2}) != 40 || result.getElementAt({3}) != 50) { .. _example-timedeltaindex-insert-31: .. dropdown:: insert (np_test_1_all.cpp:6990) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6980 :emphasize-lines: 11 } void testBusinessDateRangeDateTime() { std::cout << "========= testBusinessDateRangeDateTime ======================="; datetime64 start("2024-03-11"); // Monday datetime64 end("2024-03-22"); // Friday (2 weeks later) // Create holidays set std::set holidays; holidays.insert(datetime64("2024-03-15")); // Friday holiday auto business_dates = createBusinessDateRange(start, end, holidays); // std::cout << "Business dates from " << start.toString() // << " to " << end.toString() << " (excluding 2024-03-15):" << std::endl; //business_dates.printArray(); std::cout << " -> tests passed" << std::endl; } void testMonthRangeDateTime() { .. _example-timedeltaindex-repeat-32: .. dropdown:: repeat (np_test_1_all.cpp:18268) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18258 :emphasize-lines: 11 // Create test array auto array = createInt32Array({ 2, 3 }, 0); for (size_t i = 0; i < 2; ++i) { for (size_t j = 0; j < 3; ++j) { array.setElementAt({ i, j }, static_cast(i * 3 + j + 1)); } } // Test repeat without axis (flattened) auto repeated_flat = repeat(array, 2); if (!(repeated_flat.getShape()[0] == 12)) { std::string description = std::string("testRepeat():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(repeated_flat.getShape()[0] == 12)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(repeated_flat.getElementAt({ 0 }) == 1)) { std::string description = std::string("testRepeat():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(repeated_flat.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaindex-repeat-33: .. dropdown:: repeat (np_test_1_all.cpp:18268) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 18258 :emphasize-lines: 11 // Create test array auto array = createInt32Array({ 2, 3 }, 0); for (size_t i = 0; i < 2; ++i) { for (size_t j = 0; j < 3; ++j) { array.setElementAt({ i, j }, static_cast(i * 3 + j + 1)); } } // Test repeat without axis (flattened) auto repeated_flat = repeat(array, 2); if (!(repeated_flat.getShape()[0] == 12)) { std::string description = std::string("testRepeat():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(repeated_flat.getShape()[0] == 12)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(repeated_flat.getElementAt({ 0 }) == 1)) { std::string description = std::string("testRepeat():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(repeated_flat.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } .. _example-timedeltaindex-astype-34: .. dropdown:: astype (np_test_3_all.cpp:796) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 786 :emphasize-lines: 11 auto ufunc_square = numpy::frompyfunc(square, 1, 1); numpy::NDArray arr({ 3 }); arr.setElementAt({ 0 }, 2.0); arr.setElementAt({ 1 }, 3.0); arr.setElementAt({ 2 }, 4.0); auto result = ufunc_square(arr); // Convert back to double to check values auto typed_result = numpy::astype(result); if (std::abs(typed_result.getElementAt({ 0 }) - 4.0) > 1e-10 || std::abs(typed_result.getElementAt({ 1 }) - 9.0) > 1e-10 || std::abs(typed_result.getElementAt({ 2 }) - 16.0) > 1e-10) { std::cout << "[FAIL] Basic frompyfunc creation failed"; return 1; } // std::cout << "[OK] Basic frompyfunc creation works correctly" << std::endl; std::cout << " -> tests passed" << std::endl; return 0; .. _example-timedeltaindex-copy-35: .. 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-timedeltaindex-view-36: .. dropdown:: view (np_test_1_all.cpp:440) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 430 :emphasize-lines: 11 for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 3; ++j) { original.setElementAt({i, j}, static_cast(i * 3 + j)); } } // std::cout << "Original array:" << std::endl; //original.printArray(); // Create multiple views auto view1 = original.view(); auto view2 = original.transposeView(); auto view3 = original.sliceView({{1, 3}, {1, 3}}); // 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(); .. _example-timedeltaindex-is_numeric-37: .. dropdown:: is_numeric (np_test_1_all.cpp:7511) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7501 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void testNumericConversionStringTypes() { std::cout << "========= testNumericStringOperationsStringTypes ======================="; str32 num_str1("123.45"); str32 num_str2("67.89"); str32 not_num("hello"); // std::cout << "String '" << num_str1 << "' is numeric: " << is_numeric(num_str1) << std::endl; // std::cout << "String '" << not_num << "' is numeric: " << is_numeric(not_num) << std::endl; if (is_numeric(num_str1)) { double val1 = to_numeric(num_str1); // std::cout << "Numeric value of '" << num_str1 << "': " << val1 << std::endl; } if (is_numeric(num_str2)) { double val2 = to_numeric(num_str2); // std::cout << "Numeric value of '" << num_str2 << "': " << val2 << std::endl; .. _example-timedeltaindex-argmax-38: .. 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-timedeltaindex-argmin-39: .. 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-timedeltaindex-arr-40: .. dropdown:: arr (np_test_1_all.cpp:1388) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1378 :emphasize-lines: 11 std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(*str_obj.get_as() == "hello")) { std::string description = std::string("testObjectConstruction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(*str_obj.get_as() == \"hello\")"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test NDArray construction NDArray arr({2, 2}, 3.14); object_ arr_obj(arr); if (!(!arr_obj.is_null())) { std::string description = std::string("testObjectConstruction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(!arr_obj.is_null())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(arr_obj.is_array())) { std::string description = std::string("testObjectConstruction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(arr_obj.is_array())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-timedeltaindex-arr-41: .. dropdown:: arr (np_test_1_all.cpp:1388) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1378 :emphasize-lines: 11 std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(*str_obj.get_as() == "hello")) { std::string description = std::string("testObjectConstruction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(*str_obj.get_as() == \"hello\")"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // Test NDArray construction NDArray arr({2, 2}, 3.14); object_ arr_obj(arr); if (!(!arr_obj.is_null())) { std::string description = std::string("testObjectConstruction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(!arr_obj.is_null())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(arr_obj.is_array())) { std::string description = std::string("testObjectConstruction():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(arr_obj.is_array())"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-timedeltaindex-as_unit-42: .. dropdown:: as_unit (np_test_5_all.cpp:22866) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 22856 :emphasize-lines: 11 if (iso_week < 1 || iso_week > 53) { pass = false; fail_msg = "ISO week range"; } if (iso_day < 1 || iso_day > 7) { pass = false; fail_msg = "ISO day range 1-7"; } // isoweekday (1=Monday, 7=Sunday) int isowd = ts.isoweekday(); if (isowd != 6) { pass = false; fail_msg = "2024-06-15 is Saturday = 6"; } // weekday (0=Monday, 6=Sunday) int wd = ts.weekday(); if (wd != 5) { pass = false; fail_msg = "2024-06-15 is Saturday = 5"; } if (!pass) { std::cout << " [FAIL] : in np_test_timestamp_calendar() : " << fail_msg; throw std::runtime_error("np_test_timestamp_calendar failed: " + fail_msg); } std::cout << " -> tests passed" << std::endl; } // ============================================================================ // ROUNDING TESTS .. _example-timedeltaindex-clone-43: .. dropdown:: clone (np_test_1_all.cpp:24942) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 24932 :emphasize-lines: 11 } // Test reproducibility numpy::random::PCG64DXSM rng2(11111); if (rng2.next_uint64() != val) { std::cout << " [FAIL] : in np_test_bitgen_pcg64dxsm() : not reproducible"; throw std::runtime_error("np_test_bitgen_pcg64dxsm failed"); } // Test clone auto cloned = rng.clone(); if (cloned->name() != "PCG64DXSM") { std::cout << " [FAIL] : in np_test_bitgen_pcg64dxsm() : clone name incorrect"; throw std::runtime_error("np_test_bitgen_pcg64dxsm failed"); } std::cout << " -> tests passed" << std::endl; } // ============================================================================ // PHILOX TESTS .. _example-timedeltaindex-components-44: .. dropdown:: components (np_test_1_all.cpp:27398) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 27388 :emphasize-lines: 11 // Check that results are strings (basic validation) std::string str0 = result.getElementAt({ 0 }); std::string str1 = result.getElementAt({ 1 }); if (str0.empty() || str1.empty()) { std::cout << " [FAIL] : in test_datetime_as_string_iso() : empty string result"; throw std::runtime_error("datetime_as_string ISO test failed"); } // Check format contains date components (YYYY-MM-DD) if (str0.find("2024") == std::string::npos || str0.find("01") == std::string::npos) { std::cout << " [FAIL] : in test_datetime_as_string_iso() : incorrect ISO format"; throw std::runtime_error("datetime_as_string ISO test failed"); } std::cout << " -> tests passed" << std::endl; } void test_datetime_as_string_custom() { std::cout << "========= datetime_as_string: custom format ======================="; .. _example-timedeltaindex-days-45: .. 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-timedeltaindex-diff-46: .. dropdown:: diff (np_test_2_all.cpp:4947) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4937 :emphasize-lines: 11 // Test matrix addition and subtraction numpy::Matrix a("1 2; 3 4"); numpy::Matrix b("5 6; 7 8"); auto sum = a + b; assert_test(std::abs(sum(0, 0) - 6.0) < 1e-10, "Matrix addition"); assert_test(std::abs(sum(1, 1) - 12.0) < 1e-10, "Matrix addition"); auto diff = b - a; assert_test(std::abs(diff(0, 0) - 4.0) < 1e-10, "Matrix subtraction"); assert_test(std::abs(diff(1, 1) - 4.0) < 1e-10, "Matrix subtraction"); // Test matrix multiplication (not element-wise!) auto product = a * b; assert_test(std::abs(product(0, 0) - 19.0) < 1e-10, "Matrix multiplication 0,0"); assert_test(std::abs(product(0, 1) - 22.0) < 1e-10, "Matrix multiplication 0,1"); assert_test(std::abs(product(1, 0) - 43.0) < 1e-10, "Matrix multiplication 1,0"); assert_test(std::abs(product(1, 1) - 50.0) < 1e-10, "Matrix multiplication 1,1"); // Test scalar multiplication .. _example-timedeltaindex-difference-47: .. dropdown:: difference (np_test_1_all.cpp:19333) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 19323 :emphasize-lines: 11 std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(difference.getElementAt({ 2 }) == 5)) { std::string description = std::string("testSetDifferenceOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(difference.getElementAt({ 2 }) == 5)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Set difference works correctly\n"; // Test symmetric difference (XOR) auto xor_result = setxor1d(arr1, arr2); if (!(xor_result.getSize() == 4)) { std::string description = std::string("testSetDifferenceOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(xor_result.getSize() == 4)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(xor_result.getElementAt({ 0 }) == 1)) { std::string description = std::string("testSetDifferenceOperations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(xor_result.getElementAt({ 0 }) == 1)"; std::cout << std::string("[FAIL] ") + description << std::endl; .. _example-timedeltaindex-float_arr-48: .. dropdown:: float_arr (np_test_4_all.cpp:23233) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 23223 :emphasize-lines: 11 numpy::NDArray mask1 = numpy::ma::make_mask(int_arr); if (mask1.item(0) != numpy::bool_(false) || mask1.item(1) != numpy::bool_(true) || mask1.item(2) != numpy::bool_(true) || mask1.item(3) != numpy::bool_(false) || mask1.item(4) != numpy::bool_(true)) { throw std::runtime_error("make_mask(int array) failed - incorrect boolean conversion"); } // std::cout << " OK: Integer array conversion (non-zero = True)\n"; // Test 2: Float array numpy::NDArray float_arr({4}); float_arr.setElementAt({0}, 1.0); float_arr.setElementAt({1}, 0.0); float_arr.setElementAt({2}, 2.5); float_arr.setElementAt({3}, 0.0); numpy::NDArray mask2 = numpy::ma::make_mask(float_arr); if (mask2.item(0) != numpy::bool_(true) || mask2.item(1) != numpy::bool_(false) || mask2.item(2) != numpy::bool_(true) || mask2.item(3) != numpy::bool_(false)) { throw std::runtime_error("make_mask(float array) failed"); .. _example-timedeltaindex-format-49: .. dropdown:: format (main.cpp:22) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12 :emphasize-lines: 11 int main() { // Automatically log all output to temp/test_output.log numpy::TestLogger logger("temp/test_output.log"); int res = 0; int res1 = 0; std::string resS = ""; // call all the tests res1 = numpy_tests::np_test_main(); resS += std::format(" np_test_main: {} errors\n", res1); res += res1; std::cout << "\n------------------------- main --------------------------------------------\n"; std::cout << std::endl << "All tests completed. Nb errors = " << res << std::endl; std::cout << "Details: \n" << resS; std::cout << "\n---------------------------------------------------------------------------\n"; return res; } .. _example-timedeltaindex-idx-50: .. dropdown:: idx (np_test_2_all.cpp:7377) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7367 :emphasize-lines: 11 throw std::runtime_error(description); } auto [row, col] = to_2d_indices(13, 5); if (!(row == 2 && col == 3)) { std::string description = std::string("test_matrix_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(row == 2 && col == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Matrix indexing: (2,3) -> " << idx << " -> (" << row << "," << col << ")" << std::endl; // Test vector operations double vec[3] = { 3.0, 4.0, 0.0 }; double norm = vector_norm_2(vec, 3); if (!(std::abs(norm - 5.0) < 1e-10)) { std::string description = std::string("test_matrix_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::abs(norm - 5.0) < 1e-10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Vector norm [3,4,0]: " << norm << std::endl; .. _example-timedeltaindex-idx-51: .. dropdown:: idx (np_test_2_all.cpp:7377) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7367 :emphasize-lines: 11 throw std::runtime_error(description); } auto [row, col] = to_2d_indices(13, 5); if (!(row == 2 && col == 3)) { std::string description = std::string("test_matrix_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(row == 2 && col == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Matrix indexing: (2,3) -> " << idx << " -> (" << row << "," << col << ")" << std::endl; // Test vector operations double vec[3] = { 3.0, 4.0, 0.0 }; double norm = vector_norm_2(vec, 3); if (!(std::abs(norm - 5.0) < 1e-10)) { std::string description = std::string("test_matrix_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::abs(norm - 5.0) < 1e-10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Vector norm [3,4,0]: " << norm << std::endl; .. _example-timedeltaindex-idx-52: .. dropdown:: idx (np_test_2_all.cpp:7377) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 7367 :emphasize-lines: 11 throw std::runtime_error(description); } auto [row, col] = to_2d_indices(13, 5); if (!(row == 2 && col == 3)) { std::string description = std::string("test_matrix_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(row == 2 && col == 3)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Matrix indexing: (2,3) -> " << idx << " -> (" << row << "," << col << ")" << std::endl; // Test vector operations double vec[3] = { 3.0, 4.0, 0.0 }; double norm = vector_norm_2(vec, 3); if (!(std::abs(norm - 5.0) < 1e-10)) { std::string description = std::string("test_matrix_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::abs(norm - 5.0) < 1e-10)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "Vector norm [3,4,0]: " << norm << std::endl; .. _example-timedeltaindex-int_arr-53: .. dropdown:: int_arr (np_test_3_all.cpp:1209) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1199 :emphasize-lines: 11 } // Test 12: Type conversion utilities int np_test_frompyfunc_type_conversion() { std::cout << "========= np_test_frompyfunc_type_conversion ======================="; try { auto int_func = [](int x) { return x * 2; }; auto ufunc_int = numpy::frompyfunc(int_func, 1, 1); numpy::NDArray int_arr({ 3 }); int_arr.setElementAt({ 0 }, 1); int_arr.setElementAt({ 1 }, 2); int_arr.setElementAt({ 2 }, 3); auto obj_result = ufunc_int(int_arr); auto typed_back = numpy::astype(obj_result); if (typed_back.getElementAt({ 0 }) != 2 || typed_back.getElementAt({ 1 }) != 4 || typed_back.getElementAt({ 2 }) != 6) { .. _example-timedeltaindex-join-54: .. dropdown:: join (np_test_5_all.cpp:1341) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1331 :emphasize-lines: 11 // ============================================================================ void np_test_string_join() { std::cout << "========= join operation ======================="; // Join takes a separator string and vector of CharArrays std::vector> arrays; arrays.push_back(numpy::char_::array<32>({ "a", "b", "c" })); arrays.push_back(numpy::char_::array<32>({ "x", "y", "z" })); auto result = numpy::char_::join("-", arrays); bool passed = true; if (!passed) { std::cout << " [FAIL] : in np_test_string_join() : join operation failed"; throw std::runtime_error("np_test_string_join failed"); } std::cout << " -> tests passed" << std::endl; } .. _example-timedeltaindex-microseconds-55: .. 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-timedeltaindex-result-56: .. dropdown:: result (np_test_1_all.cpp:6090) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 6080 :emphasize-lines: 11 throw std::runtime_error(description); } // std::cout << "Timer restart test passed. Second: " << second_elapsed << " ms" << std::endl; std::cout << " -> tests passed" << std::endl; } void test_benchmark_result_storageBenchmarkSorting() { std::cout << "========= test_benchmark_result_storage ======================="; BenchmarkResult result("TestAlgorithm", 1000, 15.5, true, 4096); if (!(result.algorithm_name == "TestAlgorithm")) { std::string description = std::string("test_benchmark_result_storageBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.algorithm_name == \"TestAlgorithm\")"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(result.array_size == 1000)) { std::string description = std::string("test_benchmark_result_storageBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result.array_size == 1000)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-timedeltaindex-seconds-57: .. 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-timedeltaindex-shift-58: .. dropdown:: shift (np_test_1_all.cpp:2761) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 2751 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(left_array.getElementAt({3}) == 16384)) { std::string description = std::string("testBitShifts():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(left_array.getElementAt({3}) == 16384)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Left shift by array\n"; // Test excessive shift (should result in 0) auto excessive_left = left_shift(arr, 20); // More than 16 bits if (!(excessive_left.getElementAt({0}) == 0)) { std::string description = std::string("testBitShifts():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(excessive_left.getElementAt({0}) == 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(excessive_left.getElementAt({1}) == 0)) { std::string description = std::string("testBitShifts():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(excessive_left.getElementAt({1}) == 0)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-timedeltaindex-slice-59: .. dropdown:: slice (np_test_1_all.cpp:13009) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 12999 :emphasize-lines: 11 // Test substr valid start but excessive length auto result3 = str1.substr(2, 10); // start=2, len=10 on string of length 5 if (!(result3.to_string() == "llo")) { std::string description = std::string("test_variable_string_out_of_bounds():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result3.to_string() == \"llo\")"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] vstring_ substr(2, 10) on 'hello' returns 'llo'\n"; // Test slice method with out-of-bounds auto result4 = str1.slice(10, 15); // slice[10:15] on string of length 5 if (!(result4.to_string() == "")) { std::string description = std::string("test_variable_string_out_of_bounds():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(result4.to_string() == \"\")"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] vstring_ slice(10, 15) on 'hello' returns empty string\n"; // Test slice with negative indices auto result5 = str1.slice(-2, -1); // slice[-2:-1] should be "l" if (!(result5.to_string() == "l")) {