Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy: Modifying LaTeX output of derivatives

Tags:

python

sympy

In Sympy, is it possible to modify the way derivatives of functions are output with latex()? The default is quite cumbersome. This:

f = Function("f")(x,t)
print latex(f.diff(x,x))

will output

\frac{\partial^{2}}{\partial x^{2}}  f{\left (x,t \right )} 

which is quite verbose. If I prefer something like

f_{xx}

is there a way to force this behavior?

like image 609
Eskil Avatar asked Apr 11 '17 15:04

Eskil


1 Answers

You can subclass the LatexPrinter and define your own _print_Derivative. Here is the current implementation.

Maybe something like

from sympy import Symbol
from sympy.printing.latex import LatexPrinter
from sympy.core.function import UndefinedFunction

class MyLatexPrinter(LatexPrinter):
    def _print_Derivative(self, expr):
        # Only print the shortened way for functions of symbols
        function, *vars = expr.args
        if not isinstance(type(function), UndefinedFunction) or not all(isinstance(i, Symbol) for i in vars):
            return super()._print_Derivative(expr)
        return r'%s_{%s}' % (self._print(Symbol(function.func.__name__)), ' '.join([self._print(i) for i in vars]))

Which works like

>>> MyLatexPrinter().doprint(f(x, y).diff(x, y))
'f_{x y}'
>>> MyLatexPrinter().doprint(Derivative(x, x))
'\\frac{d}{d x} x'

To use it in the Jupyter notebook, use

init_printing(latex_printer=MyLatexPrinter().doprint)
like image 162
asmeurer Avatar answered Oct 01 '22 03:10

asmeurer