oponkork
oponkork

Reputation: 31

Creating custom printing for sympy.Derivative

Say I have a function f(x,y), I want partial derivative of f w.r.t to x appear as \partial_{x}^{n} f(x,y) so I created the following class

class D(sp.Derivative):
    def _latex(self,printer=None):
        func = printer.doprint(self.args[0])
        b = self.args[1]
        if b[1] == 1 :
            return r"\partial_{%s}%s"%(printer.doprint(b[0]),func)
        else :
            return r"\partial_{%s}^{%s}%s"%(printer.doprint(b[0]),printer.doprint(b[1]),func)

which works fine, but goes back to default behavior when I evaluate the derivative by using doit() method. Say I have

x,y = sp.symbols('x,y')
f = sp.Function('f')(x,y)

Then sp.print_latex(D(f,x)) gives \partial_{x}f{\left(x,y \right)} which is correct, but sp.print_latex(D(x*f,x).doit()) yields x \frac{\partial}{\partial x} f{\left(x,y \right)} + f{\left(x,y \right)}, which is the old behavior. How can I fix this issue?

Upvotes: 3

Views: 462

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14470

The problem is that you haven't overridden doit from the parent class and it returns plain Derivative objects rather than your subclass. Rather than creating a new Derivative class I suggest to create a new printer class:

from sympy import *

from sympy.printing.latex import LatexPrinter

class MyLatexPrinter(LatexPrinter):
    def _print_Derivative(self, expr):
        differand, *(wrt_counts) = expr.args
        if len(wrt_counts) > 1 or wrt_counts[0][1] != 1:
            raise NotImplementedError('More code needed...')
        ((wrt, count),) = wrt_counts
        return '\partial_{%s} %s)' % (self._print(wrt), self._print(differand))

x, y = symbols('x, y')
f = Function('f')
expr = (x*f(x, y)).diff(x)

printer = MyLatexPrinter()

print(printer.doprint(expr))

That gives x \partial_{x} f{\left(x,y \right)}) + f{\left(x,y \right)}

You can use init_printing(latex_printer=printer.doprint) to make this the default output.

Upvotes: 3

Related Questions