Rene
Rene

Reputation: 41

Extend and Embed Python (and NumPy) with C++ (and GSL): pass gsl_matrix to python and back

my problem "should" be simple but I am still not able to solve it.

I am currently working on a project that requires some heavy computations (done in C++) and some post-simulations data analysis (done in Python).

However, now I am changing the main algorithm and I will need to "cycle" some computations back and forth from C++ and Python. That is, I will need to move back and forth from C++ and Python a matrix of doubles.

In C++ the matrix of data is a "gsl_matrix" object while in python the same matrix is implemented as a "numpy array".

At the moment, I am running my C++ code, saving the matrix to file, reading it from python, writing it back to file and then opening it back again in C++ for further computations.

Since this is VERY inefficient, I would like to ask if somebody can give me an example on how to do it in a "clean" way.

I have been reading (and trying for 10 days) SWIG, Cython, Boost.Python and Boost.Numpy but I'm still not able to crack it.

Does anyone have a worked example to share?

Thanks!

Rene

Upvotes: 4

Views: 820

Answers (1)

Vivian Miranda
Vivian Miranda

Reputation: 2485

I think you don't need to implement yourself the wrapper, because you may use pygsl. If you really want to implement your own version, here is the routine from pygsl that might be worth to you

%{
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_matrix_complex_double.h>
%}

%include typemaps.i

// gsl_matrix typemaps
%typemap(in) gsl_matrix* %{
  PyArrayObject *_PyMatrix$argnum;
  gsl_matrix_view matrix$argnum;
  {
    _PyMatrix$argnum = (PyArrayObject*)
      PyArray_ContiguousFromObject($input, PyArray_DOUBLE, 2, 2);
    if (_PyMatrix$argnum == NULL)
      return NULL;
    matrix$argnum
      = gsl_matrix_view_array((double*)_PyMatrix$argnum->data,
                  _PyMatrix$argnum->dimensions[0],
                  _PyMatrix$argnum->dimensions[1]);    
    $1 = &matrix$argnum.matrix;
  }
%}

Upvotes: 1

Related Questions