NDArray#

class numpy::NDArray#

Core array class in the numpy namespace.

Example#

#include <numpy/np_ndarray.h>
using namespace numpy;

// Create NDArray
NDArray<double> arr = np::zeros<double>({3, 4});
NDArray<int> ones = np::ones<int>({2, 2});

// Access data
auto shape = arr.shape();
double val = arr(0, 1);

// Operations
auto result = arr + 1.0;
auto mean_val = np::mean(arr);

Constructors#

Signature

Location

Example

NDArray(const std::vector<size_t>&shape, const T &fill_value = T{})

NP_NDARRAY.H:50

View

NDArray(T \*external_data, const std::vector<size_t>&shape, std::shared_ptr<void>owner = nullptr)

NP_NDARRAY.H:54

View

NDArray(T \*data_ptr, size_toffset, const std::vector<size_t>&shape, const std::vector<ssize_t>&strides, std::shared_ptr<void>owner)

NP_NDARRAY.H:58

View

Indexing / Selection#

Signature

Return Type

Location

Example

DType getDType()

DType

NP_NDARRAY.H:115

View

T getElementAt(const std::vector<size_t>&indices)

T

NP_NDARRAY.H:72

View

size_t getOffset()

size_t

NP_NDARRAY.H:113

const std::vector<size_t>& getShape()

const std::vector<size_t>&

NP_NDARRAY.H:110

View

size_t getSize()

size_t

NP_NDARRAY.H:112

View

const std::vector<ssize_t>& getStrides()

const std::vector<ssize_t>&

NP_NDARRAY.H:111

View

std::string getTypeName()

std::string

NP_NDARRAY.H:116

View

T item()

T

NP_NDARRAY.H:203

View

T item(size_tflat_index)

T

NP_NDARRAY.H:211

View

void itemset(const T &value)

void

NP_NDARRAY.H:219

View

void itemset(size_tflat_index, const T &value)

void

NP_NDARRAY.H:227

View

std::vector<NDArray<size_t>> nonzero()

std::vector<NDArray<size_t>>

NP_NDARRAY.H:174

View

Statistics#

Signature

Return Type

Location

Example

T maxArray()

T

NP_NDARRAY.H:100

View

double meanArray()

double

NP_NDARRAY.H:98

View

T minArray()

T

NP_NDARRAY.H:99

View

T sumArray()

T

NP_NDARRAY.H:97

View

Sorting#

Signature

Return Type

Location

Example

void sort(std::optional<int>axis = std::nullopt, SortKindkind = static_cast<SortKind>(0), boolstable = false)

void

NP_NDARRAY.H:106

View

I/O#

Signature

Return Type

Location

Example

std::string tolist()

std::string

NP_NDARRAY.H:188

View

Other Methods#

Signature

Return Type

Location

Example

T \* data()

T *

NP_NDARRAY.H:121

View

const T \* data()

const T *

NP_NDARRAY.H:130

View

void dump(const std::string &filename)

void

NP_NDARRAY.H:289

View

void fill(const T &value)

void

NP_NDARRAY.H:195

View

T & flat(size_tflat_index)

T &

NP_NDARRAY.H:235

View

const T & flat(size_tflat_index)

const T &

NP_NDARRAY.H:243

View

bool isAligned()

bool

NP_NDARRAY.H:337

View

bool isCContiguous()

bool

NP_NDARRAY.H:152

View

bool isContiguous()

bool

NP_NDARRAY.H:151

View

bool isFContiguous()

bool

NP_NDARRAY.H:153

View

bool isWriteable()

bool

NP_NDARRAY.H:331

View

bool ownsData()

bool

NP_NDARRAY.H:114

View

void printArray(const std::string &title = "")

void

NP_NDARRAY.H:103

View

void setElementAt(const std::vector<size_t>&indices, const T &value)

void

NP_NDARRAY.H:73

View

void setElementAt(std::initializer_list<size_t>indices, const T &value)

void

NP_NDARRAY.H:74

View

void setflags(boolwrite = true, boolalign = false, booluic = false)

void

NP_NDARRAY.H:325

View

std::string toString(const std::string &title = "")

std::string

NP_NDARRAY.H:102

View

T \* unsafe_data()

T *

NP_NDARRAY.H:142

const T \* unsafe_data()

const T *

NP_NDARRAY.H:146

Code Examples#

The following examples are extracted from the test suite.

NDArray (np_test_1_all.cpp:890)
880    }
881    // std::cout << "[OK] array == scalar";
882
883    std::cout << " -> tests passed" << std::endl;
884}
885
886void testLogicalOperations() {
887    std::cout << "========= testLogicalOperations =======================";
888
889    // Create boolean arrays
890    auto a = NDArray<bool>({3});
891    a.setElementAt({0}, true);
892    a.setElementAt({1}, false);
893    a.setElementAt({2}, true);
894
895    auto b = NDArray<bool>({3});
896    b.setElementAt({0}, false);
897    b.setElementAt({1}, false);
898    b.setElementAt({2}, true);
899
900    // Test logical_and
NDArray (np_test_1_all.cpp:890)
880    }
881    // std::cout << "[OK] array == scalar";
882
883    std::cout << " -> tests passed" << std::endl;
884}
885
886void testLogicalOperations() {
887    std::cout << "========= testLogicalOperations =======================";
888
889    // Create boolean arrays
890    auto a = NDArray<bool>({3});
891    a.setElementAt({0}, true);
892    a.setElementAt({1}, false);
893    a.setElementAt({2}, true);
894
895    auto b = NDArray<bool>({3});
896    b.setElementAt({0}, false);
897    b.setElementAt({1}, false);
898    b.setElementAt({2}, true);
899
900    // Test logical_and
NDArray (np_test_1_all.cpp:890)
880    }
881    // std::cout << "[OK] array == scalar";
882
883    std::cout << " -> tests passed" << std::endl;
884}
885
886void testLogicalOperations() {
887    std::cout << "========= testLogicalOperations =======================";
888
889    // Create boolean arrays
890    auto a = NDArray<bool>({3});
891    a.setElementAt({0}, true);
892    a.setElementAt({1}, false);
893    a.setElementAt({2}, true);
894
895    auto b = NDArray<bool>({3});
896    b.setElementAt({0}, false);
897    b.setElementAt({1}, false);
898    b.setElementAt({2}, true);
899
900    // Test logical_and
getDType (np_test_1_all.cpp:7238)
7228              // << ", size: " << TypeTraits<longdouble>::getTypeSize() << " bytes" << std::endl;
7229    // std::cout << "  clongdouble: " << TypeTraits<clongdouble>::getTypeName()
7230              // << ", size: " << TypeTraits<clongdouble>::getTypeSize() << " bytes" << std::endl;
7231    // std::cout << "  intp: " << TypeTraits<intp>::getTypeName()
7232              // << ", size: " << TypeTraits<intp>::getTypeSize() << " bytes" << std::endl;
7233    // std::cout << "  uintp: " << TypeTraits<uintp>::getTypeName()
7234              // << ", size: " << TypeTraits<uintp>::getTypeSize() << " bytes" << std::endl;
7235    // std::cout << "  bytes: " << TypeTraits<bytes_>::getTypeName()
7236              // << ", size: " << TypeTraits<bytes_>::getTypeSize() << " bytes" << std::endl;
7237
7238    // Test getDType()
7239    // std::cout << "DType Enums:" << std::endl;
7240    // std::cout << "  longdouble DType: " << static_cast<int>(TypeTraits<longdouble>::getDType()) << std::endl;
7241    // std::cout << "  clongdouble DType: " << static_cast<int>(TypeTraits<clongdouble>::getDType()) << std::endl;
7242    // std::cout << "  intp DType: " << static_cast<int>(TypeTraits<intp>::getDType()) << std::endl;
7243    // std::cout << "  uintp DType: " << static_cast<int>(TypeTraits<uintp>::getDType()) << std::endl;
7244    // std::cout << "  bytes DType: " << static_cast<int>(TypeTraits<bytes_>::getDType()) << std::endl;
7245
7246    std::cout << " -> tests passed" << std::endl;
7247}
getElementAt (np_test_1_all.cpp:49)
39using namespace numpy::benchmark;
40using namespace numpy::char_;
41
42// Helper functions for array comparison tests
43namespace {
44    const double TOLERANCE = 1e-10;
45
46    bool allTrue(const NDArray<bool>& arr) {
47        std::vector<size_t> indices(arr.getShape().size(), 0);
48        do {
49            if (!arr.getElementAt(indices)) {
50                return false;
51            }
52        } while (incrementIndices(indices, arr.getShape()));
53        return true;
54    }
55
56    bool allFalse(const NDArray<bool>& arr) {
57        std::vector<size_t> indices(arr.getShape().size(), 0);
58        do {
59            if (arr.getElementAt(indices)) {
getShape (np_test_1_all.cpp:47)
37using namespace numpy;
38using namespace numpy::benchmark;
39using namespace numpy::char_;
40
41// Helper functions for array comparison tests
42namespace {
43    const double TOLERANCE = 1e-10;
44
45    bool allTrue(const NDArray<bool>& arr) {
46        std::vector<size_t> indices(arr.getShape().size(), 0);
47        do {
48            if (!arr.getElementAt(indices)) {
49                return false;
50            }
51        } while (incrementIndices(indices, arr.getShape()));
52        return true;
53    }
54
55    bool allFalse(const NDArray<bool>& arr) {
56        std::vector<size_t> indices(arr.getShape().size(), 0);
getSize (np_test_1_all.cpp:2172)
2162    }
2163
2164    std::cout << " -> tests passed" << std::endl;
2165}
2166
2167void testArrayEdgeCases() {
2168    std::cout << "========= testArrayEdgeCases =======================";
2169
2170    // Test 1: Empty arrays
2171    NDArray<object_> empty_array = createObjectZeros({0});
2172    if (!(empty_array.getSize() == 0)) {
2173        std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(empty_array.getSize() == 0)";
2174        std::cout << std::string("[FAIL] ") + description << std::endl;
2175        throw std::runtime_error(description);
2176    }
2177    if (!(empty_array.getShape() == std::vector<size_t>{0})) {
2178        std::string description = std::string("testArrayEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(empty_array.getShape() == std::vector<size_t>{0})";
2179        std::cout << std::string("[FAIL] ") + description << std::endl;
2180        throw std::runtime_error(description);
2181    }
getStrides (np_test_1_all.cpp:13373)
13363namespace numpy_tests {
13364
13365  using namespace numpy;
13366
13367
13368  void testBasicStrides() {
13369    std::cout << "========= testBasicStrides =======================";
13370
13371    // Test 1D array
13372    auto array1d = createInt32Array({ 5 }, 10);
13373    const auto& strides1d = array1d.getStrides();
13374
13375    // std::cout << "1D array shape: (" << array1d.getShape()[0] << ")" << std::endl;
13376    // std::cout << "1D array strides: (" << strides1d[0] << ")" << std::endl;
13377
13378    if (!(strides1d.size() == 1)) {
13379        std::string description = std::string("testBasicStrides():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(strides1d.size() == 1)";
13380        std::cout << std::string("[FAIL] ") + description << std::endl;
13381        throw std::runtime_error(description);
13382    }
13383    if (!(strides1d[0] == 1)) {
getTypeName (np_test_1_all.cpp:7227)
7217    // std::cout << "Min: " << ip_array.minArray() << std::endl;
7218    // std::cout << "Max: " << ip_array.maxArray() << std::endl;
7219
7220    std::cout << " -> tests passed" << std::endl;
7221}
7222
7223void testTypeTraitsExtendedTypes() {
7224    std::cout << "========= testTypeTraitsExtendedTypes =======================";
7225
7226    // std::cout << "Type Information:" << std::endl;
7227    // std::cout << "  longdouble: " << TypeTraits<longdouble>::getTypeName()
7228              // << ", size: " << TypeTraits<longdouble>::getTypeSize() << " bytes" << std::endl;
7229    // std::cout << "  clongdouble: " << TypeTraits<clongdouble>::getTypeName()
7230              // << ", size: " << TypeTraits<clongdouble>::getTypeSize() << " bytes" << std::endl;
7231    // std::cout << "  intp: " << TypeTraits<intp>::getTypeName()
7232              // << ", size: " << TypeTraits<intp>::getTypeSize() << " bytes" << std::endl;
7233    // std::cout << "  uintp: " << TypeTraits<uintp>::getTypeName()
7234              // << ", size: " << TypeTraits<uintp>::getTypeSize() << " bytes" << std::endl;
7235    // std::cout << "  bytes: " << TypeTraits<bytes_>::getTypeName()
7236              // << ", size: " << TypeTraits<bytes_>::getTypeSize() << " bytes" << std::endl;
item (np_test_4_all.cpp:20048)
20038/**
20039 * @file np_test_phase6.cpp
20040 * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities
20041 *
20042 * Tests:
20043 * - ndarray.nonzero() - Return indices of non-zero elements
20044 * - ndarray.tobytes() - Convert to bytes representation
20045 * - ndarray.tolist() - Convert to nested list string
20046 * - ndarray.fill() - Fill with scalar value (in-place)
20047 * - ndarray.item() - Get single element as scalar
20048 * - ndarray.itemset() - Set single element value
20049 * - ma.masked_all_like() - Create masked array with all elements masked
20050 *
20051 * Created: 2025-10-28
20052 * Status: Phase 6A Implementation - HIGH PRIORITY functions
20053 */
20054
20055#include "../numpy/np_ndarray.h"
20056#include "../numpy/np_masked_array.h"
20057#include <iostream>
item (np_test_4_all.cpp:20048)
20038/**
20039 * @file np_test_phase6.cpp
20040 * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities
20041 *
20042 * Tests:
20043 * - ndarray.nonzero() - Return indices of non-zero elements
20044 * - ndarray.tobytes() - Convert to bytes representation
20045 * - ndarray.tolist() - Convert to nested list string
20046 * - ndarray.fill() - Fill with scalar value (in-place)
20047 * - ndarray.item() - Get single element as scalar
20048 * - ndarray.itemset() - Set single element value
20049 * - ma.masked_all_like() - Create masked array with all elements masked
20050 *
20051 * Created: 2025-10-28
20052 * Status: Phase 6A Implementation - HIGH PRIORITY functions
20053 */
20054
20055#include "../numpy/np_ndarray.h"
20056#include "../numpy/np_masked_array.h"
20057#include <iostream>
itemset (np_test_4_all.cpp:20049)
20039/**
20040 * @file np_test_phase6.cpp
20041 * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities
20042 *
20043 * Tests:
20044 * - ndarray.nonzero() - Return indices of non-zero elements
20045 * - ndarray.tobytes() - Convert to bytes representation
20046 * - ndarray.tolist() - Convert to nested list string
20047 * - ndarray.fill() - Fill with scalar value (in-place)
20048 * - ndarray.item() - Get single element as scalar
20049 * - ndarray.itemset() - Set single element value
20050 * - ma.masked_all_like() - Create masked array with all elements masked
20051 *
20052 * Created: 2025-10-28
20053 * Status: Phase 6A Implementation - HIGH PRIORITY functions
20054 */
20055
20056#include "../numpy/np_ndarray.h"
20057#include "../numpy/np_masked_array.h"
20058#include <iostream>
20059#include <cassert>
itemset (np_test_4_all.cpp:20049)
20039/**
20040 * @file np_test_phase6.cpp
20041 * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities
20042 *
20043 * Tests:
20044 * - ndarray.nonzero() - Return indices of non-zero elements
20045 * - ndarray.tobytes() - Convert to bytes representation
20046 * - ndarray.tolist() - Convert to nested list string
20047 * - ndarray.fill() - Fill with scalar value (in-place)
20048 * - ndarray.item() - Get single element as scalar
20049 * - ndarray.itemset() - Set single element value
20050 * - ma.masked_all_like() - Create masked array with all elements masked
20051 *
20052 * Created: 2025-10-28
20053 * Status: Phase 6A Implementation - HIGH PRIORITY functions
20054 */
20055
20056#include "../numpy/np_ndarray.h"
20057#include "../numpy/np_masked_array.h"
20058#include <iostream>
20059#include <cassert>
nonzero (np_test_4_all.cpp:18465)
18455      }
18456
18457      std::cout << " -> tests passed\n";
18458    }
18459
18460    void np_test_phase1_nonzero() {
18461      std::cout << "========= nonzero: find nonzero indices ====";
18462
18463      // Test 1D array
18464      auto arr1d = numpy::array({0, 2, 0, 4, 5, 0, 7});
18465      auto indices1d = numpy::nonzero(arr1d);
18466
18467      // Should return vector with 1 array (for 1D input)
18468      if (indices1d.size() != 1) {
18469        std::cout << "  [FAIL] : nonzero 1D returned " << indices1d.size() << " arrays, expected 1\n";
18470        throw std::runtime_error("nonzero failed: wrong number of arrays for 1D");
18471      }
18472
18473      // Should find 4 nonzero elements
18474      if (indices1d[0].getSize() != 4) {
18475        std::cout << "  [FAIL] : nonzero 1D found " << indices1d[0].getSize() << " elements, expected 4\n";
maxArray (np_test_1_all.cpp:234)
224    array.setElementAt({1, 0}, -1.0);
225    array.setElementAt({1, 1}, 0.0);
226    array.setElementAt({1, 2}, 4.5);
227
228    // std::cout << "Test array:" << std::endl;
229    //array.printArray();
230
231    // std::cout << "Sum: " << array.sumArray() << std::endl;
232    // std::cout << "Mean: " << array.meanArray() << std::endl;
233    // std::cout << "Min: " << array.minArray() << std::endl;
234    // std::cout << "Max: " << array.maxArray() << std::endl;
235
236    std::cout << " -> tests passed" << std::endl;
237}
238
239void testReshapeAndFlatten() {
240    std::cout << "========= testReshapeAndFlatten =======================";
241
242    auto range_array = NDArray<int32>::createRange(0, 12, 1);
243    // std::cout << "Range array (0-11):" << std::endl;
244    //range_array.printArray();
meanArray (np_test_1_all.cpp:232)
222    array.setElementAt({0, 1}, 2.5);
223    array.setElementAt({0, 2}, 3.5);
224    array.setElementAt({1, 0}, -1.0);
225    array.setElementAt({1, 1}, 0.0);
226    array.setElementAt({1, 2}, 4.5);
227
228    // std::cout << "Test array:" << std::endl;
229    //array.printArray();
230
231    // std::cout << "Sum: " << array.sumArray() << std::endl;
232    // std::cout << "Mean: " << array.meanArray() << std::endl;
233    // std::cout << "Min: " << array.minArray() << std::endl;
234    // std::cout << "Max: " << array.maxArray() << std::endl;
235
236    std::cout << " -> tests passed" << std::endl;
237}
238
239void testReshapeAndFlatten() {
240    std::cout << "========= testReshapeAndFlatten =======================";
241
242    auto range_array = NDArray<int32>::createRange(0, 12, 1);
minArray (np_test_1_all.cpp:233)
223    array.setElementAt({0, 2}, 3.5);
224    array.setElementAt({1, 0}, -1.0);
225    array.setElementAt({1, 1}, 0.0);
226    array.setElementAt({1, 2}, 4.5);
227
228    // std::cout << "Test array:" << std::endl;
229    //array.printArray();
230
231    // std::cout << "Sum: " << array.sumArray() << std::endl;
232    // std::cout << "Mean: " << array.meanArray() << std::endl;
233    // std::cout << "Min: " << array.minArray() << std::endl;
234    // std::cout << "Max: " << array.maxArray() << std::endl;
235
236    std::cout << " -> tests passed" << std::endl;
237}
238
239void testReshapeAndFlatten() {
240    std::cout << "========= testReshapeAndFlatten =======================";
241
242    auto range_array = NDArray<int32>::createRange(0, 12, 1);
243    // std::cout << "Range array (0-11):" << std::endl;
sumArray (np_test_1_all.cpp:231)
221    array.setElementAt({0, 0}, 1.5);
222    array.setElementAt({0, 1}, 2.5);
223    array.setElementAt({0, 2}, 3.5);
224    array.setElementAt({1, 0}, -1.0);
225    array.setElementAt({1, 1}, 0.0);
226    array.setElementAt({1, 2}, 4.5);
227
228    // std::cout << "Test array:" << std::endl;
229    //array.printArray();
230
231    // std::cout << "Sum: " << array.sumArray() << std::endl;
232    // std::cout << "Mean: " << array.meanArray() << std::endl;
233    // std::cout << "Min: " << array.minArray() << std::endl;
234    // std::cout << "Max: " << array.maxArray() << std::endl;
235
236    std::cout << " -> tests passed" << std::endl;
237}
238
239void testReshapeAndFlatten() {
240    std::cout << "========= testReshapeAndFlatten =======================";
sort (np_test_1_all.cpp:6258)
6248    std::vector<int> data = gen.generate(100, DataPattern::FEW_UNIQUE);
6249
6250    if (!(data.size() == 100)) {
6251        std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 100)";
6252        std::cout << std::string("[FAIL] ") + description << std::endl;
6253        throw std::runtime_error(description);
6254    }
6255
6256    // Count unique values
6257    std::vector<int> sorted_copy = data;
6258    std::sort(sorted_copy.begin(), sorted_copy.end());
6259    auto unique_end = std::unique(sorted_copy.begin(), sorted_copy.end());
6260    size_t unique_count = std::distance(sorted_copy.begin(), unique_end);
6261
6262    // Should have significantly fewer unique values than total elements
6263    if (!(unique_count < data.size() / 2)) {
6264        std::string description = std::string("test_data_generator_few_uniqueBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(unique_count < data.size() / 2)";
6265        std::cout << std::string("[FAIL] ") + description << std::endl;
6266        throw std::runtime_error(description);
6267    }
tolist (np_test_4_all.cpp:20046)
20036} // namespace numpy_tests
20037
20038/**
20039 * @file np_test_phase6.cpp
20040 * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities
20041 *
20042 * Tests:
20043 * - ndarray.nonzero() - Return indices of non-zero elements
20044 * - ndarray.tobytes() - Convert to bytes representation
20045 * - ndarray.tolist() - Convert to nested list string
20046 * - ndarray.fill() - Fill with scalar value (in-place)
20047 * - ndarray.item() - Get single element as scalar
20048 * - ndarray.itemset() - Set single element value
20049 * - ma.masked_all_like() - Create masked array with all elements masked
20050 *
20051 * Created: 2025-10-28
20052 * Status: Phase 6A Implementation - HIGH PRIORITY functions
20053 */
20054
20055#include "../numpy/np_ndarray.h"
data (np_test_1_all.cpp:2084)
2074    }
2075    if (!(derived_ptr->extra == 2)) {
2076        std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(derived_ptr->extra == 2)";
2077        std::cout << std::string("[FAIL] ") + description << std::endl;
2078        throw std::runtime_error(description);
2079    }
2080
2081    // Test 6: Large object handling
2082    struct LargeObject {
2083        std::vector<double> data;
2084        LargeObject() : data(10000, 3.14159) {}  // Large object
2085    };
2086
2087    LargeObject large;
2088    object_ large_obj(large);  // Should handle large objects
2089    if (!(!large_obj.is_null())) {
2090        std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(!large_obj.is_null())";
2091        std::cout << std::string("[FAIL] ") + description << std::endl;
2092        throw std::runtime_error(description);
2093    }
2094    if (!(large_obj.is_type<LargeObject>())) {
data (np_test_1_all.cpp:2084)
2074    }
2075    if (!(derived_ptr->extra == 2)) {
2076        std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(derived_ptr->extra == 2)";
2077        std::cout << std::string("[FAIL] ") + description << std::endl;
2078        throw std::runtime_error(description);
2079    }
2080
2081    // Test 6: Large object handling
2082    struct LargeObject {
2083        std::vector<double> data;
2084        LargeObject() : data(10000, 3.14159) {}  // Large object
2085    };
2086
2087    LargeObject large;
2088    object_ large_obj(large);  // Should handle large objects
2089    if (!(!large_obj.is_null())) {
2090        std::string description = std::string("testObjectHolderEdgeCases():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(!large_obj.is_null())";
2091        std::cout << std::string("[FAIL] ") + description << std::endl;
2092        throw std::runtime_error(description);
2093    }
2094    if (!(large_obj.is_type<LargeObject>())) {
dump (np_test_4_all.cpp:22039)
22029        return 1;
22030    }
22031}
22032
22033} // namespace numpy_tests
22034
22035// Comprehensive test suite for Phase 6 NDArray Methods
22036//
22037// This file tests the Phase 6 LOW priority NDArray methods:
22038// - byteswap() - Swap byte order for endianness conversion
22039// - dump() - Serialize array to binary file
22040// - dumps() - Serialize array to byte vector
22041// - setflags() - Set array metadata flags
22042
22043#include <iostream>
22044#include <stdexcept>
22045#include <fstream>
22046#include <cstring>
22047#include <vector>
22048#include <filesystem>
22049#include "../numpy/np_ndarray.h"
fill (np_test_4_all.cpp:20047)
20037} // namespace numpy_tests
20038
20039/**
20040 * @file np_test_phase6.cpp
20041 * @brief Test suite for Phase 6A - HIGH PRIORITY NDArray methods and masked array utilities
20042 *
20043 * Tests:
20044 * - ndarray.nonzero() - Return indices of non-zero elements
20045 * - ndarray.tobytes() - Convert to bytes representation
20046 * - ndarray.tolist() - Convert to nested list string
20047 * - ndarray.fill() - Fill with scalar value (in-place)
20048 * - ndarray.item() - Get single element as scalar
20049 * - ndarray.itemset() - Set single element value
20050 * - ma.masked_all_like() - Create masked array with all elements masked
20051 *
20052 * Created: 2025-10-28
20053 * Status: Phase 6A Implementation - HIGH PRIORITY functions
20054 */
20055
20056#include "../numpy/np_ndarray.h"
20057#include "../numpy/np_masked_array.h"
flat (np_test_5_all.cpp:11172)
11162    // ============================================================================
11163    // NDITER TESTS
11164    // ============================================================================
11165
11166    void np_test_nditer_basic() {
11167      std::cout << "========= NDIter: basic C-order iteration =======================";
11168
11169      // Create 2D array
11170      numpy::NDArray<int> arr({ 3, 4 });
11171      for (size_t i = 0; i < 12; ++i) {
11172        arr.flat(i) = static_cast<int>(i);
11173      }
11174
11175      // Test C-order iteration
11176      auto it = numpy::nditer(arr, true);
11177      int count = 0;
11178      while (!it.is_finished()) {
11179        int value = *it;
11180        auto indices = it.indices();
11181        size_t flat_idx = it.flat_index();
flat (np_test_5_all.cpp:11172)
11162    // ============================================================================
11163    // NDITER TESTS
11164    // ============================================================================
11165
11166    void np_test_nditer_basic() {
11167      std::cout << "========= NDIter: basic C-order iteration =======================";
11168
11169      // Create 2D array
11170      numpy::NDArray<int> arr({ 3, 4 });
11171      for (size_t i = 0; i < 12; ++i) {
11172        arr.flat(i) = static_cast<int>(i);
11173      }
11174
11175      // Test C-order iteration
11176      auto it = numpy::nditer(arr, true);
11177      int count = 0;
11178      while (!it.is_finished()) {
11179        int value = *it;
11180        auto indices = it.indices();
11181        size_t flat_idx = it.flat_index();
isAligned (np_test_4_all.cpp:22313)
22303        void np_test_phase6_setflags_basic() {
22304            std::cout << "========= setflags basic functionality =======================";
22305
22306            numpy::NDArray<int> arr({5});
22307
22308            // Check defaults
22309            if (!arr.isWriteable()) {
22310                std::cout << "  [FAIL] : Default writeable should be true";
22311                throw std::runtime_error("default writeable test failed");
22312            }
22313            if (!arr.isAligned()) {
22314                std::cout << "  [FAIL] : Default aligned should be true";
22315                throw std::runtime_error("default aligned test failed");
22316            }
22317
22318            // Set writeable to false
22319            arr.setflags(false);
22320            if (arr.isWriteable()) {
22321                std::cout << "  [FAIL] : Writeable should be false";
22322                throw std::runtime_error("setflags writeable test failed");
22323            }
isCContiguous (np_test_1_all.cpp:393)
383    std::cout << " -> tests passed" << std::endl;
384}
385
386void testMemoryLayoutQueries() {
387    std::cout << "========= testMemoryLayoutQueries =======================";
388
389    auto array = createFloat64Array({2, 3});
390
391    // std::cout << "Array contiguous: " << (array.isContiguous() ? "Yes" : "No") << std::endl;
392    // std::cout << "Array C-contiguous: " << (array.isCContiguous() ? "Yes" : "No") << std::endl;
393    // std::cout << "Array F-contiguous: " << (array.isFContiguous() ? "Yes" : "No") << std::endl;
394
395    // Test with a transposed view
396    auto transposed = array.transposeView();
397    // std::cout << "Transposed contiguous: " << (transposed.isContiguous() ? "Yes" : "No") << std::endl;
398    // std::cout << "Transposed C-contiguous: " << (transposed.isCContiguous() ? "Yes" : "No") << std::endl;
399    // std::cout << "Transposed F-contiguous: " << (transposed.isFContiguous() ? "Yes" : "No") << std::endl;
400
401    std::cout << " -> tests passed" << std::endl;
402}
isContiguous (np_test_1_all.cpp:392)
382    //array.printArray();
383
384    std::cout << " -> tests passed" << std::endl;
385}
386
387void testMemoryLayoutQueries() {
388    std::cout << "========= testMemoryLayoutQueries =======================";
389
390    auto array = createFloat64Array({2, 3});
391
392    // std::cout << "Array contiguous: " << (array.isContiguous() ? "Yes" : "No") << std::endl;
393    // std::cout << "Array C-contiguous: " << (array.isCContiguous() ? "Yes" : "No") << std::endl;
394    // std::cout << "Array F-contiguous: " << (array.isFContiguous() ? "Yes" : "No") << std::endl;
395
396    // Test with a transposed view
397    auto transposed = array.transposeView();
398    // std::cout << "Transposed contiguous: " << (transposed.isContiguous() ? "Yes" : "No") << std::endl;
399    // std::cout << "Transposed C-contiguous: " << (transposed.isCContiguous() ? "Yes" : "No") << std::endl;
400    // std::cout << "Transposed F-contiguous: " << (transposed.isFContiguous() ? "Yes" : "No") << std::endl;
401
402    std::cout << " -> tests passed" << std::endl;
isFContiguous (np_test_1_all.cpp:394)
384    std::cout << " -> tests passed" << std::endl;
385}
386
387void testMemoryLayoutQueries() {
388    std::cout << "========= testMemoryLayoutQueries =======================";
389
390    auto array = createFloat64Array({2, 3});
391
392    // std::cout << "Array contiguous: " << (array.isContiguous() ? "Yes" : "No") << std::endl;
393    // std::cout << "Array C-contiguous: " << (array.isCContiguous() ? "Yes" : "No") << std::endl;
394    // std::cout << "Array F-contiguous: " << (array.isFContiguous() ? "Yes" : "No") << std::endl;
395
396    // Test with a transposed view
397    auto transposed = array.transposeView();
398    // std::cout << "Transposed contiguous: " << (transposed.isContiguous() ? "Yes" : "No") << std::endl;
399    // std::cout << "Transposed C-contiguous: " << (transposed.isCContiguous() ? "Yes" : "No") << std::endl;
400    // std::cout << "Transposed F-contiguous: " << (transposed.isFContiguous() ? "Yes" : "No") << std::endl;
401
402    std::cout << " -> tests passed" << std::endl;
403}
isWriteable (np_test_4_all.cpp:22309)
22299        // ============================================================================
22300        // SETFLAGS TESTS
22301        // ============================================================================
22302
22303        void np_test_phase6_setflags_basic() {
22304            std::cout << "========= setflags basic functionality =======================";
22305
22306            numpy::NDArray<int> arr({5});
22307
22308            // Check defaults
22309            if (!arr.isWriteable()) {
22310                std::cout << "  [FAIL] : Default writeable should be true";
22311                throw std::runtime_error("default writeable test failed");
22312            }
22313            if (!arr.isAligned()) {
22314                std::cout << "  [FAIL] : Default aligned should be true";
22315                throw std::runtime_error("default aligned test failed");
22316            }
22317
22318            // Set writeable to false
22319            arr.setflags(false);
ownsData (np_test_1_all.cpp:577)
567    std::cout << "========= testViewMemoryProperties =======================";
568
569    auto original = createFloat64Array({3, 4}, 2.5);
570
571    // Test various view properties
572    auto basic_view = original.view();
573    auto transpose_view = original.transposeView();
574    auto slice_view = original.sliceView({{0, 2}, {1, 3}});
575
576    // Check ownership flags
577    bool orig_owns = original.ownsData();
578    if (orig_owns != true) {
579        std::cout << "[FAIL] in testViewMemoryProperties(): original.ownsData() = " << orig_owns << ", expected true" << std::endl;
580        throw std::runtime_error("testViewMemoryProperties(): original ownership flag incorrect");
581    }
582    bool basic_owns = basic_view.ownsData();
583    if (basic_owns != false) {
584        std::cout << "[FAIL] in testViewMemoryProperties(): basic_view.ownsData() = " << basic_owns << ", expected false" << std::endl;
585        throw std::runtime_error("testViewMemoryProperties(): basic_view ownership flag incorrect");
586    }
587    bool transpose_owns = transpose_view.ownsData();
printArray (np_test_1_all.cpp:67)
57        std::vector<size_t> indices(arr.getShape().size(), 0);
58        do {
59            if (arr.getElementAt(indices)) {
60                return false;
61            }
62        } while (incrementIndices(indices, arr.getShape()));
63        return true;
64    }
65
66    template<typename T>
67    void printArray(const NDArray<T>& arr, const std::string& name) {
68        std::cout << name << ": ";
69        if (arr.getShape().size() == 1) {
70            for (size_t i = 0; i < arr.getShape()[0]; ++i) {
71                // std::cout << arr.getElementAt({i}) << " ";
72            }
73        }
74        // std::cout << std::endl;
75    }
76
77    // Helper functions for bitwise operations tests
setElementAt (np_test_1_all.cpp:135)
125    //ones_array.printArray();
126
127    std::cout << " -> tests passed" << std::endl;
128}
129
130void testElementAccess() {
131    std::cout << "========= testElementAccess =======================";
132
133    auto array = createInt32Array({3, 3}, 0);
134
135    array.setElementAt({0, 0}, 1);
136    array.setElementAt({0, 1}, 2);
137    array.setElementAt({0, 2}, 3);
138    array.setElementAt({1, 1}, 5);
139    array.setElementAt({2, 2}, 9);
140
141    // std::cout << "Array after setting elements:" << std::endl;
142    //array.printArray();
143
144    // std::cout << "Element at (1,1): " << array.getElementAt({1, 1}) << std::endl;
145    // std::cout << "Element at (2,2): " << array.getElementAt({2, 2});
setElementAt (np_test_1_all.cpp:135)
125    //ones_array.printArray();
126
127    std::cout << " -> tests passed" << std::endl;
128}
129
130void testElementAccess() {
131    std::cout << "========= testElementAccess =======================";
132
133    auto array = createInt32Array({3, 3}, 0);
134
135    array.setElementAt({0, 0}, 1);
136    array.setElementAt({0, 1}, 2);
137    array.setElementAt({0, 2}, 3);
138    array.setElementAt({1, 1}, 5);
139    array.setElementAt({2, 2}, 9);
140
141    // std::cout << "Array after setting elements:" << std::endl;
142    //array.printArray();
143
144    // std::cout << "Element at (1,1): " << array.getElementAt({1, 1}) << std::endl;
145    // std::cout << "Element at (2,2): " << array.getElementAt({2, 2});
setflags (np_test_4_all.cpp:22041)
22031}
22032
22033} // namespace numpy_tests
22034
22035// Comprehensive test suite for Phase 6 NDArray Methods
22036//
22037// This file tests the Phase 6 LOW priority NDArray methods:
22038// - byteswap() - Swap byte order for endianness conversion
22039// - dump() - Serialize array to binary file
22040// - dumps() - Serialize array to byte vector
22041// - setflags() - Set array metadata flags
22042
22043#include <iostream>
22044#include <stdexcept>
22045#include <fstream>
22046#include <cstring>
22047#include <vector>
22048#include <filesystem>
22049#include "../numpy/np_ndarray.h"
22050
22051// IMPORTANT: No using namespace directives to avoid name clashes
toString (np_test_1_all.cpp:6826)
6816void testDatetime64CreationDateTime() {
6817    std::cout << "========= testDatetime64CreationDateTime =======================";
6818
6819    // Test default constructor
6820    datetime64 default_dt;
6821    if (!(default_dt.isNaT())) {
6822        std::string description = std::string("testDatetime64CreationDateTime():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(default_dt.isNaT())";
6823        std::cout << std::string("[FAIL] ") + description << std::endl;
6824        throw std::runtime_error(description);
6825    }
6826    // std::cout << "Default datetime64 is NaT: " << default_dt.toString() << std::endl;
6827
6828    // Test value constructor
6829    datetime64 epoch_day(0, DateTimeUnit::Day);
6830    // std::cout << "Epoch day: " << epoch_day.toString() << std::endl;
6831
6832    // Test string constructor
6833    datetime64 date_from_string("2024-01-15");
6834    // std::cout << "Date from string '2024-01-15': " << date_from_string.toString() << std::endl;
6835
6836    datetime64 datetime_from_string("2024-01-15T10:30:45");