Printing System

See the Printing section in Tutorial for introduction into printing.

This guide documents the printing system in SymPy and how it works internally.

Printer Class

The main class responsible for printing is Printer (see also its source code):

class sympy.printing.printer.Printer(settings=None)

Generic printer

Its job is to provide infrastructure for implementing new printers easily.

Basically, if you want to implement a printer, all you have to do is:

  1. Subclass Printer.

  2. Define Printer.printmethod in your subclass. If a object has a method with that name, this method will be used for printing.

  3. In your subclass, define _print_<CLASS> methods

    For each class you want to provide printing to, define an appropriate method how to do it. For example if you want a class FOO to be printed in its own way, define _print_FOO:

    def _print_FOO(self, e):

    ...

    this should return how FOO instance e is printed

    Also, if BAR is a subclass of FOO, _print_FOO(bar) will be called for instance of BAR, if no _print_BAR is provided. Thus, usually, we don’t need to provide printing routines for every class we want to support – only generic routine has to be provided for a set of classes.

    A good example for this are functions - for example PrettyPrinter only defines _print_Function, and there is no _print_sin, _print_tan, etc...

    On the other hand, a good printer will probably have to define separate routines for Symbol, Atom, Number, Integral, Limit, etc...

  4. If convenient, override self.emptyPrinter

    This callable will be called to obtain printing result as a last resort, that is when no appropriate print method was found for an expression.

Example of overloading StrPrinter:

from sympy import Basic, Function, Symbol
from sympy.printing.str import StrPrinter

class CustomStrPrinter(StrPrinter):
    """
    Example of how to customize the StrPrinter for both a Sympy class and a
    user defined class subclassed from the Sympy Basic class.
    """

    def _print_Derivative(self, expr):
        """
        Custom printing of the Sympy Derivative class.

        Instead of:

        D(x(t), t) or D(x(t), t, t)

        We will print:

        x'     or     x''

        In this example, expr.args == (x(t), t), and expr.args[0] == x(t), and
        expr.args[0].func == x
        """
        return str(expr.args[0].func) + "'"*len(expr.args[1:])

    def _print_MyClass(self, expr):
        """
        Print the characters of MyClass.s alternatively lower case and upper
        case
        """
        s = ""
        i = 0
        for char in expr.s:
            if i % 2 == 0:
                s += char.lower()
            else:
                s += char.upper()
            i += 1
        return s

# Override the __str__ method of to use CustromStrPrinter
Basic.__str__ = lambda self: CustomStrPrinter().doprint(self)
# Demonstration of CustomStrPrinter:
t = Symbol('t')
x = Function('x')(t)
dxdt = x.diff(t)            # dxdt is a Derivative instance
d2xdt2 = dxdt.diff(t)       # dxdt2 is a Derivative instance
ex = MyClass('I like both lowercase and upper case')

print dxdt
print d2xdt2
print ex

The output of the above code is:

x'
x''
i lIkE BoTh lOwErCaSe aNd uPpEr cAsE

By overriding Basic.__str__, we can customize the printing of anything that is subclassed from Basic.

doprint(expr)

Returns printer’s representation for expr (as a string)

_print(expr, *args)

Internal dispatcher

Tries the following concepts to print an expression:
  1. Let the object print itself if it knows how.
  2. Take the best fitting method defined in the printer.
  3. As fall-back use the emptyPrinter method for the printer.

PrettyPrinter Class

Pretty printing subsystem is implemented in sympy.printing.pretty.pretty by the PrettyPrinter class deriving from Printer. It relies on modules sympy.printing.pretty.stringPict, and sympy.printing.pretty.pretty_symbology for rendering nice-looking formulas.

The module stringPict provides a base class stringPict and a derived class prettyForm that ease the creation and manipulation of formulas that span across multiple lines.

The module pretty_symbology provides primitives to construct 2D shapes (hline, vline, etc) together with a technique to use unicode automatically when possible.

MathMLPrinter

This class is responsible for MathML printing. See sympy.printing.mathml.

More info on mathml content: http://www.w3.org/TR/MathML2/chapter4.html

LatexPrinter

This class implements LaTeX printing. See sympy.printing.latex.

See also the extended LatexPrinter: Extended LaTeXModule for Sympy

Gtk

You can print to a grkmathview widget using the function print_gtk located in sympy.printing.gtk (it requires to have installed gtkmatmatview and libgtkmathview-bin in some systems).

GtkMathView accepts MathML, so this rendering depends on the mathml representation of the expression

Usage:

from sympy import *
print_gtk(x**2 + 2*exp(x**3))

PythonPrinter

This class implements Python printing. Usage:

>>> from sympy import print_python, sin
>>> from sympy.abc import x

>>> print_python(5*x**3 + sin(x))
x = Symbol('x')
e = 5*x**3 + sin(x)

fcode

The fcode function translates a sympy expression into Fortran code. The main purpose is to take away the burden of manually translating long mathematical expressions. Therefore the resulting expression should also require no (or very little) manual tweaking to make it compilable. The optional arguments of fcode can be used to fine-tune the behavior of fcode in such a way that manual changes in the result are no longer needed.

sympy.printing.fcode.fcode(expr, **settings)

Converts an expr to a string of Fortran 77 code

Arguments:
expr – a sympy expression to be converted
Optional arguments:
assign_to – When given, the argument is used as the name of the
variable to which the Fortran expression is assigned. (This is helpful in case of line-wrapping.)

precision – the precision for numbers such as pi [default=15] user_functions – A dictionary where keys are FunctionClass instances

and values are there string representations.
human – If True, the result is a single string that may contain
some parameter statements for the number symbols. If False, the same information is returned in a more programmer-friendly data structure.
source_format – The source format can be either ‘fixed’ or ‘free’.
[default=’fixed’]
>>> from sympy import fcode, symbols, Rational, pi, sin
>>> x, tau = symbols('x,tau')
>>> fcode((2*tau)**Rational(7,2))
'      8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)'
>>> fcode(sin(x), assign_to="s")
'      s = sin(x)'
>>> print fcode(pi)
      parameter (pi = 3.14159265358979d0)
      pi
sympy.printing.fcode.print_fcode(expr, **settings)

Prints the Fortran representation of the given expression.

See fcode for the meaning of the optional arguments.

Two basic examples:

>>> from sympy import *
>>> x = symbols("x")
>>> fcode(sqrt(1-x**2))
'      sqrt(-x**2 + 1)'
>>> fcode((3 + 4*I)/(1 - conjugate(x)))
'      (cmplx(3,4))/(-conjg(x) + 1)'

An example where line wrapping is required:

>>> expr = sqrt(1-x**2).series(x,n=20).removeO()
>>> print fcode(expr)
      -715*x**18/65536 - 429*x**16/32768 - 33*x**14/2048 - 21*x**12/1024
     @ - 7*x**10/256 - 5*x**8/128 - x**6/16 - x**4/8 - x**2/2 + 1

In case of line wrapping, it is handy to include the assignment so that lines are wrapped properly when the assignment part is added.

>>> print fcode(expr, assign_to="var")
      var = -715*x**18/65536 - 429*x**16/32768 - 33*x**14/2048 - 21*x**
     @ 12/1024 - 7*x**10/256 - 5*x**8/128 - x**6/16 - x**4/8 - x**2/2 +
     @ 1

For piecewise functions, the assign_to option is mandatory:

>>> print fcode(Piecewise((x,x<1),(x**2,True)), assign_to="var")
      if (x < 1) then
        var = x
      else
        var = x**2
      end if

Note that only top-level piecewise functions are supported due to the lack of a conditional operator in Fortran. Nested piecewise functions would require the introduction of temporary variables, which is a type of expression manipulation that goes beyond the scope of fcode.

Loops are generated if there are Indexed objects in the expression. This also requires use of the assign_to option.

>>> A, B = map(IndexedBase, ['A', 'B'])
>>> m = Symbol('m', integer=True)
>>> i = Idx('i', m)
>>> print fcode(2*B[i], assign_to=A[i])
    do i = 1, m
        A(i) = 2*B(i)
    end do

Repeated indices in an expression with Indexed objects are interpreted as summation. For instance, code for the trace of a matrix can be generated with

>>> print fcode(A[i, i], assign_to=x)
      x = 0
      do i = 1, m
          x = x + A(i, i)
      end do

By default, number symbols such as pi and E are detected and defined as Fortran parameters. The precision of the constants can be tuned with the precision argument. Parameter definitions are easily avoided using the N function.

>>> print fcode(x - pi**2 - E)
      parameter (E = 2.71828182845905d0)
      parameter (pi = 3.14159265358979d0)
      x - pi**2 - E
>>> print fcode(x - pi**2 - E, precision=25)
      parameter (E = 2.718281828459045235360287d0)
      parameter (pi = 3.141592653589793238462643d0)
      x - pi**2 - E
>>> print fcode(N(x - pi**2, 25))
      x - 9.869604401089358618834491d0

When some functions are not part of the Fortran standard, it might be desirable to introduce the names of user-defined functions in the Fortran expression.

>>> print fcode(1 - gamma(x)**2, user_functions={gamma: 'mygamma'})
      -mygamma(x)**2 + 1

However, when the user_functions argument is not provided, fcode attempts to use a reasonable default and adds a comment to inform the user of the issue.

>>> print fcode(1 - gamma(x)**2)
C     Not Fortran:
C     gamma(x)
      -gamma(x)**2 + 1

By default the output is human readable code, ready for copy and paste. With the option human=False, the return value is suitable for post-processing with source code generators that write routines with multiple instructions. The return value is a three-tuple containing: (i) a set of number symbols that must be defined as ‘Fortran parameters’, (ii) a list functions that can not be translated in pure Fortran and (iii) a string of Fortran code. A few examples:

>>> fcode(1 - gamma(x)**2, human=False)
(set(), set([gamma(x)]), '      -gamma(x)**2 + 1')
>>> fcode(1 - sin(x)**2, human=False)
(set(), set(), '      -sin(x)**2 + 1')
>>> fcode(x - pi**2, human=False)
(set([(pi, '3.14159265358979d0')]), set(), '      x - pi**2')

Preview

A useful function is preview:

sympy.printing.preview.preview(expr, output='png', viewer=None, euler=True)

View expression in PNG, DVI, PostScript or PDF form.

This will generate LaTeX representation of the given expression and compile it using available TeX distribution. Then it will run appropriate viewer for the given output format or use the user defined one. If you prefer not to use external viewer then you can use combination of ‘png’ output and ‘pyglet’ viewer. By default png output is generated.

By default pretty Euler fonts are used for typesetting (they were used to typeset the well known “Concrete Mathematics” book). For that to work, you need the ‘eulervm.sty’ LaTeX style (in Debian/Ubuntu, install the texlive-fonts-extra package). If you prefer default AMS fonts or your system lacks ‘eulervm’ LaTeX package then unset the ‘euler’ keyword argument.

To use viewer auto-detection, lets say for ‘png’ output, issue:

>> from sympy import *
>> x, y = symbols("x,y")

>> preview(x + y, output='png')

This will choose ‘pyglet by default. To select different one:

>> preview(x + y, output='png', viewer='gimp')

The ‘png’ format is considered special. For all other formats the rules are slightly different. As an example we will take ‘dvi’ output format. If you would run:

>> preview(x + y, output='dvi')

then ‘view’ will look for available ‘dvi’ viewers on your system (predefined in the function, so it will try evince, first, then kdvi and xdvi). If nothing is found you will need to set the viewer explicitly:

>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')

This will skip auto-detection and will run user specified ‘superior-dvi-viewer’. If ‘view’ fails to find it on your system it will gracefully raise an exception.

Currently this depends on pexpect, which is not available for windows.

Table Of Contents

Previous topic

Literature

Next topic

Plotting

This Page