1

I am currently trying to move some of my algorithms from Mathematica to sympy. In this context, I am trying to find a c-code-generator in correspondance to the mathematica packages:

which allow to export symbolic expressions to efficient C-Code, including vector-valued functions. I have been searching in the sympy documentation, but it appears that the codegen only works with scalar functions. What I need is a way to export vector-valued functions computationally efficient to C.

Example: Assuming I have the 2 dimensional vectors x and y and want to create a function that is returning the 2 dimensional vector out:

out=[(x(0)+y(0))^2,x(0)+y(0)+y(1)]  //MATLAB convention

That shall be exported to a C-function like that:

void c_func (double* out, double *x, double *y){
  tmp1=x[0]+y[0];
  out[0]=tmp1*tmp1; //(x[0]+y[0])^2
  out[1]=tmp1+y[1]; //x[0]+y[0]+y[1]
}

However, until now I can export only a scalar function. Therefore, I am stuck at following questions:

  1. How to use vectors as function arguments
  2. How to use vectors as return arguments
  3. How to optimally reuse mathematical operations (e.g. creating temporary variable tmp1=(x+1) that is reused for out[0] and out[1]) which is not possible if you export each vector element sequentially

Do you know, how this is implemented in sympy or do you have any alternative solutions? Thanks a lot in advance!!!!

The currently used code for scalar expression export:

from sympy import*
from sympy.utilities.codegen import codegen

x1,x2 =   symbols('x1 x2')
x=Matrix([x1,x2])
y1,y2 =   symbols('y1 y2')
y=Matrix([y1,y2])

[(c_name, c_code), (h_name, c_header)] = codegen(("f", (x1+y2)**2), "C","myheader")
print(c_code)
[(c_name, c_code), (h_name, c_header)] = codegen(("f", (x1+y1+y2)), "C","")
print(c_code)

which gives the output:

******************************************************************************/
#include "myheader.h"
#include <math.h>

double f(double x1, double y2) {
   return pow(x1 + y2, 2);
}

******************************************************************************/
#include ".h"
#include <math.h>

double f(double x1, double y1, double y2) {
   return x1 + y1 + y2;
}
DentOpt
  • 77
  • 1
  • 6

0 Answers0