Enforce custom ordering on Sympy print

孤者浪人 提交于 2019-12-21 12:22:53

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/44414547/enforce-custom-ordering-on-sympy-print

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!