StringArray =========== .. cpp:class:: numpy::StringArray numpy C++ class. Example ------- .. code-block:: cpp #include using namespace numpy; // Use StringArray StringArray obj; // ... operations ... Constructors ------------ .. list-table:: :widths: 55 25 20 :header-rows: 1 * - Signature - Location - Example * - ``StringArray(const numpy::NDArray& data, const numpy::NDArray& mask, bool copy = false)`` - df_string_array.h:68 - * - ``explicit StringArray(const numpy::NDArray& data)`` - df_string_array.h:81 - * - ``explicit StringArray(const std::vector>& values)`` - df_string_array.h:112 - * - ``explicit StringArray(const std::vector& values)`` - df_string_array.h:130 - Construction ------------ .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``static StringArray from_sequence(const std::vector>& scalars)`` - static StringArray - df_string_array.h:327 - Array Creation -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool empty() const`` - bool - df_string_array.h:182 - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::string at(size_t index) const`` - std::string - df_string_array.h:227 - :ref:`View ` * - ``StringArray take(const std::vector& indices, bool allow_fill = false, std::optional fill_value = std::nullopt) const`` - StringArray - df_string_array.h:274 - :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_string_array.h:694 - :ref:`View ` Logical ------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional all(bool skipna = true) const`` - std::optional - df_string_array.h:1079 - :ref:`View ` * - ``std::optional any(bool skipna = true) const`` - std::optional - df_string_array.h:1052 - :ref:`View ` Set Operations -------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``StringArray unique() const`` - StringArray - df_string_array.h:627 - :ref:`View ` I/O --- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``numpy::NDArray to_numpy(const std::string& na_value = "") const`` - numpy::NDArray - df_string_array.h:390 - :ref:`View ` * - ``std::string to_string() const`` - std::string - df_string_array.h:1114 - :ref:`View ` Type Handling ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``StringArray copy() const`` - StringArray - df_string_array.h:267 - :ref:`View ` Type Checking ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``bool is_na(size_t index) const`` - bool - df_string_array.h:238 - Other Methods ------------- .. list-table:: :widths: 40 20 15 25 :header-rows: 1 * - Signature - Return Type - Location - Example * - ``std::optional argmax() const`` - std::optional - df_string_array.h:747 - :ref:`View ` * - ``std::optional argmin() const`` - std::optional - df_string_array.h:726 - :ref:`View ` * - ``static StringArray concat(const std::vector& arrays)`` - static StringArray - df_string_array.h:334 - * - ``size_t count() const`` - size_t - df_string_array.h:403 - :ref:`View ` * - ``const numpy::NDArray& data() const`` - const numpy::NDArray& - df_string_array.h:200 - :ref:`View ` * - ``StringArray dropna() const`` - StringArray - df_string_array.h:377 - * - ``dtype_type dtype() const`` - dtype_type - df_string_array.h:147 - :ref:`View ` * - ``std::pair, StringArray> factorize() const`` - std::pair, StringArray> - df_string_array.h:654 - * - ``\* NA comparisons return false (not NA), following pandas convention`` - \* NA comparisons return - df_string_array.h:431 - :ref:`View ` * - ``StringArray fillna(const std::string& value) const`` - StringArray - df_string_array.h:363 - * - ``bool has_na() const`` - bool - df_string_array.h:416 - * - ``numpy::NDArray isna() const`` - numpy::NDArray - df_string_array.h:249 - * - ``size_t len() const`` - size_t - df_string_array.h:189 - * - ``const numpy::NDArray& mask() const`` - const numpy::NDArray& - df_string_array.h:207 - :ref:`View ` * - ``size_t nbytes() const`` - size_t - df_string_array.h:161 - :ref:`View ` * - ``constexpr int ndim() const`` - constexpr int - df_string_array.h:168 - :ref:`View ` * - ``numpy::NDArray notna() const`` - numpy::NDArray - df_string_array.h:256 - * - ``std::string repr() const`` - std::string - df_string_array.h:1131 - * - ``std::vector shape() const`` - std::vector - df_string_array.h:175 - :ref:`View ` * - ``size_t size() const`` - size_t - df_string_array.h:154 - :ref:`View ` * - ``StringArray str_cat(const StringArray& other, const std::string& sep = "") const`` - StringArray - df_string_array.h:1002 - * - ``StringArray str_cat(const std::string& suffix, const std::string& sep = "") const`` - StringArray - df_string_array.h:1028 - * - ``BooleanArray str_contains(const std::string& pat) const`` - BooleanArray - df_string_array.h:934 - * - ``BooleanArray str_endswith(const std::string& suffix) const`` - BooleanArray - df_string_array.h:978 - * - ``IntegerArray str_len() const`` - IntegerArray - df_string_array.h:772 - :ref:`View ` * - ``StringArray str_lower() const`` - StringArray - df_string_array.h:790 - * - ``StringArray str_lstrip() const`` - StringArray - df_string_array.h:857 - :ref:`View ` * - ``StringArray str_replace(const std::string& old_str, const std::string& new_str, int count = -1) const`` - StringArray - df_string_array.h:902 - :ref:`View ` * - ``StringArray str_rstrip() const`` - StringArray - df_string_array.h:878 - :ref:`View ` * - ``BooleanArray str_startswith(const std::string& prefix) const`` - BooleanArray - df_string_array.h:955 - * - ``StringArray str_strip() const`` - StringArray - df_string_array.h:832 - * - ``StringArray str_upper() const`` - StringArray - df_string_array.h:811 - * - ``void validate_arrays()`` - void - df_string_array.h:1144 - Code Examples ------------- The following examples are extracted from the test suite. .. _example-stringarray-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-stringarray-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-stringarray-take-2: .. dropdown:: take (np_test_5_all.cpp:4313) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 4303 :emphasize-lines: 11 for (size_t i = 0; i < 6; ++i) { arr.setElementAt({ i }, static_cast(i * 10)); // [0, 10, 20, 30, 40, 50] } // Take specific indices numpy::NDArray indices({ 3 }); indices.setElementAt({ 0 }, 5); // 50 indices.setElementAt({ 1 }, 2); // 20 indices.setElementAt({ 2 }, 0); // 0 auto result = numpy::take(arr, indices); if (result.getSize() != 3) { std::cout << " [FAIL] : in np_test_take_basic() : Wrong result size"; throw std::runtime_error("Test failed"); } if (result.getElementAt({ 0 }) != 50 || result.getElementAt({ 1 }) != 20 || result.getElementAt({ 2 }) != 0) { std::cout << " [FAIL] : in np_test_take_basic() : Wrong values extracted"; throw std::runtime_error("Test failed"); } .. _example-stringarray-argsort-3: .. 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-stringarray-all-4: .. 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-stringarray-any-5: .. 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-stringarray-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-stringarray-to_numpy-7: .. 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-stringarray-to_string-8: .. 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-stringarray-copy-9: .. 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-stringarray-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-stringarray-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-stringarray-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-stringarray-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-stringarray-dtype-14: .. 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-stringarray-false-15: .. dropdown:: false (np_test_1_all.cpp:1084) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 1074 :emphasize-lines: 11 scalar_arr.setElementAt({3}, 1.0); // Test NaN behavior - NaN comparisons should be false auto gt_result = greater(arr, scalar_arr); bool gt_sv_0 = gt_result.getElementAt({0}); if (gt_sv_0 != false) { // 1.0 > 2.0 = false std::cout << "[FAIL] in testSpecialValueHandling(): greater[0] (1.0 > 2.0) = " << gt_sv_0 << ", expected false" << std::endl; throw std::runtime_error("testSpecialValueHandling(): greater [0] failed"); } bool gt_sv_1 = gt_result.getElementAt({1}); if (gt_sv_1 != false) { // NaN > 1.0 = false (NaN comparisons are false) std::cout << "[FAIL] in testSpecialValueHandling(): greater[1] (NaN > 1.0) = " << gt_sv_1 << ", expected false" << std::endl; throw std::runtime_error("testSpecialValueHandling(): NaN comparison failed"); } bool gt_sv_2 = gt_result.getElementAt({2}); if (gt_sv_2 != true) { // inf > 1.0 = true std::cout << "[FAIL] in testSpecialValueHandling(): greater[2] (inf > 1.0) = " << gt_sv_2 << ", expected true" << std::endl; throw std::runtime_error("testSpecialValueHandling(): infinity comparison failed"); } bool gt_sv_3 = gt_result.getElementAt({3}); if (gt_sv_3 != false) { // -inf > 1.0 = false .. _example-stringarray-mask-16: .. 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-stringarray-nbytes-17: .. 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-stringarray-ndim-18: .. 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-stringarray-shape-19: .. 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-stringarray-size-20: .. 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-stringarray-str_len-21: .. dropdown:: str_len (np_test_1_all.cpp:13254) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 13244 :emphasize-lines: 11 throw std::runtime_error(description); } if (!(slice_oob_result.getElementAt({ 2 }).to_string() == "")) { std::string description = std::string("test_vectorized_string_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(slice_oob_result.getElementAt({ 2 }).to_string() == \"\")"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } // std::cout << "[OK] Vectorized str_slice with out-of-bounds returns empty strings\n"; // Test string length auto len_result = string_ops::str_len(str_array); if (!(len_result.getElementAt({ 0 }) == 5)) { std::string description = std::string("test_vectorized_string_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(len_result.getElementAt({ 0 }) == 5)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); } if (!(len_result.getElementAt({ 1 }) == 5)) { std::string description = std::string("test_vectorized_string_operations():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(len_result.getElementAt({ 1 }) == 5)"; std::cout << std::string("[FAIL] ") + description << std::endl; throw std::runtime_error(description); .. _example-stringarray-str_lstrip-22: .. dropdown:: str_lstrip (np_test_3_all.cpp:13657) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 13647 :emphasize-lines: 11 // WHITESPACE OPERATIONS TESTS // ============================================================================ void np_test_str_lstrip() { std::cout << "========= np_test_str_lstrip ======================="; NDArray arr({ 2 }); arr.data()[0] = vstring_(" hello "); arr.data()[1] = vstring_("\t\ntest\t"); auto result = str_lstrip(arr); if (result.data()[0].to_string() != "hello " || result.data()[1].to_string() != "test\t") { std::cerr << "[FAIL] lstrip test failed"; throw std::runtime_error("lstrip test failed"); } // std::cout << "[OK] Lstrip test passed" << std::endl; std::cout << " -> tests passed" << std::endl; } .. _example-stringarray-str_replace-23: .. dropdown:: str_replace (np_test_3_all.cpp:13934) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 13924 :emphasize-lines: 11 // STRING MANIPULATION TESTS // ============================================================================ void np_test_str_replace() { std::cout << "========= np_test_str_replace ======================="; NDArray arr({ 2 }); arr.data()[0] = vstring_("hello"); arr.data()[1] = vstring_("world"); auto result = str_replace(arr, vstring_("l"), vstring_("L")); if (result.data()[0].to_string() != "heLLo" || result.data()[1].to_string() != "worLd") { std::cerr << "[FAIL] replace test failed"; throw std::runtime_error("replace test failed"); } // std::cout << "[OK] Replace test passed" << std::endl; std::cout << " -> tests passed" << std::endl; } .. _example-stringarray-str_rstrip-24: .. dropdown:: str_rstrip (np_test_3_all.cpp:13676) :class-title: example-dropdown .. code-block:: cpp :linenos: :lineno-start: 13666 :emphasize-lines: 11 std::cout << " -> tests passed" << std::endl; } void np_test_str_rstrip() { std::cout << "========= np_test_str_rstrip ======================="; NDArray arr({ 2 }); arr.data()[0] = vstring_(" hello "); arr.data()[1] = vstring_("\ttest\t\n"); auto result = str_rstrip(arr); if (result.data()[0].to_string() != " hello" || result.data()[1].to_string() != "\ttest") { std::cerr << "[FAIL] rstrip test failed"; throw std::runtime_error("rstrip test failed"); } // std::cout << "[OK] Rstrip test passed" << std::endl; std::cout << " -> tests passed" << std::endl; }