Example code for getting optimized(CSE) code of jacobian from symbolic calculation
from sympy import Matrix, sin, cos, cse from sympy.abc import rho, phi from sympy.utilities.codegen import codegen from sympy.printing import print_ccode X, Y = Matrix([rho*cos(phi),rho*sin(phi),rho**2]), Matrix([rho, phi]) J = X.jacobian(Y) tmp, result = cse(J) for l in tmp: l = 'double %s = %s;'%(l[0], l[1]) print l result = result[0].tolist() for r, row in enumerate(result): for c, elem in enumerate(row): l = 'output[%d][%d] = %s;'%(r,c,elem) print l
the result will be
double x0 = cos(phi);
double x1 = sin(phi);
output[0][0] = x0;
output[0][1] = -rho*x1;
output[1][0] = x1;
output[1][1] = rho*x0;
output[2][0] = 2*rho;
output[2][1] = 0;
No comments:
Post a Comment