modelparameters.sympy.printing package¶
Subpackages¶
- modelparameters.sympy.printing.pretty package
- Submodules
- modelparameters.sympy.printing.pretty.pretty module
- modelparameters.sympy.printing.pretty.pretty_symbology module
- modelparameters.sympy.printing.pretty.stringpict module
prettyForm
stringPict
stringPict.LINE
stringPict.above()
stringPict.below()
stringPict.equalLengths()
stringPict.height()
stringPict.left()
stringPict.leftslash()
stringPict.next()
stringPict.parens()
stringPict.render()
stringPict.right()
stringPict.root()
stringPict.stack()
stringPict.terminal_width()
stringPict.width()
- Module contents
Submodules¶
modelparameters.sympy.printing.ccode module¶
C code printer
The C89CodePrinter & C99CodePrinter converts single sympy expressions into single C expressions, using the functions defined in math.h where possible.
A complete code generator, which uses ccode extensively, can be found in sympy.utilities.codegen. The codegen module can be used to generate complete source code files that are compilable without further modifications.
- class modelparameters.sympy.printing.ccode.C89CodePrinter(settings={})[source]¶
Bases:
CodePrinter
A printer to convert python expressions to strings of c code
- language = 'C'¶
- printmethod = '_ccode'¶
- reserved_words = {'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', 'double', 'else', 'entry', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'}¶
- standard = 'C89'¶
- class modelparameters.sympy.printing.ccode.C99CodePrinter(settings={})[source]¶
Bases:
_C9XCodePrinter
,C89CodePrinter
- reserved_words = {'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', 'double', 'else', 'entry', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'inline', 'int', 'long', 'register', 'restrict', 'return', 'short', 'signed', 'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'}¶
- standard = 'C99'¶
- modelparameters.sympy.printing.ccode.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
, orIndexed
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=15].
user_functions (dict, optional) – A dictionary where the keys are string representations of either
FunctionClass
orUndefinedFunction
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 ofa
.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 .. import ccode, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> ccode((2*tau)**Rational(7, 2), standard='C89') '8*sqrt(2)*pow(tau, 7.0L/2.0L)' >>> ccode(sin(x), assign_to="s", standard='C89') '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') >>> 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 anassign_to
variable is provided an if statement is created, otherwise the ternary operator is used. Note that if thePiecewise
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 .. 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. Withcontract=True
these expressions will be turned into loops, whereascontract=False
will just print the assignment expression that should be looped over:>>> from .. 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 toassign_to
. Note that any expression that can be generated normally can also exist inside a Matrix:>>> from .. 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);
- modelparameters.sympy.printing.ccode.get_math_macros()[source]¶
Returns a dictionary with math-related macros from math.h/cmath
Note that these macros are not strictly required by the C/C++-standard. For MSVC they are enabled by defining “_USE_MATH_DEFINES” (preferably via a compilation flag).
- Return type:
Dictionary mapping sympy expressions to strings (macro names)
modelparameters.sympy.printing.codeprinter module¶
- exception modelparameters.sympy.printing.codeprinter.AssignmentError[source]¶
Bases:
Exception
Raised if an assignment variable for a loop is missing.
- class modelparameters.sympy.printing.codeprinter.CodePrinter(settings=None)[source]¶
Bases:
StrPrinter
The base class for code-printing subclasses.
- doprint(expr, assign_to=None)[source]¶
Print the expression as code.
- Parameters:
expr (Expression) – The expression to be printed.
assign_to (Symbol, MatrixSymbol, or string (optional)) – If provided, the printed code will set the expression to a variable with name
assign_to
.
modelparameters.sympy.printing.conventions module¶
A few practical conventions common to all printers.
- modelparameters.sympy.printing.conventions.requires_partial(expr)[source]¶
Return whether a partial derivative symbol is required for printing
This requires checking how many free variables there are, filtering out the ones that are integers. Some expressions don’t have free variables. In that case, check its variable list explicitly to get the context of the expression.
- modelparameters.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.
>>> from .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'])
modelparameters.sympy.printing.cxxcode module¶
- class modelparameters.sympy.printing.cxxcode.CXX11CodePrinter(settings=None)[source]¶
Bases:
_CXXCodePrinterBase
,C99CodePrinter
- reserved_words = {'alignas', 'alignof', 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break', 'case', 'catch,', 'char', 'char16_t', 'char32_t', 'class', 'compl', 'const', 'const_cast', 'constexpr', 'continue', 'decltype', 'default', 'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable', 'namespace', 'new', 'noexcept', 'not', 'not_eq', 'nullptr', 'operator', 'or', 'or_eq', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'return', 'short', 'signed', 'sizeof', 'static', 'static_assert', 'static_cast', 'struct', 'switch', 'template', 'this', 'thread_local', 'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq'}¶
- standard = 'C++11'¶
- class modelparameters.sympy.printing.cxxcode.CXX17CodePrinter(settings=None)[source]¶
Bases:
_CXXCodePrinterBase
,C99CodePrinter
- reserved_words = {}¶
- standard = 'C++17'¶
- class modelparameters.sympy.printing.cxxcode.CXX98CodePrinter(settings=None)[source]¶
Bases:
_CXXCodePrinterBase
,C89CodePrinter
- reserved_words = {'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break', 'case', 'catch,', 'char', 'class', 'compl', 'const', 'const_cast', 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable', 'namespace', 'new', 'not', 'not_eq', 'operator', 'or', 'or_eq', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast', 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq'}¶
- standard = 'C++98'¶
modelparameters.sympy.printing.defaults module¶
- class modelparameters.sympy.printing.defaults.DefaultPrinting[source]¶
Bases:
object
The default implementation of printing for SymPy classes.
This implements a hack that allows us to print elements of built-in Python containers in a readable way. Natively Python uses
repr()
even ifstr()
was explicitly requested. Mix in this trait into a class to get proper default printing.
modelparameters.sympy.printing.dot module¶
- modelparameters.sympy.printing.dot.dotprint(expr, styles=[(<class 'modelparameters.sympy.core.basic.Basic'>, {'color': 'blue', 'shape': 'ellipse'}), (<class 'modelparameters.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
Options are
styles
: Styles for different classes. The default is:[(Basic, {'color': 'blue', 'shape': 'ellipse'}), (Expr, {'color': 'black'})]``
atom
: Function used to determine if an arg is an atom. The default islambda x: not isinstance(x, Basic)
. Another good choice islambda x: not x.args
.
maxdepth
: The maximum depth. The default is None, meaning no limit.repeat
: Whether to different nodes for separate common subexpressions.The default is True. For example, for
x + x*y
withrepeat=True
, it will have two nodes forx
and withrepeat=False
, it will have one (warning: even if it appears twice in the same object, like Pow(x, x), it will still only appear only once. Hence, with repeat=False, the number of arrows out of an object might not equal the number of args it has).labelfunc
: How to label leaf nodes. The default isstr
. Anothergood option is
srepr
. For example withstr
, the leaf nodes ofx + 1
are labeled,x
and1
. Withsrepr
, they are labeledSymbol('x')
andInteger(1)
.
Additional keyword arguments are included as styles for the graph.
Examples
>>> from .dot import dotprint >>> from ..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,)"; }
modelparameters.sympy.printing.fcode module¶
Fortran code printer
The FCodePrinter converts single sympy expressions into single Fortran expressions, using the functions defined in the Fortran 77 standard where possible. Some useful pointers to Fortran can be found on wikipedia:
http://en.wikipedia.org/wiki/Fortran
Most of the code below is based on the “Professional Programmer’s Guide to Fortran77” by Clive G. Page:
http://www.star.le.ac.uk/~cgp/prof77.html
Fortran is a case-insensitive language. This might cause trouble because SymPy is case sensitive. The implementation below does not care and leaves the responsibility for generating properly cased Fortran code to the user.
- class modelparameters.sympy.printing.fcode.FCodePrinter(settings={})[source]¶
Bases:
CodePrinter
A printer to convert sympy expressions to strings of Fortran code
- language = 'Fortran'¶
- printmethod = '_fcode'¶
- modelparameters.sympy.printing.fcode.fcode(expr, assign_to=None, **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
, orIndexed
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, 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.
Examples
>>> from .. 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 anassign_to
variable is provided an if statement is created, otherwise the ternary operator is used. Note that if thePiecewise
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 .. 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. Withcontract=True
these expressions will be turned into loops, whereascontract=False
will just print the assignment expression that should be looped over:>>> from .. 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 toassign_to
. Note that any expression that can be generated normally can also exist inside a Matrix:>>> from .. 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)
modelparameters.sympy.printing.gtk module¶
modelparameters.sympy.printing.jscode module¶
Javascript code printer
The JavascriptCodePrinter converts single sympy expressions into single Javascript expressions, using the functions defined in the Javascript Math object where possible.
- class modelparameters.sympy.printing.jscode.JavascriptCodePrinter(settings={})[source]¶
Bases:
CodePrinter
“A Printer to convert python expressions to strings of javascript code
- language = 'Javascript'¶
- printmethod = '_javascript'¶
- modelparameters.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
, orIndexed
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 .. 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 anassign_to
variable is provided an if statement is created, otherwise the ternary operator is used. Note that if thePiecewise
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 .. 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. Withcontract=True
these expressions will be turned into loops, whereascontract=False
will just print the assignment expression that should be looped over:>>> from .. 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 toassign_to
. Note that any expression that can be generated normally can also exist inside a Matrix:>>> from .. 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);
modelparameters.sympy.printing.julia module¶
Julia code printer
The JuliaCodePrinter converts SymPy expressions into Julia expressions.
A complete code generator, which uses julia_code extensively, can be found in sympy.utilities.codegen. The codegen module can be used to generate complete source code files.
- class modelparameters.sympy.printing.julia.JuliaCodePrinter(settings={})[source]¶
Bases:
CodePrinter
A printer to convert expressions to strings of Julia code.
- language = 'Julia'¶
- printmethod = '_julia'¶
- modelparameters.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
, orIndexed
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 .. import julia_code, symbols, sin, pi >>> x = symbols('x') >>> julia_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x'
>>> from .. import Rational, ceiling, Abs >>> 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 .. 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 aMatrixSymbol
. The dimenions must align in the latter case.>>> from .. 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 thePiecewise
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 .. 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 .. 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. Withcontract=True
these expressions will be turned into loops, whereascontract=False
will just print the assignment expression that should be looped over:>>> from .. import Eq, IndexedBase, Idx, ccode >>> 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])'
modelparameters.sympy.printing.lambdarepr module¶
- class modelparameters.sympy.printing.lambdarepr.LambdaPrinter(settings=None)[source]¶
Bases:
StrPrinter
This printer converts expressions into strings that can be used by lambdify.
- class modelparameters.sympy.printing.lambdarepr.MpmathPrinter(settings=None)[source]¶
Bases:
LambdaPrinter
Lambda printer for mpmath which maintains precision for floats
- class modelparameters.sympy.printing.lambdarepr.NumExprPrinter(settings=None)[source]¶
Bases:
LambdaPrinter
- class modelparameters.sympy.printing.lambdarepr.NumPyPrinter(settings=None)[source]¶
Bases:
LambdaPrinter
Numpy printer which handles vectorized piecewise functions, logical operators, etc.
- class modelparameters.sympy.printing.lambdarepr.TensorflowPrinter(settings=None)[source]¶
Bases:
LambdaPrinter
Tensorflow printer which handles vectorized piecewise functions, logical operators, max/min, and relational operators.
modelparameters.sympy.printing.latex module¶
A Printer which converts an expression into its LaTeX equivalent.
- class modelparameters.sympy.printing.latex.LatexPrinter(settings=None)[source]¶
Bases:
Printer
- printmethod = '_latex'¶
- modelparameters.sympy.printing.latex.latex(expr, **settings)[source]¶
Convert the given expression to LaTeX representation.
>>> from .. import latex, pi, sin, asin, Integral, Matrix, Rational >>> from ..abc import x, y, mu, r, tau
>>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}}
Not using a print statement for printing, results in double backslashes for latex commands since that’s the way Python escapes backslashes in strings.
>>> latex((2*tau)**Rational(7,2)) '8 \\sqrt{2} \\tau^{\\frac{7}{2}}'
order: 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.
mode: 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.>>> 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}
itex: Specifies if itex-specific syntax is used, including emitting
$$ $$
.>>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$
fold_frac_powers: Emit “^{p/q}” instead of “^{frac{p}{q}}” for fractional powers.
>>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True)) 8 \sqrt{2} \tau^{7/2}
fold_func_brackets: Fold function brackets where applicable.
>>> 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}}}
fold_short_frac: 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.
>>> 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
long_frac_ratio: The allowed ratio of the width of the numerator to the width of the denominator before we start breaking off long fractions. The default value is 2.
>>> 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
mul_symbol: The symbol to use for multiplication. Can be one of None, “ldot”, “dot”, or “times”.
>>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times")) \left(2 \times \tau\right)^{\sin{\left (\frac{7}{2} \right )}}
inv_trig_style: How inverse trig functions should be displayed. Can be one of “abbreviated”, “full”, or “power”. Defaults to “abbreviated”.
>>> 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 )}
mat_str: 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.
>>> 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]
mat_delim: The delimiter to wrap around matrices. Can be one of “[”, “(“, or the empty string. Defaults to “[“.
>>> print(latex(Matrix(2, 1, [x, y]), mat_delim="(")) \left(\begin{matrix}x\\y\end{matrix}\right)
symbol_names: Dictionary of symbols and the custom strings they should be emitted as.
>>> print(latex(x**2, symbol_names={x:'x_i'})) x_i^{2}
latex
also supports the builtin container types list, tuple, and dictionary.>>> print(latex([2/x, y], mode='inline')) $\left [ 2 / x, \quad y\right ]$
- modelparameters.sympy.printing.latex.print_latex(expr, **settings)[source]¶
Prints LaTeX representation of the given expression.
- modelparameters.sympy.printing.latex.translate(s)[source]¶
Check for a modifier ending the string. If present, convert the modifier to latex and translate the rest recursively.
Given a description of a Greek letter or other special character, return the appropriate latex.
Let everything else pass as given.
>>> from .latex import translate >>> translate('alphahatdotprime') "{\\dot{\\hat{\\alpha}}}'"
modelparameters.sympy.printing.llvmjitcode module¶
- class modelparameters.sympy.printing.llvmjitcode.LLVMJitCallbackPrinter(*args, **kwargs)[source]¶
Bases:
LLVMJitPrinter
- class modelparameters.sympy.printing.llvmjitcode.LLVMJitCodeCallback(signature)[source]¶
Bases:
LLVMJitCode
- class modelparameters.sympy.printing.llvmjitcode.LLVMJitPrinter(module, builder, fn, *args, **kwargs)[source]¶
Bases:
Printer
Convert expressions to LLVM IR
- emptyPrinter(expr)[source]¶
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
- modelparameters.sympy.printing.llvmjitcode.llvm_callable(args, expr, callback_type=None)[source]¶
Compile function from a Sympy expression
Expressions are evaluated using double precision arithmetic. Some single argument math functions (exp, sin, cos, etc.) are supported in expressions.
- Parameters:
args (List of Symbol) – Arguments to the generated function. Usually the free symbols in the expression. Currently each one is assumed to convert to a double precision scalar.
expr (Expr, or (Replacements, Expr) as returned from 'cse') – Expression to compile.
callback_type (string) –
Create function with signature appropriate to use as a callback. Currently supported:
’scipy.integrate’ ‘scipy.integrate.test’ ‘cubature’
- Return type:
Compiled function that can evaluate the expression.
Examples
>>> from ... import sympy.printing.llvmjitcode as jit >>> from ..abc import a >>> e = a*a + a + 1 >>> e1 = jit.llvm_callable([a], e) >>> e.subs(a, 1.1) # Evaluate via substitution 3.31000000000000 >>> e1(1.1) # Evaluate using JIT-compiled code 3.3100000000000005
Callbacks for integration functions can be JIT compiled. >>> from … import sympy.printing.llvmjitcode as jit >>> from ..abc import a >>> from .. import integrate >>> from scipy.integrate import quad >>> e = a*a >>> e1 = jit.llvm_callable([a], e, callback_type=’scipy.integrate’) >>> integrate(e, (a, 0.0, 2.0)) 2.66666666666667 >>> quad(e1, 0.0, 2.0)[0] 2.66666666666667
The ‘cubature’ callback is for the Python wrapper around the cubature package ( https://github.com/saullocastro/cubature ) and ( http://ab-initio.mit.edu/wiki/index.php/Cubature )
There are two signatures for the SciPy integration callbacks. The first (‘scipy.integrate’) is the function to be passed to the integration routine, and will pass the signature checks. The second (‘scipy.integrate.test’) is only useful for directly calling the function using ctypes variables. It will not pass the signature checks for scipy.integrate.
The return value from the cse module can also be compiled. This can improve the performance of the compiled function. If multiple expressions are given to cse, the compiled function returns a tuple. The ‘cubature’ callback handles multiple expressions (set fdim to match in the integration call.) >>> from … import sympy.printing.llvmjitcode as jit >>> from .. import cse, exp >>> from ..abc import x,y >>> e1 = x*x + y*y >>> e2 = 4*(x*x + y*y) + 8.0 >>> after_cse = cse([e1,e2]) >>> after_cse ([(x0, x**2), (x1, y**2)], [x0 + x1, 4*x0 + 4*x1 + 8.0]) >>> j1 = jit.llvm_callable([x,y], after_cse) >>> j1(1.0, 2.0) (5.0, 28.0)
modelparameters.sympy.printing.mathematica module¶
Mathematica code printer
- class modelparameters.sympy.printing.mathematica.MCodePrinter(settings={})[source]¶
Bases:
CodePrinter
A printer to convert python expressions to strings of the Wolfram’s Mathematica code
- doprint(expr)¶
Returns printer’s representation for expr (as a string)
- printmethod = '_mcode'¶
- modelparameters.sympy.printing.mathematica.mathematica_code(expr, **settings)[source]¶
Converts an expr to a string of the Wolfram Mathematica code
Examples
>>> from .. 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'
modelparameters.sympy.printing.mathml module¶
A MathML printer.
- class modelparameters.sympy.printing.mathml.MathMLPrinter(settings=None)[source]¶
Bases:
Printer
Prints an expression to the MathML markup language
Whenever possible tries to use Content markup and not Presentation markup.
References: https://www.w3.org/TR/MathML3/
- printmethod = '_mathml'¶
modelparameters.sympy.printing.octave module¶
Octave (and Matlab) code printer
The OctaveCodePrinter converts SymPy expressions into Octave expressions. It uses a subset of the Octave language for Matlab compatibility.
A complete code generator, which uses octave_code extensively, can be found in sympy.utilities.codegen. The codegen module can be used to generate complete source code files.
- class modelparameters.sympy.printing.octave.OctaveCodePrinter(settings={})[source]¶
Bases:
CodePrinter
A printer to convert expressions to strings of Octave/Matlab code.
- language = 'Octave'¶
- printmethod = '_octave'¶
- modelparameters.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
, orIndexed
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 .. import octave_code, symbols, sin, pi >>> x = symbols('x') >>> octave_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x'
>>> from .. import Rational, ceiling, Abs >>> 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 .. 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 aMatrixSymbol
. The dimenions must align in the latter case.>>> from .. 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 thePiecewise
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 .. 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 .. 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. Withcontract=True
these expressions will be turned into loops, whereascontract=False
will just print the assignment expression that should be looped over:>>> from .. import Eq, IndexedBase, Idx, ccode >>> 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));'
modelparameters.sympy.printing.precedence module¶
A module providing information about the necessity of brackets
modelparameters.sympy.printing.preview module¶
- modelparameters.sympy.printing.preview.preview(expr, output='png', viewer=None, euler=True, packages=(), filename=None, outputbuffer=None, preamble=None, dvioptions=None, outputTexFile=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 .. 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 you will need to set the viewer explicitly.
>>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')
This will skip auto-detection and will run user specified ‘superior-dvi-viewer’. If ‘view’ fails to find it on your system it will gracefully raise an exception.
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 genereted file to this filename instead.
There is also support for writing to a 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)
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")
modelparameters.sympy.printing.printer module¶
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:
Let the object print itself if it knows how.
Take the best fitting method defined in the printer.
As fall-back use the emptyPrinter method for the printer.
Some more information how the single concepts work and who should use which:
The object prints itself
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.
Nevertheless, to get a fitting representation, the printers look for a specific method in every object, that will be called if it’s available and is then responsible for the representation. The name of that method depends on the specific printer and is defined under Printer.printmethod.
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(…), in order to dispatch, we will try calling printer methods 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, we proceed with trying Rational bases in the inheritance order.
As 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).
- class modelparameters.sympy.printing.printer.Printer(settings=None)[source]¶
Bases:
object
Generic printer
Its job is to provide infrastructure for implementing new printers easily.
Basically, if you want to implement a printer, all you have to do is:
Subclass Printer.
Define Printer.printmethod in your subclass. If a object has a method with that name, this method will be used for printing.
In your subclass, define
_print_<CLASS>
methodsFor each class you want to provide printing to, define an appropriate method how to do it. For example if you want a class FOO to be printed in its own way, define _print_FOO:
def _print_FOO(self, e): ...
this should return how FOO instance e is printed
Also, if
BAR
is a subclass ofFOO
,_print_FOO(bar)
will be called for instance ofBAR
, if no_print_BAR
is provided. Thus, usually, we don’t need to provide printing routines for every class we want to support – only generic routine has to be provided for a set of classes.A good example for this are functions - for example
PrettyPrinter
only defines_print_Function
, and there is no_print_sin
,_print_tan
, etc…On the other hand, a good printer will probably have to define separate routines for
Symbol
,Atom
,Number
,Integral
,Limit
, etc…If convenient, override
self.emptyPrinter
This callable will be called to obtain printing result as a last resort, that is when no appropriate print method was found for an expression.
Examples of overloading StrPrinter:
from .. import Basic, Function, Symbol from .str import StrPrinter class CustomStrPrinter(StrPrinter): """ Examples of how to customize the StrPrinter for both a SymPy class and a user defined class subclassed from the SymPy Basic class. """ def _print_Derivative(self, expr): """ Custom printing of the SymPy Derivative class. Instead of: D(x(t), t) or D(x(t), t, t) We will print: x' or x'' In this example, expr.args == (x(t), t), and expr.args[0] == x(t), and expr.args[0].func == x """ return str(expr.args[0].func) + "'"*len(expr.args[1:]) def _print_MyClass(self, expr): """ Print the characters of MyClass.s alternatively lower case and upper case """ s = "" i = 0 for char in expr.s: if i % 2 == 0: s += char.lower() else: s += char.upper() i += 1 return s # Override the __str__ method of to use CustromStrPrinter Basic.__str__ = lambda self: CustomStrPrinter().doprint(self) # Demonstration of CustomStrPrinter: t = Symbol('t') x = Function('x')(t) dxdt = x.diff(t) # dxdt is a Derivative instance d2xdt2 = dxdt.diff(t) # dxdt2 is a Derivative instance ex = MyClass('I like both lowercase and upper case') print dxdt print d2xdt2 print ex
The output of the above code is:
x' x'' i lIkE BoTh lOwErCaSe aNd uPpEr cAsE
By overriding Basic.__str__, we can customize the printing of anything that is subclassed from Basic.
- property order¶
- printmethod = None¶
modelparameters.sympy.printing.python module¶
- class modelparameters.sympy.printing.python.PythonPrinter(settings=None)[source]¶
Bases:
ReprPrinter
,StrPrinter
A printer which converts an expression into its Python interpretation.
modelparameters.sympy.printing.rcode module¶
R code printer
The RCodePrinter converts single sympy expressions into single R expressions, using the functions defined in math.h where possible.
- class modelparameters.sympy.printing.rcode.RCodePrinter(settings={})[source]¶
Bases:
CodePrinter
A printer to convert python expressions to strings of R code
- language = 'R'¶
- printmethod = '_rcode'¶
- modelparameters.sympy.printing.rcode.print_rcode(expr, **settings)[source]¶
Prints R representation of the given expression.
- modelparameters.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
, orIndexed
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
orUndefinedFunction
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 .. 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 anassign_to
variable is provided an if statement is created, otherwise the ternary operator is used. Note that if thePiecewise
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 .. 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. Withcontract=True
these expressions will be turned into loops, whereascontract=False
will just print the assignment expression that should be looped over:>>> from .. 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 toassign_to
. Note that any expression that can be generated normally can also exist inside a Matrix:>>> from .. 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);
modelparameters.sympy.printing.repr module¶
A Printer for generating executable code.
The most important function here is srepr that returns a string so that the relation eval(srepr(expr))=expr holds in an appropriate environment.
modelparameters.sympy.printing.rust module¶
Rust code printer
The RustCodePrinter converts SymPy expressions into Rust expressions.
A complete code generator, which uses rust_code extensively, can be found in sympy.utilities.codegen. The codegen module can be used to generate complete source code files.
- class modelparameters.sympy.printing.rust.RustCodePrinter(settings={})[source]¶
Bases:
CodePrinter
A printer to convert python expressions to strings of Rust code
- language = 'Rust'¶
- printmethod = '_rust_code'¶
- modelparameters.sympy.printing.rust.print_rust_code(expr, **settings)[source]¶
Prints Rust representation of the given expression.
- modelparameters.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
, orIndexed
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
orUndefinedFunction
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 ofa
.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 .. 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 anassign_to
variable is provided an if statement is created, otherwise the ternary operator is used. Note that if thePiecewise
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 .. 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. Withcontract=True
these expressions will be turned into loops, whereascontract=False
will just print the assignment expression that should be looped over:>>> from .. 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 toassign_to
. Note that any expression that can be generated normally can also exist inside a Matrix:>>> from .. 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()];
modelparameters.sympy.printing.str module¶
A Printer for generating readable representation of most sympy classes.
- class modelparameters.sympy.printing.str.StrPrinter(settings=None)[source]¶
Bases:
Printer
- emptyPrinter(expr)[source]¶
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
- printmethod = '_sympystr'¶
- class modelparameters.sympy.printing.str.StrReprPrinter(settings=None)[source]¶
Bases:
StrPrinter
(internal) – see sstrrepr
modelparameters.sympy.printing.tableform module¶
- class modelparameters.sympy.printing.tableform.TableForm(data, **kwarg)[source]¶
Bases:
object
Create a nice table representation of data.
Examples
>>> from .. import TableForm >>> t = TableForm([[5, 7], [4, 2], [10, 3]]) >>> print(t) 5 7 4 2 10 3
You can use the SymPy’s printing system to produce tables in any format (ascii, latex, html, …).
>>> print(t.as_latex()) \begin{tabular}{l l} $5$ & $7$ \\ $4$ & $2$ \\ $10$ & $3$ \\ \end{tabular}
modelparameters.sympy.printing.theanocode module¶
modelparameters.sympy.printing.tree module¶
- modelparameters.sympy.printing.tree.pprint_nodes(subtrees)[source]¶
Prettyprints systems of nodes.
Examples
>>> from .tree import pprint_nodes >>> print(pprint_nodes(["a", "b1\nb2", "c"])) +-a +-b1 | b2 +-c
- modelparameters.sympy.printing.tree.print_node(node)[source]¶
Returns information about the “node”.
This includes class name, string representation and assumptions.
- modelparameters.sympy.printing.tree.print_tree(node)[source]¶
Prints a tree representation of “node”.
Examples
>>> from ..printing import print_tree >>> from .. import Symbol >>> x = Symbol('x', odd=True) >>> y = Symbol('y', even=True) >>> print_tree(y**x) Pow: y**x +-Symbol: y | algebraic: True | commutative: True | complex: True | even: True | hermitian: True | imaginary: 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 hermitian: True imaginary: False integer: True irrational: False noninteger: False nonzero: True odd: True rational: True real: True transcendental: False zero: False
See also: tree()
Module contents¶
Printing subsystem