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

问题描述 投票: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
投票

导数(像所有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

但是,获取它们是一定顺序,但是需要更改关联的打印机。参见,例如,here

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