modelparameters.sympy.codegen package¶
Submodules¶
modelparameters.sympy.codegen.ast module¶
Types used to represent a full function/module as an Abstract Syntax Tree.
Most types are small, and are merely used as tokens in the AST. A tree diagram has been included below to illustrate the relationships between the AST types.
AST Type Tree¶
- class modelparameters.sympy.codegen.ast.AddAugmentedAssignment(lhs, rhs=0, **assumptions)[source]¶
Bases:
AugmentedAssignment
- default_assumptions = {}¶
- class modelparameters.sympy.codegen.ast.Assignment(lhs, rhs=0, **assumptions)[source]¶
Bases:
Relational
Represents variable assignment for code generation.
- Parameters:
lhs (Expr) – Sympy object representing the lhs of the expression. These should be singular objects, such as one would use in writing code. Notable types include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that subclass these types are also supported.
rhs (Expr) – Sympy object representing the rhs of the expression. This can be any type, provided its shape corresponds to that of the lhs. For example, a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as the dimensions will not align.
Examples
>>> from .. import symbols, MatrixSymbol, Matrix >>> from .ast import Assignment >>> x, y, z = symbols('x, y, z') >>> Assignment(x, y) Assignment(x, y) >>> Assignment(x, 0) Assignment(x, 0) >>> A = MatrixSymbol('A', 1, 3) >>> mat = Matrix([x, y, z]).T >>> Assignment(A, mat) Assignment(A, Matrix([[x, y, z]])) >>> Assignment(A[0, 1], x) Assignment(A[0, 1], x)
- default_assumptions = {}¶
- rel_op = ':='¶
- class modelparameters.sympy.codegen.ast.AugmentedAssignment(lhs, rhs=0, **assumptions)[source]¶
Bases:
Assignment
Base class for augmented assignments
- default_assumptions = {}¶
- property rel_op¶
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’.
- class modelparameters.sympy.codegen.ast.CodeBlock(*args)[source]¶
Bases:
Basic
Represents a block of code
For now only assignments are supported. This restriction will be lifted in the future.
Useful methods on this object are
left_hand_sides
: Tuple of left-hand sides of assignments, in order.left_hand_sides
: Tuple of right-hand sides of assignments, in order.topological_sort
: Class method. Return a CodeBlock with assignmentssorted so that variables are assigned before they are used.
cse
: Return a new CodeBlock with common subexpressions eliminated andpulled out as assignments.
Example
>>> from .. import symbols, ccode >>> from .ast import CodeBlock, Assignment >>> x, y = symbols('x y')
>>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1)) >>> print(ccode(c)) x = 1; y = x + 1;
- cse(symbols=None, optimizations=None, postprocess=None, order='canonical')[source]¶
Return a new code block with common subexpressions eliminated
See the docstring of
sympy.simplify.cse_main.cse()
for more information.Examples
>>> from .. import symbols, sin >>> from .ast import CodeBlock, Assignment >>> x, y, z = symbols('x y z')
>>> c = CodeBlock( ... Assignment(x, 1), ... Assignment(y, sin(x) + 1), ... Assignment(z, sin(x) - 1), ... ) ... >>> c.cse() CodeBlock(Assignment(x, 1), Assignment(x0, sin(x)), Assignment(y, x0 + 1), Assignment(z, x0 - 1))
- default_assumptions = {}¶
- classmethod topological_sort(assignments)[source]¶
Return a CodeBlock with topologically sorted assignments so that variables are assigned before they are used.
The existing order of assignments is preserved as much as possible.
This function assumes that variables are assigned to only once.
This is a class constructor so that the default constructor for CodeBlock can error when variables are used before they are assigned.
Example
>>> from .. import symbols >>> from .ast import CodeBlock, Assignment >>> x, y, z = symbols('x y z')
>>> assignments = [ ... Assignment(x, y + z), ... Assignment(y, z + 1), ... Assignment(z, 2), ... ] >>> CodeBlock.topological_sort(assignments) CodeBlock(Assignment(z, 2), Assignment(y, z + 1), Assignment(x, y + z))
- class modelparameters.sympy.codegen.ast.DivAugmentedAssignment(lhs, rhs=0, **assumptions)[source]¶
Bases:
AugmentedAssignment
- default_assumptions = {}¶
- class modelparameters.sympy.codegen.ast.For(target, iter, body)[source]¶
Bases:
Basic
Represents a ‘for-loop’ in the code.
- Expressions are of the form:
- “for target in iter:
body…”
- Parameters:
target (symbol) –
iter (iterable) –
body (sympy expr) –
Examples
>>> from .. import symbols, Range >>> from .ast import aug_assign, For >>> x, n = symbols('x n') >>> For(n, Range(10), [aug_assign(x, '+', n)]) For(n, Range(0, 10, 1), CodeBlock(AddAugmentedAssignment(x, n)))
- property body¶
Return the sympy expression (body) from the for-loop representation. This is run for each value of target. Must be an iterable object or CodeBlock.
- default_assumptions = {}¶
- property iterable¶
Return the iterable from the for-loop representation. This is the object that target takes values from. Must be an iterable object.
- property target¶
Return the symbol (target) from the for-loop representation. This object changes each iteration. Target must be a symbol.
- class modelparameters.sympy.codegen.ast.ModAugmentedAssignment(lhs, rhs=0, **assumptions)[source]¶
Bases:
AugmentedAssignment
- default_assumptions = {}¶
- class modelparameters.sympy.codegen.ast.MulAugmentedAssignment(lhs, rhs=0, **assumptions)[source]¶
Bases:
AugmentedAssignment
- default_assumptions = {}¶
- class modelparameters.sympy.codegen.ast.SubAugmentedAssignment(lhs, rhs=0, **assumptions)[source]¶
Bases:
AugmentedAssignment
- default_assumptions = {}¶
- modelparameters.sympy.codegen.ast.aug_assign(lhs, op, rhs)[source]¶
Create ‘lhs op= rhs’.
Represents augmented variable assignment for code generation. This is a convenience function. You can also use the AugmentedAssignment classes directly, like AddAugmentedAssignment(x, y).
- Parameters:
lhs (Expr) – Sympy object representing the lhs of the expression. These should be singular objects, such as one would use in writing code. Notable types include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that subclass these types are also supported.
rhs (Expr) – Sympy object representing the rhs of the expression. This can be any type, provided its shape corresponds to that of the lhs. For example, a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as the dimensions will not align.
Examples
>>> from .. import symbols >>> from .ast import aug_assign >>> x, y = symbols('x, y') >>> aug_assign(x, '+', y) AddAugmentedAssignment(x, y)
modelparameters.sympy.codegen.cfunctions module¶
Functions with corresponding implementations in C.
The functions defined in this module allows the user to express functions such as expm1
as a SymPy function for symbolic manipulation.
- class modelparameters.sympy.codegen.cfunctions.Cbrt(*args)[source]¶
Bases:
Function
Represents the cube root function.
The reason why one would use
Cbrt(x)
overcbrt(x)
is that the latter is internally represented asPow(x, Rational(1, 3))
which may not be what one wants when doing code-generation.Examples
>>> from ..abc import x >>> from .cfunctions import Cbrt >>> Cbrt(x) Cbrt(x) >>> Cbrt(x).diff(x) 1/(3*x**(2/3))
See also
- default_assumptions = {}¶
- nargs = {1}¶
- class modelparameters.sympy.codegen.cfunctions.Sqrt(*args)[source]¶
Bases:
Function
Represents the square root function.
The reason why one would use
Sqrt(x)
oversqrt(x)
is that the latter is internally represented asPow(x, S.Half)
which may not be what one wants when doing code-generation.Examples
>>> from ..abc import x >>> from .cfunctions import Sqrt >>> Sqrt(x) Sqrt(x) >>> Sqrt(x).diff(x) 1/(2*sqrt(x))
See also
- default_assumptions = {}¶
- nargs = {1}¶
- class modelparameters.sympy.codegen.cfunctions.exp2(arg)[source]¶
Bases:
Function
Represents the exponential function with base two.
The benefit of using
exp2(x)
over2**x
is that the latter is not as efficient under finite precision arithmetic.Examples
>>> from ..abc import x >>> from .cfunctions import exp2 >>> exp2(2).evalf() == 4 True >>> exp2(x).diff(x) log(2)*exp2(x)
See also
- default_assumptions = {}¶
- classmethod eval(arg)[source]¶
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.
Examples of eval() for the function “sign”¶
@classmethod def eval(cls, arg):
- if arg is S.NaN:
return S.NaN
if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, Mul):
coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One:
return cls(coeff) * cls(terms)
- nargs = {1}¶
- class modelparameters.sympy.codegen.cfunctions.expm1(arg)[source]¶
Bases:
Function
Represents the exponential function minus one.
The benefit of using
expm1(x)
overexp(x) - 1
is that the latter is prone to cancellation under finite precision arithmetic when x is close to zero.Examples
>>> from ..abc import x >>> from .cfunctions import expm1 >>> '%.0e' % expm1(1e-99).evalf() '1e-99' >>> from math import exp >>> exp(1e-99) - 1 0.0 >>> expm1(x).diff(x) exp(x)
See also
- default_assumptions = {}¶
- classmethod eval(arg)[source]¶
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.
Examples of eval() for the function “sign”¶
@classmethod def eval(cls, arg):
- if arg is S.NaN:
return S.NaN
if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, Mul):
coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One:
return cls(coeff) * cls(terms)
- nargs = {1}¶
- class modelparameters.sympy.codegen.cfunctions.fma(*args)[source]¶
Bases:
Function
Represents “fused multiply add”.
The benefit of using
fma(x, y, z)
overx*y + z
is that, under finite precision arithmetic, the former is supported by special instructions on some CPUs.Examples
>>> from ..abc import x, y, z >>> from .cfunctions import fma >>> fma(x, y, z).diff(x) y
- default_assumptions = {}¶
- nargs = {3}¶
- class modelparameters.sympy.codegen.cfunctions.hypot(*args)[source]¶
Bases:
Function
Represents the hypotenuse function.
The hypotenuse function is provided by e.g. the math library in the C99 standard, hence one may want to represent the function symbolically when doing code-generation.
Examples
>>> from ..abc import x, y >>> from .cfunctions import hypot >>> hypot(3, 4).evalf() == 5 True >>> hypot(x, y) hypot(x, y) >>> hypot(x, y).diff(x) x/hypot(x, y)
- default_assumptions = {}¶
- nargs = {2}¶
- class modelparameters.sympy.codegen.cfunctions.log10(arg)[source]¶
Bases:
Function
Represents the logarithm function with base ten.
Examples
>>> from ..abc import x >>> from .cfunctions import log10 >>> log10(100).evalf() == 2 True >>> log10(x).diff(x) 1/(x*log(10))
See also
- default_assumptions = {}¶
- classmethod eval(arg)[source]¶
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.
Examples of eval() for the function “sign”¶
@classmethod def eval(cls, arg):
- if arg is S.NaN:
return S.NaN
if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, Mul):
coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One:
return cls(coeff) * cls(terms)
- nargs = {1}¶
- class modelparameters.sympy.codegen.cfunctions.log1p(arg)[source]¶
Bases:
Function
Represents the natural logarithm of a number plus one.
The benefit of using
log1p(x)
overlog(x + 1)
is that the latter is prone to cancellation under finite precision arithmetic when x is close to zero.Examples
>>> from ..abc import x >>> from .cfunctions import log1p >>> '%.0e' % log1p(1e-99).evalf() '1e-99' >>> from math import log >>> log(1 + 1e-99) 0.0 >>> log1p(x).diff(x) 1/(x + 1)
See also
- default_assumptions = {}¶
- classmethod eval(arg)[source]¶
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.
Examples of eval() for the function “sign”¶
@classmethod def eval(cls, arg):
- if arg is S.NaN:
return S.NaN
if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, Mul):
coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One:
return cls(coeff) * cls(terms)
- nargs = {1}¶
- class modelparameters.sympy.codegen.cfunctions.log2(arg)[source]¶
Bases:
Function
Represents the logarithm function with base two.
The benefit of using
log2(x)
overlog(x)/log(2)
is that the latter is not as efficient under finite precision arithmetic.Examples
>>> from ..abc import x >>> from .cfunctions import log2 >>> log2(4).evalf() == 2 True >>> log2(x).diff(x) 1/(x*log(2))
- default_assumptions = {}¶
- classmethod eval(arg)[source]¶
Returns a canonical form of cls applied to arguments args.
The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.
Examples of eval() for the function “sign”¶
@classmethod def eval(cls, arg):
- if arg is S.NaN:
return S.NaN
if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, Mul):
coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One:
return cls(coeff) * cls(terms)
- nargs = {1}¶
modelparameters.sympy.codegen.ffunctions module¶
Functions with corresponding implementations in Fortran.
The functions defined in this module allows the user to express functions such as dsign
as a SymPy function for symbolic manipulation.
- class modelparameters.sympy.codegen.ffunctions.F95Function(*args)[source]¶
Bases:
FFunction
- default_assumptions = {}¶
- class modelparameters.sympy.codegen.ffunctions.FFunction(*args)[source]¶
Bases:
Function
- default_assumptions = {}¶
- class modelparameters.sympy.codegen.ffunctions.cmplx(*args)[source]¶
Bases:
FFunction
Fortran complex conversion function.
- default_assumptions = {}¶
- nargs = {2}¶
- class modelparameters.sympy.codegen.ffunctions.dsign(*args)[source]¶
Bases:
FFunction
Fortran sign intrinsic with for double precision arguments.
- default_assumptions = {}¶
- nargs = {2}¶
- class modelparameters.sympy.codegen.ffunctions.isign(*args)[source]¶
Bases:
FFunction
Fortran sign intrinsic with for integer arguments.
- default_assumptions = {}¶
- nargs = {2}¶
- class modelparameters.sympy.codegen.ffunctions.kind(*args)[source]¶
Bases:
FFunction
Fortran kind function.
- default_assumptions = {}¶
- nargs = {1}¶
- class modelparameters.sympy.codegen.ffunctions.literal_dp(num, dps=None, prec=None, precision=None)[source]¶
Bases:
_literal
Fortran double precision real literal
- default_assumptions = {'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'irrational': None, 'rational': None, 'real': True}¶
- is_commutative = True¶
- is_complex = True¶
- is_hermitian = True¶
- is_imaginary = False¶
- is_irrational = None¶
- is_rational = None¶
- is_real = True¶
- class modelparameters.sympy.codegen.ffunctions.literal_sp(num, dps=None, prec=None, precision=None)[source]¶
Bases:
_literal
Fortran single precision real literal
- default_assumptions = {'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'irrational': None, 'rational': None, 'real': True}¶
- is_commutative = True¶
- is_complex = True¶
- is_hermitian = True¶
- is_imaginary = False¶
- is_irrational = None¶
- is_rational = None¶
- is_real = True¶
- class modelparameters.sympy.codegen.ffunctions.merge(*args)[source]¶
Bases:
F95Function
Fortran merge function
- default_assumptions = {}¶
- nargs = {3}¶