MemoryMappedArray#

class numpy::MemoryMappedArray#

numpy C++ class.

Example#

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

// Use MemoryMappedArray
MemoryMappedArray obj;
// ... operations ...

Constructors#

Signature

Location

Example

MemoryMappedArray(const std::string &filename, const std::vector<size_t>&shape, MMapModemode = MMapMode::READ_WRITE, size_toffset = 0)

NP_MEMMAP.H:502

MemoryMappedArray(const MemoryMappedArray &)

NP_MEMMAP.H:565

noexcept MemoryMappedArray(MemoryMappedArray &&other)

NP_MEMMAP.H:569

MemoryMappedArray(const std::string &filename, boolread_only = true)

NP_MEMORY_POOL.H:323

MemoryMappedArray(const MemoryMappedArray &)

NP_MEMORY_POOL.H:327

noexcept MemoryMappedArray(MemoryMappedArray &&other)

NP_MEMORY_POOL.H:330

Operators#

Signature

Return Type

Location

Example

MemoryMappedArray & operator=(const MemoryMappedArray &)

MemoryMappedArray &

NP_MEMMAP.H:566

MemoryMappedArray & noexcept operator=(MemoryMappedArray &&other)

MemoryMappedArray & noexcept

NP_MEMMAP.H:573

operator NDArray<T>&()

NP_MEMMAP.H:611

operator const NDArray<T>&()

NP_MEMMAP.H:612

MemoryMappedArray & operator=(const MemoryMappedArray &)

MemoryMappedArray &

NP_MEMORY_POOL.H:328

MemoryMappedArray & noexcept operator=(MemoryMappedArray &&other)

MemoryMappedArray & noexcept

NP_MEMORY_POOL.H:331

T & operator[](size_tindex)

T &

NP_MEMORY_POOL.H:337

const T & operator[](size_tindex)

const T &

NP_MEMORY_POOL.H:338

Construction#

Signature

Return Type

Location

Example

MemoryMappedArray<T> from_npy(const std::string &filename, MMapModemode = MMapMode::READ_ONLY)

MemoryMappedArray<T>

NP_MEMMAP.H:541

View

Indexing / Selection#

Signature

Return Type

Location

Example

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

T

NP_MEMMAP.H:622

View

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

const std::vector<size_t>&

NP_MEMMAP.H:619

View

size_t getSize()

size_t

NP_MEMMAP.H:620

View

Math Operations#

Signature

Return Type

Location

Example

MMapMode mode()

MMapMode

NP_MEMMAP.H:603

View

Type Checking#

Signature

Return Type

Location

Example

bool is_open()

bool

NP_MEMMAP.H:606

View

bool is_valid()

bool

NP_MEMORY_POOL.H:345

Other Methods#

Signature

Return Type

Location

Example

NDArray<T>& array()

NDArray<T>&

NP_MEMMAP.H:615

View

const NDArray<T>& array()

const NDArray<T>&

NP_MEMMAP.H:616

View

T \* begin()

T *

NP_MEMORY_POOL.H:340

View

const T \* begin()

const T *

NP_MEMORY_POOL.H:342

View

void close()

void

NP_MEMMAP.H:592

View

T \* data()

T *

NP_MEMORY_POOL.H:333

View

const T \* data()

const T *

NP_MEMORY_POOL.H:334

View

T \* end()

T *

NP_MEMORY_POOL.H:341

View

const T \* end()

const T *

NP_MEMORY_POOL.H:343

View

const std::string & filename()

const std::string &

NP_MEMMAP.H:600

void flush()

void

NP_MEMMAP.H:584

View

void initializeMappedArray(const std::string &filename, const std::vector<size_t>&shape, MMapModemode, size_toffset)

void

NP_MEMMAP.H:522

void printArray()

void

NP_MEMMAP.H:628

View

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

void

NP_MEMMAP.H:624

View

size_t size()

size_t

NP_MEMORY_POOL.H:335

View

std::string toString()

std::string

NP_MEMMAP.H:626

View

Code Examples#

The following examples are extracted from the test suite.

from_npy (np_test_3_all.cpp:10846)
10836          for (size_t j = 0; j < 6; ++j) {
10837            arr.setElementAt({ i, j }, value++);
10838          }
10839        }
10840        save(arr, filename);
10841        // std::cout << "[OK] Created NPY file" << std::endl;
10842      }
10843
10844      // Load as memory-mapped array
10845      {
10846        auto mmap_npy = memmap::MemoryMappedArray<double>::from_npy(filename, memmap::MMapMode::READ_WRITE);
10847
10848        // Verify shape
10849        auto shape = mmap_npy.getShape();
10850        if (!(shape.size() == 2)) {
10851            std::string description = std::string("np_test_io_memmap_npy_files():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(shape.size() == 2)";
10852            std::cout << std::string("[FAIL] ") + description << std::endl;
10853            throw std::runtime_error(description);
10854        }
10855        if (!(shape[0] == 4)) {
10856            std::string description = std::string("np_test_io_memmap_npy_files():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(shape[0] == 4)";
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    }
mode (np_test_4_all.cpp:20711)
20701#include <stdexcept>
20702
20703using namespace numpy;
20704
20705namespace numpy_tests {
20706namespace numpy_tests_phase6b {
20707
20708void np_test_phase6b_can_cast() {
20709    std::cout << "=== Test can_cast() ===";
20710
20711    // Test SAFE casting mode (default)
20712    {
20713        // Same type is always safe
20714        if (!(can_cast(DType::INT32, DType::INT32, CastingMode::SAFE) == true)) {
20715            std::string description = std::string("np_test_phase6b_can_cast():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(can_cast(DType::INT32, DType::INT32, CastingMode::SAFE) == true)";
20716            std::cout << std::string("[FAIL] ") + description << std::endl;
20717            throw std::runtime_error(description);
20718        }
20719        if (!(can_cast(DType::FLOAT64, DType::FLOAT64, CastingMode::SAFE) == true)) {
20720            std::string description = std::string("np_test_phase6b_can_cast():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(can_cast(DType::FLOAT64, DType::FLOAT64, CastingMode::SAFE) == true)";
20721            std::cout << std::string("[FAIL] ") + description << std::endl;
is_open (np_test_3_all.cpp:11184)
11174      mmap1.setElementAt({ 1, 1 }, 42);
11175      mmap1.flush();
11176
11177      // Move constructor
11178      auto mmap2 = std::move(mmap1);
11179      if (!(mmap2.getElementAt({ 1, 1 }) == 42)) {
11180          std::string description = std::string("np_test_io_memmap_move_semantics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(mmap2.getElementAt({ 1, 1 }) == 42)";
11181          std::cout << std::string("[FAIL] ") + description << std::endl;
11182          throw std::runtime_error(description);
11183      }
11184      if (!(mmap2.is_open())) {
11185          std::string description = std::string("np_test_io_memmap_move_semantics():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(mmap2.is_open())";
11186          std::cout << std::string("[FAIL] ") + description << std::endl;
11187          throw std::runtime_error(description);
11188      }
11189      // std::cout << "[OK] Move constructor works" << std::endl;
11190
11191      // Move assignment
11192      auto mmap3 = memmap::memmap<int32_t>(filename, { 3, 3 }, "r+");
11193      mmap3 = std::move(mmap2);
11194      if (!(mmap3.getElementAt({ 1, 1 }) == 42)) {
array (np_test_1_all.cpp:243)
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();
245
246    auto reshaped = range_array.reshapeArray({3, 4});
247    // std::cout << "Reshaped to 3x4:";
248    //reshaped.printArray();
249
250    auto flattened = reshaped.flattenArray();
251    // std::cout << "Flattened:" << std::endl;
252    //flattened.printArray();
array (np_test_1_all.cpp:243)
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();
245
246    auto reshaped = range_array.reshapeArray({3, 4});
247    // std::cout << "Reshaped to 3x4:";
248    //reshaped.printArray();
249
250    auto flattened = reshaped.flattenArray();
251    // std::cout << "Flattened:" << std::endl;
252    //flattened.printArray();
begin (np_test_1_all.cpp:6171)
6161    // Test sorted data generation
6162    std::vector<int> data = gen.generate(50, DataPattern::SORTED);
6163
6164    if (!(data.size() == 50)) {
6165        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 50)";
6166        std::cout << std::string("[FAIL] ") + description << std::endl;
6167        throw std::runtime_error(description);
6168    }
6169
6170    // Verify data is sorted
6171    if (!(std::is_sorted(data.begin(), data.end()))) {
6172        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::is_sorted(data.begin(), data.end()))";
6173        std::cout << std::string("[FAIL] ") + description << std::endl;
6174        throw std::runtime_error(description);
6175    }
6176
6177    // std::cout << "Sorted data generation test passed" << std::endl;
6178
6179    std::cout << " -> tests passed" << std::endl;
6180}
begin (np_test_1_all.cpp:6171)
6161    // Test sorted data generation
6162    std::vector<int> data = gen.generate(50, DataPattern::SORTED);
6163
6164    if (!(data.size() == 50)) {
6165        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 50)";
6166        std::cout << std::string("[FAIL] ") + description << std::endl;
6167        throw std::runtime_error(description);
6168    }
6169
6170    // Verify data is sorted
6171    if (!(std::is_sorted(data.begin(), data.end()))) {
6172        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::is_sorted(data.begin(), data.end()))";
6173        std::cout << std::string("[FAIL] ") + description << std::endl;
6174        throw std::runtime_error(description);
6175    }
6176
6177    // std::cout << "Sorted data generation test passed" << std::endl;
6178
6179    std::cout << " -> tests passed" << std::endl;
6180}
close (np_test_1_all.cpp:26157)
26147    void np_test_recarray_fromfile() {
26148      std::cout << "========= fromfile: create RecordArray from file =======================";
26149
26150      // Create temporary test file
26151      std::string filename = "D:/Projects/Cpp2/temp/test_recarray.csv";
26152      std::ofstream outfile(filename);
26153      outfile << "1,10.5\n";
26154      outfile << "2,20.5\n";
26155      outfile << "3,30.5\n";
26156      outfile.close();
26157
26158      // Define dtype
26159      std::vector<std::pair<std::string, numpy::DType>> fields = {
26160          {"id", numpy::DType::INT32},
26161          {"value", numpy::DType::FLOAT64}
26162      };
26163      auto dtype = std::make_shared<numpy::StructuredDType>(fields);
26164
26165      // Load from file
26166      auto result = numpy::fromfile(filename, dtype, ",");
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>())) {
end (np_test_1_all.cpp:6171)
6161    // Test sorted data generation
6162    std::vector<int> data = gen.generate(50, DataPattern::SORTED);
6163
6164    if (!(data.size() == 50)) {
6165        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 50)";
6166        std::cout << std::string("[FAIL] ") + description << std::endl;
6167        throw std::runtime_error(description);
6168    }
6169
6170    // Verify data is sorted
6171    if (!(std::is_sorted(data.begin(), data.end()))) {
6172        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::is_sorted(data.begin(), data.end()))";
6173        std::cout << std::string("[FAIL] ") + description << std::endl;
6174        throw std::runtime_error(description);
6175    }
6176
6177    // std::cout << "Sorted data generation test passed" << std::endl;
6178
6179    std::cout << " -> tests passed" << std::endl;
6180}
end (np_test_1_all.cpp:6171)
6161    // Test sorted data generation
6162    std::vector<int> data = gen.generate(50, DataPattern::SORTED);
6163
6164    if (!(data.size() == 50)) {
6165        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(data.size() == 50)";
6166        std::cout << std::string("[FAIL] ") + description << std::endl;
6167        throw std::runtime_error(description);
6168    }
6169
6170    // Verify data is sorted
6171    if (!(std::is_sorted(data.begin(), data.end()))) {
6172        std::string description = std::string("test_data_generator_sortedBenchmarkSorting():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(std::is_sorted(data.begin(), data.end()))";
6173        std::cout << std::string("[FAIL] ") + description << std::endl;
6174        throw std::runtime_error(description);
6175    }
6176
6177    // std::cout << "Sorted data generation test passed" << std::endl;
6178
6179    std::cout << " -> tests passed" << std::endl;
6180}
flush (np_test_2_all.cpp:10646)
10636      std::vector<size_t> shape = { 10, 5 };
10637      auto mmap_array = numpy::memmap::memmap<float>(TEMP_DIR + "test_memmap_new.npy", shape, "w+");
10638
10639      // Write some data
10640      for (size_t i = 0; i < 10; ++i) {
10641        for (size_t j = 0; j < 5; ++j) {
10642          mmap_array.setElementAt({ i, j }, static_cast<float>(i * 5 + j + 1));
10643        }
10644      }
10645
10646      mmap_array.flush();
10647      // std::cout << "[OK] Created and wrote to memory-mapped file\n";
10648
10649      // Test reading from existing memory-mapped file
10650      auto mmap_readonly = numpy::memmap::memmap<float>(TEMP_DIR + "test_memmap_new.npy", shape, "r");
10651
10652      for (size_t i = 0; i < 10; ++i) {
10653        for (size_t j = 0; j < 5; ++j) {
10654          float expected = static_cast<float>(i * 5 + j + 1);
10655          if (!(approx_equal(mmap_readonly.getElementAt({ i, j }), expected, 1e-6f))) {
10656              std::string description = std::string("testMemoryMapping():") + __FILE__ + ":" + std::to_string(__LINE__) + ": !(approx_equal(mmap_readonly.getElementAt({ i, j }), expected, 1e-6f))";
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});
size (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);
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");