Overriding printing library to put prefix on symbols for code generation

44 views
Skip to first unread message

Richard Brown

unread,
Nov 3, 2015, 6:03:45 PM11/3/15
to sympy
Hi there

I'm a relative python/sympy newbie, and I need a little help on a problem. I'm writing a piece of code that translates a system of differential equations into either C, Python, or MATLAB/Octave code that can be interfaced to solvers in those languages. The models are specified using .ini files, and I'm using sympy's code generators to translate the model equations (which are in python syntax). So far so good.

What I want to be able to do, is take an expression like

prefix = 'foo'
str = 'x**2 - sin(x) + exp(xy)'

and turn it into C (or MATLAB) like

'pow(foo_x, 2) - sin(foo_x) + exp(foo_x * foo_y)'

I know this involves overriding the printing library somehow, but I'm getting confused with where to start. Should I be overriding the __str__ method of atom?

Any help would be gratefully accepted

Richard

Jason Moore

unread,
Nov 3, 2015, 11:01:53 PM11/3/15
to sy...@googlegroups.com
How about something like this:

In [1]: from sympy.abc import a, b, c

In [2]: from sympy.printing.ccode import CCodePrinter

In [3]: class MyPrinter(CCodePrinter):
    def _print_Symbol(self, expr):
        name = super(CCodePrinter, self)._print_Symbol(expr)
        return 'foo_' + name
   ...:    

In [4]: MyPrinter().doprint(a)
Out[4]: 'foo_a'

--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To post to this group, send email to sy...@googlegroups.com.
Visit this group at http://groups.google.com/group/sympy.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/d4c5d051-d835-4a63-a966-191938935a2d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jason Moore

unread,
Nov 4, 2015, 8:21:46 AM11/4/15
to sy...@googlegroups.com
This should be:


class MyPrinter(CCodePrinter):
    def _print_Symbol(self, expr):
        name = super(MyPrinter, self)._print_Symbol(expr)
        return 'foo_' + name

Richard Brown

unread,
Nov 4, 2015, 3:37:03 PM11/4/15
to sympy
As easy as that! Thank you, that's essentially exactly what I wanted to do.

cheers

Richard
Reply all
Reply to author
Forward
0 new messages