2

Consider two variables defined using sympy in an IPython (Jupyter) notebook:

R_g     =Symbol(r'R_{g}')
L_g     =Symbol(r'L_{g}')

Imagine I do some mathematical operations and then I end up with a complicated expression, whose features can be illustrated by a simple example as follows:

 a=R_g*L_g
 print a

This prints:

L_{g}*R_{g}

I want it to print

R_g*L_g

and not

$R_g L_g$

The reason is that I want to copy-paste this expression into a fortran code. It becomes a challenge because I am using Latex to format variables. So I have to format terms that have variables like

 IL_np1  =Symbol(r'I_{L}^{n+1}')
wander95
  • 1,298
  • 1
  • 15
  • 22

2 Answers2

2

Just name your symbols appropriately:

R_g = Symbol(r'R_g')
L_g = Symbol(r'L_g')
a = R_g * L_g

print(a)

Output:

R_g*L_g

Or clean up manually:

>>> s = Symbol(r'I_{L}^{n+1}')
>>> s
I_{L}^{n+1}

def make_clean_name(symbol, toremove='{}', replace=None): 
    replace = {'^': '**'}  if replace is None else {}
    return ''.join(replace.get(x, x) for x in symbol.name if x not in toremove)

>>> make_clean_name(s)
'I_L**n+1'
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • I am trying to use Latex display to format terms so I have variables like `IL_np1 =Symbol(r'I_{L}^{n+1}')` – wander95 Jan 27 '17 at 15:54
2

You could use a custom Symbol subclass that prints one way with latex() and another with fcode().

class CustomSymbol(Symbol):
    def __new__(cls, fcode_name, latex_name, **kwargs):
        x = Symbol.__new__(CustomSymbol, fcode_name, **kwargs)
        x.latex_name = latex_name
        return x

    def _latex(self, printer):
        return self.latex_name

It works like

In [114]: latex(CustomSymbol('x_2', 'x_{2}'))
Out[114]: 'x_{2}'

In [115]: fcode(CustomSymbol('x_2', 'x_{2}'))
Out[115]: '      x_2'

I've set the default name as the fcode name. If you want it the other way around, you can define _fcode instead of _latex.

asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • this looks interesting. Will try and get back – wander95 Jan 31 '17 at 15:46
  • preliminary results encouraging. Can you or anyone explain how this worked? – wander95 Jan 31 '17 at 15:56
  • @wander95 every printer in SymPy lets you define its behavior on custom SymPy objects by defining a special method. In this case, the methods for the LaTeX and Fortran printers are `_latex` and `_fcode`, respectively. See http://docs.sympy.org/latest/modules/printing.html for more details. – asmeurer Jan 31 '17 at 18:19