Small matrices in armadillo from numpy via carma

38 Views Asked by At

I am trying to create a project using both python (for io and plotting etc.) as well as c++ and armadillo in particular (for heavier computations), linking the two via carma.

I am quite new to c++ and armadillo - so apologies for asking perhaps a silly question.

My goal is to pass some numpy arrays by reference to c++, do some computations on the arrays and then continue to process them in python and I get this to work. I have noticed, however, that small and larger matrices behave differently when I pass them to c++.

In particular, for matrices up to size around 4 x 4, they seem to get copied to a new memory address once passed to c++ by reference, whereas larger matrices remain at their original memory address.

Here is a minimal working example:

c++

#include <carma>
#include <armadillo>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <iostream>

void autoconvert(arma::Mat<double> & small, arma::Mat<double> & large) {

    std::cout << "memory addresses of armadillo matrices:" << std::endl;
    std::cout << small.n_rows << " X " << small.n_cols << " mem-addr: " << reinterpret_cast<uintptr_t>(small.memptr()) << std::endl;
    std::cout << large.n_rows << " X " << large.n_cols << " mem-addr: " << reinterpret_cast<uintptr_t>(large.memptr()) << std::endl;
}

// Module definition
PYBIND11_MODULE(autoconvert_module, m) {
    m.def("autoconvert", &autoconvert);
}

python

import numpy as np

import autoconvert_module

small = np.asarray(np.random.standard_normal((4,4)), order='F')
large = np.asarray(np.random.standard_normal((5,5)), order='F')

print('memory addresses of numpy arrays:')
print(' X '.join([str(d) for d in small.shape]), 'mem-addr:', small.ctypes.data)
print(' X '.join([str(d) for d in large.shape]), 'mem-addr:', large.ctypes.data)

autoconvert_module.autoconvert(
    small,
    large
)

My suspicion is that this may have to do with carma / armadillo - internal optimizations for small matrices.

0

There are 0 best solutions below