问题描述
我正在尝试在 SymPy 中进行一些符号计算,但我无法使用乳胶打印并获得我想要的图形输出.这一直困扰着我,并且花了几个小时(可能是几天)试图改进一种自定义对象打印方式的方法(在 LaTeX 中,在 pprint 表示中它有很好的文档记录).
I'm trying to do some symbolic calculations in SymPy but I'm unable to use latex printing and get the graphical output I want. That has always troubled me and have spent several hours (perhaps days) trying to fine a way to customize how objects are printed (in LaTeX, in pprint representation it's well documented).
但是,在这种情况下,我试图对取决于 x、y、z 的未定义函数 psi 进行符号计算.然而,这些计算意味着具有 psi* vec r 的三倍旋度的项.
However, in this case I'm trying to make symbolic calculations on an Undefined Function, psi, which depends on x, y, z. However, those calculations imply terms which have up to three times the curl of psi* vec r.
我有以下代码
init_printing(use_latex=True)
R = ReferenceFrame(r"E", variables=["x", "y", "z"])
psi = Function(r"psi")(R[0], R[1], R[2])
rpsi = (R[0]*R.x + R[1]*R.y + R[2]*R.z)*psi
如果您不熟悉,R[i]
是第 i 个变量(x、y 或 z)和 Rx
,Ry
和 Rz
是酉笛卡尔向量,在对 ReferenceFrame(来自 sympy.physics 的函数)的调用中实例化.
Where, in case you aren't familiar with it, R[i]
is the i-th variable (x, y or z) and R.x
, R.y
and R.z
are the unitary cartesian vectors, instantiated in the call to ReferenceFrame (a function from sympy.physics).
例如,当我尝试查看 curl(curl(rpsi, R), R)
时,输出中充满了 "psi(x, y, z)" (在 Latex 中编译并显示为图像)跟随表达式变得乏味.
When I try to take a look at curl(curl(rpsi, R), R)
for example, the output is so filled with "psi(x, y, z)" (compiled in latex and showed as an image) that it gets tedious to follow the expression.
有没有办法自定义被编译的乳胶字符串(这将适用于我正在做的其他计算).如果这不可能,如何解决这个特定问题(即每次打印函数时都显示自变量).
Is there a way to customize the latex string that gets compiled (which would apply to other calculations that I'm doing). If that is not possible, how can solve this particular problem (i.e. independent variables displaying every time the function is printed).
我正在使用带有 qtconsole 的 jupyter.
I'm using jupyter with qtconsole.
干杯,
推荐答案
最简单的方法是创建一个自定义函数,根据需要打印.您可以通过继承 Function
并定义 _latex
来实现这一点(参见 http://docs.sympy.org/latest/modules/printing.html#sympy.printing.latex.LatexPrinter.printmethod).
The simplest way would be to create a custom function, which prints as you want. You can achieve this by subclassing Function
and defining _latex
(see http://docs.sympy.org/latest/modules/printing.html#sympy.printing.latex.LatexPrinter.printmethod).
In [33]: class psi(Function):
....: def _latex(self, printer):
....: return r'psi'
....:
In [34]: latex(psi(x, y, z))
Out[34]: '\psi'
如果您想打印参数,请使用 self.args
访问它们并使用 printer._print
(例如,通常的打印机类似于 r'phi{left (' + ', '.join(printer._print(i) for i in self.args) + '
ight )}'
).
If you want to print the arguments, access them with self.args
and use printer._print
(e.g., the usual printer would be something like r'phi{left (' + ', '.join(printer._print(i) for i in self.args) + '
ight )}'
).
这篇关于SymPy 仅打印函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!