Printing

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

Printing subsystem driver

SymPy’s printing system works the following way: Any expression can be passed to a designated Printer who then is responsible to return an adequate representation of that expression.

The basic concept is the following:

  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.

Which Method is Responsible for Printing?

The whole printing process is started by calling .doprint(expr) on the printer which you want to use. This method looks for an appropriate method which can print the given expression in the given style that the printer defines. While looking for the method, it follows these steps:

  1. Let the object print itself if it knows how.

    The printer looks for a specific method in every object. The name of that method depends on the specific printer and is defined under Printer.printmethod. For example, StrPrinter calls _sympystr and LatexPrinter calls _latex. Look at the documentation of the printer that you want to use. The name of the method is specified there.

    This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefore all printing code was combined into the different printers, which works great for built-in SymPy objects, but not that good for user defined classes where it is inconvenient to patch the printers.

  2. Take the best fitting method defined in the printer.

    The printer loops through expr classes (class + its bases), and tries to dispatch the work to _print_<EXPR_CLASS>

    e.g., suppose we have the following class hierarchy:

        Basic
        |
        Atom
        |
        Number
        |
    Rational
    

    then, for expr=Rational(...), the Printer will try to call printer methods in the order as shown in the figure below:

    p._print(expr)
    |
    |-- p._print_Rational(expr)
    |
    |-- p._print_Number(expr)
    |
    |-- p._print_Atom(expr)
    |
    `-- p._print_Basic(expr)
    

    if ._print_Rational method exists in the printer, then it is called, and the result is returned back. Otherwise, the printer tries to call ._print_Number and so on.

  3. As a fall-back use the emptyPrinter method for the printer.

    As fall-back self.emptyPrinter will be called with the expression. If not defined in the Printer subclass this will be the same as str(expr).

Example of Custom Printer

In the example below, we have a printer which prints the derivative of a function in a shorter form.

from sympy.core.symbol import Symbol
from sympy.printing.latex import LatexPrinter, print_latex
from sympy.core.function import UndefinedFunction, Function


class MyLatexPrinter(LatexPrinter):
    """Print derivative of a function of symbols in a shorter form.
    """
    def _print_Derivative(self, expr):
        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)

        # If you want the printer to work correctly for nested
        # expressions then use self._print() instead of str() or latex().
        # See the example of nested modulo below in the custom printing
        # method section.
        return "{}_{{{}}}".format(
            self._print(Symbol(function.func.__name__)),
                        ''.join(self._print(i) for i in vars))


def print_my_latex(expr):
    """ Most of the printers define their own wrappers for print().
    These wrappers usually take printer settings. Our printer does not have
    any settings.
    """
    print(MyLatexPrinter().doprint(expr))


y = Symbol("y")
x = Symbol("x")
f = Function("f")
expr = f(x, y).diff(x, y)

# Print the expression using the normal latex printer and our custom
# printer.
print_latex(expr)
print_my_latex(expr)

The output of the code above is:

\frac{\partial^{2}}{\partial x\partial y}  f{\left(x,y \right)}
f_{xy}

Example of Custom Printing Method

In the example below, the latex printing of the modulo operator is modified. This is done by overriding the method _latex of Mod.

>>> from sympy import Symbol, Mod, Integer, print_latex
>>> # Always use printer._print()
>>> class ModOp(Mod):
...     def _latex(self, printer):
...         a, b = [printer._print(i) for i in self.args]
...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)

Comparing the output of our custom operator to the builtin one:

>>> x = Symbol('x')
>>> m = Symbol('m')
>>> print_latex(Mod(x, m))
x \bmod m
>>> print_latex(ModOp(x, m))
\operatorname{Mod}{\left(x, m\right)}

Common mistakes

It’s important to always use self._print(obj) to print subcomponents of an expression when customizing a printer. Mistakes include:

  1. Using self.doprint(obj) instead:

    >>> # This example does not work properly, as only the outermost call may use
    >>> # doprint.
    >>> class ModOpModeWrong(Mod):
    ...     def _latex(self, printer):
    ...         a, b = [printer.doprint(i) for i in self.args]
    ...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)
    

    This fails when the mode argument is passed to the printer:

    >>> print_latex(ModOp(x, m), mode='inline')  # ok
    $\operatorname{Mod}{\left(x, m\right)}$
    >>> print_latex(ModOpModeWrong(x, m), mode='inline')  # bad
    $\operatorname{Mod}{\left($x$, $m$\right)}$
    
  2. Using str(obj) instead:

    >>> class ModOpNestedWrong(Mod):
    ...     def _latex(self, printer):
    ...         a, b = [str(i) for i in self.args]
    ...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)
    

    This fails on nested objects:

    >>> # Nested modulo.
    >>> print_latex(ModOp(ModOp(x, m), Integer(7)))  # ok
    \operatorname{Mod}{\left(\operatorname{Mod}{\left(x, m\right)}, 7\right)}
    >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7)))  # bad
    \operatorname{Mod}{\left(ModOpNestedWrong(x, m), 7\right)}
    
  3. Using LatexPrinter()._print(obj) instead.

    >>> from sympy.printing.latex import LatexPrinter
    >>> class ModOpSettingsWrong(Mod):
    ...     def _latex(self, printer):
    ...         a, b = [LatexPrinter()._print(i) for i in self.args]
    ...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)
    

    This causes all the settings to be discarded in the subobjects. As an example, the full_prec setting which shows floats to full precision is ignored:

    >>> from sympy import Float
    >>> print_latex(ModOp(Float(1) * x, m), full_prec=True)  # ok
    \operatorname{Mod}{\left(1.00000000000000 x, m\right)}
    >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True)  # bad
    \operatorname{Mod}{\left(1.0 x, m\right)}
    

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

class sympy.printing.printer.Printer(settings=None)[source]

Generic printer

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

If you want to define your custom Printer or your custom printing method for your custom class then see the example above: printer_example .

printmethod: str = None
_print(expr, **kwargs) str[source]

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.

doprint(expr)[source]

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

classmethod set_global_settings(**settings)[source]

Set system-wide printing settings.

PrettyPrinter Class

The pretty printing subsystem is implemented in sympy.printing.pretty.pretty by the PrettyPrinter class deriving from Printer. It relies on the 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.

class sympy.printing.pretty.pretty.PrettyPrinter(settings=None)[source]

Printer, which converts an expression into 2D ASCII-art figure.

printmethod: str = '_pretty'
sympy.printing.pretty.pretty.pretty(expr, *, order=None, full_prec='auto', use_unicode=True, wrap_line=True, num_columns=None, use_unicode_sqrt_char=True, root_notation=True, mat_symbol_style='plain', imaginary_unit='i', perm_cyclic=True)

Returns a string containing the prettified form of expr.

For information on keyword arguments see pretty_print function.

sympy.printing.pretty.pretty.pretty_print(expr, **kwargs)[source]

Prints expr in pretty form.

pprint is just a shortcut for this function.

Parameters:

expr : expression

The expression to print.

wrap_line : bool, optional (default=True)

Line wrapping enabled/disabled.

num_columns : int or None, optional (default=None)

Number of columns before line breaking (default to None which reads the terminal width), useful when using SymPy without terminal.

use_unicode : bool or None, optional (default=None)

Use unicode characters, such as the Greek letter pi instead of the string pi.

full_prec : bool or string, optional (default=”auto”)

Use full precision.

order : bool or string, optional (default=None)

Set to ‘none’ for long expressions if slow; default is None.

use_unicode_sqrt_char : bool, optional (default=True)

Use compact single-character square root symbol (when unambiguous).

root_notation : bool, optional (default=True)

Set to ‘False’ for printing exponents of the form 1/n in fractional form. By default exponent is printed in root form.

mat_symbol_style : string, optional (default=”plain”)

Set to “bold” for printing MatrixSymbols using a bold mathematical symbol face. By default the standard face is used.

imaginary_unit : string, optional (default=”i”)

Letter to use for imaginary unit when use_unicode is True. Can be “i” (default) or “j”.

C code printers

This class implements C code printing, i.e. it converts Python expressions to strings of C code (see also C89CodePrinter).

Usage:

>>> from sympy.printing import print_ccode
>>> from sympy.functions import sin, cos, Abs, gamma
>>> from sympy.abc import x
>>> print_ccode(sin(x)**2 + cos(x)**2, standard='C89')
pow(sin(x), 2) + pow(cos(x), 2)
>>> print_ccode(2*x + cos(x), assign_to="result", standard='C89')
result = 2*x + cos(x);
>>> print_ccode(Abs(x**2), standard='C89')
fabs(pow(x, 2))
>>> print_ccode(gamma(x**2), standard='C99')
tgamma(pow(x, 2))
sympy.printing.c.known_functions_C89 = {'Abs': [(<function <lambda>>, 'fabs'), (<function <lambda>>, 'abs')], 'acos': 'acos', 'asin': 'asin', 'atan': 'atan', 'atan2': 'atan2', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'exp': 'exp', 'floor': 'floor', 'log': 'log', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh'}
sympy.printing.c.known_functions_C99 = {'Abs': [(<function <lambda>>, 'fabs'), (<function <lambda>>, 'abs')], 'Cbrt': 'cbrt', 'Max': 'fmax', 'Min': 'fmin', 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'erf': 'erf', 'erfc': 'erfc', 'exp': 'exp', 'exp2': 'exp2', 'expm1': 'expm1', 'floor': 'floor', 'fma': 'fma', 'gamma': 'tgamma', 'hypot': 'hypot', 'log': 'log', 'log10': 'log10', 'log1p': 'log1p', 'log2': 'log2', 'loggamma': 'lgamma', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh'}
class sympy.printing.c.C89CodePrinter(settings=None)[source]

A printer to convert Python expressions to strings of C code

printmethod: str = '_ccode'
indent_code(code)[source]

Accepts a string of code or a list of code lines

class sympy.printing.c.C99CodePrinter(settings=None)[source]
printmethod: str = '_ccode'
sympy.printing.c.ccode(expr, assign_to=None, standard='c99', **settings)[source]

Converts an expr to a string of c code

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements.

standard : str, optional

String specifying the standard. If your compiler supports a more modern standard you may set this to ‘c99’ to allow the printer to use more math functions. [default=’c89’].

precision : integer, optional

The precision for numbers such as pi [default=17].

user_functions : dict, optional

A dictionary where the keys are string representations of either FunctionClass or UndefinedFunction instances and the values are their desired C string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)] or [(argument_test, cfunction_formater)]. See below for examples.

dereference : iterable, optional

An iterable of symbols that should be dereferenced in the printed code expression. These would be values passed by address to the function. For example, if dereference=[a], the resulting code would print (*a) instead of a.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

Examples

>>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> expr = (2*tau)**Rational(7, 2)
>>> ccode(expr)
'8*M_SQRT2*pow(tau, 7.0/2.0)'
>>> ccode(expr, math_macros={})
'8*sqrt(2)*pow(tau, 7.0/2.0)'
>>> ccode(sin(x), assign_to="s")
's = sin(x);'
>>> from sympy.codegen.ast import real, float80
>>> ccode(expr, type_aliases={real: float80})
'8*M_SQRT2l*powl(tau, 7.0L/2.0L)'

Simple custom printing can be defined for certain types by passing a dictionary of {“type” : “function”} to the user_functions kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)].

>>> custom_functions = {
...   "ceiling": "CEIL",
...   "Abs": [(lambda x: not x.is_integer, "fabs"),
...           (lambda x: x.is_integer, "ABS")],
...   "func": "f"
... }
>>> func = Function('func')
>>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions)
'f(fabs(x) + CEIL(x))'

or if the C-function takes a subset of the original arguments:

>>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [
...   (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
...   (lambda b, e: b != 2, 'pow')]})
'exp2(x) + pow(3, x)'

Piecewise expressions are converted into conditionals. If an assign_to variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(ccode(expr, tau, standard='C89'))
if (x > 0) {
tau = x + 1;
}
else {
tau = x;
}

Support for loops is provided through Indexed types. With contract=True these expressions will be turned into loops, whereas contract=False will just print the assignment expression that should be looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89')
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'

Matrices are also supported, but a MatrixSymbol of the same dimensions must be provided to assign_to. Note that any expression that can be generated normally can also exist inside a Matrix:

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(ccode(mat, A, standard='C89'))
A[0] = pow(x, 2);
if (x > 0) {
   A[1] = x + 1;
}
else {
   A[1] = x;
}
A[2] = sin(x);
sympy.printing.c.print_ccode(expr, **settings)[source]

Prints C representation of the given expression.

C++ code printers

This module contains printers for C++ code, i.e. functions to convert SymPy expressions to strings of C++ code.

Usage:

>>> from sympy.printing import cxxcode
>>> from sympy.functions import Min, gamma
>>> from sympy.abc import x
>>> print(cxxcode(Min(gamma(x) - 1, x), standard='C++11'))
std::min(x, std::tgamma(x) - 1)
class sympy.printing.cxx.CXX98CodePrinter(settings=None)[source]
printmethod: str = '_cxxcode'
class sympy.printing.cxx.CXX11CodePrinter(settings=None)[source]
printmethod: str = '_cxxcode'
sympy.printing.codeprinter.cxxcode(expr, assign_to=None, standard='c++11', **settings)[source]

C++ equivalent of ccode().

RCodePrinter

This class implements R code printing (i.e. it converts Python expressions to strings of R code).

Usage:

>>> from sympy.printing import print_rcode
>>> from sympy.functions import sin, cos, Abs
>>> from sympy.abc import x
>>> print_rcode(sin(x)**2 + cos(x)**2)
sin(x)^2 + cos(x)^2
>>> print_rcode(2*x + cos(x), assign_to="result")
result = 2*x + cos(x);
>>> print_rcode(Abs(x**2))
abs(x^2)
sympy.printing.rcode.known_functions = {'Abs': 'abs', 'Max': 'max', 'Min': 'min', 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'beta': 'beta', 'ceiling': 'ceiling', 'cos': 'cos', 'cosh': 'cosh', 'digamma': 'digamma', 'erf': 'erf', 'exp': 'exp', 'factorial': 'factorial', 'floor': 'floor', 'gamma': 'gamma', 'log': 'log', 'sign': 'sign', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh', 'trigamma': 'trigamma'}
class sympy.printing.rcode.RCodePrinter(settings={})[source]

A printer to convert SymPy expressions to strings of R code

printmethod: str = '_rcode'
indent_code(code)[source]

Accepts a string of code or a list of code lines

sympy.printing.rcode.rcode(expr, assign_to=None, **settings)[source]

Converts an expr to a string of r code

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements.

precision : integer, optional

The precision for numbers such as pi [default=15].

user_functions : dict, optional

A dictionary where the keys are string representations of either FunctionClass or UndefinedFunction instances and the values are their desired R string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, rfunction_string)] or [(argument_test, rfunction_formater)]. See below for examples.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

Examples

>>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> rcode((2*tau)**Rational(7, 2))
'8*sqrt(2)*tau^(7.0/2.0)'
>>> rcode(sin(x), assign_to="s")
's = sin(x);'

Simple custom printing can be defined for certain types by passing a dictionary of {“type” : “function”} to the user_functions kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)].

>>> custom_functions = {
...   "ceiling": "CEIL",
...   "Abs": [(lambda x: not x.is_integer, "fabs"),
...           (lambda x: x.is_integer, "ABS")],
...   "func": "f"
... }
>>> func = Function('func')
>>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
'f(fabs(x) + CEIL(x))'

or if the R-function takes a subset of the original arguments:

>>> rcode(2**x + 3**x, user_functions={'Pow': [
...   (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
...   (lambda b, e: b != 2, 'pow')]})
'exp2(x) + pow(3, x)'

Piecewise expressions are converted into conditionals. If an assign_to variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(rcode(expr, assign_to=tau))
tau = ifelse(x > 0,x + 1,x);

Support for loops is provided through Indexed types. With contract=True these expressions will be turned into loops, whereas contract=False will just print the assignment expression that should be looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> rcode(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'

Matrices are also supported, but a MatrixSymbol of the same dimensions must be provided to assign_to. Note that any expression that can be generated normally can also exist inside a Matrix:

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(rcode(mat, A))
A[0] = x^2;
A[1] = ifelse(x > 0,x + 1,x);
A[2] = sin(x);
sympy.printing.rcode.print_rcode(expr, **settings)[source]

Prints R representation of the given expression.

Fortran Printing

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.fortran.fcode(expr, assign_to=None, **settings)[source]

Converts an expr to a string of fortran code

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements.

precision : integer, optional

DEPRECATED. Use type_mappings instead. The precision for numbers such as pi [default=17].

user_functions : dict, optional

A dictionary where keys are FunctionClass instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

source_format : optional

The source format can be either ‘fixed’ or ‘free’. [default=’fixed’]

standard : integer, optional

The Fortran standard to be followed. This is specified as an integer. Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77. Note that currently the only distinction internally is between standards before 95, and those 95 and after. This may change later as more features are added.

name_mangling : bool, optional

If True, then the variables that would become identical in case-insensitive Fortran are mangled by appending different number of _ at the end. If False, SymPy Will not interfere with naming of variables. [default=True]

Examples

>>> from sympy import fcode, symbols, Rational, sin, ceiling, floor
>>> 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)'

Custom printing can be defined for certain types by passing a dictionary of “type” : “function” to the user_functions kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)].

>>> custom_functions = {
...   "ceiling": "CEIL",
...   "floor": [(lambda x: not x.is_integer, "FLOOR1"),
...             (lambda x: x.is_integer, "FLOOR2")]
... }
>>> fcode(floor(x) + ceiling(x), user_functions=custom_functions)
'      CEIL(x) + FLOOR1(x)'

Piecewise expressions are converted into conditionals. If an assign_to variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(fcode(expr, tau))
      if (x > 0) then
         tau = x + 1
      else
         tau = x
      end if

Support for loops is provided through Indexed types. With contract=True these expressions will be turned into loops, whereas contract=False will just print the assignment expression that should be looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> fcode(e.rhs, assign_to=e.lhs, contract=False)
'      Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))'

Matrices are also supported, but a MatrixSymbol of the same dimensions must be provided to assign_to. Note that any expression that can be generated normally can also exist inside a Matrix:

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(fcode(mat, A))
      A(1, 1) = x**2
         if (x > 0) then
      A(2, 1) = x + 1
         else
      A(2, 1) = x
         end if
      A(3, 1) = sin(x)
sympy.printing.fortran.print_fcode(expr, **settings)[source]

Prints the Fortran representation of the given expression.

See fcode for the meaning of the optional arguments.

class sympy.printing.fortran.FCodePrinter(settings=None)[source]

A printer to convert SymPy expressions to strings of Fortran code

printmethod: str = '_fcode'
indent_code(code)[source]

Accepts a string of code or a list of code lines

Two basic examples:

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

An example where line wrapping is required:

>>> expr = sqrt(1-x**2).series(x,n=20).removeO()
>>> print(fcode(expr))
    -715.0d0/65536.0d0*x**18 - 429.0d0/32768.0d0*x**16 - 33.0d0/
    @ 2048.0d0*x**14 - 21.0d0/1024.0d0*x**12 - 7.0d0/256.0d0*x**10 -
    @ 5.0d0/128.0d0*x**8 - 1.0d0/16.0d0*x**6 - 1.0d0/8.0d0*x**4 - 1.0d0
    @ /2.0d0*x**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.0d0/65536.0d0*x**18 - 429.0d0/32768.0d0*x**16 - 33.0d0/
     @ 2048.0d0*x**14 - 21.0d0/1024.0d0*x**12 - 7.0d0/256.0d0*x**10 -
     @ 5.0d0/128.0d0*x**8 - 1.0d0/16.0d0*x**6 - 1.0d0/8.0d0*x**4 - 1.0d0
     @ /2.0d0*x**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 by default only top-level piecewise functions are supported due to the lack of a conditional operator in Fortran 77. Inline conditionals can be supported using the merge function introduced in Fortran 95 by setting of the kwarg standard=95:

>>> print(fcode(Piecewise((x,x<1),(x**2,True)), standard=95))
      merge(x, x**2, x < 1)

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.7182818284590452d0)
      parameter (pi = 3.1415926535897932d0)
      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'}))
      1 - mygamma(x)**2

However, when the user_functions argument is not provided, fcode will by default raise an Exception, but if the user intends to provide a function with the same name, code can still be generated, by passing the option strict=False. The code then contains a comment informing the user of the issue:

>>> print(fcode(1 - gamma(x)**2, strict=False))
C     Not supported in Fortran:
C     gamma
      1 - gamma(x)**2

The printer can be configured to omit these comments:

>>> print(fcode(1 - gamma(x)**2, allow_unknown_functions=True))
      1 - gamma(x)**2

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 cannot be translated in pure Fortran and (iii) a string of Fortran code. A few examples:

>>> fcode(1 - gamma(x)**2, human=False)
(set(), {gamma(x)}, '      1 - gamma(x)**2')
>>> fcode(1 - sin(x)**2, human=False)
(set(), set(), '      1 - sin(x)**2')
>>> fcode(x - pi**2, human=False)
({(pi, '3.1415926535897932d0')}, set(), '      x - pi**2')

SMT-Lib printing

class sympy.printing.smtlib.SMTLibPrinter(settings: dict | None = None, symbol_table=None)[source]
printmethod: str = '_smtlib'
_default_settings: dict = {'known_constants': {}, 'known_functions': {<class 'sympy.core.add.Add'>: '+', <class 'sympy.core.mul.Mul'>: '*', <class 'sympy.core.power.Pow'>: 'pow', <class 'sympy.core.relational.Equality'>: '=', <class 'sympy.core.relational.GreaterThan'>: '>=', <class 'sympy.core.relational.LessThan'>: '<=', <class 'sympy.core.relational.StrictGreaterThan'>: '>', <class 'sympy.core.relational.StrictLessThan'>: '<', Abs: 'abs', And: 'and', ITE: 'ite', Implies: '=>', Max: 'max', Min: 'min', Not: 'not', Or: 'or', Q.eq: '=', Q.ge: '>=', Q.gt: '>', Q.le: '<=', Q.lt: '<', Xor: 'xor', acos: 'arccos', asin: 'arcsin', atan: 'arctan', atan2: 'arctan2', cos: 'cos', cosh: 'cosh', exp: 'exp', log: 'log', sin: 'sin', sinh: 'sinh', tan: 'tan', tanh: 'tanh'}, 'known_types': {<class 'bool'>: 'Bool', <class 'float'>: 'Real', <class 'int'>: 'Int'}, 'precision': None}
sympy.printing.smtlib.smtlib_code(expr, auto_assert=True, auto_declare=True, precision=None, symbol_table=None, known_types=None, known_constants=None, known_functions=None, prefix_expressions=None, suffix_expressions=None, log_warn=None)[source]

Converts expr to a string of smtlib code.

Parameters:

expr : Expr | List[Expr]

A SymPy expression or system to be converted.

auto_assert : bool, optional

If false, do not modify expr and produce only the S-Expression equivalent of expr. If true, assume expr is a system and assert each boolean element.

auto_declare : bool, optional

If false, do not produce declarations for the symbols used in expr. If true, prepend all necessary declarations for variables used in expr based on symbol_table.

precision : integer, optional

The evalf(..) precision for numbers such as pi.

symbol_table : dict, optional

A dictionary where keys are Symbol or Function instances and values are their Python type i.e. bool, int, float, or Callable[...]. If incomplete, an attempt will be made to infer types from expr.

known_types: dict, optional

A dictionary where keys are bool, int, float etc. and values are their corresponding SMT type names. If not given, a partial listing compatible with several solvers will be used.

known_functions : dict, optional

A dictionary where keys are Function, Relational, BooleanFunction, or Expr instances and values are their SMT string representations. If not given, a partial listing optimized for dReal solver (but compatible with others) will be used.

known_constants: dict, optional

A dictionary where keys are NumberSymbol instances and values are their SMT variable names. When using this feature, extra caution must be taken to avoid naming collisions between user symbols and listed constants. If not given, constants will be expanded inline i.e. 3.14159 instead of MY_SMT_VARIABLE_FOR_PI.

prefix_expressions: list, optional

A list of lists of str and/or expressions to convert into SMTLib and prefix to the output.

suffix_expressions: list, optional

A list of lists of str and/or expressions to convert into SMTLib and postfix to the output.

log_warn: lambda function, optional

A function to record all warnings during potentially risky operations. Soundness is a core value in SMT solving, so it is good to log all assumptions made.

Examples

>>> from sympy import smtlib_code, symbols, sin, Eq
>>> x = symbols('x')
>>> smtlib_code(sin(x).series(x).removeO(), log_warn=print)
Could not infer type of `x`. Defaulting to float.
Non-Boolean expression `x**5/120 - x**3/6 + x` will not be asserted. Converting to SMTLib verbatim.
'(declare-const x Real)\n(+ x (* (/ -1 6) (pow x 3)) (* (/ 1 120) (pow x 5)))'
>>> from sympy import Rational
>>> x, y, tau = symbols("x, y, tau")
>>> smtlib_code((2*tau)**Rational(7, 2), log_warn=print)
Could not infer type of `tau`. Defaulting to float.
Non-Boolean expression `8*sqrt(2)*tau**(7/2)` will not be asserted. Converting to SMTLib verbatim.
'(declare-const tau Real)\n(* 8 (pow 2 (/ 1 2)) (pow tau (/ 7 2)))'

Piecewise expressions are implemented with ite expressions by default. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> pw = Piecewise((x + 1, x > 0), (x, True))
>>> smtlib_code(Eq(pw, 3), symbol_table={x: float}, log_warn=print)
'(declare-const x Real)\n(assert (= (ite (> x 0) (+ 1 x) x) 3))'

Custom printing can be defined for certain types by passing a dictionary of PythonType : “SMT Name” to the known_types, known_constants, and known_functions kwargs.

>>> from typing import Callable
>>> from sympy import Function, Add
>>> f = Function('f')
>>> g = Function('g')
>>> smt_builtin_funcs = {  # functions our SMT solver will understand
...   f: "existing_smtlib_fcn",
...   Add: "sum",
... }
>>> user_def_funcs = {  # functions defined by the user must have their types specified explicitly
...   g: Callable[[int], float],
... }
>>> smtlib_code(f(x) + g(x), symbol_table=user_def_funcs, known_functions=smt_builtin_funcs, log_warn=print)
Non-Boolean expression `f(x) + g(x)` will not be asserted. Converting to SMTLib verbatim.
'(declare-const x Int)\n(declare-fun g (Int) Real)\n(sum (existing_smtlib_fcn x) (g x))'

Mathematica code printing

sympy.printing.mathematica.known_functions = {'Chi': [(<function <lambda>>, 'CoshIntegral')], 'Ci': [(<function <lambda>>, 'CosIntegral')], 'DiracDelta': [(<function <lambda>>, 'DiracDelta')], 'Ei': [(<function <lambda>>, 'ExpIntegralEi')], 'FallingFactorial': [(<function <lambda>>, 'FactorialPower')], 'Heaviside': [(<function <lambda>>, 'HeavisideTheta')], 'KroneckerDelta': [(<function <lambda>>, 'KroneckerDelta')], 'Max': [(<function <lambda>>, 'Max')], 'Min': [(<function <lambda>>, 'Min')], 'RisingFactorial': [(<function <lambda>>, 'Pochhammer')], 'Shi': [(<function <lambda>>, 'SinhIntegral')], 'Si': [(<function <lambda>>, 'SinIntegral')], 'acos': [(<function <lambda>>, 'ArcCos')], 'acosh': [(<function <lambda>>, 'ArcCosh')], 'acot': [(<function <lambda>>, 'ArcCot')], 'acoth': [(<function <lambda>>, 'ArcCoth')], 'acsc': [(<function <lambda>>, 'ArcCsc')], 'acsch': [(<function <lambda>>, 'ArcCsch')], 'airyai': [(<function <lambda>>, 'AiryAi')], 'airyaiprime': [(<function <lambda>>, 'AiryAiPrime')], 'airybi': [(<function <lambda>>, 'AiryBi')], 'airybiprime': [(<function <lambda>>, 'AiryBiPrime')], 'appellf1': [(<function <lambda>>, 'AppellF1')], 'asec': [(<function <lambda>>, 'ArcSec')], 'asech': [(<function <lambda>>, 'ArcSech')], 'asin': [(<function <lambda>>, 'ArcSin')], 'asinh': [(<function <lambda>>, 'ArcSinh')], 'assoc_laguerre': [(<function <lambda>>, 'LaguerreL')], 'assoc_legendre': [(<function <lambda>>, 'LegendreP')], 'atan': [(<function <lambda>>, 'ArcTan')], 'atan2': [(<function <lambda>>, 'ArcTan')], 'atanh': [(<function <lambda>>, 'ArcTanh')], 'besseli': [(<function <lambda>>, 'BesselI')], 'besselj': [(<function <lambda>>, 'BesselJ')], 'besselk': [(<function <lambda>>, 'BesselK')], 'bessely': [(<function <lambda>>, 'BesselY')], 'beta': [(<function <lambda>>, 'Beta')], 'catalan': [(<function <lambda>>, 'CatalanNumber')], 'chebyshevt': [(<function <lambda>>, 'ChebyshevT')], 'chebyshevu': [(<function <lambda>>, 'ChebyshevU')], 'conjugate': [(<function <lambda>>, 'Conjugate')], 'cos': [(<function <lambda>>, 'Cos')], 'cosh': [(<function <lambda>>, 'Cosh')], 'cot': [(<function <lambda>>, 'Cot')], 'coth': [(<function <lambda>>, 'Coth')], 'csc': [(<function <lambda>>, 'Csc')], 'csch': [(<function <lambda>>, 'Csch')], 'dirichlet_eta': [(<function <lambda>>, 'DirichletEta')], 'elliptic_e': [(<function <lambda>>, 'EllipticE')], 'elliptic_f': [(<function <lambda>>, 'EllipticE')], 'elliptic_k': [(<function <lambda>>, 'EllipticK')], 'elliptic_pi': [(<function <lambda>>, 'EllipticPi')], 'erf': [(<function <lambda>>, 'Erf')], 'erf2': [(<function <lambda>>, 'Erf')], 'erf2inv': [(<function <lambda>>, 'InverseErf')], 'erfc': [(<function <lambda>>, 'Erfc')], 'erfcinv': [(<function <lambda>>, 'InverseErfc')], 'erfi': [(<function <lambda>>, 'Erfi')], 'erfinv': [(<function <lambda>>, 'InverseErf')], 'exp': [(<function <lambda>>, 'Exp')], 'expint': [(<function <lambda>>, 'ExpIntegralE')], 'factorial': [(<function <lambda>>, 'Factorial')], 'factorial2': [(<function <lambda>>, 'Factorial2')], 'fresnelc': [(<function <lambda>>, 'FresnelC')], 'fresnels': [(<function <lambda>>, 'FresnelS')], 'gamma': [(<function <lambda>>, 'Gamma')], 'gcd': [(<function <lambda>>, 'GCD')], 'gegenbauer': [(<function <lambda>>, 'GegenbauerC')], 'hankel1': [(<function <lambda>>, 'HankelH1')], 'hankel2': [(<function <lambda>>, 'HankelH2')], 'harmonic': [(<function <lambda>>, 'HarmonicNumber')], 'hermite': [(<function <lambda>>, 'HermiteH')], 'hyper': [(<function <lambda>>, 'HypergeometricPFQ')], 'jacobi': [(<function <lambda>>, 'JacobiP')], 'jn': [(<function <lambda>>, 'SphericalBesselJ')], 'laguerre': [(<function <lambda>>, 'LaguerreL')], 'lcm': [(<function <lambda>>, 'LCM')], 'legendre': [(<function <lambda>>, 'LegendreP')], 'lerchphi': [(<function <lambda>>, 'LerchPhi')], 'li': [(<function <lambda>>, 'LogIntegral')], 'log': [(<function <lambda>>, 'Log')], 'loggamma': [(<function <lambda>>, 'LogGamma')], 'lucas': [(<function <lambda>>, 'LucasL')], 'mathieuc': [(<function <lambda>>, 'MathieuC')], 'mathieucprime': [(<function <lambda>>, 'MathieuCPrime')], 'mathieus': [(<function <lambda>>, 'MathieuS')], 'mathieusprime': [(<function <lambda>>, 'MathieuSPrime')], 'meijerg': [(<function <lambda>>, 'MeijerG')], 'polygamma': [(<function <lambda>>, 'PolyGamma')], 'polylog': [(<function <lambda>>, 'PolyLog')], 'riemann_xi': [(<function <lambda>>, 'RiemannXi')], 'sec': [(<function <lambda>>, 'Sec')], 'sech': [(<function <lambda>>, 'Sech')], 'sin': [(<function <lambda>>, 'Sin')], 'sinc': [(<function <lambda>>, 'Sinc')], 'sinh': [(<function <lambda>>, 'Sinh')], 'sqrt': [(<function <lambda>>, 'Sqrt')], 'stieltjes': [(<function <lambda>>, 'StieltjesGamma')], 'subfactorial': [(<function <lambda>>, 'Subfactorial')], 'tan': [(<function <lambda>>, 'Tan')], 'tanh': [(<function <lambda>>, 'Tanh')], 'uppergamma': [(<function <lambda>>, 'Gamma')], 'yn': [(<function <lambda>>, 'SphericalBesselY')], 'zeta': [(<function <lambda>>, 'Zeta')]}
class sympy.printing.mathematica.MCodePrinter(settings={})[source]

A printer to convert Python expressions to strings of the Wolfram’s Mathematica code

printmethod: str = '_mcode'
sympy.printing.mathematica.mathematica_code(expr, **settings)[source]

Converts an expr to a string of the Wolfram Mathematica code

Examples

>>> from sympy import mathematica_code as mcode, symbols, sin
>>> x = symbols('x')
>>> mcode(sin(x).series(x).removeO())
'(1/120)*x^5 - 1/6*x^3 + x'

Maple code printing

class sympy.printing.maple.MapleCodePrinter(settings=None)[source]

Printer which converts a SymPy expression into a maple code.

printmethod: str = '_maple'
sympy.printing.maple.maple_code(expr, assign_to=None, **settings)[source]

Converts expr to a string of Maple code.

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This can be helpful for expressions that generate multi-line statements.

precision : integer, optional

The precision for numbers such as pi [default=16].

user_functions : dict, optional

A dictionary where keys are FunctionClass instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

inline: bool, optional

If True, we try to create single-statement code instead of multiple statements. [default=True].

sympy.printing.maple.print_maple_code(expr, **settings)[source]

Prints the Maple representation of the given expression.

See maple_code() for the meaning of the optional arguments.

Examples

>>> from sympy import print_maple_code, symbols
>>> x, y = symbols('x y')
>>> print_maple_code(x, assign_to=y)
y := x

Javascript Code printing

sympy.printing.jscode.known_functions = {'Abs': 'Math.abs', 'Max': 'Math.max', 'Min': 'Math.min', 'acos': 'Math.acos', 'acosh': 'Math.acosh', 'asin': 'Math.asin', 'asinh': 'Math.asinh', 'atan': 'Math.atan', 'atan2': 'Math.atan2', 'atanh': 'Math.atanh', 'ceiling': 'Math.ceil', 'cos': 'Math.cos', 'cosh': 'Math.cosh', 'exp': 'Math.exp', 'floor': 'Math.floor', 'log': 'Math.log', 'sign': 'Math.sign', 'sin': 'Math.sin', 'sinh': 'Math.sinh', 'tan': 'Math.tan', 'tanh': 'Math.tanh'}
class sympy.printing.jscode.JavascriptCodePrinter(settings={})[source]

“A Printer to convert Python expressions to strings of JavaScript code

printmethod: str = '_javascript'
indent_code(code)[source]

Accepts a string of code or a list of code lines

sympy.printing.jscode.jscode(expr, assign_to=None, **settings)[source]

Converts an expr to a string of javascript code

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements.

precision : integer, optional

The precision for numbers such as pi [default=15].

user_functions : dict, optional

A dictionary where keys are FunctionClass instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, js_function_string)]. See below for examples.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

Examples

>>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs
>>> x, tau = symbols("x, tau")
>>> jscode((2*tau)**Rational(7, 2))
'8*Math.sqrt(2)*Math.pow(tau, 7/2)'
>>> jscode(sin(x), assign_to="s")
's = Math.sin(x);'

Custom printing can be defined for certain types by passing a dictionary of “type” : “function” to the user_functions kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, js_function_string)].

>>> custom_functions = {
...   "ceiling": "CEIL",
...   "Abs": [(lambda x: not x.is_integer, "fabs"),
...           (lambda x: x.is_integer, "ABS")]
... }
>>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions)
'fabs(x) + CEIL(x)'

Piecewise expressions are converted into conditionals. If an assign_to variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(jscode(expr, tau))
if (x > 0) {
   tau = x + 1;
}
else {
   tau = x;
}

Support for loops is provided through Indexed types. With contract=True these expressions will be turned into loops, whereas contract=False will just print the assignment expression that should be looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> jscode(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'

Matrices are also supported, but a MatrixSymbol of the same dimensions must be provided to assign_to. Note that any expression that can be generated normally can also exist inside a Matrix:

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(jscode(mat, A))
A[0] = Math.pow(x, 2);
if (x > 0) {
   A[1] = x + 1;
}
else {
   A[1] = x;
}
A[2] = Math.sin(x);

Julia code printing

sympy.printing.julia.known_fcns_src1 = ['sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'asin', 'acos', 'atan', 'acot', 'asec', 'acsc', 'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', 'acoth', 'asech', 'acsch', 'sinc', 'atan2', 'sign', 'floor', 'log', 'exp', 'cbrt', 'sqrt', 'erf', 'erfc', 'erfi', 'factorial', 'gamma', 'digamma', 'trigamma', 'polygamma', 'beta', 'airyai', 'airyaiprime', 'airybi', 'airybiprime', 'besselj', 'bessely', 'besseli', 'besselk', 'erfinv', 'erfcinv']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

sympy.printing.julia.known_fcns_src2 = {'Abs': 'abs', 'ceiling': 'ceil', 'conjugate': 'conj', 'hankel1': 'hankelh1', 'hankel2': 'hankelh2', 'im': 'imag', 're': 'real'}
class sympy.printing.julia.JuliaCodePrinter(settings={})[source]

A printer to convert expressions to strings of Julia code.

printmethod: str = '_julia'
indent_code(code)[source]

Accepts a string of code or a list of code lines

sympy.printing.julia.julia_code(expr, assign_to=None, **settings)[source]

Converts \(expr\) to a string of Julia code.

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This can be helpful for expressions that generate multi-line statements.

precision : integer, optional

The precision for numbers such as pi [default=16].

user_functions : dict, optional

A dictionary where keys are FunctionClass instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

inline: bool, optional

If True, we try to create single-statement code instead of multiple statements. [default=True].

Examples

>>> from sympy import julia_code, symbols, sin, pi
>>> x = symbols('x')
>>> julia_code(sin(x).series(x).removeO())
'x .^ 5 / 120 - x .^ 3 / 6 + x'
>>> from sympy import Rational, ceiling
>>> x, y, tau = symbols("x, y, tau")
>>> julia_code((2*tau)**Rational(7, 2))
'8 * sqrt(2) * tau .^ (7 // 2)'

Note that element-wise (Hadamard) operations are used by default between symbols. This is because its possible in Julia to write “vectorized” code. It is harmless if the values are scalars.

>>> julia_code(sin(pi*x*y), assign_to="s")
's = sin(pi * x .* y)'

If you need a matrix product “*” or matrix power “^”, you can specify the symbol as a MatrixSymbol.

>>> from sympy import Symbol, MatrixSymbol
>>> n = Symbol('n', integer=True, positive=True)
>>> A = MatrixSymbol('A', n, n)
>>> julia_code(3*pi*A**3)
'(3 * pi) * A ^ 3'

This class uses several rules to decide which symbol to use a product. Pure numbers use “*”, Symbols use “.*” and MatrixSymbols use “*”. A HadamardProduct can be used to specify componentwise multiplication “.*” of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write “(x^2*y)*A^3”, we generate:

>>> julia_code(x**2*y*A**3)
'(x .^ 2 .* y) * A ^ 3'

Matrices are supported using Julia inline notation. When using assign_to with matrices, the name can be specified either as a string or as a MatrixSymbol. The dimensions must align in the latter case.

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
>>> julia_code(mat, assign_to='A')
'A = [x .^ 2 sin(x) ceil(x)]'

Piecewise expressions are implemented with logical masking by default. Alternatively, you can pass “inline=False” to use if-else conditionals. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> pw = Piecewise((x + 1, x > 0), (x, True))
>>> julia_code(pw, assign_to=tau)
'tau = ((x > 0) ? (x + 1) : (x))'

Note that any expression that can be generated normally can also exist inside a Matrix:

>>> mat = Matrix([[x**2, pw, sin(x)]])
>>> julia_code(mat, assign_to='A')
'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]'

Custom printing can be defined for certain types by passing a dictionary of “type” : “function” to the user_functions kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Julia function.

>>> from sympy import Function
>>> f = Function('f')
>>> g = Function('g')
>>> custom_functions = {
...   "f": "existing_julia_fcn",
...   "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
...         (lambda x: not x.is_Matrix, "my_fcn")]
... }
>>> mat = Matrix([[1, x]])
>>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'

Support for loops is provided through Indexed types. With contract=True these expressions will be turned into loops, whereas contract=False will just print the assignment expression that should be looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> julia_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])'

Octave (and Matlab) Code printing

sympy.printing.octave.known_fcns_src1 = ['sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'asin', 'acos', 'acot', 'atan', 'atan2', 'asec', 'acsc', 'sinh', 'cosh', 'tanh', 'coth', 'csch', 'sech', 'asinh', 'acosh', 'atanh', 'acoth', 'asech', 'acsch', 'erfc', 'erfi', 'erf', 'erfinv', 'erfcinv', 'besseli', 'besselj', 'besselk', 'bessely', 'bernoulli', 'beta', 'euler', 'exp', 'factorial', 'floor', 'fresnelc', 'fresnels', 'gamma', 'harmonic', 'log', 'polylog', 'sign', 'zeta', 'legendre']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

sympy.printing.octave.known_fcns_src2 = {'Abs': 'abs', 'Chi': 'coshint', 'Ci': 'cosint', 'DiracDelta': 'dirac', 'Heaviside': 'heaviside', 'LambertW': 'lambertw', 'Max': 'max', 'Min': 'min', 'Mod': 'mod', 'RisingFactorial': 'pochhammer', 'Shi': 'sinhint', 'Si': 'sinint', 'arg': 'angle', 'binomial': 'bincoeff', 'ceiling': 'ceil', 'chebyshevt': 'chebyshevT', 'chebyshevu': 'chebyshevU', 'conjugate': 'conj', 'im': 'imag', 'laguerre': 'laguerreL', 'li': 'logint', 'loggamma': 'gammaln', 'polygamma': 'psi', 're': 'real'}
class sympy.printing.octave.OctaveCodePrinter(settings={})[source]

A printer to convert expressions to strings of Octave/Matlab code.

printmethod: str = '_octave'
indent_code(code)[source]

Accepts a string of code or a list of code lines

sympy.printing.octave.octave_code(expr, assign_to=None, **settings)[source]

Converts \(expr\) to a string of Octave (or Matlab) code.

The string uses a subset of the Octave language for Matlab compatibility.

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This can be helpful for expressions that generate multi-line statements.

precision : integer, optional

The precision for numbers such as pi [default=16].

user_functions : dict, optional

A dictionary where keys are FunctionClass instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

inline: bool, optional

If True, we try to create single-statement code instead of multiple statements. [default=True].

Examples

>>> from sympy import octave_code, symbols, sin, pi
>>> x = symbols('x')
>>> octave_code(sin(x).series(x).removeO())
'x.^5/120 - x.^3/6 + x'
>>> from sympy import Rational, ceiling
>>> x, y, tau = symbols("x, y, tau")
>>> octave_code((2*tau)**Rational(7, 2))
'8*sqrt(2)*tau.^(7/2)'

Note that element-wise (Hadamard) operations are used by default between symbols. This is because its very common in Octave to write “vectorized” code. It is harmless if the values are scalars.

>>> octave_code(sin(pi*x*y), assign_to="s")
's = sin(pi*x.*y);'

If you need a matrix product “*” or matrix power “^”, you can specify the symbol as a MatrixSymbol.

>>> from sympy import Symbol, MatrixSymbol
>>> n = Symbol('n', integer=True, positive=True)
>>> A = MatrixSymbol('A', n, n)
>>> octave_code(3*pi*A**3)
'(3*pi)*A^3'

This class uses several rules to decide which symbol to use a product. Pure numbers use “*”, Symbols use “.*” and MatrixSymbols use “*”. A HadamardProduct can be used to specify componentwise multiplication “.*” of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write “(x^2*y)*A^3”, we generate:

>>> octave_code(x**2*y*A**3)
'(x.^2.*y)*A^3'

Matrices are supported using Octave inline notation. When using assign_to with matrices, the name can be specified either as a string or as a MatrixSymbol. The dimensions must align in the latter case.

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
>>> octave_code(mat, assign_to='A')
'A = [x.^2 sin(x) ceil(x)];'

Piecewise expressions are implemented with logical masking by default. Alternatively, you can pass “inline=False” to use if-else conditionals. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> pw = Piecewise((x + 1, x > 0), (x, True))
>>> octave_code(pw, assign_to=tau)
'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));'

Note that any expression that can be generated normally can also exist inside a Matrix:

>>> mat = Matrix([[x**2, pw, sin(x)]])
>>> octave_code(mat, assign_to='A')
'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];'

Custom printing can be defined for certain types by passing a dictionary of “type” : “function” to the user_functions kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Octave function.

>>> from sympy import Function
>>> f = Function('f')
>>> g = Function('g')
>>> custom_functions = {
...   "f": "existing_octave_fcn",
...   "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
...         (lambda x: not x.is_Matrix, "my_fcn")]
... }
>>> mat = Matrix([[1, x]])
>>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'

Support for loops is provided through Indexed types. With contract=True these expressions will be turned into loops, whereas contract=False will just print the assignment expression that should be looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> octave_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'

Rust code printing

sympy.printing.rust.known_functions = {'Abs': 'abs', 'Max': 'max', 'Min': 'min', 'Pow': [(<function <lambda>>, 'recip', 2), (<function <lambda>>, 'sqrt', 2), (<function <lambda>>, 'sqrt().recip', 2), (<function <lambda>>, 'cbrt', 2), (<function <lambda>>, 'exp2', 3), (<function <lambda>>, 'powi', 1), (<function <lambda>>, 'powf', 1)], 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'exp': [(<function <lambda>>, 'exp', 2)], 'floor': 'floor', 'log': 'ln', 'sign': 'signum', 'sin': 'sin', 'sinh': 'sinh', 'sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh'}
class sympy.printing.rust.RustCodePrinter(settings={})[source]

A printer to convert SymPy expressions to strings of Rust code

printmethod: str = '_rust_code'
indent_code(code)[source]

Accepts a string of code or a list of code lines

sympy.printing.rust.rust_code(expr, assign_to=None, **settings)[source]

Converts an expr to a string of Rust code

Parameters:

expr : Expr

A SymPy expression to be converted.

assign_to : optional

When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, Symbol, MatrixSymbol, or Indexed type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements.

precision : integer, optional

The precision for numbers such as pi [default=15].

user_functions : dict, optional

A dictionary where the keys are string representations of either FunctionClass or UndefinedFunction instances and the values are their desired C string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples.

dereference : iterable, optional

An iterable of symbols that should be dereferenced in the printed code expression. These would be values passed by address to the function. For example, if dereference=[a], the resulting code would print (*a) instead of a.

human : bool, optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True].

contract: bool, optional

If True, Indexed instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True].

Examples

>>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> rust_code((2*tau)**Rational(7, 2))
'8*1.4142135623731*tau.powf(7_f64/2.0)'
>>> rust_code(sin(x), assign_to="s")
's = x.sin();'

Simple custom printing can be defined for certain types by passing a dictionary of {“type” : “function”} to the user_functions kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)].

>>> custom_functions = {
...   "ceiling": "CEIL",
...   "Abs": [(lambda x: not x.is_integer, "fabs", 4),
...           (lambda x: x.is_integer, "ABS", 4)],
...   "func": "f"
... }
>>> func = Function('func')
>>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
'(fabs(x) + x.CEIL()).f()'

Piecewise expressions are converted into conditionals. If an assign_to variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the Piecewise lacks a default term, represented by (expr, True) then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything.

>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(rust_code(expr, tau))
tau = if (x > 0) {
    x + 1
} else {
    x
};

Support for loops is provided through Indexed types. With contract=True these expressions will be turned into loops, whereas contract=False will just print the assignment expression that should be looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> rust_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'

Matrices are also supported, but a MatrixSymbol of the same dimensions must be provided to assign_to. Note that any expression that can be generated normally can also exist inside a Matrix:

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(rust_code(mat, A))
A = [x.powi(2), if (x > 0) {
    x + 1
} else {
    x
}, x.sin()];

Aesara Code printing

class sympy.printing.aesaracode.AesaraPrinter(*args, **kwargs)[source]

Code printer which creates Aesara symbolic expression graphs.

Parameters:

cache : dict

Cache dictionary to use. If None (default) will use the global cache. To create a printer which does not depend on or alter global state pass an empty dictionary. Note: the dictionary is not copied on initialization of the printer and will be updated in-place, so using the same dict object when creating multiple printers or making multiple calls to aesara_code() or aesara_function() means the cache is shared between all these applications.

Attributes

cache

(dict) A cache of Aesara variables which have been created for SymPy symbol-like objects (e.g. sympy.core.symbol.Symbol or sympy.matrices.expressions.MatrixSymbol). This is used to ensure that all references to a given symbol in an expression (or multiple expressions) are printed as the same Aesara variable, which is created only once. Symbols are differentiated only by name and type. The format of the cache’s contents should be considered opaque to the user.

printmethod: str = '_aesara'
doprint(expr, dtypes=None, broadcastables=None)[source]

Convert a SymPy expression to a Aesara graph variable.

The dtypes and broadcastables arguments are used to specify the data type, dimension, and broadcasting behavior of the Aesara variables corresponding to the free symbols in expr. Each is a mapping from SymPy symbols to the value of the corresponding argument to aesara.tensor.var.TensorVariable.

See the corresponding documentation page for more information on broadcasting in Aesara.

Parameters:

expr : sympy.core.expr.Expr

SymPy expression to print.

dtypes : dict

Mapping from SymPy symbols to Aesara datatypes to use when creating new Aesara variables for those symbols. Corresponds to the dtype argument to aesara.tensor.var.TensorVariable. Defaults to 'floatX' for symbols not included in the mapping.

broadcastables : dict

Mapping from SymPy symbols to the value of the broadcastable argument to aesara.tensor.var.TensorVariable to use when creating Aesara variables for those symbols. Defaults to the empty tuple for symbols not included in the mapping (resulting in a scalar).

Returns:

aesara.graph.basic.Variable

A variable corresponding to the expression’s value in a Aesara symbolic expression graph.

sympy.printing.aesaracode.aesara_code(expr, cache=None, **kwargs)[source]

Convert a SymPy expression into a Aesara graph variable.

Parameters:

expr : sympy.core.expr.Expr

SymPy expression object to convert.

cache : dict

Cached Aesara variables (see AesaraPrinter.cache). Defaults to the module-level global cache.

dtypes : dict

broadcastables : dict

Returns:

aesara.graph.basic.Variable

A variable corresponding to the expression’s value in a Aesara symbolic expression graph.

sympy.printing.aesaracode.aesara_function(inputs, outputs, scalar=False, *, dim=None, dims=None, broadcastables=None, **kwargs)[source]

Create a Aesara function from SymPy expressions.

The inputs and outputs are converted to Aesara variables using aesara_code() and then passed to aesara.function.

Parameters:

inputs

Sequence of symbols which constitute the inputs of the function.

outputs

Sequence of expressions which constitute the outputs(s) of the function. The free symbols of each expression must be a subset of inputs.

scalar : bool

Convert 0-dimensional arrays in output to scalars. This will return a Python wrapper function around the Aesara function object.

cache : dict

Cached Aesara variables (see AesaraPrinter.cache). Defaults to the module-level global cache.

dtypes : dict

broadcastables : dict

dims : dict

Alternative to broadcastables argument. Mapping from elements of inputs to integers indicating the dimension of their associated arrays/tensors. Overrides broadcastables argument if given.

dim : int

Another alternative to the broadcastables argument. Common number of dimensions to use for all arrays/tensors. aesara_function([x, y], [...], dim=2) is equivalent to using broadcastables={x: (False, False), y: (False, False)}.

Returns:

callable

A callable object which takes values of inputs as positional arguments and returns an output array for each of the expressions in outputs. If outputs is a single expression the function will return a Numpy array, if it is a list of multiple expressions the function will return a list of arrays. See description of the squeeze argument above for the behavior when a single output is passed in a list. The returned object will either be an instance of aesara.compile.function.types.Function or a Python wrapper function around one. In both cases, the returned value will have a aesara_function attribute which points to the return value of aesara.function.

Examples

>>> from sympy.abc import x, y, z
>>> from sympy.printing.aesaracode import aesara_function

A simple function with one input and one output:

>>> f1 = aesara_function([x], [x**2 - 1], scalar=True)
>>> f1(3)
8.0

A function with multiple inputs and one output:

>>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True)
>>> f2(3, 4, 2)
5.0

A function with multiple inputs and multiple outputs:

>>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
>>> f3(2, 3)
[13.0, -5.0]

See also

dim_handling

sympy.printing.aesaracode.dim_handling(inputs, dim=None, dims=None, broadcastables=None)[source]

Get value of broadcastables argument to aesara_code() from keyword arguments to aesara_function().

Included for backwards compatibility.

Parameters:

inputs

Sequence of input symbols.

dim : int

Common number of dimensions for all inputs. Overrides other arguments if given.

dims : dict

Mapping from input symbols to number of dimensions. Overrides broadcastables argument if given.

broadcastables : dict

Explicit value of broadcastables argument to AesaraPrinter.doprint(). If not None function will return this value unchanged.

Returns:

dict

Dictionary mapping elements of inputs to their “broadcastable” values (tuple of bools).

Gtk

You can print to a gtkmathview widget using the function print_gtk located in sympy.printing.gtk (it requires to have installed gtkmathview 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))
sympy.printing.gtk.print_gtk(x, start_viewer=True)[source]

Print to Gtkmathview, a gtk widget capable of rendering MathML.

Needs libgtkmathview-bin

LambdaPrinter

This classes implements printing to strings that can be used by the sympy.utilities.lambdify.lambdify() function.

class sympy.printing.lambdarepr.LambdaPrinter(settings=None)[source]

This printer converts expressions into strings that can be used by lambdify.

printmethod: str = '_lambdacode'
sympy.printing.lambdarepr.lambdarepr(expr, **settings)[source]

Returns a string usable for lambdifying.

LatexPrinter

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

sympy.printing.latex.accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec', 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root', 'arg']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

class sympy.printing.latex.LatexPrinter(settings=None)[source]
printmethod: str = '_latex'
parenthesize_super(s)[source]

Protect superscripts in s

If the parenthesize_super option is set, protect with parentheses, else wrap in braces.

sympy.printing.latex.latex(expr, *, full_prec=False, fold_frac_powers=False, fold_func_brackets=False, fold_short_frac=None, inv_trig_style='abbreviated', itex=False, ln_notation=False, long_frac_ratio=None, mat_delim='[', mat_str=None, mode='plain', mul_symbol=None, order=None, symbol_names={}, root_notation=True, mat_symbol_style='plain', imaginary_unit='i', gothic_re_im=False, decimal_separator='period', perm_cyclic=True, parenthesize_super=True, min=None, max=None, diff_operator='d', adjoint_style='dagger')

Convert the given expression to LaTeX string representation.

Parameters:

full_prec: boolean, optional

If set to True, a floating point number is printed with full precision.

fold_frac_powers : boolean, optional

Emit ^{p/q} instead of ^{\frac{p}{q}} for fractional powers.

fold_func_brackets : boolean, optional

Fold function brackets where applicable.

fold_short_frac : boolean, optional

Emit p / q instead of \frac{p}{q} when the denominator is simple enough (at most two terms and no powers). The default value is True for inline mode, False otherwise.

inv_trig_style : string, optional

How inverse trig functions should be displayed. Can be one of 'abbreviated', 'full', or 'power'. Defaults to 'abbreviated'.

itex : boolean, optional

Specifies if itex-specific syntax is used, including emitting $$...$$.

ln_notation : boolean, optional

If set to True, \ln is used instead of default \log.

long_frac_ratio : float or None, optional

The allowed ratio of the width of the numerator to the width of the denominator before the printer breaks off long fractions. If None (the default value), long fractions are not broken up.

mat_delim : string, optional

The delimiter to wrap around matrices. Can be one of '[', '(', or the empty string ''. Defaults to '['.

mat_str : string, optional

Which matrix environment string to emit. 'smallmatrix', 'matrix', 'array', etc. Defaults to 'smallmatrix' for inline mode, 'matrix' for matrices of no more than 10 columns, and 'array' otherwise.

mode: string, optional

Specifies how the generated code will be delimited. mode can be one of 'plain', 'inline', 'equation' or 'equation*'. If mode is set to 'plain', then the resulting code will not be delimited at all (this is the default). If mode is set to 'inline' then inline LaTeX $...$ will be used. If mode is set to 'equation' or 'equation*', the resulting code will be enclosed in the equation or equation* environment (remember to import amsmath for equation*), unless the itex option is set. In the latter case, the $$...$$ syntax is used.

mul_symbol : string or None, optional

The symbol to use for multiplication. Can be one of None, 'ldot', 'dot', or 'times'.

order: string, optional

Any of the supported monomial orderings (currently 'lex', 'grlex', or 'grevlex'), 'old', and 'none'. This parameter does nothing for \(~.Mul\) objects. Setting order to 'old' uses the compatibility ordering for ~.Add defined in Printer. For very large expressions, set the order keyword to 'none' if speed is a concern.

symbol_names : dictionary of strings mapped to symbols, optional

Dictionary of symbols and the custom strings they should be emitted as.

root_notation : boolean, optional

If set to False, exponents of the form 1/n are printed in fractonal form. Default is True, to print exponent in root form.

mat_symbol_style : string, optional

Can be either 'plain' (default) or 'bold'. If set to 'bold', a \(~.MatrixSymbol\) A will be printed as \mathbf{A}, otherwise as A.

imaginary_unit : string, optional

String to use for the imaginary unit. Defined options are 'i' (default) and 'j'. Adding r or t in front gives \mathrm or \text, so 'ri' leads to \mathrm{i} which gives \(\mathrm{i}\).

gothic_re_im : boolean, optional

If set to True, \(\Re\) and \(\Im\) is used for re and im, respectively. The default is False leading to \(\operatorname{re}\) and \(\operatorname{im}\).

decimal_separator : string, optional

Specifies what separator to use to separate the whole and fractional parts of a floating point number as in \(2.5\) for the default, period or \(2{,}5\) when comma is specified. Lists, sets, and tuple are printed with semicolon separating the elements when comma is chosen. For example, [1; 2; 3] when comma is chosen and [1,2,3] for when period is chosen.

parenthesize_super : boolean, optional

If set to False, superscripted expressions will not be parenthesized when powered. Default is True, which parenthesizes the expression when powered.

min: Integer or None, optional

Sets the lower bound for the exponent to print floating point numbers in fixed-point format.

max: Integer or None, optional

Sets the upper bound for the exponent to print floating point numbers in fixed-point format.

diff_operator: string, optional

String to use for differential operator. Default is 'd', to print in italic form. 'rd', 'td' are shortcuts for \mathrm{d} and \text{d}.

adjoint_style: string, optional

String to use for the adjoint symbol. Defined options are 'dagger' (default),``’star’, and ``'hermitian'.

Notes

Not using a print statement for printing, results in double backslashes for latex commands since that’s the way Python escapes backslashes in strings.

>>> from sympy import latex, Rational
>>> from sympy.abc import tau
>>> latex((2*tau)**Rational(7,2))
'8 \\sqrt{2} \\tau^{\\frac{7}{2}}'
>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}

Examples

>>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log
>>> from sympy.abc import x, y, mu, r, tau

Basic usage:

>>> print(latex((2*tau)**Rational(7,2)))
8 \sqrt{2} \tau^{\frac{7}{2}}

mode and itex options:

>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$
>>> print(latex((2*mu)**Rational(7,2), mode='plain'))
8 \sqrt{2} \mu^{\frac{7}{2}}
>>> print(latex((2*tau)**Rational(7,2), mode='inline'))
$8 \sqrt{2} \tau^{7 / 2}$
>>> print(latex((2*mu)**Rational(7,2), mode='equation*'))
\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}
>>> print(latex((2*mu)**Rational(7,2), mode='equation'))
\begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation}
>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True))
$$8 \sqrt{2} \mu^{\frac{7}{2}}$$

Fraction options:

>>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True))
8 \sqrt{2} \tau^{7/2}
>>> print(latex((2*tau)**sin(Rational(7,2))))
\left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}}
>>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True))
\left(2 \tau\right)^{\sin {\frac{7}{2}}}
>>> print(latex(3*x**2/y))
\frac{3 x^{2}}{y}
>>> print(latex(3*x**2/y, fold_short_frac=True))
3 x^{2} / y
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2))
\frac{\int r\, dr}{2 \pi}
>>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0))
\frac{1}{2 \pi} \int r\, dr

Multiplication options:

>>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times"))
\left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}}

Trig options:

>>> print(latex(asin(Rational(7,2))))
\operatorname{asin}{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="full"))
\arcsin{\left(\frac{7}{2} \right)}
>>> print(latex(asin(Rational(7,2)), inv_trig_style="power"))
\sin^{-1}{\left(\frac{7}{2} \right)}

Matrix options:

>>> print(latex(Matrix(2, 1, [x, y])))
\left[\begin{matrix}x\\y\end{matrix}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array"))
\left[\begin{array}{c}x\\y\end{array}\right]
>>> print(latex(Matrix(2, 1, [x, y]), mat_delim="("))
\left(\begin{matrix}x\\y\end{matrix}\right)

Custom printing of symbols:

>>> print(latex(x**2, symbol_names={x: 'x_i'}))
x_i^{2}

Logarithms:

>>> print(latex(log(10)))
\log{\left(10 \right)}
>>> print(latex(log(10), ln_notation=True))
\ln{\left(10 \right)}

latex() also supports the builtin container types list, tuple, and dict:

>>> print(latex([2/x, y], mode='inline'))
$\left[ 2 / x, \  y\right]$

Unsupported types are rendered as monospaced plaintext:

>>> print(latex(int))
\mathtt{\text{<class 'int'>}}
>>> print(latex("plain % text"))
\mathtt{\text{plain \% text}}

See Example of Custom Printing Method for an example of how to override this behavior for your own types by implementing _latex.

Changed in version 1.7.0: Unsupported types no longer have their str representation treated as valid latex.

sympy.printing.latex.print_latex(expr, **settings)[source]

Prints LaTeX representation of the given expression. Takes the same settings as latex().

MathMLPrinter

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

More info on mathml : https://www.w3.org/TR/MathML2

class sympy.printing.mathml.MathMLPrinterBase(settings=None)[source]

Contains common code required for MathMLContentPrinter and MathMLPresentationPrinter.

doprint(expr)[source]

Prints the expression as MathML.

class sympy.printing.mathml.MathMLContentPrinter(settings=None)[source]

Prints an expression to the Content MathML markup language.

References: https://www.w3.org/TR/MathML2/chapter4.html

printmethod: str = '_mathml_content'
mathml_tag(e)[source]

Returns the MathML tag for an expression.

class sympy.printing.mathml.MathMLPresentationPrinter(settings=None)[source]

Prints an expression to the Presentation MathML markup language.

References: https://www.w3.org/TR/MathML2/chapter3.html

printmethod: str = '_mathml_presentation'
mathml_tag(e)[source]

Returns the MathML tag for an expression.

sympy.printing.mathml.mathml(expr, printer='content', *, order=None, encoding='utf-8', fold_frac_powers=False, fold_func_brackets=False, fold_short_frac=None, inv_trig_style='abbreviated', ln_notation=False, long_frac_ratio=None, mat_delim='[', mat_symbol_style='plain', mul_symbol=None, root_notation=True, symbol_names={}, mul_symbol_mathml_numbers='&#xB7;')

Returns the MathML representation of expr. If printer is presentation then prints Presentation MathML else prints content MathML.

sympy.printing.mathml.print_mathml(expr, printer='content', **settings)[source]

Prints a pretty representation of the MathML code for expr. If printer is presentation then prints Presentation MathML else prints content MathML.

Examples

>>> ##
>>> from sympy import print_mathml
>>> from sympy.abc import x
>>> print_mathml(x+1) 
<apply>
    <plus/>
    <ci>x</ci>
    <cn>1</cn>
</apply>
>>> print_mathml(x+1, printer='presentation')
<mrow>
    <mi>x</mi>
    <mo>+</mo>
    <mn>1</mn>
</mrow>

PythonCodePrinter

Python code printers

This module contains Python code printers for plain Python as well as NumPy & SciPy enabled code.

class sympy.printing.pycode.MpmathPrinter(settings=None)[source]

Lambda printer for mpmath which maintains precision for floats

sympy.printing.pycode.pycode(expr, **settings)[source]

Converts an expr to a string of Python code

Parameters:

expr : Expr

A SymPy expression.

fully_qualified_modules : bool

Whether or not to write out full module names of functions (math.sin vs. sin). default: True.

standard : str or None, optional

Only ‘python3’ (default) is supported. This parameter may be removed in the future.

Examples

>>> from sympy import pycode, tan, Symbol
>>> pycode(tan(Symbol('x')) + 1)
'math.tan(x) + 1'

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)

srepr

This printer generates executable code. This code satisfies the identity eval(srepr(expr)) == expr.

srepr() gives more low level textual output than repr()

Example:

>>> repr(5*x**3 + sin(x))
'5*x**3 + sin(x)'

>>> srepr(5*x**3 + sin(x))
"Add(Mul(Integer(5), Pow(Symbol('x'), Integer(3))), sin(Symbol('x')))"

srepr() gives the repr form, which is what repr() would normally give but for SymPy we don’t actually use srepr() for __repr__ because it’s is so verbose, it is unlikely that anyone would want it called by default. Another reason is that lists call repr on their elements, like print([a, b, c]) calls repr(a), repr(b), repr(c). So if we used srepr for __repr__ any list with SymPy objects would include the srepr form, even if we used str() or print().

class sympy.printing.repr.ReprPrinter(settings=None)[source]
printmethod: str = '_sympyrepr'
emptyPrinter(expr)[source]

The fallback printer.

reprify(args, sep)[source]

Prints each item in \(args\) and joins them with \(sep\).

sympy.printing.repr.srepr(expr, *, order=None, perm_cyclic=True)

return expr in repr form

StrPrinter

This module generates readable representations of SymPy expressions.

class sympy.printing.str.StrPrinter(settings=None)[source]
printmethod: str = '_sympystr'
sympy.printing.str.sstr(expr, *, order=None, full_prec='auto', sympy_integers=False, abbrev=False, perm_cyclic=True, min=None, max=None)

Returns the expression as a string.

For large expressions where speed is a concern, use the setting order=’none’. If abbrev=True setting is used then units are printed in abbreviated form.

Examples

>>> from sympy import symbols, Eq, sstr
>>> a, b = symbols('a b')
>>> sstr(Eq(a + b, 0))
'Eq(a + b, 0)'
sympy.printing.str.sstrrepr(expr, *, order=None, full_prec='auto', sympy_integers=False, abbrev=False, perm_cyclic=True, min=None, max=None)

return expr in mixed str/repr form

i.e. strings are returned in repr form with quotes, and everything else is returned in str form.

This function could be useful for hooking into sys.displayhook

Tree Printing

The functions in this module create a representation of an expression as a tree.

sympy.printing.tree.pprint_nodes(subtrees)[source]

Prettyprints systems of nodes.

Examples

>>> from sympy.printing.tree import pprint_nodes
>>> print(pprint_nodes(["a", "b1\nb2", "c"]))
+-a
+-b1
| b2
+-c
sympy.printing.tree.print_node(node, assumptions=True)[source]

Returns information about the “node”.

This includes class name, string representation and assumptions.

Parameters:

assumptions : bool, optional

See the assumptions keyword in tree

sympy.printing.tree.tree(node, assumptions=True)[source]

Returns a tree representation of “node” as a string.

It uses print_node() together with pprint_nodes() on node.args recursively.

Parameters:

asssumptions : bool, optional

The flag to decide whether to print out all the assumption data (such as is_integer`, ``is_real) associated with the expression or not.

Enabling the flag makes the result verbose, and the printed result may not be determinisitic because of the randomness used in backtracing the assumptions.

See also

print_tree

sympy.printing.tree.print_tree(node, assumptions=True)[source]

Prints a tree representation of “node”.

Parameters:

asssumptions : bool, optional

The flag to decide whether to print out all the assumption data (such as is_integer`, ``is_real) associated with the expression or not.

Enabling the flag makes the result verbose, and the printed result may not be determinisitic because of the randomness used in backtracing the assumptions.

Examples

>>> from sympy.printing import print_tree
>>> from sympy import Symbol
>>> x = Symbol('x', odd=True)
>>> y = Symbol('y', even=True)

Printing with full assumptions information:

>>> print_tree(y**x)
Pow: y**x
+-Symbol: y
| algebraic: True
| commutative: True
| complex: True
| even: True
| extended_real: True
| finite: True
| hermitian: True
| imaginary: False
| infinite: False
| integer: True
| irrational: False
| noninteger: False
| odd: False
| rational: True
| real: True
| transcendental: False
+-Symbol: x
  algebraic: True
  commutative: True
  complex: True
  even: False
  extended_nonzero: True
  extended_real: True
  finite: True
  hermitian: True
  imaginary: False
  infinite: False
  integer: True
  irrational: False
  noninteger: False
  nonzero: True
  odd: True
  rational: True
  real: True
  transcendental: False
  zero: False

Hiding the assumptions:

>>> print_tree(y**x, assumptions=False)
Pow: y**x
+-Symbol: y
+-Symbol: x

See also

tree

Preview

A useful function is preview:

sympy.printing.preview.preview(expr, output='png', viewer=None, euler=True, packages=(), filename=None, outputbuffer=None, preamble=None, dvioptions=None, outputTexFile=None, extra_preamble=None, fontsize=None, **latex_settings)[source]

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

If the expr argument is an expression, it will be exported to LaTeX and then compiled using the available TeX distribution. The first argument, ‘expr’, may also be a LaTeX string. The function will then run the appropriate viewer for the given output format or use the user defined one. 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 symbols, preview, Symbol
>>> x, y = symbols("x,y")
>>> preview(x + y, output='png')

This will choose ‘pyglet’ by default. To select a different one, do

>>> 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, it will fall back to using a system file association (via open and xdg-open). To always use your system file association without searching for the above readers, use

>>> from sympy.printing.preview import system_default_viewer
>>> preview(x + y, output='dvi', viewer=system_default_viewer)

If this still does not find the viewer you want, it can be set 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.

You may also enter 'file' for the viewer argument. Doing so will cause this function to return a file object in read-only mode, if filename is unset. However, if it was set, then ‘preview’ writes the generated file to this filename instead.

There is also support for writing to a io.BytesIO like object, which needs to be passed to the outputbuffer argument.

>>> from io import BytesIO
>>> obj = BytesIO()
>>> preview(x + y, output='png', viewer='BytesIO',
...         outputbuffer=obj)

The LaTeX preamble can be customized by setting the ‘preamble’ keyword argument. This can be used, e.g., to set a different font size, use a custom documentclass or import certain set of LaTeX packages.

>>> preamble = "\\documentclass[10pt]{article}\n" \
...            "\\usepackage{amsmath,amsfonts}\\begin{document}"
>>> preview(x + y, output='png', preamble=preamble)

It is also possible to use the standard preamble and provide additional information to the preamble using the extra_preamble keyword argument.

>>> from sympy import sin
>>> extra_preamble = "\\renewcommand{\\sin}{\\cos}"
>>> preview(sin(x), output='png', extra_preamble=extra_preamble)

If the value of ‘output’ is different from ‘dvi’ then command line options can be set (‘dvioptions’ argument) for the execution of the ‘dvi’+output conversion tool. These options have to be in the form of a list of strings (see subprocess.Popen).

Additional keyword args will be passed to the latex() call, e.g., the symbol_names flag.

>>> phidd = Symbol('phidd')
>>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'})

For post-processing the generated TeX File can be written to a file by passing the desired filename to the ‘outputTexFile’ keyword argument. To write the TeX code to a file named "sample.tex" and run the default png viewer to display the resulting bitmap, do

>>> preview(x + y, outputTexFile="sample.tex")

Implementation - Helper Classes/Functions

sympy.printing.conventions.split_super_sub(text)[source]

Split a symbol name into a name, superscripts and subscripts

The first part of the symbol name is considered to be its actual ‘name’, followed by super- and subscripts. Each superscript is preceded with a “^” character or by “__”. Each subscript is preceded by a “_” character. The three return values are the actual name, a list with superscripts and a list with subscripts.

Examples

>>> from sympy.printing.conventions import split_super_sub
>>> split_super_sub('a_x^1')
('a', ['1'], ['x'])
>>> split_super_sub('var_sub1__sup_sub2')
('var', ['sup'], ['sub1', 'sub2'])

CodePrinter

This class is a base class for other classes that implement code-printing functionality, and additionally lists a number of functions that cannot be easily translated to C or Fortran.

class sympy.printing.codeprinter.CodePrinter(settings=None)[source]

The base class for code-printing subclasses.

printmethod: str = '_sympystr'
doprint(expr, assign_to=None)[source]

Print the expression as code.

Parameters:

expr : Expression

The expression to be printed.

assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional)

If provided, the printed code will set the expression to a variable or multiple variables with the name or names given in assign_to.

exception sympy.printing.codeprinter.AssignmentError[source]

Raised if an assignment variable for a loop is missing.

Precedence

sympy.printing.precedence.PRECEDENCE = {'Add': 40, 'And': 30, 'Atom': 1000, 'BitwiseAnd': 38, 'BitwiseOr': 36, 'BitwiseXor': 37, 'Func': 70, 'Lambda': 1, 'Mul': 50, 'Not': 100, 'Or': 20, 'Pow': 60, 'Relational': 35, 'Xor': 10}

Default precedence values for some basic types.

sympy.printing.precedence.PRECEDENCE_VALUES = {'Add': 40, 'And': 30, 'Equality': 50, 'Equivalent': 10, 'Function': 70, 'HadamardPower': 60, 'HadamardProduct': 50, 'Implies': 10, 'KroneckerProduct': 50, 'MatAdd': 40, 'MatPow': 60, 'MatrixSolve': 50, 'Mod': 50, 'NegativeInfinity': 40, 'Not': 100, 'Or': 20, 'Pow': 60, 'Relational': 35, 'Sub': 40, 'TensAdd': 40, 'TensMul': 50, 'Unequality': 50, 'Xor': 10}

A dictionary assigning precedence values to certain classes. These values are treated like they were inherited, so not every single class has to be named here.

sympy.printing.precedence.PRECEDENCE_FUNCTIONS = {'Float': <function precedence_Float>, 'FracElement': <function precedence_FracElement>, 'Integer': <function precedence_Integer>, 'Mul': <function precedence_Mul>, 'PolyElement': <function precedence_PolyElement>, 'Rational': <function precedence_Rational>, 'UnevaluatedExpr': <function precedence_UnevaluatedExpr>}

Sometimes it’s not enough to assign a fixed precedence value to a class. Then a function can be inserted in this dictionary that takes an instance of this class as argument and returns the appropriate precedence value.

sympy.printing.precedence.precedence(item)[source]

Returns the precedence of a given object.

This is the precedence for StrPrinter.

Pretty-Printing Implementation Helpers

sympy.printing.pretty.pretty_symbology.U(name)[source]

Get a unicode character by name or, None if not found.

This exists because older versions of Python use older unicode databases.

sympy.printing.pretty.pretty_symbology.pretty_use_unicode(flag=None)[source]

Set whether pretty-printer should use unicode by default

sympy.printing.pretty.pretty_symbology.pretty_try_use_unicode()[source]

See if unicode output is available and leverage it if possible

sympy.printing.pretty.pretty_symbology.xstr(*args)[source]

The following two functions return the Unicode version of the inputted Greek letter.

sympy.printing.pretty.pretty_symbology.g(l)[source]
sympy.printing.pretty.pretty_symbology.G(l)[source]
sympy.printing.pretty.pretty_symbology.greek_letters = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lamda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

sympy.printing.pretty.pretty_symbology.digit_2txt = {'0': 'ZERO', '1': 'ONE', '2': 'TWO', '3': 'THREE', '4': 'FOUR', '5': 'FIVE', '6': 'SIX', '7': 'SEVEN', '8': 'EIGHT', '9': 'NINE'}
sympy.printing.pretty.pretty_symbology.symb_2txt = {'(': 'LEFT PARENTHESIS', ')': 'RIGHT PARENTHESIS', '+': 'PLUS SIGN', '-': 'MINUS', '=': 'EQUALS SIGN', '[': 'LEFT SQUARE BRACKET', ']': 'RIGHT SQUARE BRACKET', 'int': 'INTEGRAL', 'sum': 'SUMMATION', '{': 'LEFT CURLY BRACKET', '{}': 'CURLY BRACKET', '}': 'RIGHT CURLY BRACKET'}

The following functions return the Unicode subscript/superscript version of the character.

sympy.printing.pretty.pretty_symbology.sub = {'(': '₍', ')': '₎', '+': '₊', '-': '₋', '0': '₀', '1': '₁', '2': '₂', '3': '₃', '4': '₄', '5': '₅', '6': '₆', '7': '₇', '8': '₈', '9': '₉', '=': '₌', 'a': 'ₐ', 'beta': 'ᵦ', 'chi': 'ᵪ', 'e': 'ₑ', 'gamma': 'ᵧ', 'h': 'ₕ', 'i': 'ᵢ', 'k': 'ₖ', 'l': 'ₗ', 'm': 'ₘ', 'n': 'ₙ', 'o': 'ₒ', 'p': 'ₚ', 'phi': 'ᵩ', 'r': 'ᵣ', 'rho': 'ᵨ', 's': 'ₛ', 't': 'ₜ', 'u': 'ᵤ', 'v': 'ᵥ', 'x': 'ₓ'}
sympy.printing.pretty.pretty_symbology.sup = {'(': '⁽', ')': '⁾', '+': '⁺', '-': '⁻', '0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹', '=': '⁼', 'i': 'ⁱ', 'n': 'ⁿ'}

The following functions return Unicode vertical objects.

sympy.printing.pretty.pretty_symbology.xobj(symb, length)[source]

Construct spatial object of given length.

return: [] of equal-length strings

sympy.printing.pretty.pretty_symbology.vobj(symb, height)[source]

Construct vertical object of a given height

see: xobj

sympy.printing.pretty.pretty_symbology.hobj(symb, width)[source]

Construct horizontal object of a given width

see: xobj

The following constants are for rendering roots and fractions.

sympy.printing.pretty.pretty_symbology.root = {2: '√', 3: '∛', 4: '∜'}
sympy.printing.pretty.pretty_symbology.VF(txt)[source]
sympy.printing.pretty.pretty_symbology.frac = {(1, 2): '½', (1, 3): '⅓', (1, 4): '¼', (1, 5): '⅕', (1, 6): '⅙', (1, 8): '⅛', (2, 3): '⅔', (2, 5): '⅖', (3, 4): '¾', (3, 5): '⅗', (3, 8): '⅜', (4, 5): '⅘', (5, 6): '⅚', (5, 8): '⅝', (7, 8): '⅞'}

The following constants/functions are for rendering atoms and symbols.

sympy.printing.pretty.pretty_symbology.xsym(sym)[source]

get symbology for a ‘character’

sympy.printing.pretty.pretty_symbology.atoms_table = {'And': '∧', 'Arrow': '→', 'ArrowFromBar': '↦', 'Complexes': 'ℂ', 'Contradiction': '┬', 'Dagger': '†', 'Degree': '°', 'Differential': 'ⅆ', 'Dots': '…', 'ElementOf': '∈', 'EmptySequence': 'EmptySequence', 'EmptySet': '∅', 'Equiv': '⇔', 'Exp1': 'ℯ', 'IdentityMatrix': '𝕀', 'ImaginaryUnit': 'ⅈ', 'Implies': '⇔', 'Infinity': '∞', 'Integers': 'ℤ', 'Intersection': '∩', 'Modifier Letter Low Ring': '˳', 'Multiplication': '×', 'Nand': '⊼', 'Naturals': 'ℕ', 'Naturals0': 'ℕ₀', 'NegativeInfinity': '-∞', 'Nor': '⊽', 'Not': '¬', 'NotArrow': '↛', 'NotEquiv': '⇎', 'NotImplies': '⇎', 'OneMatrix': '𝟙', 'Or': '∨', 'Pi': 'π', 'Rationals': 'ℚ', 'Reals': 'ℝ', 'Ring': '∘', 'SmallElementOf': '∊', 'SuperscriptMinus': '⁻', 'SuperscriptPlus': '⁺', 'SymmetricDifference': '∆', 'Tautology': '┴', 'TensorProduct': '⨂', 'Union': '∪', 'Universe': '𝕌', 'Xor': '⊻', 'ZeroMatrix': '𝟘'}
sympy.printing.pretty.pretty_symbology.pretty_atom(atom_name, default=None, printer=None)[source]

return pretty representation of an atom

sympy.printing.pretty.pretty_symbology.pretty_symbol(symb_name, bold_name=False)[source]

return pretty representation of a symbol

sympy.printing.pretty.pretty_symbology.annotated(letter)[source]

Return a stylised drawing of the letter letter, together with information on how to put annotations (super- and subscripts to the left and to the right) on it.

See pretty.py functions _print_meijerg, _print_hyper on how to use this information.

Prettyprinter by Jurjen Bos. (I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay). All objects have a method that create a “stringPict”, that can be used in the str method for pretty printing.

Updates by Jason Gedge (email <my last name> at cs mun ca)
  • terminal_string() method

  • minor fixes and changes (mostly to prettyForm)

TODO:
  • Allow left/center/right alignment options for above/below and top/center/bottom alignment options for left/right

class sympy.printing.pretty.stringpict.stringPict(s, baseline=0)[source]

An ASCII picture. The pictures are represented as a list of equal length strings.

above(*args)[source]

Put pictures above this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of bottom picture.

below(*args)[source]

Put pictures under this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of top picture

Examples

>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("x+3").below(
...       stringPict.LINE, '3')[0]) 
x+3
---
 3
height()[source]

The height of the picture in characters.

left(*args)[source]

Put pictures (left to right) at left. Returns string, baseline arguments for stringPict.

leftslash()[source]

Precede object by a slash of the proper size.

static next(*args)[source]

Put a string of stringPicts next to each other. Returns string, baseline arguments for stringPict.

parens(left='(', right=')', ifascii_nougly=False)[source]

Put parentheses around self. Returns string, baseline arguments for stringPict.

left or right can be None or empty string which means ‘no paren from that side’

render(*args, **kwargs)[source]

Return the string form of self.

Unless the argument line_break is set to False, it will break the expression in a form that can be printed on the terminal without being broken up.

right(*args)[source]

Put pictures next to this one. Returns string, baseline arguments for stringPict. (Multiline) strings are allowed, and are given a baseline of 0.

Examples

>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0])
     1
10 + -
     2
root(n=None)[source]

Produce a nice root symbol. Produces ugly results for big n inserts.

static stack(*args)[source]

Put pictures on top of each other, from top to bottom. Returns string, baseline arguments for stringPict. The baseline is the baseline of the second picture. Everything is centered. Baseline is the baseline of the second picture. Strings are allowed. The special value stringPict.LINE is a row of ‘-’ extended to the width.

terminal_width()[source]

Return the terminal width if possible, otherwise return 0.

width()[source]

The width of the picture in characters.

class sympy.printing.pretty.stringpict.prettyForm(s, baseline=0, binding=0, unicode=None)[source]

Extension of the stringPict class that knows about basic math applications, optimizing double minus signs.

“Binding” is interpreted as follows:

ATOM this is an atom: never needs to be parenthesized
FUNC this is a function application: parenthesize if added (?)
DIV  this is a division: make wider division if divided
POW  this is a power: only parenthesize if exponent
MUL  this is a multiplication: parenthesize if powered
ADD  this is an addition: parenthesize if multiplied or powered
NEG  this is a negative number: optimize if added, parenthesize if
     multiplied or powered
OPEN this is an open object: parenthesize if added, multiplied, or
     powered (example: Piecewise)
static apply(function, *args)[source]

Functions of one or more variables.

dotprint

sympy.printing.dot.dotprint(expr, styles=((<class 'sympy.core.basic.Basic'>, {'color': 'blue', 'shape': 'ellipse'}), (<class 'sympy.core.expr.Expr'>, {'color': 'black'})), atom=<function <lambda>>, maxdepth=None, repeat=True, labelfunc=<class 'str'>, **kwargs)[source]

DOT description of a SymPy expression tree

Parameters:

styles : list of lists composed of (Class, mapping), optional

Styles for different classes.

The default is

(
    (Basic, {'color': 'blue', 'shape': 'ellipse'}),
    (Expr,  {'color': 'black'})
)

atom : function, optional

Function used to determine if an arg is an atom.

A good choice is lambda x: not x.args.

The default is lambda x: not isinstance(x, Basic).

maxdepth : integer, optional

The maximum depth.

The default is None, meaning no limit.

repeat : boolean, optional

Whether to use different nodes for common subexpressions.

The default is True.

For example, for x + x*y with repeat=True, it will have two nodes for x; with repeat=False, it will have one node.

Warning

Even if a node appears twice in the same object like x in Pow(x, x), it will still only appear once. Hence, with repeat=False, the number of arrows out of an object might not equal the number of args it has.

labelfunc : function, optional

A function to create a label for a given leaf node.

The default is str.

Another good option is srepr.

For example with str, the leaf nodes of x + 1 are labeled, x and 1. With srepr, they are labeled Symbol('x') and Integer(1).

**kwargs : optional

Additional keyword arguments are included as styles for the graph.

Examples

>>> from sympy import dotprint
>>> from sympy.abc import x
>>> print(dotprint(x+2)) 
digraph{

# Graph style
"ordering"="out"
"rankdir"="TD"

#########
# Nodes #
#########

"Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"];
"Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"];
"Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];

#########
# Edges #
#########

"Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
"Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
}