Ask Your Question
0

sympy codegen with indices

asked 2012-01-28 17:42:55 +0200

Shashank gravatar image

I am doing a symbolic calculation in sage and I need a C-code of the output. I found an example in sympy documentation that does this.

from sympy import symbols
from sympy.utilities.codegen import codegen
from sympy.abc import x, y, z
[(c_name, c_code), (h_name, c_header)] = \
codegen(("f", x+y*z), "C", "test", header=False, empty=False)
print c_code,

However, this does not work when the variables I am passing to f have indices for example,

from sympy import symbols
from sympy.utilities.codegen import codegen
from sympy.abc import x[0], x[1], x[2]
[(c_name, c_code), (h_name, c_header)] = \
codegen(("f", x[0]+x[1]*x[2]), "C", "test", header=False, empty=False)
print c_code,

This results in an error. Is there a way to generate a C-code with indices in them?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2012-01-28 19:17:57 +0200

Shashank gravatar image

Found the solution. We have to explicitly define index

from sympy.tensor import IndexedBase, Idx
from sympy import symbols
n,m = symbols('n m', integer=True)
A = IndexedBase('A')
x = IndexedBase('x')
y = IndexedBase('y')
i = Idx('i', m)
j = Idx('j', n)

codegen(('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C","file", header=False, empty=False)
edit flag offensive delete link more

Comments

To get your 'answer code to work I need: 'from sympy.utilities.codegen import codegen' and 'from sympy import Eq'

rtrwalker gravatar imagertrwalker ( 2013-03-27 19:47:49 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2012-01-28 17:42:55 +0200

Seen: 1,087 times

Last updated: Jan 28 '12