SymPy
does a wonderful work keeping track of all the operations I do to my symbolic expressions. But a the moment of printing the result for latex output I would like to enforce a certain ordering of the term. This is just for convention, and unfortunately that convention is not alphabetical on the symbol name(as reasonably sympy
does)
import sympy as sp
sp.init_printing()
U,tp, z, d = sp.symbols('U t_\perp z d')
# do many operations with those symbols
# the final expression is:
z+tp**2+U+U/(z-3*tp)+d
My problem is that SymPy
presents the expression ordered as
U + U/(-3*t_\perp + z) + d + t_\perp**2 + z
But this ordering is not the convention in my field. For us z
has to be the leftmost expression, then tp
, then U
even if it is capitalized, d
is the most irrelevant and is put at the right. All this variables hold a particular meaning and that is the reason we write them in such order, and the reason in the code variables are named in such way.
I don't want to rename z
to a
and as suggested in Prevent Sympy from rearranging the equation and then at the moment of printing transform that a
into z
. In Force SymPy to keep the order of terms there is a hint I can write a sorting function but I could not find documentation about it.
If you can put the terms in the order you want then setting the order
flag for the Latex printer to 'none' will print them in that order.
>>> import sympy as sp
>>> sp.init_printing()
>>> U,tp, z, d = sp.symbols('U t_\perp z d')
>>> eq=z+tp**2+U+U/(z-3*tp)+d
Here we put them in order (knowing the power of tp
is 2) and rebuild as an Add with evaluate=False
to keep the order unchanged
>>> p = Add(*[eq.coeff(i)*i for i in (z, U, tp**2, d)],evaluate=False)
And now we print that expression with a printer instance with order='none'
:
>>> from sympy.printing.latex import LatexPrinter
>>> s=LatexPrinter(dict(order='none'))
>>> s._print_Add(p)
z + U \left(1 + \frac{1}{z - 3 t_\perp}\right) + t_\perp^{2} + d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With