如何更紧凑地打印导数(下标符号)

问题描述 投票:0回答:1

目前我对SymPy的输出有一点困难。默认情况下,通过执行以下内容(假设使用Jupyter Notebook)。

from sympy import *

t, x = symbols('t x')
u    = Function('u')(t, x)

display(Eq(I*u.diff(t) + u.diff(x,x) + abs(u)**2*u))

它打印的是

Default output

我想这样,但是

Desired output

以增加可读性。有谁知道如何实现这个目标?我对SymPy比较陌生,真的很想得到这样的输出。

期待您的解答!

EDIT1:

我采纳了@smichr的建议,稍作调整,写成了一个函数。希望我涵盖了所有重要的东西。下面是这个函数

# Assuming that symbols and functions with greek letters are defined like this
# omega = Function('\\omega')(t, x)

def show(expr):
    functions = expr.atoms(Function)
    reps = {}

    for fun in functions:
        # Consider the case that some functions won't have the name
        # attribute e.g. Abs of an elementary function
        try:            
            reps[fun] = Symbol(fun.name) # Otherwise functions with greek symbols aren't replaced
        except AttributeError:
            continue

    dreps = [(deriv, Symbol(deriv.expr.subs(reps).name + "_{," + 
                            ''.join(par.name for par in deriv.variables) + "}"))  \
             for deriv in expr.atoms(Derivative)]

    # Ensure that higher order derivatives are replaced first, then lower ones. 
    # Otherwise you get d/dr w_r instead of w_rr
    dreps.sort(key=lambda x: len(x[0].variables), reverse=True)
    output = expr.subs(dreps).subs(reps)

    display(output)

zeta, eta = symbols('\\zeta \\eta')
psi       = Function('\\psi')(zeta, eta)

eq = Eq(I*psi.diff(zeta) + psi.diff(eta, eta) + abs(psi)**2*psi, 0)
show(eq)

其中显示Edited functiuons output

python printing latex output sympy
1个回答
1
投票

Derivative (像所有的SymPy对象一样)有参数--有时被命名--你可以用这些参数做任何对你有用的事情。在这种情况下,似乎你想要的是用一个字母来代替函数和衍生变量的复合符号。这里是一个尝试,可以根据需要进行调整。

>>> reps={u:'u'}
>>> dreps = [(i,i.expr.subs(reps).name+"_"+''.join(v.name for v in i.variables)
    for i in eq.atoms(Derivative)]
>>> eq.subs(dreps).subs(reps)
u*Abs(u)**2 + I*u_t + u_xx

然而,要得到它们是有一定顺序的, 需要改变相关的打印机。例如,请看 此处.

© www.soinside.com 2019 - 2024. All rights reserved.