modelparameters.sympy.core package

Submodules

modelparameters.sympy.core.add module

class modelparameters.sympy.core.add.Add(*args, **options)[source]

Bases: Expr, AssocOp

as_coeff_Add(rational=False)[source]

Efficiently extract the coefficient of a summation.

as_coeff_add(*deps)[source]

Returns a tuple (coeff, args) where self is treated as an Add and coeff is the Number term and args is a tuple of all other terms.

Examples

>>> from ..abc import x
>>> (7 + 3*x).as_coeff_add()
(7, (3*x,))
>>> (7*x).as_coeff_add()
(0, (7*x,))
as_coefficients_dict()[source]

Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. If an expression is not an Add it is considered to have a single term.

Examples

>>> from ..abc import a, x
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
as_content_primitive(radical=False, clear=True)[source]

Return the tuple (R, self/R) where R is the positive Rational extracted from self. If radical is True (default is False) then common radicals will be removed and included as a factor of the primitive expression.

Examples

>>> from .. import sqrt
>>> (3 + 3*sqrt(2)).as_content_primitive()
(3, 1 + sqrt(2))

Radical content can also be factored out of the primitive:

>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))

See docstring of Expr.as_content_primitive for more examples.

as_numer_denom()[source]

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

See also

normal

return a/b instead of a, b

as_real_imag(deep=True, **hints)[source]

returns a tuple representing a complex number

Examples

>>> from .. import I
>>> (7 + 9*I).as_real_imag()
(7, 9)
>>> ((1 + I)/(1 - I)).as_real_imag()
(0, 1)
>>> ((1 + 2*I)*(1 + 3*I)).as_real_imag()
(-5, 5)
as_two_terms()[source]

Return head and tail of self.

This is the most efficient way to get the head and tail of an expression.

  • if you want only the head, use self.args[0];

  • if you want to process the arguments of the tail then use self.as_coef_add() which gives the head and a tuple containing the arguments of the tail when treated as an Add.

  • if you want the coefficient when self is treated as a Mul then use self.as_coeff_mul()[0]

>>> from ..abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)
classmethod class_key()[source]

Nice order of classes

default_assumptions = {}
extract_leading_order(symbols, point=None)[source]

Returns the leading term and its order.

Examples

>>> from ..abc import x
>>> (x + 1 + 1/x**5).extract_leading_order(x)
((x**(-5), O(x**(-5))),)
>>> (1 + x).extract_leading_order(x)
((1, O(1)),)
>>> (x + x**2).extract_leading_order(x)
((x, O(x)),)
classmethod flatten(seq)[source]

Takes the sequence “seq” of nested Adds and returns a flatten list.

Returns: (commutative_part, noncommutative_part, order_symbols)

Applies associativity, all terms are commutable with respect to addition.

NB: the removal of 0 is already handled by AssocOp.__new__

See also

sympy.core.mul.Mul.flatten

getO()[source]

Returns the additive O(..) symbol if there is one, else None.

identity = 0
is_Add = True
matches(expr, repl_dict={}, old=False)[source]

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

Examples

>>> from .. import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
primitive()[source]

Return (R, self/R) where R` is the Rational GCD of self`.

R is collected only from the leading coefficient of each term.

Examples

>>> from ..abc import x, y
>>> (2*x + 4*y).primitive()
(2, x + 2*y)
>>> (2*x/3 + 4*y/9).primitive()
(2/9, 3*x + 2*y)
>>> (2*x/3 + 4.2*y).primitive()
(1/3, 2*x + 12.6*y)

No subprocessing of term factors is performed:

>>> ((2 + 2*x)*x + 2).primitive()
(1, x*(2*x + 2) + 2)

Recursive subprocessing can be done with the as_content_primitive() method:

>>> ((2 + 2*x)*x + 2).as_content_primitive()
(2, x*(x + 1) + 1)

See also: primitive() function in polytools.py

removeO()[source]

Removes the additive O(..) symbol if there is one

modelparameters.sympy.core.alphabets module

modelparameters.sympy.core.assumptions module

This module contains the machinery handling assumptions.

All symbolic objects have assumption attributes that can be accessed via .is_<assumption name> attribute.

Assumptions determine certain properties of symbolic objects and can have 3 possible values: True, False, None. True is returned if the object has the property and False is returned if it doesn’t or can’t (i.e. doesn’t make sense):

>>> from .. import I
>>> I.is_algebraic
True
>>> I.is_real
False
>>> I.is_prime
False

When the property cannot be determined (or when a method is not implemented) None will be returned, e.g. a generic symbol, x, may or may not be positive so a value of None is returned for x.is_positive.

By default, all symbolic values are in the largest set in the given context without specifying the property. For example, a symbol that has a property being integer, is also real, complex, etc.

Here follows a list of possible assumption names:

commutative

object commutes with any other object with respect to multiplication operation.

complex

object can have only values from the set of complex numbers.

imaginary

object value is a number that can be written as a real number multiplied by the imaginary unit I. See [3]_. Please note, that 0 is not considered to be an imaginary number, see issue #7649.

real

object can have only values from the set of real numbers.

integer

object can have only values from the set of integers.

odd
even

object can have only values from the set of odd (even) integers [2]_.

prime

object is a natural number greater than 1 that has no positive divisors other than 1 and itself. See [6].

composite

object is a positive integer that has at least one positive divisor other than 1 or the number itself. See [4].

zero

object has the value of 0.

nonzero

object is a real number that is not zero.

rational

object can have only values from the set of rationals.

algebraic

object can have only values from the set of algebraic numbers [11].

transcendental

object can have only values from the set of transcendental numbers [10].

irrational

object value cannot be represented exactly by Rational, see [5].

finite
infinite

object absolute value is bounded (arbitrarily large). See [7], [8], [9].

negative
nonnegative

object can have only negative (nonnegative) values [1]_.

positive
nonpositive

object can have only positive (only nonpositive) values.

hermitian
antihermitian

object belongs to the field of hermitian (antihermitian) operators.

Examples

>>> from .. import Symbol
>>> x = Symbol('x', real=True); x
x
>>> x.is_real
True
>>> x.is_complex
True

See also

sympy.core.numbers.ImaginaryUnit sympy.core.numbers.Zero sympy.core.numbers.One

Notes

Assumption values are stored in obj._assumptions dictionary or are returned by getter methods (with property decorators) or are attributes of objects/classes.

References

class modelparameters.sympy.core.assumptions.ManagedProperties(*args, **kws)[source]

Bases: BasicMeta

Metaclass for classes with old-style assumptions

class modelparameters.sympy.core.assumptions.StdFactKB(facts=None)[source]

Bases: FactKB

A FactKB specialised for the built-in rules

This is the only kind of FactKB that Basic objects should use.

copy() a shallow copy of D[source]
property generator
rules = <modelparameters.sympy.core.facts.FactRules object>
modelparameters.sympy.core.assumptions.as_property(fact)[source]

Convert a fact name to the name of the corresponding property

modelparameters.sympy.core.assumptions.make_property(fact)[source]

Create the automagic property corresponding to a fact.

modelparameters.sympy.core.backend module

modelparameters.sympy.core.basic module

Base class for all the objects in SymPy

class modelparameters.sympy.core.basic.Atom(*args)[source]

Bases: Basic

A parent class for atomic things. An atom is an expression with no subexpressions.

Examples

Symbol, Number, Rational, Integer, … But not: Add, Mul, Pow, …

classmethod class_key()[source]

Nice order of classes.

default_assumptions = {}
doit(**hints)[source]

Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.

>>> from .. import Integral
>>> from ..abc import x
>>> 2*Integral(x, x)
2*Integral(x, x)
>>> (2*Integral(x, x)).doit()
x**2
>>> (2*Integral(x, x)).doit(deep=False)
2*Integral(x, x)
is_Atom = True
matches(expr, repl_dict={}, old=False)[source]

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

Examples

>>> from .. import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
sort_key(order=None)[source]

Return a sort key.

Examples

>>> from ..core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
xreplace(rule, hack2=False)[source]

Replace occurrences of objects within the expression.

Parameters:

rule (dict-like) – Expresses a replacement rule

Returns:

xreplace

Return type:

the result of the replacement

Examples

>>> from .. import symbols, pi, exp
>>> x, y, z = symbols('x y z')
>>> (1 + x*y).xreplace({x: pi})
pi*y + 1
>>> (1 + x*y).xreplace({x: pi, y: 2})
1 + 2*pi

Replacements occur only if an entire node in the expression tree is matched:

>>> (x*y + z).xreplace({x*y: pi})
z + pi
>>> (x*y*z).xreplace({x*y: pi})
x*y*z
>>> (2*x).xreplace({2*x: y, x: z})
y
>>> (2*2*x).xreplace({2*x: y, x: z})
4*z
>>> (x + y + 2).xreplace({x + y: 2})
x + y + 2
>>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
x + exp(y) + 2

xreplace doesn’t differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does:

>>> from .. import Integral
>>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
Integral(y, (y, 1, 2*y))

Trying to replace x with an expression raises an error:

>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) 
ValueError: Invalid limits given: ((2*y, 1, 4*y),)

See also

replace

replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements

subs

substitution of subexpressions as defined by the objects themselves.

class modelparameters.sympy.core.basic.Basic(*args)[source]

Bases: object

Base class for all objects in SymPy.

Conventions:

  1. Always use .args, when accessing parameters of some instance:

    >>> from .. import cot
    >>> from ..abc import x, y
    
    >>> cot(x).args
    (x,)
    
    >>> cot(x).args[0]
    x
    
    >>> (x*y).args
    (x, y)
    
    >>> (x*y).args[1]
    y
    
  2. Never use internal methods or variables (the ones prefixed with _):

    >>> cot(x)._args    # do not use this, use cot(x).args instead
    (x,)
    
property args

Returns a tuple of arguments of ‘self’.

Examples

>>> from .. import cot
>>> from ..abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y

Notes

Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

as_content_primitive(radical=False, clear=True)[source]

A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression.

See docstring of Expr.as_content_primitive

as_poly(*gens, **args)[source]

Converts self to a polynomial or returns None.

>>> from .. import sin
>>> from ..abc import x, y
>>> print((x**2 + x*y).as_poly())
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y))
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y))
None
property assumptions0

Return object type assumptions.

For example:

Symbol(‘x’, real=True) Symbol(‘x’, integer=True)

are different objects. In other words, besides Python type (Symbol in this case), the initial assumptions are also forming their typeinfo.

Examples

>>> from .. import Symbol
>>> from ..abc import x
>>> x.assumptions0
{'commutative': True}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'hermitian': True,
'imaginary': False, 'negative': False, 'nonnegative': True,
'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True,
'zero': False}
atoms(*types)[source]

Returns the atoms that form the current object.

By default, only objects that are truly atomic and can’t be divided into smaller pieces are returned: symbols, numbers, and number symbols like I and pi. It is possible to request atoms of any type, however, as demonstrated below.

Examples

>>> from .. import I, pi, sin
>>> from ..abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
{1, 2, I, pi, x, y}

If one or more types are given, the results will contain only those types of atoms.

Examples

>>> from .. import Number, NumberSymbol, Symbol
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
{x, y}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
{1, 2}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
{1, 2, pi}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
{1, 2, I, pi}

Note that I (imaginary unit) and zoo (complex infinity) are special types of number symbols and are not part of the NumberSymbol class.

The type can be given implicitly, too:

>>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
{x, y}

Be careful to check your assumptions when using the implicit option since S(1).is_Integer = True but type(S(1)) is One, a special type of sympy atom, while type(S(2)) is type Integer and will find all integers in an expression:

>>> from .. import S
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
{1}
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
{1, 2}

Finally, arguments to atoms() can select more than atomic atoms: any sympy type (loaded in core/__init__.py) can be listed as an argument and those types of “atoms” as found in scanning the arguments of the expression recursively:

>>> from .. import Function, Mul
>>> from .function import AppliedUndef
>>> f = Function('f')
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
{f(x), sin(y + I*pi)}
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
{f(x)}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
{I*pi, 2*sin(y + I*pi)}
property canonical_variables

Return a dictionary mapping any variable defined in self.variables as underscore-suffixed numbers corresponding to their position in self.variables. Enough underscores are added to ensure that there will be no clash with existing free symbols.

Examples

>>> from .. import Lambda
>>> from ..abc import x
>>> Lambda(x, 2*x).canonical_variables
{x: 0_}
classmethod class_key()[source]

Nice order of classes.

compare(other)[source]

Return -1, 0, 1 if the object is smaller, equal, or greater than other.

Not in the mathematical sense. If the object is of a different type from the “other” then their classes are ordered according to the sorted_classes list.

Examples

>>> from ..abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
copy()[source]
count(query)[source]

Count the number of matching subexpressions.

count_ops(visual=None)[source]

wrapper for count_ops that returns the operation count.

default_assumptions = {}
doit(**hints)[source]

Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.

>>> from .. import Integral
>>> from ..abc import x
>>> 2*Integral(x, x)
2*Integral(x, x)
>>> (2*Integral(x, x)).doit()
x**2
>>> (2*Integral(x, x)).doit(deep=False)
2*Integral(x, x)
dummy_eq(other, symbol=None)[source]

Compare two expressions and handle dummy symbols.

Examples

>>> from .. import Dummy
>>> from ..abc import x, y
>>> u = Dummy('u')
>>> (u**2 + 1).dummy_eq(x**2 + 1)
True
>>> (u**2 + 1) == (x**2 + 1)
False
>>> (u**2 + y).dummy_eq(x**2 + y, x)
True
>>> (u**2 + y).dummy_eq(x**2 + y, y)
False
find(query, group=False)[source]

Find all subexpressions matching a query.

property free_symbols

Return from the atoms of self those which are free symbols.

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.

Any other method that uses bound variables should implement a free_symbols method.

classmethod fromiter(args, **assumptions)[source]

Create a new object from an iterable.

This is a convenience function that allows one to create objects from any iterable, without having to convert to a list or tuple first.

Examples

>>> from .. import Tuple
>>> Tuple.fromiter(i for i in range(5))
(0, 1, 2, 3, 4)
property func

The top-level function in an expression.

The following should hold for all objects:

>> x == x.func(*x.args)

Examples

>>> from ..abc import x
>>> a = 2*x
>>> a.func
<class 'sympy.core.mul.Mul'>
>>> a.args
(2, x)
>>> a.func(*a.args)
2*x
>>> a == a.func(*a.args)
True
has(*patterns)[source]

Test whether any subexpression matches any of the patterns.

Examples

>>> from .. import sin
>>> from ..abc import x, y, z
>>> (x**2 + sin(x*y)).has(z)
False
>>> (x**2 + sin(x*y)).has(x, y, z)
True
>>> x.has(x)
True

Note has is a structural algorithm with no knowledge of mathematics. Consider the following half-open interval:

>>> from ..sets import Interval
>>> i = Interval.Lopen(0, 5); i
Interval.Lopen(0, 5)
>>> i.args
(0, 5, True, False)
>>> i.has(4)  # there is no "4" in the arguments
False
>>> i.has(0)  # there *is* a "0" in the arguments
True

Instead, use contains to determine whether a number is in the interval or not:

>>> i.contains(4)
True
>>> i.contains(0)
False

Note that expr.has(*patterns) is exactly equivalent to any(expr.has(p) for p in patterns). In particular, False is returned when the list of patterns is empty.

>>> x.has()
False
is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = False
is_Indexed = False
is_Integer = False
is_Matrix = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Point = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Relational = False
is_Symbol = False
is_Vector = False
is_Wild = False
property is_algebraic
property is_antihermitian
property is_commutative
property is_comparable

Return True if self can be computed to a real number (or already is a real number) with precision, else False.

Examples

>>> from .. import exp_polar, pi, I
>>> (I*exp_polar(I*pi/2)).is_comparable
True
>>> (I*exp_polar(I*pi*2)).is_comparable
False

A False result does not mean that self cannot be rewritten into a form that would be comparable. For example, the difference computed below is zero but without simplification it does not evaluate to a zero with precision:

>>> e = 2**pi*(1 + 2**pi)
>>> dif = e - e.expand()
>>> dif.is_comparable
False
>>> dif.n(2)._prec
1
property is_complex
property is_composite
property is_even
property is_finite
property is_hermitian
is_hypergeometric(k)[source]
property is_imaginary
property is_infinite
property is_integer
property is_irrational
property is_negative
property is_noninteger
property is_nonnegative
property is_nonpositive
property is_nonzero
is_number = False
property is_odd
property is_polar
property is_positive
property is_prime
property is_rational
property is_real
is_symbol = False
property is_transcendental
property is_zero
match(pattern, old=False)[source]

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.xreplace(self.match(pattern)) == self

Examples

>>> from .. import Wild
>>> from ..abc import x, y
>>> p = Wild("p")
>>> q = Wild("q")
>>> r = Wild("r")
>>> e = (x+y)**(x+y)
>>> e.match(p**p)
{p_: x + y}
>>> e.match(p**q)
{p_: x + y, q_: x + y}
>>> e = (2*x)**2
>>> e.match(p*q**r)
{p_: 4, q_: x, r_: 2}
>>> (p*q**r).xreplace(e.match(p*q**r))
4*x**2

The old flag will give the old-style pattern matching where expressions and patterns are essentially solved to give the match. Both of the following give None unless old=True:

>>> (x - 2).match(p - x, old=True)
{p_: 2*x - 2}
>>> (2/x).match(p*x, old=True)
{p_: 2/x**2}
matches(expr, repl_dict={}, old=False)[source]

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

Examples

>>> from .. import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
rcall(*args)[source]

Apply on the argument recursively through the expression tree.

This method is used to simulate a common abuse of notation for operators. For instance in SymPy the the following will not work:

(x+Lambda(y, 2*y))(z) == x+2*z,

however you can use

>>> from .. import Lambda
>>> from ..abc import x, y, z
>>> (x + Lambda(y, 2*y)).rcall(z)
x + 2*z
replace(query, value, map=False, simultaneous=True, exact=False)[source]

Replace matching subexpressions of self with value.

If map = True then also return the mapping {old: new} where old was a sub-expression found with query and new is the replacement value for it. If the expression itself doesn’t match the query, then the returned value will be self.xreplace(map) otherwise it should be self.subs(ordered(map.items())).

Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The default approach is to do the replacement in a simultaneous fashion so changes made are targeted only once. If this is not desired or causes problems, simultaneous can be set to False. In addition, if an expression containing more than one Wild symbol is being used to match subexpressions and the exact flag is True, then the match will only succeed if non-zero values are received for each Wild that appears in the match pattern.

The list of possible combinations of queries and replacement values is listed below:

Examples

Initial setup

>>> from .. import log, sin, cos, tan, Wild, Mul, Add
>>> from ..abc import x, y
>>> f = log(sin(x)) + tan(sin(x**2))
1.1. type -> type

obj.replace(type, newtype)

When object of type type is found, replace it with the result of passing its argument(s) to newtype.

>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> (x*y).replace(Mul, Add)
x + y
1.2. type -> func

obj.replace(type, func)

When object of type type is found, apply func to its argument(s). func must be written to handle the number of arguments of type.

>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args)))
sin(2*x*y)
2.1. pattern -> expr

obj.replace(pattern(wild), expr(wild))

Replace subexpressions matching pattern with the expression written in terms of the Wild symbols in pattern.

>>> a = Wild('a')
>>> f.replace(sin(a), tan(a))
log(tan(x)) + tan(tan(x**2))
>>> f.replace(sin(a), tan(a/2))
log(tan(x/2)) + tan(tan(x**2/2))
>>> f.replace(sin(a), a)
log(x) + tan(x**2)
>>> (x*y).replace(a*x, a)
y

When the default value of False is used with patterns that have more than one Wild symbol, non-intuitive results may be obtained:

>>> b = Wild('b')
>>> (2*x).replace(a*x + b, b - a)
2/x

For this reason, the exact option can be used to make the replacement only when the match gives non-zero values for all Wild symbols:

>>> (2*x + y).replace(a*x + b, b - a, exact=True)
y - 2
>>> (2*x).replace(a*x + b, b - a, exact=True)
2*x
2.2. pattern -> func

obj.replace(pattern(wild), lambda wild: expr(wild))

All behavior is the same as in 2.1 but now a function in terms of pattern variables is used rather than an expression:

>>> f.replace(sin(a), lambda a: sin(2*a))
log(sin(2*x)) + tan(sin(2*x**2))
3.1. func -> func

obj.replace(filter, func)

Replace subexpression e with func(e) if filter(e) is True.

>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)

The expression itself is also targeted by the query but is done in such a fashion that changes are not made twice.

>>> e = x*(x*y + 1)
>>> e.replace(lambda x: x.is_Mul, lambda x: 2*x)
2*x*(2*x*y + 1)

See also

subs

substitution of subexpressions as defined by the objects themselves.

xreplace

exact node replacement in expr tree; also capable of using matching rules

rewrite(*args, **hints)[source]

Rewrite functions in terms of other functions.

Rewrites expression containing applications of functions of one kind in terms of functions of different kind. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function.

As a pattern this function accepts a list of functions to to rewrite (instances of DefinedFunction class). As rule you can use string or a destination function instance (in this case rewrite() will use the str() function).

There is also the possibility to pass hints on how to rewrite the given expressions. For now there is only one such hint defined called ‘deep’. When ‘deep’ is set to False it will forbid functions to rewrite their contents.

Examples

>>> from .. import sin, exp
>>> from ..abc import x

Unspecified pattern:

>>> sin(x).rewrite(exp)
-I*(exp(I*x) - exp(-I*x))/2

Pattern as a single function:

>>> sin(x).rewrite(sin, exp)
-I*(exp(I*x) - exp(-I*x))/2

Pattern as a list of functions:

>>> sin(x).rewrite([sin, ], exp)
-I*(exp(I*x) - exp(-I*x))/2
sort_key(order=None)[source]

Return a sort key.

Examples

>>> from ..core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
subs(*args, **kwargs)[source]

Substitutes old for new in an expression after sympifying args.

args is either:
  • two arguments, e.g. foo.subs(old, new)

  • one iterable argument, e.g. foo.subs(iterable). The iterable may be
    o an iterable container with (old, new) pairs. In this case the

    replacements are processed in the order given with successive patterns possibly affecting replacements already made.

    o a dict or set whose key/value items correspond to old/new pairs.

    In this case the old/new pairs will be sorted by op count and in case of a tie, by number of args and the default_sort_key. The resulting sorted list is then processed as an iterable container (see previous).

If the keyword simultaneous is True, the subexpressions will not be evaluated until all the substitutions have been made.

Examples

>>> from .. import pi, exp, limit, oo
>>> from ..abc import x, y
>>> (1 + x*y).subs(x, pi)
pi*y + 1
>>> (1 + x*y).subs({x:pi, y:2})
1 + 2*pi
>>> (1 + x*y).subs([(x, pi), (y, 2)])
1 + 2*pi
>>> reps = [(y, x**2), (x, 2)]
>>> (x + y).subs(reps)
6
>>> (x + y).subs(reversed(reps))
x**2 + 2
>>> (x**2 + x**4).subs(x**2, y)
y**2 + y

To replace only the x**2 but not the x**4, use xreplace:

>>> (x**2 + x**4).xreplace({x**2: y})
x**4 + y

To delay evaluation until all substitutions have been made, set the keyword simultaneous to True:

>>> (x/y).subs([(x, 0), (y, 0)])
0
>>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
nan

This has the added feature of not allowing subsequent substitutions to affect those already made:

>>> ((x + y)/y).subs({x + y: y, y: x + y})
1
>>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
y/(x + y)

In order to obtain a canonical result, unordered iterables are sorted by count_op length, number of arguments and by the default_sort_key to break any ties. All other iterables are left unsorted.

>>> from .. import sqrt, sin, cos
>>> from ..abc import a, b, c, d, e
>>> A = (sqrt(sin(2*x)), a)
>>> B = (sin(2*x), b)
>>> C = (cos(2*x), c)
>>> D = (x, d)
>>> E = (exp(x), e)
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
>>> expr.subs(dict([A, B, C, D, E]))
a*c*sin(d*e) + b

The resulting expression represents a literal replacement of the old arguments with the new arguments. This may not reflect the limiting behavior of the expression:

>>> (x**3 - 3*x).subs({x: oo})
nan
>>> limit(x**3 - 3*x, x, oo)
oo

If the substitution will be followed by numerical evaluation, it is better to pass the substitution to evalf as

>>> (1/x).evalf(subs={x: 3.0}, n=21)
0.333333333333333333333

rather than

>>> (1/x).subs({x: 3.0}).evalf(21)
0.333333333333333314830

as the former will ensure that the desired level of precision is obtained.

See also

replace

replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements

xreplace

exact node replacement in expr tree; also capable of using matching rules

evalf

calculates the given formula to a desired level of precision

xreplace(rule)[source]

Replace occurrences of objects within the expression.

Parameters:

rule (dict-like) – Expresses a replacement rule

Returns:

xreplace

Return type:

the result of the replacement

Examples

>>> from .. import symbols, pi, exp
>>> x, y, z = symbols('x y z')
>>> (1 + x*y).xreplace({x: pi})
pi*y + 1
>>> (1 + x*y).xreplace({x: pi, y: 2})
1 + 2*pi

Replacements occur only if an entire node in the expression tree is matched:

>>> (x*y + z).xreplace({x*y: pi})
z + pi
>>> (x*y*z).xreplace({x*y: pi})
x*y*z
>>> (2*x).xreplace({2*x: y, x: z})
y
>>> (2*2*x).xreplace({2*x: y, x: z})
4*z
>>> (x + y + 2).xreplace({x + y: 2})
x + y + 2
>>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
x + exp(y) + 2

xreplace doesn’t differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does:

>>> from .. import Integral
>>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
Integral(y, (y, 1, 2*y))

Trying to replace x with an expression raises an error:

>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) 
ValueError: Invalid limits given: ((2*y, 1, 4*y),)

See also

replace

replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements

subs

substitution of subexpressions as defined by the objects themselves.

class modelparameters.sympy.core.basic.preorder_traversal(node, keys=None)[source]

Bases: object

Do a pre-order traversal of a tree.

This iterator recursively yields nodes that it has visited in a pre-order fashion. That is, it yields the current node then descends through the tree breadth-first to yield all of a node’s children’s pre-order traversal.

For an expression, the order of the traversal depends on the order of .args, which in many cases can be arbitrary.

Parameters:
  • node (sympy expression) – The expression to traverse.

  • keys ((default None) sort key(s)) – The key(s) used to sort args of Basic objects. When None, args of Basic objects are processed in arbitrary order. If key is defined, it will be passed along to ordered() as the only key(s) to use to sort the arguments; if key is simply True then the default keys of ordered will be used.

Yields:

subtree (sympy expression) – All of the subtrees in the tree.

Examples

>>> from .. import symbols
>>> from .basic import preorder_traversal
>>> x, y, z = symbols('x y z')

The nodes are returned in the order that they are encountered unless key is given; simply passing key=True will guarantee that the traversal is unique.

>>> list(preorder_traversal((x + y)*z, keys=None)) 
[z*(x + y), z, x + y, y, x]
>>> list(preorder_traversal((x + y)*z, keys=True))
[z*(x + y), z, x + y, x, y]
skip()[source]

Skip yielding current node’s (last yielded node’s) subtrees.

Examples

>>> from ..core import symbols
>>> from .basic import preorder_traversal
>>> x, y, z = symbols('x y z')
>>> pt = preorder_traversal((x+y*z)*z)
>>> for i in pt:
...     print(i)
...     if i == x+y*z:
...             pt.skip()
z*(x + y*z)
z
x + y*z

modelparameters.sympy.core.cache module

Caching facility for SymPy

modelparameters.sympy.core.cache.cacheit(func)
modelparameters.sympy.core.cache.clear_cache()

clear cache content

modelparameters.sympy.core.cache.print_cache()

print cache info

modelparameters.sympy.core.compatibility module

Reimplementations of constructs introduced in later versions of Python than we support. Also some functions that are needed SymPy-wide and are located here for easy import.

class modelparameters.sympy.core.compatibility.NotIterable[source]

Bases: object

Use this as mixin when creating a class which is not supposed to return true when iterable() is called on its instances. I.e. avoid infinite loop when calling e.g. list() on the instance

modelparameters.sympy.core.compatibility.as_int(n)[source]

Convert the argument to a builtin integer.

The return value is guaranteed to be equal to the input. ValueError is raised if the input has a non-integral value.

Examples

>>> from .compatibility import as_int
>>> from .. import sqrt
>>> 3.0
3.0
>>> as_int(3.0) # convert to int and test for equality
3
>>> int(sqrt(10))
3
>>> as_int(sqrt(10))
Traceback (most recent call last):
...
ValueError: ... is not an integer
modelparameters.sympy.core.compatibility.default_sort_key(item, order=None)[source]

Return a key that can be used for sorting.

The key has the structure:

(class_key, (len(args), args), exponent.sort_key(), coefficient)

This key is supplied by the sort_key routine of Basic objects when item is a Basic object or an object (other than a string) that sympifies to a Basic object. Otherwise, this function produces the key.

The order argument is passed along to the sort_key routine and is used to determine how the terms within an expression are ordered. (See examples below) order options are: ‘lex’, ‘grlex’, ‘grevlex’, and reversed values of the same (e.g. ‘rev-lex’). The default order value is None (which translates to ‘lex’).

Examples

>>> from .. import S, I, default_sort_key, sin, cos, sqrt
>>> from .function import UndefinedFunction
>>> from ..abc import x

The following are equivalent ways of getting the key for an object:

>>> x.sort_key() == default_sort_key(x)
True

Here are some examples of the key that is produced:

>>> default_sort_key(UndefinedFunction('f'))
((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'),
    (0, ()), (), 1), 1)
>>> default_sort_key('1')
((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1)
>>> default_sort_key(S.One)
((1, 0, 'Number'), (0, ()), (), 1)
>>> default_sort_key(2)
((1, 0, 'Number'), (0, ()), (), 2)

While sort_key is a method only defined for SymPy objects, default_sort_key will accept anything as an argument so it is more robust as a sorting key. For the following, using key= lambda i: i.sort_key() would fail because 2 doesn’t have a sort_key method; that’s why default_sort_key is used. Note, that it also handles sympification of non-string items likes ints:

>>> a = [2, I, -I]
>>> sorted(a, key=default_sort_key)
[2, -I, I]

The returned key can be used anywhere that a key can be specified for a function, e.g. sort, min, max, etc…:

>>> a.sort(key=default_sort_key); a[0]
2
>>> min(a, key=default_sort_key)
2

Note

The key returned is useful for getting items into a canonical order that will be the same across platforms. It is not directly useful for sorting lists of expressions:

>>> a, b = x, 1/x

Since a has only 1 term, its value of sort_key is unaffected by order:

>>> a.sort_key() == a.sort_key('rev-lex')
True

If a and b are combined then the key will differ because there are terms that can be ordered:

>>> eq = a + b
>>> eq.sort_key() == eq.sort_key('rev-lex')
False
>>> eq.as_ordered_terms()
[x, 1/x]
>>> eq.as_ordered_terms('rev-lex')
[1/x, x]

But since the keys for each of these terms are independent of order’s value, they don’t sort differently when they appear separately in a list:

>>> sorted(eq.args, key=default_sort_key)
[1/x, x]
>>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
[1/x, x]

The order of terms obtained when using these keys is the order that would be obtained if those terms were factors in a product.

Although it is useful for quickly putting expressions in canonical order, it does not sort expressions based on their complexity defined by the number of operations, power of variables and others:

>>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key)
[sin(x)*cos(x), sin(x)]
>>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key)
[sqrt(x), x, x**2, x**3]

See also

ordered, sympy.core.expr.as_ordered_factors, sympy.core.expr.as_ordered_terms

modelparameters.sympy.core.compatibility.is_sequence(i, include=None)[source]

Return a boolean indicating whether i is a sequence in the SymPy sense. If anything that fails the test below should be included as being a sequence for your application, set ‘include’ to that object’s type; multiple types should be passed as a tuple of types.

Note: although generators can generate a sequence, they often need special handling to make sure their elements are captured before the generator is exhausted, so these are not included by default in the definition of a sequence.

See also: iterable

Examples

>>> from ..utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True
modelparameters.sympy.core.compatibility.iterable(i, exclude=((<class 'str'>, ), <class 'dict'>, <class 'modelparameters.sympy.core.compatibility.NotIterable'>))[source]

Return a boolean indicating whether i is SymPy iterable. True also indicates that the iterator is finite, i.e. you e.g. call list(…) on the instance.

When SymPy is working with iterables, it is almost always assuming that the iterable is not a string or a mapping, so those are excluded by default. If you want a pure Python definition, make exclude=None. To exclude multiple items, pass them as a tuple.

You can also set the _iterable attribute to True or False on your class, which will override the checks here, including the exclude test.

As a rule of thumb, some SymPy functions use this to check if they should recursively map over an object. If an object is technically iterable in the Python sense but does not desire this behavior (e.g., because its iteration is not finite, or because iteration might induce an unwanted computation), it should disable it by setting the _iterable attribute to False.

See also: is_sequence

Examples

>>> from ..utilities.iterables import iterable
>>> from .. import Tuple
>>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1]
>>> for i in things:
...     print('%s %s' % (iterable(i), type(i)))
True <... 'list'>
True <... 'tuple'>
True <... 'set'>
True <class 'sympy.core.containers.Tuple'>
True <... 'generator'>
False <... 'dict'>
False <... 'str'>
False <... 'int'>
>>> iterable({}, exclude=None)
True
>>> iterable({}, exclude=str)
True
>>> iterable("no", exclude=str)
False
modelparameters.sympy.core.compatibility.maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

modelparameters.sympy.core.compatibility.ordered(seq, keys=None, default=True, warn=False)[source]

Return an iterator of the seq where keys are used to break ties in a conservative fashion: if, after applying a key, there are no ties then no other keys will be computed.

Two default keys will be applied if 1) keys are not provided or 2) the given keys don’t resolve all ties (but only if default is True). The two keys are _nodes (which places smaller expressions before large) and default_sort_key which (if the sort_key for an object is defined properly) should resolve any ties.

If warn is True then an error will be raised if there were no keys remaining to break ties. This can be used if it was expected that there should be no ties between items that are not identical.

Examples

>>> from ..utilities.iterables import ordered
>>> from .. import count_ops
>>> from ..abc import x, y

The count_ops is not sufficient to break ties in this list and the first two items appear in their original order (i.e. the sorting is stable):

>>> list(ordered([y + 2, x + 2, x**2 + y + 3],
...    count_ops, default=False, warn=False))
...
[y + 2, x + 2, x**2 + y + 3]

The default_sort_key allows the tie to be broken:

>>> list(ordered([y + 2, x + 2, x**2 + y + 3]))
...
[x + 2, y + 2, x**2 + y + 3]

Here, sequences are sorted by length, then sum:

>>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [
...    lambda x: len(x),
...    lambda x: sum(x)]]
...
>>> list(ordered(seq, keys, default=False, warn=False))
[[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]

If warn is True, an error will be raised if there were not enough keys to break ties:

>>> list(ordered(seq, keys, default=False, warn=True))
Traceback (most recent call last):
...
ValueError: not enough keys to break ties

Notes

The decorated sort is one of the fastest ways to sort a sequence for which special item comparison is desired: the sequence is decorated, sorted on the basis of the decoration (e.g. making all letters lower case) and then undecorated. If one wants to break ties for items that have the same decorated value, a second key can be used. But if the second key is expensive to compute then it is inefficient to decorate all items with both keys: only those items having identical first key values need to be decorated. This function applies keys successively only when needed to break ties. By yielding an iterator, use of the tie-breaker is delayed as long as possible.

This function is best used in cases when use of the first key is expected to be a good hashing function; if there are no unique hashes from application of a key then that key should not have been used. The exception, however, is that even if there are many collisions, if the first group is small and one does not need to process all items in the list then time will not be wasted sorting what one was not interested in. For example, if one were looking for the minimum in a list and there were several criteria used to define the sort order, then this function would be good at returning that quickly if the first group of candidates is small relative to the number of items being processed.

modelparameters.sympy.core.compatibility.u_decode(x)[source]
modelparameters.sympy.core.compatibility.with_metaclass(meta, *bases)[source]

Create a base class with a metaclass.

For example, if you have the metaclass

>>> class Meta(type):
...     pass

Use this as the metaclass by doing

>>> from .compatibility import with_metaclass
>>> class MyClass(with_metaclass(Meta, object)):
...     pass

This is equivalent to the Python 2:

class MyClass(object):
    __metaclass__ = Meta

or Python 3:

class MyClass(object, metaclass=Meta):
    pass

That is, the first argument is the metaclass, and the remaining arguments are the base classes. Note that if the base class is just object, you may omit it.

>>> MyClass.__mro__
(<class 'MyClass'>, <... 'object'>)
>>> type(MyClass)
<class 'Meta'>

modelparameters.sympy.core.containers module

Module for SymPy containers

(SymPy objects that store other SymPy objects)

The containers implemented in this module are subclassed to Basic. They are supposed to work seamlessly within the SymPy framework.

class modelparameters.sympy.core.containers.Dict(*args)[source]

Bases: Basic

Wrapper around the builtin dict object

The Dict is a subclass of Basic, so that it works well in the SymPy framework. Because it is immutable, it may be included in sets, but its values must all be given at instantiation and cannot be changed afterwards. Otherwise it behaves identically to the Python dict.

>>> from .containers import Dict
>>> D = Dict({1: 'one', 2: 'two'})
>>> for key in D:
...    if key == 1:
...        print('%s %s' % (key, D[key]))
1 one

The args are sympified so the 1 and 2 are Integers and the values are Symbols. Queries automatically sympify args so the following work:

>>> 1 in D
True
>>> D.has('one') # searches keys and values
True
>>> 'one' in D # not in the keys
False
>>> D[1]
one
property args

Returns a tuple of arguments of ‘self’.

Examples

>>> from .. import cot
>>> from ..abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y

Notes

Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

default_assumptions = {}
get(k[, d]) D[k] if k in D, else d.  d defaults to None.[source]
items() list of D's (key, value) pairs, as 2-tuples[source]
keys() list of D's keys[source]
values() list of D's values[source]
class modelparameters.sympy.core.containers.Tuple(*args, **kwargs)[source]

Bases: Basic

Wrapper around the builtin tuple object

The Tuple is a subclass of Basic, so that it works well in the SymPy framework. The wrapped tuple is available as self.args, but you can also access elements or slices with [:] syntax.

Parameters:

sympify (bool) – If False, sympify is not called on args. This can be used for speedups for very large tuples where the elements are known to already be sympy objects.

Example

>>> from .. import symbols
>>> from .containers import Tuple
>>> a, b, c, d = symbols('a b c d')
>>> Tuple(a, b, c)[1:]
(b, c)
>>> Tuple(a, b, c).subs(a, d)
(d, b, c)
default_assumptions = {}
index(value[, start[, stop]]) integer -- return first index of value.[source]

Raises ValueError if the value is not present.

tuple_count(value)[source]

T.count(value) -> integer – return number of occurrences of value

modelparameters.sympy.core.containers.tuple_wrapper(method)[source]

Decorator that converts any tuple in the function arguments into a Tuple.

The motivation for this is to provide simple user interfaces. The user can call a function with regular tuples in the argument, and the wrapper will convert them to Tuples before handing them to the function.

>>> from .containers import tuple_wrapper
>>> def f(*args):
...    return args
>>> g = tuple_wrapper(f)

The decorated function g sees only the Tuple argument:

>>> g(0, (1, 2), 3)
(0, (1, 2), 3)

modelparameters.sympy.core.core module

The core’s core.

class modelparameters.sympy.core.core.BasicMeta(*args, **kws)[source]

Bases: type

class modelparameters.sympy.core.core.Registry[source]

Bases: object

Base class for registry objects.

Registries map a name to an object using attribute notation. Registry classes behave singletonically: all their instances share the same state, which is stored in the class object.

All subclasses should set __slots__ = [].

modelparameters.sympy.core.coreerrors module

Definitions of common exceptions for sympy.core module.

exception modelparameters.sympy.core.coreerrors.BaseCoreError[source]

Bases: Exception

Base class for core related exceptions.

exception modelparameters.sympy.core.coreerrors.NonCommutativeExpression[source]

Bases: BaseCoreError

Raised when expression didn’t have commutative property.

modelparameters.sympy.core.decorators module

SymPy core decorators.

The purpose of this module is to expose decorators without any other dependencies, so that they can be easily imported anywhere in sympy/core.

modelparameters.sympy.core.decorators.call_highest_priority(method_name)[source]

A decorator for binary special methods to handle _op_priority.

Binary special methods in Expr and its subclasses use a special attribute ‘_op_priority’ to determine whose special method will be called to handle the operation. In general, the object having the highest value of ‘_op_priority’ will handle the operation. Expr and subclasses that define custom binary special methods (__mul__, etc.) should decorate those methods with this decorator to add the priority logic.

The method_name argument is the name of the method of the other class that will be called. Use this decorator in the following manner:

# Call other.__rmul__ if other._op_priority > self._op_priority
@call_highest_priority('__rmul__')
def __mul__(self, other):
    ...

# Call other.__mul__ if other._op_priority > self._op_priority
@call_highest_priority('__mul__')
def __rmul__(self, other):
...
modelparameters.sympy.core.decorators.deprecated(**decorator_kwargs)[source]

This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.

modelparameters.sympy.core.evalf module

Adaptive numerical evaluation of SymPy expressions, using mpmath for mathematical functions.

class modelparameters.sympy.core.evalf.EvalfMixin[source]

Bases: object

Mixin class adding evalf capabililty.

evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)[source]

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>

Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}. The substitutions must be given as a dictionary.

maxn=<integer>

Allow a maximum temporary working precision of maxn digits (default=100)

chop=<bool>

Replace tiny real or imaginary parts in subresults by exact zeros (default=False)

strict=<bool>

Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)

quad=<str>

Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.

verbose=<bool>

Print debug information (default=False)

n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>

Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}. The substitutions must be given as a dictionary.

maxn=<integer>

Allow a maximum temporary working precision of maxn digits (default=100)

chop=<bool>

Replace tiny real or imaginary parts in subresults by exact zeros (default=False)

strict=<bool>

Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)

quad=<str>

Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.

verbose=<bool>

Print debug information (default=False)

modelparameters.sympy.core.evalf.N(x, n=15, **options)[source]

Calls x.evalf(n, **options).

Both .n() and N() are equivalent to .evalf(); use the one that you like better. See also the docstring of .evalf() for information on the options.

Examples

>>> from .. import Sum, oo, N
>>> from ..abc import k
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(_, 4)
1.291
exception modelparameters.sympy.core.evalf.PrecisionExhausted[source]

Bases: ArithmeticError

modelparameters.sympy.core.evalf.add_terms(terms, prec, target_prec)[source]

Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.

Returns:

  • - None, None if there are no non-zero terms;

  • - terms[0] if there is only 1 term;

  • - scaled_zero if the sum of the terms produces a zero by cancellation – e.g. mpfs representing 1 and -1 would produce a scaled zero which need special handling since they are not actually zero and they are purposely malformed to ensure that they can’t be used in anything but accuracy calculations;

  • - a tuple that is scaled to target_prec that corresponds to the – sum of the terms.

  • The returned mpf tuple will be normalized to target_prec; the input

  • prec is used to define the working precision.

  • XXX explain why this is needed and why one can’t just loop using mpf_add

modelparameters.sympy.core.evalf.as_mpmath(x, prec, options)[source]
modelparameters.sympy.core.evalf.bitcount(n)[source]
modelparameters.sympy.core.evalf.check_convergence(numer, denom, n)[source]

Returns (h, g, p) where – h is:

> 0 for convergence of rate 1/factorial(n)**h < 0 for divergence of rate factorial(n)**(-h) = 0 for geometric or polynomial convergence or divergence

– abs(g) is:

> 1 for geometric convergence of rate 1/h**n < 1 for geometric divergence of rate h**n = 1 for polynomial convergence or divergence

(g < 0 indicates an alternating series)

– p is:

> 1 for polynomial convergence of rate 1/n**h <= 1 for polynomial divergence of rate n**(-h)

modelparameters.sympy.core.evalf.check_target(expr, result, prec)[source]
modelparameters.sympy.core.evalf.chop_parts(value, prec)[source]

Chop off tiny real or complex parts.

modelparameters.sympy.core.evalf.complex_accuracy(result)[source]

Returns relative accuracy of a complex number with given accuracies for the real and imaginary parts. The relative accuracy is defined in the complex norm sense as ||z|+|error|| / |z| where error is equal to (real absolute error) + (imag absolute error)*i.

The full expression for the (logarithmic) error can be approximated easily by using the max norm to approximate the complex norm.

In the worst case (re and im equal), this is wrong by a factor sqrt(2), or by log2(sqrt(2)) = 0.5 bit.

modelparameters.sympy.core.evalf.do_integral(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf(x, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_abs(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_add(v, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_atan(v, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_bernoulli(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_ceiling(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_floor(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_im(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_integral(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_log(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_mul(v, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_piecewise(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_pow(v, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_prod(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_re(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_subs(prec, subs)[source]

Change all Float entries in subs to have precision prec.

modelparameters.sympy.core.evalf.evalf_sum(expr, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_symbol(x, prec, options)[source]
modelparameters.sympy.core.evalf.evalf_trig(v, prec, options)[source]

This function handles sin and cos of complex arguments.

TODO: should also handle tan of complex arguments.

modelparameters.sympy.core.evalf.fastlog(x)[source]

Fast approximation of log2(x) for an mpf value tuple x.

Notes: Calculated as exponent + width of mantissa. This is an approximation for two reasons: 1) it gives the ceil(log2(abs(x))) value and 2) it is too high by 1 in the case that x is an exact power of 2. Although this is easy to remedy by testing to see if the odd mpf mantissa is 1 (indicating that one was dealing with an exact power of 2) that would decrease the speed and is not necessary as this is only being used as an approximation for the number of bits in x. The correct return value could be written as “x[2] + (x[3] if x[1] != 1 else 0)”.

Since mpf tuples always have an odd mantissa, no check is done

to see if the mantissa is a multiple of 2 (in which case the result would be too large by 1).

Examples

>>> from .. import log
>>> from .evalf import fastlog, bitcount
>>> s, m, e = 0, 5, 1
>>> bc = bitcount(m)
>>> n = [1, -1][s]*m*2**e
>>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
(10, 3.3, 4)
modelparameters.sympy.core.evalf.finalize_complex(re, im, prec)[source]
modelparameters.sympy.core.evalf.get_abs(expr, prec, options)[source]
modelparameters.sympy.core.evalf.get_complex_part(expr, no, prec, options)[source]

no = 0 for real part, no = 1 for imaginary part

modelparameters.sympy.core.evalf.get_integer_part(expr, no, options, return_ints=False)[source]

With no = 1, computes ceiling(expr) With no = -1, computes floor(expr)

Note: this function either gives the exact result or signals failure.

modelparameters.sympy.core.evalf.hypsum(expr, n, start, prec)[source]

Sum a rapidly convergent infinite hypergeometric series with given general term, e.g. e = hypsum(1/factorial(n), n). The quotient between successive terms must be a quotient of integer polynomials.

modelparameters.sympy.core.evalf.iszero(mpf, scaled=False)[source]
modelparameters.sympy.core.evalf.pure_complex(v, or_real=False)[source]

Return a and b if v matches a + I*b where b is not zero and a and b are Numbers, else None. If or_real is True then 0 will be returned for b if v is a real number.

>>> from .evalf import pure_complex
>>> from .. import sqrt, I, S
>>> a, b, surd = S(2), S(3), sqrt(2)
>>> pure_complex(a)
>>> pure_complex(a, or_real=True)
(2, 0)
>>> pure_complex(surd)
>>> pure_complex(a + b*I)
(2, 3)
>>> pure_complex(I)
(0, 1)
modelparameters.sympy.core.evalf.scaled_zero(mag, sign=1)[source]

Return an mpf representing a power of two with magnitude mag and -1 for precision. Or, if mag is a scaled_zero tuple, then just remove the sign from within the list that it was initially wrapped in.

Examples

>>> from .evalf import scaled_zero
>>> from .. import Float
>>> z, p = scaled_zero(100)
>>> z, p
(([0], 1, 100, 1), -1)
>>> ok = scaled_zero(z)
>>> ok
(0, 1, 100, 1)
>>> Float(ok)
1.26765060022823e+30
>>> Float(ok, p)
0.e+30
>>> ok, p = scaled_zero(100, -1)
>>> Float(scaled_zero(ok), p)
-0.e+30

modelparameters.sympy.core.evaluate module

modelparameters.sympy.core.evaluate.evaluate(x)[source]

Control automatic evaluation

This context managers controls whether or not all SymPy functions evaluate by default.

Note that much of SymPy expects evaluated expressions. This functionality is experimental and is unlikely to function as intended on large expressions.

Examples

>>> from ..abc import x
>>> from .evaluate import evaluate
>>> print(x + x)
2*x
>>> with evaluate(False):
...     print(x + x)
x + x

modelparameters.sympy.core.expr module

class modelparameters.sympy.core.expr.AtomicExpr(*args)[source]

Bases: Atom, Expr

A parent class for object which are both atoms and Exprs.

For example: Symbol, Number, Rational, Integer, … But not: Add, Mul, Pow, …

default_assumptions = {}
is_Atom = True
is_number = False
class modelparameters.sympy.core.expr.Expr(*args)[source]

Bases: Basic, EvalfMixin

Base class for algebraic expressions.

Everything that requires arithmetic operations to be defined should subclass this class, instead of Basic (which should be used only for argument storage and expression manipulation, i.e. pattern matching, substitutions, etc).

See also

sympy.core.basic.Basic

adjoint()[source]
apart(x=None, **args)[source]

See the apart function in sympy.polys

args_cnc(cset=False, warn=True, split_1=True)[source]

Return [commutative factors, non-commutative factors] of self.

self is treated as a Mul and the ordering of the factors is maintained. If cset is True the commutative factors will be returned in a set. If there were repeated factors (as may happen with an unevaluated Mul) then an error will be raised unless it is explicitly supressed by setting warn to False.

Note: -1 is always separated from a Number unless split_1 is False.

>>> from .. import symbols, oo
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[[-1, 2, x, y], []]
>>> (-2.5*x).args_cnc()
[[-1, 2.5, x], []]
>>> (-2*x*A*B*y).args_cnc()
[[-1, 2, x, y], [A, B]]
>>> (-2*x*A*B*y).args_cnc(split_1=False)
[[-2, x, y], [A, B]]
>>> (-2*x*y).args_cnc(cset=True)
[{-1, 2, x, y}, []]

The arg is always treated as a Mul:

>>> (-2 + x + A).args_cnc()
[[], [x - 2 + A]]
>>> (-oo).args_cnc() # -oo is a singleton
[[-1, oo], []]
as_base_exp()[source]
as_coeff_Add(rational=False)[source]

Efficiently extract the coefficient of a summation.

as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)[source]

Return the tuple (c, args) where self is written as an Add, a.

c should be a Rational added to any terms of the Add that are independent of deps.

args should be a tuple of all other terms of a; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you don’t know if self is an Add or not but you want to treat self as an Add or if you want to process the individual arguments of the tail of self as an Add.

  • if you know self is an Add and want only the head, use self.args[0];

  • if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail.

  • if you want to split self into an independent and dependent parts use self.as_independent(*deps)

>>> from .. import S
>>> from ..abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x).as_coeff_add()
(3, (x,))
>>> (3 + x + y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)[source]

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_mul(*deps, **kwargs)[source]

Return the tuple (c, args) where self is written as a Mul, m.

c should be a Rational multiplied by any factors of the Mul that are independent of deps.

args should be a tuple of all other factors of m; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you don’t know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul.

  • if you know self is a Mul and want only the head, use self.args[0];

  • if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail;

  • if you want to split self into an independent and dependent parts use self.as_independent(*deps)

>>> from .. import S
>>> from ..abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())
as_coefficient(expr)[source]

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into the product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

Examples

>>> from .. import E, pi, sin, I, Poly
>>> from ..abc import x
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)

Two terms have E in them so a sum is returned. (If one were desiring the coefficient of the term exactly matching E then the constant from the returned expression could be selected. Or, for greater precision, a method of Poly can be used to indicate the desired term from which the coefficient is desired.)

>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> _.args[0]  # just want the exact match
2
>>> p = Poly(2*E + x*E); p
Poly(x*E + 2*E, x, E, domain='ZZ')
>>> p.coeff_monomial(E)
2
>>> p.nth(0, 1)
2

Since the following cannot be written as a product containing E as a factor, None is returned. (If the coefficient 2*x is desired then the coeff method should be used.)

>>> (2*E*x + x).as_coefficient(E)
>>> (2*E*x + x).coeff(E)
2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)

See also

coeff

return sum of terms have a given factor

as_coeff_Add

separate the additive constant from an expression

as_coeff_Mul

separate the multiplicative constant from an expression

as_independent

separate x-dependent terms/factors from others

sympy.polys.polytools.coeff_monomial

efficiently find the single coefficient of a monomial in Poly

sympy.polys.polytools.nth

like coeff_monomial but powers of monomial terms are used

as_coefficients_dict()[source]

Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. If an expression is not an Add it is considered to have a single term.

Examples

>>> from ..abc import a, x
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
as_content_primitive(radical=False, clear=True)[source]

This method should recursively remove a Rational from all arguments and return that (content) and the new self (primitive). The content should always be positive and Mul(*foo.as_content_primitive()) == foo. The primitive need no be in canonical form and should try to preserve the underlying structure if possible (i.e. expand_mul should not be applied to self).

Examples

>>> from .. import sqrt
>>> from ..abc import x, y, z
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)

The as_content_primitive function is recursive and retains structure:

>>> eq.as_content_primitive()
(2, x + 3*y*(y + 1) + 1)

Integer powers will have Rationals extracted from the base:

>>> ((2 + 6*x)**2).as_content_primitive()
(4, (3*x + 1)**2)
>>> ((2 + 6*x)**(2*y)).as_content_primitive()
(1, (2*(3*x + 1))**(2*y))

Terms may end up joining once their as_content_primitives are added:

>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(11, x*(y + 1))
>>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(9, x*(y + 1))
>>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
(1, 6.0*x*(y + 1) + 3*z*(y + 1))
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
(121, x**2*(y + 1)**2)
>>> ((5*(x*(1 + y)) + 2.0*x*(3 + 3*y))**2).as_content_primitive()
(1, 121.0*x**2*(y + 1)**2)

Radical content can also be factored out of the primitive:

>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))

If clear=False (default is True) then content will not be removed from an Add if it can be distributed to leave one or more terms with integer coefficients.

>>> (x/2 + y).as_content_primitive()
(1/2, x + 2*y)
>>> (x/2 + y).as_content_primitive(clear=False)
(1, x/2 + y)
as_expr(*gens)[source]

Convert a polynomial to a SymPy expression.

Examples

>>> from .. import sin
>>> from ..abc import x, y
>>> f = (x**2 + x*y).as_poly(x, y)
>>> f.as_expr()
x**2 + x*y
>>> sin(x).as_expr()
sin(x)
as_independent(*deps, **hint)[source]

A mostly naive separation of a Mul or Add into arguments that are not are dependent on deps. To obtain as complete a separation of variables as possible, use a separation method first, e.g.:

  • separatevars() to change Mul, Add and Pow (including exp) into Mul

  • .expand(mul=True) to change Add or Mul into Add

  • .expand(log=True) to change log expr into an Add

The only non-naive thing that is done here is to respect noncommutative ordering of variables and to always return (0, 0) for self of zero regardless of hints.

For nonzero self, the returned tuple (i, d) has the following interpretation:

  • i will has no variable that appears in deps

  • d will be 1 or else have terms that contain variables that are in deps

  • if self is an Add then self = i + d

  • if self is a Mul then self = i*d

  • otherwise (self, S.One) or (S.One, self) is returned.

To force the expression to be treated as an Add, use the hint as_Add=True

Examples

– self is an Add

>>> from .. import sin, cos, exp
>>> from ..abc import x, y, z
>>> (x + x*y).as_independent(x)
(0, x*y + x)
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> (2*x*sin(x) + y + x + z).as_independent(x)
(y + z, 2*x*sin(x) + x)
>>> (2*x*sin(x) + y + x + z).as_independent(x, y)
(z, 2*x*sin(x) + x + y)

– self is a Mul

>>> (x*sin(x)*cos(y)).as_independent(x)
(cos(y), x*sin(x))

non-commutative terms cannot always be separated out when self is a Mul

>>> from .. import symbols
>>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
>>> (n1 + n1*n2).as_independent(n2)
(n1, n1*n2)
>>> (n2*n1 + n1*n2).as_independent(n2)
(0, n1*n2 + n2*n1)
>>> (n1*n2*n3).as_independent(n1)
(1, n1*n2*n3)
>>> (n1*n2*n3).as_independent(n2)
(n1, n2*n3)
>>> ((x-n1)*(x-y)).as_independent(x)
(1, (x - y)*(x - n1))

– self is anything else:

>>> (sin(x)).as_independent(x)
(1, sin(x))
>>> (sin(x)).as_independent(y)
(sin(x), 1)
>>> exp(x+y).as_independent(x)
(1, exp(x + y))

– force self to be treated as an Add:

>>> (3*x).as_independent(x, as_Add=True)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=False)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=False)
(1, x - 3)

Note how the below differs from the above in making the constant on the dep term positive.

>>> (y*(-3+x)).as_independent(x)
(y, x - 3)
– use .as_independent() for true independence testing instead

of .has(). The former considers only symbols in the free symbols while the latter considers all symbols

>>> from .. import Integral
>>> I = Integral(x, (x, 1, 2))
>>> I.has(x)
True
>>> x in I.free_symbols
False
>>> I.as_independent(x) == (I, 1)
True
>>> (I + x).as_independent(x) == (I, x)
True

Note: when trying to get independent terms, a separation method might need to be used first. In this case, it is important to keep track of what you send to this routine so you know how to interpret the returned values

>>> from .. import separatevars, log
>>> separatevars(exp(x+y)).as_independent(x)
(exp(y), exp(x))
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> separatevars(x + x*y).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).expand(mul=True).as_independent(y)
(x, x*y)
>>> a, b=symbols('a b', positive=True)
>>> (log(a*b).expand(log=True)).as_independent(b)
(log(a), log(b))

See also

separatevars, expand, Add.as_two_terms, Mul.as_two_terms, as_coeff_add, as_coeff_mul

as_leading_term(*symbols)[source]

Returns the leading (nonzero) term of the series expansion of self.

The _eval_as_leading_term routines are used to do this, and they must always return a non-zero value.

Examples

>>> from ..abc import x
>>> (1 + x + x**2).as_leading_term(x)
1
>>> (1/x**2 + x + x**2).as_leading_term(x)
x**(-2)
as_numer_denom()[source]

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

See also

normal

return a/b instead of a, b

as_ordered_factors(order=None)[source]

Return list of ordered factors (if Mul) else [self].

as_ordered_terms(order=None, data=False)[source]

Transform an expression to an ordered list of terms.

Examples

>>> from .. import sin, cos
>>> from ..abc import x
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
as_powers_dict()[source]

Return self as a dictionary of factors with each factor being treated as a power. The keys are the bases of the factors and the values, the corresponding exponents. The resulting dictionary should be used with caution if the expression is a Mul and contains non- commutative factors since the order that they appeared will be lost in the dictionary.

as_real_imag(deep=True, **hints)[source]

Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method can’t be confused with re() and im() functions, which does not perform complex expansion at evaluation.

However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.

>>> from .. import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from ..abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
as_terms()[source]

Transform an expression to a list of terms.

cancel(*gens, **args)[source]

See the cancel function in sympy.polys

coeff(x, n=1, right=False)[source]

Returns the coefficient from the term(s) containing x**n. If n is zero then all terms independent of x will be returned.

When x is noncommutative, the coefficient to the left (default) or right of x can be returned. The keyword ‘right’ is ignored when x is commutative.

See also

as_coefficient

separate the expression into a coefficient and factor

as_coeff_Add

separate the additive constant from an expression

as_coeff_Mul

separate the multiplicative constant from an expression

as_independent

separate x-dependent terms/factors from others

sympy.polys.polytools.coeff_monomial

efficiently find the single coefficient of a monomial in Poly

sympy.polys.polytools.nth

like coeff_monomial but powers of monomial terms are used

Examples

>>> from .. import symbols
>>> from ..abc import x, y, z

You can select terms that have an explicit negative in front of them:

>>> (-x + 2*y).coeff(-1)
x
>>> (x - 2*y).coeff(-1)
2*y

You can select terms with no Rational coefficient:

>>> (x + 2*y).coeff(1)
x
>>> (3 + 2*x + 4*x**2).coeff(1)
0

You can select terms independent of x by making n=0; in this case expr.as_independent(x)[0] is returned (and 0 will be returned instead of None):

>>> (3 + 2*x + 4*x**2).coeff(x, 0)
3
>>> eq = ((x + 1)**3).expand() + 1
>>> eq
x**3 + 3*x**2 + 3*x + 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 2]
>>> eq -= 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 0]

You can select terms that have a numerical term in front of them:

>>> (-x - 2*y).coeff(2)
-y
>>> from .. import sqrt
>>> (x + sqrt(2)*x).coeff(sqrt(2))
x

The matching is exact:

>>> (3 + 2*x + 4*x**2).coeff(x)
2
>>> (3 + 2*x + 4*x**2).coeff(x**2)
4
>>> (3 + 2*x + 4*x**2).coeff(x**3)
0
>>> (z*(x + y)**2).coeff((x + y)**2)
z
>>> (z*(x + y)**2).coeff(x + y)
0

In addition, no factoring is done, so 1 + z*(1 + y) is not obtained from the following:

>>> (x + z*(x + x*y)).coeff(x)
1

If such factoring is desired, factor_terms can be used first:

>>> from .. import factor_terms
>>> factor_terms(x + z*(x + x*y)).coeff(x)
z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False)
>>> n.coeff(n)
1
>>> (3*n).coeff(n)
3
>>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
1 + m
>>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
m

If there is more than one possible coefficient 0 is returned:

>>> (n*m + m*n).coeff(n)
0

If there is only one possible coefficient, it is returned:

>>> (n*m + x*m*n).coeff(m*n)
x
>>> (n*m + x*m*n).coeff(m*n, right=1)
1
collect(syms, func=None, evaluate=True, exact=False, distribute_order_term=True)[source]

See the collect function in sympy.simplify

combsimp()[source]

See the combsimp function in sympy.simplify

compute_leading_term(x, logx=None)[source]

as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first.

conjugate()[source]
could_extract_minus_sign()[source]

Canonical way to choose an element in the set {e, -e} where e is any expression. If the canonical element is e, we have e.could_extract_minus_sign() == True, else e.could_extract_minus_sign() == False.

For any expression, the set {e.could_extract_minus_sign(), (-e).could_extract_minus_sign()} must be {True, False}.

>>> from ..abc import x, y
>>> (x-y).could_extract_minus_sign() != (y-x).could_extract_minus_sign()
True
count_ops(visual=None)[source]

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)[source]
equals(other, failing_expression=False)[source]

Return True if self == other, False if it doesn’t, or None. If failing_expression is True then the expression which did not simplify to a 0 will be returned instead of None.

If self is a Number (or complex number) that is not zero, then the result is False.

If self is a number and has not evaluated to zero, evalf will be used to test whether the expression evaluates to zero. If it does so and the result has significance (i.e. the precision is either -1, for a Rational result, or is greater than 1) then the evalf value will be used to return True or False.

expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[source]

Expand an expression using hints.

See the docstring of the expand() function in sympy.core.function for more information.

extract_additively(c)[source]

Return self - c if it’s possible to subtract c from self and make all matching coefficients move towards zero, else return None.

Examples

>>> from ..abc import x, y
>>> e = 2*x + 3
>>> e.extract_additively(x + 1)
x + 2
>>> e.extract_additively(3*x)
>>> e.extract_additively(4)
>>> (y*(x + 1)).extract_additively(x + 1)
>>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
(x + 1)*(x + 2*y) + 3

Sometimes auto-expansion will return a less simplified result than desired; gcd_terms might be used in such cases:

>>> from .. import gcd_terms
>>> (4*x*(y + 1) + y).extract_additively(x)
4*x*(y + 1) + x*(4*y + 3) - x*(4*y + 4) + y
>>> gcd_terms(_)
x*(4*y + 3) + y
extract_branch_factor(allow_half=False)[source]

Try to write self as exp_polar(2*pi*I*n)*z in a nice way. Return (z, n).

>>> from .. import exp_polar, I, pi
>>> from ..abc import x, y
>>> exp_polar(I*pi).extract_branch_factor()
(exp_polar(I*pi), 0)
>>> exp_polar(2*I*pi).extract_branch_factor()
(1, 1)
>>> exp_polar(-pi*I).extract_branch_factor()
(exp_polar(I*pi), -1)
>>> exp_polar(3*pi*I + x).extract_branch_factor()
(exp_polar(x + I*pi), 1)
>>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
(y*exp_polar(2*pi*x), -1)
>>> exp_polar(-I*pi/2).extract_branch_factor()
(exp_polar(-I*pi/2), 0)

If allow_half is True, also extract exp_polar(I*pi):

>>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
(1, 1/2)
>>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
(1, 1)
>>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
(1, 3/2)
>>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
(1, -1/2)
extract_multiplicatively(c)[source]

Return None if it’s not possible to make self in the form c * something in a nice way, i.e. preserving the properties of arguments of self.

>>> from .. import symbols, Rational
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_multiplicatively(x**2 * y)
x*y**2
>>> ((x*y)**3).extract_multiplicatively(x**4 * y)
>>> (2*x).extract_multiplicatively(2)
x
>>> (2*x).extract_multiplicatively(3)
>>> (Rational(1, 2)*x).extract_multiplicatively(3)
x/6
factor(*gens, **args)[source]

See the factor() function in sympy.polys.polytools

fourier_series(limits=None)[source]

Compute fourier sine/cosine series of self.

See the docstring of the fourier_series() in sympy.series.fourier for more information.

fps(x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False)[source]

Compute formal power power series of self.

See the docstring of the fps() function in sympy.series.formal for more information.

getO()[source]

Returns the additive O(..) symbol if there is one, else None.

getn()[source]

Returns the order of the expression.

The order is determined either from the O(…) term. If there is no O(…) term, it returns None.

Examples

>>> from .. import O
>>> from ..abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
integrate(*args, **kwargs)[source]

See the integrate function in sympy.integrals

invert(g, *gens, **args)[source]

Return the multiplicative inverse of self mod g where self (and g) may be symbolic expressions).

See also

sympy.core.numbers.mod_inverse, sympy.polys.polytools.invert

is_algebraic_expr(*syms)[source]

This tests whether a given expression is algebraic or not, in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.

This function returns False for expressions that are “algebraic expressions” with symbolic exponents. This is a simple extension to the is_rational_function, including rational exponentiation.

Examples

>>> from .. import Symbol, sqrt
>>> x = Symbol('x', real=True)
>>> sqrt(1 + x).is_rational_function()
False
>>> sqrt(1 + x).is_algebraic_expr()
True

This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be an algebraic expression to become one.

>>> from .. import exp, factor
>>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
>>> a.is_algebraic_expr(x)
False
>>> factor(a).is_algebraic_expr()
True

References

is_constant(*wrt, **flags)[source]

Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.

If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, two strategies are tried:

1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if wrt is different than the free symbols.

2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.

If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag failing_number is True – in that case the numerical value will be returned.

If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.

Examples

>>> from .. import cos, sin, Sum, S, pi
>>> from ..abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
property is_number

Returns True if self has no free symbols. It will be faster than if not self.free_symbols, however, since is_number will fail as soon as it hits a free symbol.

Examples

>>> from .. import log, Integral
>>> from ..abc import x
>>> x.is_number
False
>>> (2*x).is_number
False
>>> (2 + log(2)).is_number
True
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True
is_polynomial(*syms)[source]

Return True if self is a polynomial in syms and False otherwise.

This checks if self is an exact polynomial in syms. This function returns False for expressions that are “polynomials” with symbolic exponents. Thus, you should be able to apply polynomial algorithms to expressions for which this returns True, and Poly(expr, *syms) should work if and only if expr.is_polynomial(*syms) returns True. The polynomial does not have to be in expanded form. If no symbols are given, all free symbols in the expression will be used.

This is not part of the assumptions system. You cannot do Symbol(‘z’, polynomial=True).

Examples

>>> from .. import Symbol
>>> x = Symbol('x')
>>> ((x**2 + 1)**4).is_polynomial(x)
True
>>> ((x**2 + 1)**4).is_polynomial()
True
>>> (2**x + 1).is_polynomial(x)
False
>>> n = Symbol('n', nonnegative=True, integer=True)
>>> (x**n + 1).is_polynomial(x)
False

This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a polynomial to become one.

>>> from .. import sqrt, factor, cancel
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)
>>> a.is_polynomial(y)
False
>>> factor(a)
y + 1
>>> factor(a).is_polynomial(y)
True
>>> b = (y**2 + 2*y + 1)/(y + 1)
>>> b.is_polynomial(y)
False
>>> cancel(b)
y + 1
>>> cancel(b).is_polynomial(y)
True

See also .is_rational_function()

is_rational_function(*syms)[source]

Test whether function is a ratio of two polynomials in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.

This function returns False for expressions that are “rational functions” with symbolic exponents. Thus, you should be able to call .as_numer_denom() and apply polynomial algorithms to the result for expressions for which this returns True.

This is not part of the assumptions system. You cannot do Symbol(‘z’, rational_function=True).

Examples

>>> from .. import Symbol, sin
>>> from ..abc import x, y
>>> (x/y).is_rational_function()
True
>>> (x**2).is_rational_function()
True
>>> (x/sin(y)).is_rational_function(y)
False
>>> n = Symbol('n', integer=True)
>>> (x**n + 1).is_rational_function(x)
False

This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a rational function to become one.

>>> from .. import sqrt, factor
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)/y
>>> a.is_rational_function(y)
False
>>> factor(a)
(y + 1)/y
>>> factor(a).is_rational_function(y)
True

See also is_algebraic_expr().

leadterm(x)[source]

Returns the leading term a*x**b as a tuple (a, b).

Examples

>>> from ..abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
limit(x, xlim, dir='+')[source]

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+', logx=None)[source]

Wrapper for series yielding an iterator of the terms of the series.

Note: an infinite series will yield an infinite iterator. The following, for exaxmple, will never terminate. It will just keep printing terms of the sin(x) series:

for term in sin(x).lseries(x):
    print term

The advantage of lseries() over nseries() is that many times you are just interested in the next term in the series (i.e. the first term for example), but you don’t know how many you should ask for in nseries() using the “n” parameter.

See also nseries().

normal()[source]
nseries(x=None, x0=0, n=6, dir='+', logx=None)[source]

Wrapper to _eval_nseries if assumptions allow, else to series.

If x is given, x0 is 0, dir=’+’, and self has x, then _eval_nseries is called. This calculates “n” terms in the innermost expressions and then builds up the final series just by “cross-multiplying” everything out.

The optional logx parameter can be used to replace any log(x) in the returned series with a symbolic value to avoid evaluating log(x) at 0. A symbol to use in place of log(x) should be provided.

Advantage – it’s fast, because we don’t have to determine how many terms we need to calculate in advance.

Disadvantage – you may end up with less terms than you may have expected, but the O(x**n) term appended will always be correct and so the result, though perhaps shorter, will also be correct.

If any of those assumptions is not met, this is treated like a wrapper to series which will try harder to return the correct number of terms.

See also lseries().

Examples

>>> from .. import sin, log, Symbol
>>> from ..abc import x, y
>>> sin(x).nseries(x, 0, 6)
x - x**3/6 + x**5/120 + O(x**6)
>>> log(x+1).nseries(x, 0, 5)
x - x**2/2 + x**3/3 - x**4/4 + O(x**5)

Handling of the logx parameter — in the following example the expansion fails since sin does not have an asymptotic expansion at -oo (the limit of log(x) as x approaches 0):

>>> e = sin(log(x))
>>> e.nseries(x, 0, 6)
Traceback (most recent call last):
...
PoleError: ...
...
>>> logx = Symbol('logx')
>>> e.nseries(x, 0, 6, logx=logx)
sin(logx)

In the following example, the expansion works but gives only an Order term unless the logx parameter is used:

>>> e = x**y
>>> e.nseries(x, 0, 2)
O(log(x)**2)
>>> e.nseries(x, 0, 2, logx=logx)
exp(logx*y)
nsimplify(constants=[], tolerance=None, full=False)[source]

See the nsimplify function in sympy.simplify

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

See the powsimp function in sympy.simplify

primitive()[source]

Return the positive Rational that can be extracted non-recursively from every term of self (i.e., self is treated like an Add). This is like the as_coeff_Mul() method but primitive always extracts a positive Rational (never a negative or a Float).

Examples

>>> from ..abc import x
>>> (3*(x + 1)**2).primitive()
(3, (x + 1)**2)
>>> a = (6*x + 2); a.primitive()
(2, 3*x + 1)
>>> b = (x/2 + 3); b.primitive()
(1/2, x + 6)
>>> (a*b).primitive() == (1, a*b)
True
radsimp(**kwargs)[source]

See the radsimp function in sympy.simplify

ratsimp()[source]

See the ratsimp function in sympy.simplify

refine(assumption=True)[source]

See the refine function in sympy.assumptions

removeO()[source]

Removes the additive O(..) symbol if there is one

round(p=0)[source]

Return x rounded to the given decimal place.

If a complex number would results, apply round to the real and imaginary components of the number.

Examples

>>> from .. import pi, E, I, S, Add, Mul, Number
>>> S(10.5).round()
11.
>>> pi.round()
3.
>>> pi.round(2)
3.14
>>> (2*pi + E*I).round()
6. + 3.*I

The round method has a chopping effect:

>>> (2*pi + I/10).round()
6.
>>> (pi/10 + 2*I).round()
2.*I
>>> (pi/10 + E*I).round(2)
0.31 + 2.72*I

Notes

Do not confuse the Python builtin function, round, with the SymPy method of the same name. The former always returns a float (or raises an error if applied to a complex value) while the latter returns either a Number or a complex number:

>>> isinstance(round(S(123), -2), Number)
False
>>> isinstance(S(123).round(-2), Number)
True
>>> isinstance((3*I).round(), Mul)
True
>>> isinstance((1 + 3*I).round(), Add)
True
separate(deep=False, force=False)[source]

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+', logx=None)[source]

Series expansion of “self” around x = x0 yielding either terms of the series one by one (the lazy series given when n=None), else all the terms at once when n != None.

Returns the series expansion of “self” around the point x = x0 with respect to x up to O((x - x0)**n, x, x0) (default n is 6).

If x=None and self is univariate, the univariate symbol will be supplied, otherwise an error will be raised.

>>> from .. import cos, exp
>>> from ..abc import x, y
>>> cos(x).series()
1 - x**2/2 + x**4/24 + O(x**6)
>>> cos(x).series(n=4)
1 - x**2/2 + O(x**4)
>>> cos(x).series(x, x0=1, n=2)
cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
>>> e = cos(x + exp(y))
>>> e.series(y, n=2)
cos(x + 1) - y*sin(x + 1) + O(y**2)
>>> e.series(x, n=2)
cos(exp(y)) - x*sin(exp(y)) + O(x**2)

If n=None then a generator of the series terms will be returned.

>>> term=cos(x).series(n=None)
>>> [next(term) for i in range(2)]
[1, -x**2/2]

For dir=+ (default) the series is calculated from the right and for dir=- the series from the left. For smooth functions this flag will not alter the results.

>>> abs(x).series(dir="+")
x
>>> abs(x).series(dir="-")
-x
simplify(ratio=1.7, measure=None)[source]

See the simplify function in sympy.simplify

sort_key(order=None)[source]

Return a sort key.

Examples

>>> from ..core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
taylor_term(n, x, *previous_terms)[source]

General method for the taylor term.

This method is slow, because it differentiates n-times. Subclasses can redefine it to make it faster by using the “previous_terms”.

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

See the together function in sympy.polys

transpose()[source]
trigsimp(**args)[source]

See the trigsimp function in sympy.simplify

class modelparameters.sympy.core.expr.UnevaluatedExpr(arg, **kwargs)[source]

Bases: Expr

Expression that is not evaluated unless released.

Examples

>>> from .. import UnevaluatedExpr
>>> from ..abc import a, b, x, y
>>> x*(1/x)
1
>>> x*UnevaluatedExpr(1/x)
x*1/x
default_assumptions = {}
doit(*args, **kwargs)[source]

Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.

>>> from .. import Integral
>>> from ..abc import x
>>> 2*Integral(x, x)
2*Integral(x, x)
>>> (2*Integral(x, x)).doit()
x**2
>>> (2*Integral(x, x)).doit(deep=False)
2*Integral(x, x)

modelparameters.sympy.core.exprtools module

Tools for manipulating of large commutative expressions.

class modelparameters.sympy.core.exprtools.Factors(factors=None)[source]

Bases: object

Efficient representation of f_1*f_2*...*f_n.

as_expr()[source]

Return the underlying expression.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y
>>> Factors((x*y**2).as_powers_dict()).as_expr()
x*y**2
div(other)[source]

Return self and other with gcd removed from each. This is optimized for the case when there are many factors in common.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y, z
>>> from .. import S
>>> a = Factors((x*y**2).as_powers_dict())
>>> a.div(a)
(Factors({}), Factors({}))
>>> a.div(x*z)
(Factors({y: 2}), Factors({z: 1}))

The / operator only gives quo:

>>> a/x
Factors({y: 2})

Factors treats its factors as though they are all in the numerator, so if you violate this assumption the results will be correct but will not strictly correspond to the numerator and denominator of the ratio:

>>> a.div(x/z)
(Factors({y: 2}), Factors({z: -1}))

Factors is also naive about bases: it does not attempt any denesting of Rational-base terms, for example the following does not become 2**(2*x)/2.

>>> Factors(2**(2*x + 2)).div(S(8))
(Factors({2: 2*x + 2}), Factors({8: 1}))

factor_terms can clean up such Rational-bases powers:

>>> from .exprtools import factor_terms
>>> n, d = Factors(2**(2*x + 2)).div(S(8))
>>> n.as_expr()/d.as_expr()
2**(2*x + 2)/8
>>> factor_terms(_)
2**(2*x)/2
factors
gcd(other)[source]

Return Factors of gcd(self, other). The keys are the intersection of factors with the minimum exponent for each factor.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.gcd(b)
Factors({x: 1, y: 1})
gens
property is_one
>>> from .exprtools import Factors
>>> Factors(1).is_one
True
property is_zero
>>> from .exprtools import Factors
>>> Factors(0).is_zero
True
lcm(other)[source]

Return Factors of lcm(self, other) which are the union of factors with the maximum exponent for each factor.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.lcm(b)
Factors({x: 1, y: 2, z: -1})
mul(other)[source]

Return Factors of self * other.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.mul(b)
Factors({x: 2, y: 3, z: -1})
>>> a*b
Factors({x: 2, y: 3, z: -1})
normal(other)[source]

Return self and other with gcd removed from each. The only differences between this and method div is that this is 1) optimized for the case when there are few factors in common and 2) this does not raise an error if other is zero.

See also

div

pow(other)[source]

Return self raised to a non-negative integer power.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y
>>> a = Factors((x*y**2).as_powers_dict())
>>> a**2
Factors({x: 2, y: 4})
quo(other)[source]

Return numerator Factor of self / other.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.quo(b)  # same as a/b
Factors({y: 1})
rem(other)[source]

Return denominator Factors of self / other.

Examples

>>> from .exprtools import Factors
>>> from ..abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.rem(b)
Factors({z: -1})
>>> a.rem(a)
Factors({})
class modelparameters.sympy.core.exprtools.Term(term, numer=None, denom=None)[source]

Bases: object

Efficient representation of coeff*(numer/denom).

as_expr()[source]
coeff
denom
gcd(other)[source]
inv()[source]
lcm(other)[source]
mul(other)[source]
numer
pow(other)[source]
quo(other)[source]
modelparameters.sympy.core.exprtools.decompose_power(expr)[source]

Decompose power into symbolic base and integer exponent.

This is strictly only valid if the exponent from which the integer is extracted is itself an integer or the base is positive. These conditions are assumed and not checked here.

Examples

>>> from .exprtools import decompose_power
>>> from ..abc import x, y
>>> decompose_power(x)
(x, 1)
>>> decompose_power(x**2)
(x, 2)
>>> decompose_power(x**(2*y))
(x**y, 2)
>>> decompose_power(x**(2*y/3))
(x**(y/3), 2)
modelparameters.sympy.core.exprtools.decompose_power_rat(expr)[source]

Decompose power into symbolic base and rational exponent.

modelparameters.sympy.core.exprtools.factor_nc(expr)[source]

Return the factored form of expr while handling non-commutative expressions.

Examples

>>> from .exprtools import factor_nc
>>> from .. import Symbol
>>> from ..abc import x
>>> A = Symbol('A', commutative=False)
>>> B = Symbol('B', commutative=False)
>>> factor_nc((x**2 + 2*A*x + A**2).expand())
(x + A)**2
>>> factor_nc(((x + A)*(x + B)).expand())
(x + A)*(x + B)
modelparameters.sympy.core.exprtools.factor_terms(expr, radical=False, clear=False, fraction=False, sign=True)[source]

Remove common factors from terms in all arguments without changing the underlying structure of the expr. No expansion or simplification (and no processing of non-commutatives) is performed.

If radical=True then a radical common to all terms will be factored out of any Add sub-expressions of the expr.

If clear=False (default) then coefficients will not be separated from a single Add if they can be distributed to leave one or more terms with integer coefficients.

If fraction=True (default is False) then a common denominator will be constructed for the expression.

If sign=True (default) then even if the only factor in common is a -1, it will be factored out of the expression.

Examples

>>> from .. import factor_terms, Symbol
>>> from ..abc import x, y
>>> factor_terms(x + x*(2 + 4*y)**3)
x*(8*(2*y + 1)**3 + 1)
>>> A = Symbol('A', commutative=False)
>>> factor_terms(x*A + x*A + x*y*A)
x*(y*A + 2*A)

When clear is False, a rational will only be factored out of an Add expression if all terms of the Add have coefficients that are fractions:

>>> factor_terms(x/2 + 1, clear=False)
x/2 + 1
>>> factor_terms(x/2 + 1, clear=True)
(x + 2)/2

If a -1 is all that can be factored out, to not factor it out, the flag sign must be False:

>>> factor_terms(-x - y)
-(x + y)
>>> factor_terms(-x - y, sign=False)
-x - y
>>> factor_terms(-2*x - 2*y, sign=False)
-2*(x + y)

See also

gcd_terms, sympy.polys.polytools.terms_gcd

modelparameters.sympy.core.exprtools.gcd_terms(terms, isprimitive=False, clear=True, fraction=True)[source]

Compute the GCD of terms and put them together.

terms can be an expression or a non-Basic sequence of expressions which will be handled as though they are terms from a sum.

If isprimitive is True the _gcd_terms will not run the primitive method on the terms.

clear controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1.

fraction, when True (default), will put the expression over a common denominator.

Examples

>>> from ..core import gcd_terms
>>> from ..abc import x, y
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
y*(x + 1)*(x + y + 1)
>>> gcd_terms(x/2 + 1)
(x + 2)/2
>>> gcd_terms(x/2 + 1, clear=False)
x/2 + 1
>>> gcd_terms(x/2 + y/2, clear=False)
(x + y)/2
>>> gcd_terms(x/2 + 1/x)
(x**2 + 2)/(2*x)
>>> gcd_terms(x/2 + 1/x, fraction=False)
(x + 2/x)/2
>>> gcd_terms(x/2 + 1/x, fraction=False, clear=False)
x/2 + 1/x
>>> gcd_terms(x/2/y + 1/x/y)
(x**2 + 2)/(2*x*y)
>>> gcd_terms(x/2/y + 1/x/y, clear=False)
(x**2/2 + 1)/(x*y)
>>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False)
(x/2 + 1/x)/y

The clear flag was ignored in this case because the returned expression was a rational expression, not a simple sum.

See also

factor_terms, sympy.polys.polytools.terms_gcd

modelparameters.sympy.core.facts module

This is rule-based deduction system for SymPy

The whole thing is split into two parts

  • rules compilation and preparation of tables

  • runtime inference

For rule-based inference engines, the classical work is RETE algorithm [1], [2] Although we are not implementing it in full (or even significantly) it’s still still worth a read to understand the underlying ideas.

In short, every rule in a system of rules is one of two forms:

  • atom -> … (alpha rule)

  • And(atom1, atom2, …) -> … (beta rule)

The major complexity is in efficient beta-rules processing and usually for an expert system a lot of effort goes into code that operates on beta-rules.

Here we take minimalistic approach to get something usable first.

  • (preparation) of alpha- and beta- networks, everything except

  • (runtime) FactRules.deduce_all_facts

    ( Kirr: I’ve never thought that doing ) ( logic stuff is that difficult… )

    o ^__^
    o (oo)_______
    (__) )/

    ||—-w | || ||

Some references on the topic

[1] http://en.wikipedia.org/wiki/Rete_algorithm [2] http://reports-archive.adm.cs.cmu.edu/anon/1995/CMU-CS-95-113.pdf

http://en.wikipedia.org/wiki/Propositional_formula http://en.wikipedia.org/wiki/Inference_rule http://en.wikipedia.org/wiki/List_of_rules_of_inference

class modelparameters.sympy.core.facts.FactKB(rules)[source]

Bases: dict

A simple propositional knowledge base relying on compiled inference rules.

deduce_all_facts(facts)[source]

Update the KB with all the implications of a list of facts.

Facts can be specified as a dictionary or as a list of (key, value) pairs.

class modelparameters.sympy.core.facts.FactRules(rules)[source]

Bases: object

Rules that describe how to deduce facts in logic space

When defined, these rules allow implications to quickly be determined for a set of facts. For this precomputed deduction tables are used. see deduce_all_facts (forward-chaining)

Also it is possible to gather prerequisites for a fact, which is tried to be proven. (backward-chaining)

Definition Syntax

a -> b – a=T -> b=T (and automatically b=F -> a=F) a -> !b – a=T -> b=F a == b – a -> b & b -> a a -> b & c – a=T -> b=T & c=T # TODO b | c

Internals

.full_implications[k, v]: all the implications of fact k=v .beta_triggers[k, v]: beta rules that might be triggered when k=v .prereq – {} k <- [] of k’s prerequisites

.defined_facts – set of defined fact names

exception modelparameters.sympy.core.facts.InconsistentAssumptions[source]

Bases: ValueError

class modelparameters.sympy.core.facts.Prover[source]

Bases: object

ai - prover of logic rules

given a set of initial rules, Prover tries to prove all possible rules which follow from given premises.

As a result proved_rules are always either in one of two forms: alpha or beta:

Alpha rules

This are rules of the form:

a -> b & c & d & ...

Beta rules

This are rules of the form:

&(a,b,...) -> c & d & ...

i.e. beta rules are join conditions that say that something follows when several facts are true at the same time.

process_rule(a, b)[source]

process a -> b rule

property rules_alpha
property rules_beta
split_alpha_beta()[source]

split proved rules into alpha and beta chains

exception modelparameters.sympy.core.facts.TautologyDetected[source]

Bases: Exception

(internal) Prover uses it for reporting detected tautology

modelparameters.sympy.core.facts.apply_beta_to_alpha_route(alpha_implications, beta_rules)[source]

apply additional beta-rules (And conditions) to already-built alpha implication tables

TODO: write about

  • static extension of alpha-chains

  • attaching refs to beta-nodes to alpha chains

e.g.

alpha_implications:

a -> [b, !c, d] b -> [d] …

beta_rules:

&(b,d) -> e

then we’ll extend a’s rule to the following

a -> [b, !c, d, e]

modelparameters.sympy.core.facts.deduce_alpha_implications(implications)[source]

deduce all implications

Description by example

given set of logic rules:

a -> b b -> c

we deduce all possible rules:

a -> b, c b -> c

implications: [] of (a,b) return: {} of a -> set([b, c, …])

modelparameters.sympy.core.facts.rules_2prereq(rules)[source]

build prerequisites table from rules

Description by example

given set of logic rules:

a -> b, c b -> c

we build prerequisites (from what points something can be deduced):

b <- a c <- a, b

rules: {} of a -> [b, c, …] return: {} of c <- [a, b, …]

Note however, that this prerequisites may be not enough to prove a fact. An example is ‘a -> b’ rule, where prereq(a) is b, and prereq(b) is a. That’s because a=T -> b=T, and b=F -> a=F, but a=F -> b=?

modelparameters.sympy.core.facts.transitive_closure(implications)[source]

Computes the transitive closure of a list of implications

Uses Warshall’s algorithm, as described at http://www.cs.hope.edu/~cusack/Notes/Notes/DiscreteMath/Warshall.pdf.

modelparameters.sympy.core.function module

There are three types of functions implemented in SymPy:

  1. defined functions (in the sense that they can be evaluated) like exp or sin; they have a name and a body:

    f = exp

  2. undefined function which have a name but no body. Undefined functions can be defined using a Function class as follows:

    f = Function(‘f’)

    (the result will be a Function instance)

  3. anonymous function (or lambda function) which have a body (defined with dummy variables) but have no name:

    f = Lambda(x, exp(x)*x) f = Lambda((x, y), exp(x)*y)

The fourth type of functions are composites, like (sin + cos)(x); these work in SymPy core, but are not yet part of SymPy.

>>> import sympy
>>> f = sympy.Function("f")
>>> from ..abc import x
>>> f(x)
f(x)
>>> print(sympy.srepr(f(x).func))
Function('f')
>>> f(x).args
(x,)
class modelparameters.sympy.core.function.Application(*args)[source]

Bases: Basic

Base class for applied functions.

Instances of Application represent the result of applying an application of any type to any object.

default_assumptions = {}
classmethod eval(*args)[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)

property func

The top-level function in an expression.

The following should hold for all objects:

>> x == x.func(*x.args)

Examples

>>> from ..abc import x
>>> a = 2*x
>>> a.func
<class 'sympy.core.mul.Mul'>
>>> a.args
(2, x)
>>> a.func(*a.args)
2*x
>>> a == a.func(*a.args)
True
is_Function = True
class modelparameters.sympy.core.function.AppliedUndef(*args)[source]

Bases: Function

Base class for expressions resulting from the application of an undefined function.

default_assumptions = {}
is_commutative = True
is_hermitian = True
is_imaginary = False
is_real = True
exception modelparameters.sympy.core.function.ArgumentIndexError[source]

Bases: ValueError

class modelparameters.sympy.core.function.Derivative(expr, *variables, **assumptions)[source]

Bases: Expr

Carries out differentiation of the given expression with respect to symbols.

expr must define ._eval_derivative(symbol) method that returns the differentiation result. This function only needs to consider the non-trivial case where expr contains symbol and it should call the diff() method internally (not _eval_derivative); Derivative should be the only one to call _eval_derivative.

Simplification of high-order derivatives:

Because there can be a significant amount of simplification that can be done when multiple differentiations are performed, results will be automatically simplified in a fairly conservative fashion unless the keyword simplify is set to False.

>>> from .. import sqrt, diff
>>> from ..abc import x
>>> e = sqrt((x + 1)**2 + x)
>>> diff(e, x, 5, simplify=False).count_ops()
136
>>> diff(e, x, 5).count_ops()
30

Ordering of variables:

If evaluate is set to True and the expression can not be evaluated, the list of differentiation symbols will be sorted, that is, the expression is assumed to have continuous derivatives up to the order asked. This sorting assumes that derivatives wrt Symbols commute, derivatives wrt non-Symbols commute, but Symbol and non-Symbol derivatives don’t commute with each other.

Derivative wrt non-Symbols:

This class also allows derivatives wrt non-Symbols that have _diff_wrt set to True, such as Function and Derivative. When a derivative wrt a non- Symbol is attempted, the non-Symbol is temporarily converted to a Symbol while the differentiation is performed.

Note that this may seem strange, that Derivative allows things like f(g(x)).diff(g(x)), or even f(cos(x)).diff(cos(x)). The motivation for allowing this syntax is to make it easier to work with variational calculus (i.e., the Euler-Lagrange method). The best way to understand this is that the action of derivative with respect to a non-Symbol is defined by the above description: the object is substituted for a Symbol and the derivative is taken with respect to that. This action is only allowed for objects for which this can be done unambiguously, for example Function and Derivative objects. Note that this leads to what may appear to be mathematically inconsistent results. For example:

>>> from .. import cos, sin, sqrt
>>> from ..abc import x
>>> (2*cos(x)).diff(cos(x))
2
>>> (2*sqrt(1 - sin(x)**2)).diff(cos(x))
0

This appears wrong because in fact 2*cos(x) and 2*sqrt(1 - sin(x)**2) are identically equal. However this is the wrong way to think of this. Think of it instead as if we have something like this:

>>> from ..abc import c, s
>>> def F(u):
...     return 2*u
...
>>> def G(u):
...     return 2*sqrt(1 - u**2)
...
>>> F(cos(x))
2*cos(x)
>>> G(sin(x))
2*sqrt(-sin(x)**2 + 1)
>>> F(c).diff(c)
2
>>> F(c).diff(c)
2
>>> G(s).diff(c)
0
>>> G(sin(x)).diff(cos(x))
0

Here, the Symbols c and s act just like the functions cos(x) and sin(x), respectively. Think of 2*cos(x) as f(c).subs(c, cos(x)) (or f(c) at c = cos(x)) and 2*sqrt(1 - sin(x)**2) as g(s).subs(s, sin(x)) (or g(s) at s = sin(x)), where f(u) == 2*u and g(u) == 2*sqrt(1 - u**2). Here, we define the function first and evaluate it at the function, but we can actually unambiguously do this in reverse in SymPy, because expr.subs(Function, Symbol) is well-defined: just structurally replace the function everywhere it appears in the expression.

This is the same notational convenience used in the Euler-Lagrange method when one says F(t, f(t), f’(t)).diff(f(t)). What is actually meant is that the expression in question is represented by some F(t, u, v) at u = f(t) and v = f’(t), and F(t, f(t), f’(t)).diff(f(t)) simply means F(t, u, v).diff(u) at u = f(t).

We do not allow derivatives to be taken with respect to expressions where this is not so well defined. For example, we do not allow expr.diff(x*y) because there are multiple ways of structurally defining where x*y appears in an expression, some of which may surprise the reader (for example, a very strict definition would have that (x*y*z).diff(x*y) == 0).

>>> from ..abc import x, y, z
>>> (x*y*z).diff(x*y)
Traceback (most recent call last):
...
ValueError: Can't differentiate wrt the variable: x*y, 1

Note that this definition also fits in nicely with the definition of the chain rule. Note how the chain rule in SymPy is defined using unevaluated Subs objects:

>>> from .. import symbols, Function
>>> f, g = symbols('f g', cls=Function)
>>> f(2*g(x)).diff(x)
2*Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1),
                                      (_xi_1,), (2*g(x),))
>>> f(g(x)).diff(x)
Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1),
                                    (_xi_1,), (g(x),))

Finally, note that, to be consistent with variational calculus, and to ensure that the definition of substituting a Function for a Symbol in an expression is well-defined, derivatives of functions are assumed to not be related to the function. In other words, we have:

>>> from .. import diff
>>> diff(f(x), x).diff(f(x))
0

The same is true for derivatives of different orders:

>>> diff(f(x), x, 2).diff(diff(f(x), x, 1))
0
>>> diff(f(x), x, 1).diff(diff(f(x), x, 2))
0

Note, any class can allow derivatives to be taken with respect to itself. See the docstring of Expr._diff_wrt.

Examples

Some basic examples:

>>> from .. import Derivative, Symbol, Function
>>> f = Function('f')
>>> g = Function('g')
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> Derivative(x**2, x, evaluate=True)
2*x
>>> Derivative(Derivative(f(x,y), x), y)
Derivative(f(x, y), x, y)
>>> Derivative(f(x), x, 3)
Derivative(f(x), x, x, x)
>>> Derivative(f(x, y), y, x, evaluate=True)
Derivative(f(x, y), x, y)

Now some derivatives wrt functions:

>>> Derivative(f(x)**2, f(x), evaluate=True)
2*f(x)
>>> Derivative(f(g(x)), x, evaluate=True)
Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1),
                                    (_xi_1,), (g(x),))
as_finite_difference(points=1, x0=None, wrt=None)[source]

Expresses a Derivative instance as a finite difference.

Parameters:
  • points (sequence or coefficient, optional) – If sequence: discrete values (length >= order+1) of the independent variable used for generating the finite difference weights. If it is a coefficient, it will be used as the step-size for generating an equidistant sequence of length order+1 centered around x0. Default: 1 (step-size 1)

  • x0 (number or Symbol, optional) – the value of the independent variable (wrt) at which the derivative is to be approximated. Default: same as wrt.

  • wrt (Symbol, optional) – “with respect to” the variable for which the (partial) derivative is to be approximated for. If not provided it is required that the derivative is ordinary. Default: None.

Examples

>>> from .. import symbols, Function, exp, sqrt, Symbol
>>> x, h = symbols('x h')
>>> f = Function('f')
>>> f(x).diff(x).as_finite_difference()
-f(x - 1/2) + f(x + 1/2)

The default step size and number of points are 1 and order + 1 respectively. We can change the step size by passing a symbol as a parameter:

>>> f(x).diff(x).as_finite_difference(h)
-f(-h/2 + x)/h + f(h/2 + x)/h

We can also specify the discretized values to be used in a sequence:

>>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h])
-3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)

The algorithm is not restricted to use equidistant spacing, nor do we need to make the approximation around x0, but we can get an expression estimating the derivative at an offset:

>>> e, sq2 = exp(1), sqrt(2)
>>> xl = [x-h, x+h, x+e*h]
>>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2)  
2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/...

Partial derivatives are also supported:

>>> y = Symbol('y')
>>> d2fdxdy=f(x,y).diff(x,y)
>>> d2fdxdy.as_finite_difference(wrt=x)
-Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)

We can apply as_finite_difference to Derivative instances in compound expressions using replace:

>>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative,
...     lambda arg: arg.as_finite_difference())
42**(-f(x - 1/2) + f(x + 1/2)) + 1

See also

sympy.calculus.finite_diff.apply_finite_diff, sympy.calculus.finite_diff.differentiate_finite, sympy.calculus.finite_diff.finite_diff_weights

default_assumptions = {}
doit(**hints)[source]

Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.

>>> from .. import Integral
>>> from ..abc import x
>>> 2*Integral(x, x)
2*Integral(x, x)
>>> (2*Integral(x, x)).doit()
x**2
>>> (2*Integral(x, x)).doit(deep=False)
2*Integral(x, x)
doit_numerically(z0)[source]

Evaluate the derivative at z numerically.

When we can represent derivatives at a point, this should be folded into the normal evalf. For now, we need a special method.

property expr
property free_symbols

Return from the atoms of self those which are free symbols.

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.

Any other method that uses bound variables should implement a free_symbols method.

is_Derivative = True
property variables
class modelparameters.sympy.core.function.Function(*args)[source]

Bases: Application, Expr

Base class for applied mathematical functions.

It also serves as a constructor for undefined function classes.

Examples

First example shows how to use Function as a constructor for undefined function classes:

>>> from .. import Function, Symbol
>>> x = Symbol('x')
>>> f = Function('f')
>>> g = Function('g')(x)
>>> f
f
>>> f(x)
f(x)
>>> g
g(x)
>>> f(x).diff(x)
Derivative(f(x), x)
>>> g.diff(x)
Derivative(g(x), x)

In the following example Function is used as a base class for my_func that represents a mathematical function my_func. Suppose that it is well known, that my_func(0) is 1 and my_func at infinity goes to 0, so we want those two simplifications to occur automatically. Suppose also that my_func(x) is real exactly when x is real. Here is an implementation that honours those requirements:

>>> from .. import Function, S, oo, I, sin
>>> class my_func(Function):
...
...     @classmethod
...     def eval(cls, x):
...         if x.is_Number:
...             if x is S.Zero:
...                 return S.One
...             elif x is S.Infinity:
...                 return S.Zero
...
...     def _eval_is_real(self):
...         return self.args[0].is_real
...
>>> x = S('x')
>>> my_func(0) + sin(0)
1
>>> my_func(oo)
0
>>> my_func(3.54).n() # Not yet implemented for my_func.
my_func(3.54)
>>> my_func(I).is_real
False

In order for my_func to become useful, several other methods would need to be implemented. See source code of some of the already implemented functions for more complete examples.

Also, if the function can take more than one argument, then nargs must be defined, e.g. if my_func can take one or two arguments then,

>>> class my_func(Function):
...     nargs = (1, 2)
...
>>>
as_base_exp()[source]

Returns the method as the 2-tuple (base, exponent).

classmethod class_key()[source]

Nice order of classes.

default_assumptions = {}
fdiff(argindex=1)[source]

Returns the first derivative of the function.

property is_commutative

Returns whether the functon is commutative.

class modelparameters.sympy.core.function.FunctionClass(*args, **kwargs)[source]

Bases: ManagedProperties

Base class for function classes. FunctionClass is a subclass of type.

Use Function(‘<function name>’ [ , signature ]) to create undefined function classes.

property nargs

Return a set of the allowed number of arguments for the function.

Examples

>>> from .function import Function
>>> from ..abc import x, y
>>> f = Function('f')

If the function can take any number of arguments, the set of whole numbers is returned:

>>> Function('f').nargs
S.Naturals0

If the function was initialized to accept one or more arguments, a corresponding set will be returned:

>>> Function('f', nargs=1).nargs
{1}
>>> Function('f', nargs=(2, 1)).nargs
{1, 2}

The undefined function, after application, also has the nargs attribute; the actual number of arguments is always available by checking the args attribute:

>>> f = Function('f')
>>> f(1).nargs
S.Naturals0
>>> len(f(1).args)
1
class modelparameters.sympy.core.function.Lambda(variables, expr)[source]

Bases: Expr

Lambda(x, expr) represents a lambda function similar to Python’s ‘lambda x: expr’. A function of several variables is written as Lambda((x, y, …), expr).

A simple example:

>>> from .. import Lambda
>>> from ..abc import x
>>> f = Lambda(x, x**2)
>>> f(4)
16

For multivariate functions, use:

>>> from ..abc import y, z, t
>>> f2 = Lambda((x, y, z, t), x + y**z + t**z)
>>> f2(1, 2, 3, 4)
73

A handy shortcut for lots of arguments:

>>> p = x, y, z
>>> f = Lambda(p, x + y*z)
>>> f(*p)
x + y*z
default_assumptions = {}
property expr

The return value of the function

property free_symbols

Return from the atoms of self those which are free symbols.

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.

Any other method that uses bound variables should implement a free_symbols method.

is_Function = True
property is_identity

Return True if this Lambda is an identity function.

property variables

The variables used in the internal representation of the function

exception modelparameters.sympy.core.function.PoleError[source]

Bases: Exception

class modelparameters.sympy.core.function.Subs(expr, variables, point, **assumptions)[source]

Bases: Expr

Represents unevaluated substitutions of an expression.

Subs(expr, x, x0) receives 3 arguments: an expression, a variable or list of distinct variables and a point or list of evaluation points corresponding to those variables.

Subs objects are generally useful to represent unevaluated derivatives calculated at a point.

The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity.

There’s no automatic expansion - use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression.

When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects - in this case the expression is always expanded (for the unevaluated form, use Derivative()).

A simple example:

>>> from .. import Subs, Function, sin
>>> from ..abc import x, y, z
>>> f = Function('f')
>>> e = Subs(f(x).diff(x), x, y)
>>> e.subs(y, 0)
Subs(Derivative(f(x), x), (x,), (0,))
>>> e.subs(f, sin).doit()
cos(y)

An example with several variables:

>>> Subs(f(x)*sin(y) + z, (x, y), (0, 1))
Subs(z + f(x)*sin(y), (x, y), (0, 1))
>>> _.doit()
z + f(0)*sin(1)
default_assumptions = {}
doit()[source]

Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.

>>> from .. import Integral
>>> from ..abc import x
>>> 2*Integral(x, x)
2*Integral(x, x)
>>> (2*Integral(x, x)).doit()
x**2
>>> (2*Integral(x, x)).doit(deep=False)
2*Integral(x, x)
evalf(prec=None, **options)[source]

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>

Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}. The substitutions must be given as a dictionary.

maxn=<integer>

Allow a maximum temporary working precision of maxn digits (default=100)

chop=<bool>

Replace tiny real or imaginary parts in subresults by exact zeros (default=False)

strict=<bool>

Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)

quad=<str>

Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.

verbose=<bool>

Print debug information (default=False)

property expr

The expression on which the substitution operates

property free_symbols

Return from the atoms of self those which are free symbols.

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.

Any other method that uses bound variables should implement a free_symbols method.

n(prec=None, **options)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>

Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}. The substitutions must be given as a dictionary.

maxn=<integer>

Allow a maximum temporary working precision of maxn digits (default=100)

chop=<bool>

Replace tiny real or imaginary parts in subresults by exact zeros (default=False)

strict=<bool>

Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)

quad=<str>

Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.

verbose=<bool>

Print debug information (default=False)

property point

The values for which the variables are to be substituted

property variables

The variables to be evaluated

class modelparameters.sympy.core.function.UndefinedFunction(name, bases=(AppliedUndef,), __dict__=None, **kwargs)[source]

Bases: FunctionClass

The (meta)class of undefined functions.

class modelparameters.sympy.core.function.WildFunction(*args)[source]

Bases: Function, AtomicExpr

A WildFunction function matches any function (with its arguments).

Examples

>>> from .. import WildFunction, Function, cos
>>> from ..abc import x, y
>>> F = WildFunction('F')
>>> f = Function('f')
>>> F.nargs
S.Naturals0
>>> x.match(F)
>>> F.match(F)
{F_: F_}
>>> f(x).match(F)
{F_: f(x)}
>>> cos(x).match(F)
{F_: cos(x)}
>>> f(x, y).match(F)
{F_: f(x, y)}

To match functions with a given number of arguments, set nargs to the desired value at instantiation:

>>> F = WildFunction('F', nargs=2)
>>> F.nargs
{2}
>>> f(x).match(F)
>>> f(x, y).match(F)
{F_: f(x, y)}

To match functions with a range of arguments, set nargs to a tuple containing the desired number of arguments, e.g. if nargs = (1, 2) then functions with 1 or 2 arguments will be matched.

>>> F = WildFunction('F', nargs=(1, 2))
>>> F.nargs
{1, 2}
>>> f(x).match(F)
{F_: f(x)}
>>> f(x, y).match(F)
{F_: f(x, y)}
>>> f(x, y, 1).match(F)
default_assumptions = {}
include = {}
matches(expr, repl_dict={}, old=False)[source]

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

Examples

>>> from .. import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
modelparameters.sympy.core.function.count_ops(expr, visual=False)[source]

Return a representation (integer or expression) of the operations in expr.

If visual is False (default) then the sum of the coefficients of the visual expression will be returned.

If visual is True then the number of each type of operation is shown with the core class types (or their virtual equivalent) multiplied by the number of times they occur.

If expr is an iterable, the sum of the op counts of the items will be returned.

Examples

>>> from ..abc import a, b, x, y
>>> from .. import sin, count_ops

Although there isn’t a SUB object, minus signs are interpreted as either negations or subtractions:

>>> (x - y).count_ops(visual=True)
SUB
>>> (-x).count_ops(visual=True)
NEG

Here, there are two Adds and a Pow:

>>> (1 + a + b**2).count_ops(visual=True)
2*ADD + POW

In the following, an Add, Mul, Pow and two functions:

>>> (sin(x)*x + sin(x)**2).count_ops(visual=True)
ADD + MUL + POW + 2*SIN

for a total of 5:

>>> (sin(x)*x + sin(x)**2).count_ops(visual=False)
5

Note that “what you type” is not always what you get. The expression 1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather than two DIVs:

>>> (1/x/y).count_ops(visual=True)
DIV + MUL

The visual option can be used to demonstrate the difference in operations for expressions in different forms. Here, the Horner representation is compared with the expanded form of a polynomial:

>>> eq=x*(1 + x*(2 + x*(3 + x)))
>>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True)
-MUL + 3*POW

The count_ops function also handles iterables:

>>> count_ops([x, sin(x), None, True, x + 2], visual=False)
2
>>> count_ops([x, sin(x), None, True, x + 2], visual=True)
ADD + SIN
>>> count_ops({x: sin(x), x + 2: y + 1}, visual=True)
2*ADD + SIN
modelparameters.sympy.core.function.diff(f, *symbols, **kwargs)[source]

Differentiate f with respect to symbols.

This is just a wrapper to unify .diff() and the Derivative class; its interface is similar to that of integrate(). You can use the same shortcuts for multiple variables as with Derivative. For example, diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative of f(x).

You can pass evaluate=False to get an unevaluated Derivative class. Note that if there are 0 symbols (such as diff(f(x), x, 0), then the result will be the function (the zeroth derivative), even if evaluate=False.

Examples

>>> from .. import sin, cos, Function, diff
>>> from ..abc import x, y
>>> f = Function('f')
>>> diff(sin(x), x)
cos(x)
>>> diff(f(x), x, x, x)
Derivative(f(x), x, x, x)
>>> diff(f(x), x, 3)
Derivative(f(x), x, x, x)
>>> diff(sin(x)*cos(y), x, 2, y, 2)
sin(x)*cos(y)
>>> type(diff(sin(x), x))
cos
>>> type(diff(sin(x), x, evaluate=False))
<class 'sympy.core.function.Derivative'>
>>> type(diff(sin(x), x, 0))
sin
>>> type(diff(sin(x), x, 0, evaluate=False))
sin
>>> diff(sin(x))
cos(x)
>>> diff(sin(x*y))
Traceback (most recent call last):
...
ValueError: specify differentiation variables to differentiate sin(x*y)

Note that diff(sin(x)) syntax is meant only for convenience in interactive sessions and should be avoided in library code.

References

http://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html

See also

Derivative

sympy.geometry.util.idiff

computes the derivative implicitly

modelparameters.sympy.core.function.expand(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[source]

Expand an expression using methods given as hints.

Hints evaluated unless explicitly set to False are: basic, log, multinomial, mul, power_base, and power_exp The following hints are supported but not applied unless set to True: complex, func, and trig. In addition, the following meta-hints are supported by some or all of the other hints: frac, numer, denom, modulus, and force. deep is supported by all hints. Additionally, subclasses of Expr may define their own hints or meta-hints.

The basic hint is used for any special rewriting of an object that should be done automatically (along with the other hints like mul) when expand is called. This is a catch-all hint to handle any sort of expansion that may not be described by the existing hint names. To use this hint an object should override the _eval_expand_basic method. Objects may also define their own expand methods, which are not run by default. See the API section below.

If deep is set to True (the default), things like arguments of functions are recursively expanded. Use deep=False to only expand on the top level.

If the force hint is used, assumptions about variables will be ignored in making the expansion.

Hints

These hints are run by default

mul

Distributes multiplication over addition:

>>> from .. import cos, exp, sin
>>> from ..abc import x, y, z
>>> (y*(x + z)).expand(mul=True)
x*y + y*z

multinomial

Expand (x + y + …)**n where n is a positive integer.

>>> ((x + y + z)**2).expand(multinomial=True)
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2

power_exp

Expand addition in exponents into multiplied bases.

>>> exp(x + y).expand(power_exp=True)
exp(x)*exp(y)
>>> (2**(x + y)).expand(power_exp=True)
2**x*2**y

power_base

Split powers of multiplied bases.

This only happens by default if assumptions allow, or if the force meta-hint is used:

>>> ((x*y)**z).expand(power_base=True)
(x*y)**z
>>> ((x*y)**z).expand(power_base=True, force=True)
x**z*y**z
>>> ((2*y)**z).expand(power_base=True)
2**z*y**z

Note that in some cases where this expansion always holds, SymPy performs it automatically:

>>> (x*y)**2
x**2*y**2

log

Pull out power of an argument as a coefficient and split logs products into sums of logs.

Note that these only work if the arguments of the log function have the proper assumptions–the arguments must be positive and the exponents must be real–or else the force hint must be True:

>>> from .. import log, symbols
>>> log(x**2*y).expand(log=True)
log(x**2*y)
>>> log(x**2*y).expand(log=True, force=True)
2*log(x) + log(y)
>>> x, y = symbols('x,y', positive=True)
>>> log(x**2*y).expand(log=True)
2*log(x) + log(y)

basic

This hint is intended primarily as a way for custom subclasses to enable expansion by default.

These hints are not run by default:

complex

Split an expression into real and imaginary parts.

>>> x, y = symbols('x,y')
>>> (x + y).expand(complex=True)
re(x) + re(y) + I*im(x) + I*im(y)
>>> cos(x).expand(complex=True)
-I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))

Note that this is just a wrapper around as_real_imag(). Most objects that wish to redefine _eval_expand_complex() should consider redefining as_real_imag() instead.

func

Expand other functions.

>>> from .. import gamma
>>> gamma(x + 1).expand(func=True)
x*gamma(x)

trig

Do trigonometric expansions.

>>> cos(x + y).expand(trig=True)
-sin(x)*sin(y) + cos(x)*cos(y)
>>> sin(2*x).expand(trig=True)
2*sin(x)*cos(x)

Note that the forms of sin(n*x) and cos(n*x) in terms of sin(x) and cos(x) are not unique, due to the identity sin^2(x) + cos^2(x) = 1. The current implementation uses the form obtained from Chebyshev polynomials, but this may change. See this MathWorld article for more information.

Notes

  • You can shut off unwanted methods:

    >>> (exp(x + y)*(x + y)).expand()
    x*exp(x)*exp(y) + y*exp(x)*exp(y)
    >>> (exp(x + y)*(x + y)).expand(power_exp=False)
    x*exp(x + y) + y*exp(x + y)
    >>> (exp(x + y)*(x + y)).expand(mul=False)
    (x + y)*exp(x)*exp(y)
    
  • Use deep=False to only expand on the top level:

    >>> exp(x + exp(x + y)).expand()
    exp(x)*exp(exp(x)*exp(y))
    >>> exp(x + exp(x + y)).expand(deep=False)
    exp(x)*exp(exp(x + y))
    
  • Hints are applied in an arbitrary, but consistent order (in the current implementation, they are applied in alphabetical order, except multinomial comes before mul, but this may change). Because of this, some hints may prevent expansion by other hints if they are applied first. For example, mul may distribute multiplications and prevent log and power_base from expanding them. Also, if mul is applied before multinomial`, the expression might not be fully distributed. The solution is to use the various ``expand_hint helper functions or to use hint=False to this function to finely control which hints are applied. Here are some examples:

    >>> from .. import expand, expand_mul, expand_power_base
    >>> x, y, z = symbols('x,y,z', positive=True)
    
    >>> expand(log(x*(y + z)))
    log(x) + log(y + z)
    

    Here, we see that log was applied before mul. To get the mul expanded form, either of the following will work:

    >>> expand_mul(log(x*(y + z)))
    log(x*y + x*z)
    >>> expand(log(x*(y + z)), log=False)
    log(x*y + x*z)
    

    A similar thing can happen with the power_base hint:

    >>> expand((x*(y + z))**x)
    (x*y + x*z)**x
    

    To get the power_base expanded form, either of the following will work:

    >>> expand((x*(y + z))**x, mul=False)
    x**x*(y + z)**x
    >>> expand_power_base((x*(y + z))**x)
    x**x*(y + z)**x
    
    >>> expand((x + y)*y/x)
    y + y**2/x
    

    The parts of a rational expression can be targeted:

    >>> expand((x + y)*y/x/(x + 1), frac=True)
    (x*y + y**2)/(x**2 + x)
    >>> expand((x + y)*y/x/(x + 1), numer=True)
    (x*y + y**2)/(x*(x + 1))
    >>> expand((x + y)*y/x/(x + 1), denom=True)
    y*(x + y)/(x**2 + x)
    
  • The modulus meta-hint can be used to reduce the coefficients of an expression post-expansion:

    >>> expand((3*x + 1)**2)
    9*x**2 + 6*x + 1
    >>> expand((3*x + 1)**2, modulus=5)
    4*x**2 + x + 1
    
  • Either expand() the function or .expand() the method can be used. Both are equivalent:

    >>> expand((x + 1)**2)
    x**2 + 2*x + 1
    >>> ((x + 1)**2).expand()
    x**2 + 2*x + 1
    

API

Objects can define their own expand hints by defining _eval_expand_hint(). The function should take the form:

def _eval_expand_hint(self, **hints):
    # Only apply the method to the top-level expression
    ...

See also the example below. Objects should define _eval_expand_hint() methods only if hint applies to that specific object. The generic _eval_expand_hint() method defined in Expr will handle the no-op case.

Each hint should be responsible for expanding that hint only. Furthermore, the expansion should be applied to the top-level expression only. expand() takes care of the recursion that happens when deep=True.

You should only call _eval_expand_hint() methods directly if you are 100% sure that the object has the method, as otherwise you are liable to get unexpected AttributeError``s.  Note, again, that you do not need to recursively apply the hint to args of your object: this is handled automatically by ``expand(). _eval_expand_hint() should generally not be used at all outside of an _eval_expand_hint() method. If you want to apply a specific expansion from within another method, use the public expand() function, method, or expand_hint() functions.

In order for expand to work, objects must be rebuildable by their args, i.e., obj.func(*obj.args) == obj must hold.

Expand methods are passed **hints so that expand hints may use ‘metahints’–hints that control how different expand methods are applied. For example, the force=True hint described above that causes expand(log=True) to ignore assumptions is such a metahint. The deep meta-hint is handled exclusively by expand() and is not passed to _eval_expand_hint() methods.

Note that expansion hints should generally be methods that perform some kind of ‘expansion’. For hints that simply rewrite an expression, use the .rewrite() API.

Examples

>>> from .. import Expr, sympify
>>> class MyClass(Expr):
...     def __new__(cls, *args):
...         args = sympify(args)
...         return Expr.__new__(cls, *args)
...
...     def _eval_expand_double(self, **hints):
...         '''
...         Doubles the args of MyClass.
...
...         If there more than four args, doubling is not performed,
...         unless force=True is also used (False by default).
...         '''
...         force = hints.pop('force', False)
...         if not force and len(self.args) > 4:
...             return self
...         return self.func(*(self.args + self.args))
...
>>> a = MyClass(1, 2, MyClass(3, 4))
>>> a
MyClass(1, 2, MyClass(3, 4))
>>> a.expand(double=True)
MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4))
>>> a.expand(double=True, deep=False)
MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))
>>> b = MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True)
MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True, force=True)
MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
modelparameters.sympy.core.function.expand_complex(expr, deep=True)[source]

Wrapper around expand that only uses the complex hint. See the expand docstring for more information.

Examples

>>> from .. import expand_complex, exp, sqrt, I
>>> from ..abc import z
>>> expand_complex(exp(z))
I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z))
>>> expand_complex(sqrt(I))
sqrt(2)/2 + sqrt(2)*I/2

See also

Expr.as_real_imag

modelparameters.sympy.core.function.expand_func(expr, deep=True)[source]

Wrapper around expand that only uses the func hint. See the expand docstring for more information.

Examples

>>> from .. import expand_func, gamma
>>> from ..abc import x
>>> expand_func(gamma(x + 2))
x*(x + 1)*gamma(x)
modelparameters.sympy.core.function.expand_log(expr, deep=True, force=False)[source]

Wrapper around expand that only uses the log hint. See the expand docstring for more information.

Examples

>>> from .. import symbols, expand_log, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
(x + y)*(log(x) + 2*log(y))*exp(x + y)
modelparameters.sympy.core.function.expand_mul(expr, deep=True)[source]

Wrapper around expand that only uses the mul hint. See the expand docstring for more information.

Examples

>>> from .. import symbols, expand_mul, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_mul(exp(x+y)*(x+y)*log(x*y**2))
x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)
modelparameters.sympy.core.function.expand_multinomial(expr, deep=True)[source]

Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information.

Examples

>>> from .. import symbols, expand_multinomial, exp
>>> x, y = symbols('x y', positive=True)
>>> expand_multinomial((x + exp(x + 1))**2)
x**2 + 2*x*exp(x + 1) + exp(2*x + 2)
modelparameters.sympy.core.function.expand_power_base(expr, deep=True, force=False)[source]

Wrapper around expand that only uses the power_base hint.

See the expand docstring for more information.

A wrapper to expand(power_base=True) which separates a power with a base that is a Mul into a product of powers, without performing any other expansions, provided that assumptions about the power’s base and exponent allow.

deep=False (default is True) will only apply to the top-level expression.

force=True (default is False) will cause the expansion to ignore assumptions about the base and exponent. When False, the expansion will only happen if the base is non-negative or the exponent is an integer.

>>> from ..abc import x, y, z
>>> from .. import expand_power_base, sin, cos, exp
>>> (x*y)**2
x**2*y**2
>>> (2*x)**y
(2*x)**y
>>> expand_power_base(_)
2**y*x**y
>>> expand_power_base((x*y)**z)
(x*y)**z
>>> expand_power_base((x*y)**z, force=True)
x**z*y**z
>>> expand_power_base(sin((x*y)**z), deep=False)
sin((x*y)**z)
>>> expand_power_base(sin((x*y)**z), force=True)
sin(x**z*y**z)
>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y)
2**y*sin(x)**y + 2**y*cos(x)**y
>>> expand_power_base((2*exp(y))**x)
2**x*exp(y)**x
>>> expand_power_base((2*cos(x))**y)
2**y*cos(x)**y

Notice that sums are left untouched. If this is not the desired behavior, apply full expand() to the expression:

>>> expand_power_base(((x+y)*z)**2)
z**2*(x + y)**2
>>> (((x+y)*z)**2).expand()
x**2*z**2 + 2*x*y*z**2 + y**2*z**2
>>> expand_power_base((2*y)**(1+z))
2**(z + 1)*y**(z + 1)
>>> ((2*y)**(1+z)).expand()
2*2**z*y*y**z
modelparameters.sympy.core.function.expand_power_exp(expr, deep=True)[source]

Wrapper around expand that only uses the power_exp hint.

See the expand docstring for more information.

Examples

>>> from .. import expand_power_exp
>>> from ..abc import x, y
>>> expand_power_exp(x**(y + 2))
x**2*x**y
modelparameters.sympy.core.function.expand_trig(expr, deep=True)[source]

Wrapper around expand that only uses the trig hint. See the expand docstring for more information.

Examples

>>> from .. import expand_trig, sin
>>> from ..abc import x, y
>>> expand_trig(sin(x+y)*(x+y))
(x + y)*(sin(x)*cos(y) + sin(y)*cos(x))
modelparameters.sympy.core.function.nfloat(expr, n=15, exponent=False)[source]

Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True).

Examples

>>> from .function import nfloat
>>> from ..abc import x, y
>>> from .. import cos, pi, sqrt
>>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y))
x**4 + 0.5*x + sqrt(y) + 1.5
>>> nfloat(x**4 + sqrt(y), exponent=True)
x**4.0 + y**0.5

modelparameters.sympy.core.logic module

Logic expressions handling

Note

at present this is mainly needed for facts.py , feel free however to improve this stuff for general purpose.

class modelparameters.sympy.core.logic.And(*args)[source]

Bases: AndOr_Base

expand()[source]
op_x_notx = False
class modelparameters.sympy.core.logic.AndOr_Base(*args)[source]

Bases: Logic

classmethod flatten(args)[source]
class modelparameters.sympy.core.logic.Logic(*args)[source]

Bases: object

Logical expression

static fromstring(text)[source]

Logic from string with space around & and | but none after !.

e.g.

!a & b | c

op_2class = {'!': <class 'modelparameters.sympy.core.logic.Not'>, '&': <class 'modelparameters.sympy.core.logic.And'>, '|': <class 'modelparameters.sympy.core.logic.Or'>}
class modelparameters.sympy.core.logic.Not(arg)[source]

Bases: Logic

property arg
class modelparameters.sympy.core.logic.Or(*args)[source]

Bases: AndOr_Base

op_x_notx = True
modelparameters.sympy.core.logic.fuzzy_and(args)[source]

Return True (all True), False (any False) or None.

Examples

>>> from .logic import fuzzy_and
>>> from .. import Dummy

If you had a list of objects to test the commutivity of and you want the fuzzy_and logic applied, passing an iterator will allow the commutativity to only be computed as many times as necessary. With this list, False can be returned after analyzing the first symbol:

>>> syms = [Dummy(commutative=False), Dummy()]
>>> fuzzy_and(s.is_commutative for s in syms)
False

That False would require less work than if a list of pre-computed items was sent:

>>> fuzzy_and([s.is_commutative for s in syms])
False
modelparameters.sympy.core.logic.fuzzy_bool(x)[source]

Return True, False or None according to x.

Whereas bool(x) returns True or False, fuzzy_bool allows for the None value and non-false values (which become None), too.

Examples

>>> from .logic import fuzzy_bool
>>> from ..abc import x
>>> fuzzy_bool(x), fuzzy_bool(None)
(None, None)
>>> bool(x), bool(None)
(True, False)
modelparameters.sympy.core.logic.fuzzy_not(v)[source]

Not in fuzzy logic

Return None if v is None else not v.

Examples

>>> from .logic import fuzzy_not
>>> fuzzy_not(True)
False
>>> fuzzy_not(None)
>>> fuzzy_not(False)
True
modelparameters.sympy.core.logic.fuzzy_or(args)[source]

Or in fuzzy logic. Returns True (any True), False (all False), or None

See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is related to the two by the standard De Morgan’s law.

>>> from .logic import fuzzy_or
>>> fuzzy_or([True, False])
True
>>> fuzzy_or([True, None])
True
>>> fuzzy_or([False, False])
False
>>> print(fuzzy_or([False, None]))
None

modelparameters.sympy.core.mod module

class modelparameters.sympy.core.mod.Mod(p, q)[source]

Bases: Function

Represents a modulo operation on symbolic expressions.

Receives two arguments, dividend p and divisor q.

The convention used is the same as Python’s: the remainder always has the same sign as the divisor.

Examples

>>> from ..abc import x, y
>>> x**2 % y
Mod(x**2, y)
>>> _.subs({x: 5, y: 6})
1
default_assumptions = {}
classmethod eval(p, q)[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)

modelparameters.sympy.core.mul module

class modelparameters.sympy.core.mul.Mul(*args, **options)[source]

Bases: Expr, AssocOp

as_base_exp()[source]
as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a product.

as_coeff_mul(*deps, **kwargs)[source]

Return the tuple (c, args) where self is written as a Mul, m.

c should be a Rational multiplied by any factors of the Mul that are independent of deps.

args should be a tuple of all other factors of m; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you don’t know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul.

  • if you know self is a Mul and want only the head, use self.args[0];

  • if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail;

  • if you want to split self into an independent and dependent parts use self.as_independent(*deps)

>>> from .. import S
>>> from ..abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())
as_coefficients_dict()[source]

Return a dictionary mapping terms to their coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. The dictionary is considered to have a single term.

Examples

>>> from ..abc import a, x
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
>>> _[a]
0
as_content_primitive(radical=False, clear=True)[source]

Return the tuple (R, self/R) where R is the positive Rational extracted from self.

Examples

>>> from .. import sqrt
>>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
(6, -sqrt(2)*(-sqrt(2) + 1))

See docstring of Expr.as_content_primitive for more examples.

as_numer_denom()[source]

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

See also

normal

return a/b instead of a, b

as_ordered_factors(order=None)[source]

Transform an expression into an ordered list of factors.

Examples

>>> from .. import sin, cos
>>> from ..abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
[2, x, y, sin(x), cos(x)]
as_powers_dict()[source]

Return self as a dictionary of factors with each factor being treated as a power. The keys are the bases of the factors and the values, the corresponding exponents. The resulting dictionary should be used with caution if the expression is a Mul and contains non- commutative factors since the order that they appeared will be lost in the dictionary.

as_real_imag(deep=True, **hints)[source]

Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method can’t be confused with re() and im() functions, which does not perform complex expansion at evaluation.

However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.

>>> from .. import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from ..abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
as_two_terms()[source]

Return head and tail of self.

This is the most efficient way to get the head and tail of an expression.

  • if you want only the head, use self.args[0];

  • if you want to process the arguments of the tail then use self.as_coef_mul() which gives the head and a tuple containing the arguments of the tail when treated as a Mul.

  • if you want the coefficient when self is treated as an Add then use self.as_coeff_add()[0]

>>> from ..abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)
classmethod class_key()[source]

Nice order of classes.

default_assumptions = {}
classmethod flatten(seq)[source]

Return commutative, noncommutative and order arguments by combining related terms.

Notes

  • In an expression like a*b*c, python process this through sympy as Mul(Mul(a, b), c). This can have undesirable consequences.

    >>> from .. import Mul, sqrt
    >>> from ..abc import x, y, z
    >>> 2*(x + 1) # this is the 2-arg Mul behavior
    2*x + 2
    >>> y*(x + 1)*2
    2*y*(x + 1)
    >>> 2*(x + 1)*y # 2-arg result will be obtained first
    y*(2*x + 2)
    >>> Mul(2, x + 1, y) # all 3 args simultaneously processed
    2*y*(x + 1)
    >>> 2*((x + 1)*y) # parentheses can control this behavior
    2*y*(x + 1)
    

    Powers with compound bases may not find a single base to combine with unless all arguments are processed at once. Post-processing may be necessary in such cases. {c.f. https://github.com/sympy/sympy/issues/5728}

    >>> a = sqrt(x*sqrt(y))
    >>> a**3
    (x*sqrt(y))**(3/2)
    >>> Mul(a,a,a)
    (x*sqrt(y))**(3/2)
    >>> a*a*a
    x*sqrt(y)*sqrt(x*sqrt(y))
    >>> _.subs(a.base, z).subs(z, a.base)
    (x*sqrt(y))**(3/2)
    
    • If more than two terms are being multiplied then all the previous terms will be re-processed for each new argument. So if each of a, b and c were Mul expression, then a*b*c (or building up the product with *=) will process all the arguments of a and b twice: once when a*b is computed and again when c is multiplied.

      Using Mul(a, b, c) will process all arguments once.

  • The results of Mul are cached according to arguments, so flatten will only be called once for Mul(a, b, c). If you can structure a calculation so the arguments are most likely to be repeats then this can save time in computing the answer. For example, say you had a Mul, M, that you wished to divide by d[i] and multiply by n[i] and you suspect there are many repeats in n. It would be better to compute M*n[i]/d[i] rather than M/d[i]*n[i] since every time n[i] is a repeat, the product, M*n[i] will be returned without flattening – the cached value will be returned. If you divide by the d[i] first (and those are more unique than the n[i]) then that will create a new Mul, M/d[i] the args of which will be traversed again when it is multiplied by n[i].

    {c.f. https://github.com/sympy/sympy/issues/5706}

    This consideration is moot if the cache is turned off.

NB

The validity of the above notes depends on the implementation details of Mul and flatten which may change at any time. Therefore, you should only consider them when your code is highly performance sensitive.

Removal of 1 from the sequence is already handled by AssocOp.__new__.

identity = 1
is_Mul = True
matches(expr, repl_dict={}, old=False)[source]

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

Examples

>>> from .. import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
class modelparameters.sympy.core.mul.NC_Marker[source]

Bases: object

is_Mul = False
is_Number = False
is_Order = False
is_Poly = False
is_commutative = False
modelparameters.sympy.core.mul.expand_2arg(e)[source]
modelparameters.sympy.core.mul.prod(a, start=1)[source]
Return product of elements of a. Start with int 1 so if only

ints are included then an int result is returned.

Examples

>>> from .. import prod, S
>>> prod(range(3))
0
>>> type(_) is int
True
>>> prod([S(2), 3])
6
>>> _.is_Integer
True

You can start the product at something other than 1:

>>> prod([1, 2], 3)
6

modelparameters.sympy.core.multidimensional module

Provides functionality for multidimensional usage of scalar-functions.

Read the vectorize docstring for more details.

modelparameters.sympy.core.multidimensional.apply_on_element(f, args, kwargs, n)[source]

Returns a structure with the same dimension as the specified argument, where each basic element is replaced by the function f applied on it. All other arguments stay the same.

modelparameters.sympy.core.multidimensional.iter_copy(structure)[source]

Returns a copy of an iterable object (also copying all embedded iterables).

modelparameters.sympy.core.multidimensional.structure_copy(structure)[source]

Returns a copy of the given structure (numpy-array, list, iterable, ..).

class modelparameters.sympy.core.multidimensional.vectorize(*mdargs)[source]

Bases: object

Generalizes a function taking scalars to accept multidimensional arguments.

For example

>>> from .. import diff, sin, symbols, Function
>>> from .multidimensional import vectorize
>>> x, y, z = symbols('x y z')
>>> f, g, h = list(map(Function, 'fgh'))
>>> @vectorize(0)
... def vsin(x):
...     return sin(x)
>>> vsin([1, x, y])
[sin(1), sin(x), sin(y)]
>>> @vectorize(0, 1)
... def vdiff(f, y):
...     return diff(f, y)
>>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z])
[[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]]

modelparameters.sympy.core.numbers module

class modelparameters.sympy.core.numbers.AlgebraicNumber(expr, coeffs=None, alias=None, **args)[source]

Bases: Expr

Class for representing algebraic numbers in SymPy.

alias
as_expr(x=None)[source]

Create a Basic expression from self.

as_poly(x=None)[source]

Create a Poly instance from self.

coeffs()[source]

Returns all SymPy coefficients of an algebraic number.

default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'transcendental': False}
is_AlgebraicNumber = True
is_algebraic = True
property is_aliased

Returns True if alias was set.

is_commutative = True
is_complex = True
is_number = True
is_transcendental = False
minpoly
native_coeffs()[source]

Returns all native coefficients of an algebraic number.

rep
root
to_algebraic_integer()[source]

Convert self to an algebraic integer.

class modelparameters.sympy.core.numbers.Catalan(*args, **kwargs)[source]

Bases: NumberSymbol

Catalan’s constant.

K = 0.91596559ldots is given by the infinite series

\[K = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}\]

Catalan is a singleton, and can be accessed by S.Catalan.

Examples

>>> from .. import S
>>> S.Catalan.is_irrational
>>> S.Catalan > 0
True
>>> S.Catalan > 1
False

References

approximation_interval(number_cls)[source]
default_assumptions = {'commutative': True, 'complex': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'irrational': None, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True, 'zero': False}
is_commutative = True
is_complex = True
is_finite = True
is_hermitian = True
is_imaginary = False
is_infinite = False
is_irrational = None
is_negative = False
is_nonnegative = True
is_nonpositive = False
is_nonzero = True
is_number = True
is_positive = True
is_real = True
is_zero = False
class modelparameters.sympy.core.numbers.ComplexInfinity(*args, **kwargs)[source]

Bases: AtomicExpr

Complex infinity.

In complex analysis the symbol tildeinfty, called “complex infinity”, represents a quantity with infinite magnitude, but undetermined complex phase.

ComplexInfinity is a singleton, and can be accessed by S.ComplexInfinity, or can be imported as zoo.

Examples

>>> from .. import zoo, oo
>>> zoo + 42
zoo
>>> 42/zoo
0
>>> zoo + zoo
nan
>>> zoo*zoo
zoo

See also

Infinity

ceiling()[source]
default_assumptions = {'commutative': True, 'finite': False, 'infinite': True, 'prime': False, 'zero': False}
floor()[source]
is_commutative = True
is_finite = False
is_infinite = True
is_number = True
is_prime = False
is_zero = False
class modelparameters.sympy.core.numbers.EulerGamma(*args, **kwargs)[source]

Bases: NumberSymbol

The Euler-Mascheroni constant.

gamma = 0.5772157ldots (also called Euler’s constant) is a mathematical constant recurring in analysis and number theory. It is defined as the limiting difference between the harmonic series and the natural logarithm:

\[\gamma = \lim\limits_{n\to\infty} \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)\]

EulerGamma is a singleton, and can be accessed by S.EulerGamma.

Examples

>>> from .. import S
>>> S.EulerGamma.is_irrational
>>> S.EulerGamma > 0
True
>>> S.EulerGamma > 1
False

References

approximation_interval(number_cls)[source]
default_assumptions = {'commutative': True, 'complex': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'irrational': None, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True, 'zero': False}
is_commutative = True
is_complex = True
is_finite = True
is_hermitian = True
is_imaginary = False
is_infinite = False
is_irrational = None
is_negative = False
is_nonnegative = True
is_nonpositive = False
is_nonzero = True
is_number = True
is_positive = True
is_real = True
is_zero = False
class modelparameters.sympy.core.numbers.Exp1(*args, **kwargs)[source]

Bases: NumberSymbol

The e constant.

The transcendental number e = 2.718281828ldots is the base of the natural logarithm and of the exponential function, e = exp(1). Sometimes called Euler’s number or Napier’s constant.

Exp1 is a singleton, and can be accessed by S.Exp1, or can be imported as E.

Examples

>>> from .. import exp, log, E
>>> E is exp(1)
True
>>> log(E)
1

References

approximation_interval(number_cls)[source]
default_assumptions = {'algebraic': False, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'integer': False, 'irrational': True, 'negative': False, 'noninteger': True, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'odd': False, 'positive': True, 'prime': False, 'rational': False, 'real': True, 'transcendental': True, 'zero': False}
is_algebraic = False
is_commutative = True
is_complex = True
is_composite = False
is_even = False
is_finite = True
is_hermitian = True
is_imaginary = False
is_infinite = False
is_integer = False
is_irrational = True
is_negative = False
is_noninteger = True
is_nonnegative = True
is_nonpositive = False
is_nonzero = True
is_number = True
is_odd = False
is_positive = True
is_prime = False
is_rational = False
is_real = True
is_transcendental = True
is_zero = False
class modelparameters.sympy.core.numbers.Float(num, dps=None, prec=None, precision=None)[source]

Bases: Number

Represent a floating-point number of arbitrary precision.

Examples

>>> from .. import Float
>>> Float(3.5)
3.50000000000000
>>> Float(3)
3.00000000000000

Creating Floats from strings (and Python int and long types) will give a minimum precision of 15 digits, but the precision will automatically increase to capture all digits entered.

>>> Float(1)
1.00000000000000
>>> Float(10**20)
100000000000000000000.
>>> Float('1e20')
100000000000000000000.

However, floating-point numbers (Python float types) retain only 15 digits of precision:

>>> Float(1e20)
1.00000000000000e+20
>>> Float(1.23456789123456789)
1.23456789123457

It may be preferable to enter high-precision decimal numbers as strings:

Float(‘1.23456789123456789’) 1.23456789123456789

The desired number of digits can also be specified:

>>> Float('1e-3', 3)
0.00100
>>> Float(100, 4)
100.0

Float can automatically count significant figures if a null string is sent for the precision; space are also allowed in the string. (Auto- counting is only allowed for strings, ints and longs).

>>> Float('123 456 789 . 123 456', '')
123456789.123456
>>> Float('12e-3', '')
0.012
>>> Float(3, '')
3.

If a number is written in scientific notation, only the digits before the exponent are considered significant if a decimal appears, otherwise the “e” signifies only how to move the decimal:

>>> Float('60.e2', '')  # 2 digits significant
6.0e+3
>>> Float('60e2', '')  # 4 digits significant
6000.
>>> Float('600e-2', '')  # 3 digits significant
6.00

Notes

Floats are inexact by their nature unless their value is a binary-exact value.

>>> approx, exact = Float(.1, 1), Float(.125, 1)

For calculation purposes, evalf needs to be able to change the precision but this will not increase the accuracy of the inexact value. The following is the most accurate 5-digit approximation of a value of 0.1 that had only 1 digit of precision:

>>> approx.evalf(5)
0.099609

By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float or evalf to obtain an arbitrary precision with matching accuracy:

>>> Float(exact, 5)
0.12500
>>> exact.evalf(20)
0.12500000000000000000

Trying to make a high-precision Float from a float is not disallowed, but one must keep in mind that the underlying float (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros:

>>> Float(0.3, 20)
0.29999999999999998890

If you want a 20-digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python’s float is used:

>>> Float('0.3', 20)
0.30000000000000000000

Although you can increase the precision of an existing Float using Float it will not increase the accuracy – the underlying value is not changed:

>>> def show(f): # binary rep of Float
...     from .. import Mul, Pow
...     s, m, e, b = f._mpf_
...     v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False)
...     print('%s at prec=%s' % (v, f._prec))
...
>>> t = Float('0.3', 3)
>>> show(t)
4915/2**14 at prec=13
>>> show(Float(t, 20)) # higher prec, not higher accuracy
4915/2**14 at prec=70
>>> show(Float(t, 2)) # lower prec
307/2**10 at prec=10

The same thing happens when evalf is used on a Float:

>>> show(t.evalf(20))
4915/2**14 at prec=70
>>> show(t.evalf(2))
307/2**10 at prec=10

Finally, Floats can be instantiated with an mpf tuple (n, c, p) to produce the number (-1)**n*c*2**p:

>>> n, c, p = 1, 5, 0
>>> (-1)**n*c*2**p
-5
>>> Float((1, 5, 0))
-5.00000000000000

An actual mpf tuple also contains the number of bits in c as the last element of the tuple:

>>> _._mpf_
(1, 5, 0, 3)

This is not needed for instantiation and is not the same thing as the precision. The mpf tuple and the precision are two separate quantities that Float tracks.

ceiling()[source]
default_assumptions = {'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'irrational': None, 'rational': None, 'real': True}
epsilon_eq(other, epsilon='1e-15')[source]
floor()[source]
is_Float = True
is_commutative = True
is_complex = True
is_hermitian = True
is_imaginary = False
is_irrational = None
is_number = True
is_rational = None
is_real = True
property num
class modelparameters.sympy.core.numbers.GoldenRatio(*args, **kwargs)[source]

Bases: NumberSymbol

The golden ratio, phi.

phi = frac{1 + sqrt{5}}{2} is algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum.

GoldenRatio is a singleton, and can be accessed by S.GoldenRatio.

Examples

>>> from .. import S
>>> S.GoldenRatio > 1
True
>>> S.GoldenRatio.expand(func=True)
1/2 + sqrt(5)/2
>>> S.GoldenRatio.is_irrational
True

References

approximation_interval(number_cls)[source]
default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'integer': False, 'irrational': True, 'negative': False, 'noninteger': True, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'odd': False, 'positive': True, 'prime': False, 'rational': False, 'real': True, 'transcendental': False, 'zero': False}
is_algebraic = True
is_commutative = True
is_complex = True
is_composite = False
is_even = False
is_finite = True
is_hermitian = True
is_imaginary = False
is_infinite = False
is_integer = False
is_irrational = True
is_negative = False
is_noninteger = True
is_nonnegative = True
is_nonpositive = False
is_nonzero = True
is_number = True
is_odd = False
is_positive = True
is_prime = False
is_rational = False
is_real = True
is_transcendental = False
is_zero = False
class modelparameters.sympy.core.numbers.Half(*args, **kwargs)[source]

Bases: RationalConstant

The rational number 1/2.

Half is a singleton, and can be accessed by S.Half.

Examples

>>> from .. import S, Rational
>>> Rational(1, 2) is S.Half
True

References

default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'hermitian': True, 'imaginary': False, 'integer': False, 'irrational': False, 'noninteger': True, 'nonzero': True, 'odd': False, 'prime': False, 'rational': True, 'real': True, 'transcendental': False, 'zero': False}
is_algebraic = True
is_commutative = True
is_complex = True
is_composite = False
is_even = False
is_hermitian = True
is_imaginary = False
is_integer = False
is_irrational = False
is_noninteger = True
is_nonzero = True
is_number = True
is_odd = False
is_prime = False
is_rational = True
is_real = True
is_transcendental = False
is_zero = False
p = 1
q = 2
class modelparameters.sympy.core.numbers.ImaginaryUnit(*args, **kwargs)[source]

Bases: AtomicExpr

The imaginary unit, i = sqrt{-1}.

I is a singleton, and can be accessed by S.I, or can be imported as I.

Examples

>>> from .. import I, sqrt
>>> sqrt(-1)
I
>>> I*I
-1
>>> 1/I
-I

References

as_base_exp()[source]
default_assumptions = {'algebraic': True, 'antihermitian': True, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'finite': True, 'imaginary': True, 'infinite': False, 'integer': False, 'irrational': False, 'negative': False, 'noninteger': False, 'nonnegative': False, 'nonpositive': False, 'nonzero': False, 'odd': False, 'positive': False, 'prime': False, 'rational': False, 'real': False, 'transcendental': False, 'zero': False}
is_algebraic = True
is_antihermitian = True
is_commutative = True
is_complex = True
is_composite = False
is_even = False
is_finite = True
is_imaginary = True
is_infinite = False
is_integer = False
is_irrational = False
is_negative = False
is_noninteger = False
is_nonnegative = False
is_nonpositive = False
is_nonzero = False
is_number = True
is_odd = False
is_positive = False
is_prime = False
is_rational = False
is_real = False
is_transcendental = False
is_zero = False
class modelparameters.sympy.core.numbers.Infinity(*args, **kwargs)[source]

Bases: Number

Positive infinite quantity.

In real analysis the symbol infty denotes an unbounded limit: xtoinfty means that x grows without bound.

Infinity is often used not only to define a limit but as a value in the affinely extended real number system. Points labeled +infty and -infty can be added to the topological space of the real numbers, producing the two-point compactification of the real numbers. Adding algebraic properties to this gives us the extended real numbers.

Infinity is a singleton, and can be accessed by S.Infinity, or can be imported as oo.

Examples

>>> from .. import oo, exp, limit, Symbol
>>> 1 + oo
oo
>>> 42/oo
0
>>> x = Symbol('x')
>>> limit(exp(x), x, oo)
oo

See also

NegativeInfinity, NaN

References

ceiling()[source]
default_assumptions = {'commutative': True, 'complex': True, 'finite': False, 'hermitian': True, 'imaginary': False, 'infinite': True, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'prime': False, 'real': True, 'zero': False}
floor()[source]
is_commutative = True
is_complex = True
is_finite = False
is_hermitian = True
is_imaginary = False
is_infinite = True
is_negative = False
is_nonnegative = True
is_nonpositive = False
is_nonzero = True
is_number = True
is_positive = True
is_prime = False
is_real = True
is_zero = False
class modelparameters.sympy.core.numbers.Integer(i)[source]

Bases: Rational

as_numer_denom()[source]

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

See also

normal

return a/b instead of a, b

ceiling()[source]
default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'integer': True, 'irrational': False, 'noninteger': False, 'rational': True, 'real': True, 'transcendental': False}
floor()[source]
is_Integer = True
is_algebraic = True
is_commutative = True
is_complex = True
property is_composite

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

property is_even

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

is_hermitian = True
is_imaginary = False
is_integer = True
is_irrational = False
is_noninteger = False
property is_nonzero

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

is_number = True
property is_odd

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

property is_prime

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

is_rational = True
is_real = True
is_transcendental = False
property is_zero

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

p
q = 1
class modelparameters.sympy.core.numbers.IntegerConstant[source]

Bases: Integer

default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'integer': True, 'irrational': False, 'noninteger': False, 'rational': True, 'real': True, 'transcendental': False}
is_algebraic = True
is_commutative = True
is_complex = True
is_hermitian = True
is_imaginary = False
is_integer = True
is_irrational = False
is_noninteger = False
is_rational = True
is_real = True
is_transcendental = False
class modelparameters.sympy.core.numbers.NaN(*args, **kwargs)[source]

Bases: Number

Not a Number.

This serves as a place holder for numeric values that are indeterminate. Most operations on NaN, produce another NaN. Most indeterminate forms, such as 0/0 or oo - oo` produce NaN.  Two exceptions are ``0**0 and oo**0, which all produce 1 (this is consistent with Python’s float).

NaN is loosely related to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python float('nan'). Differences are noted below.

NaN is mathematically not equal to anything else, even NaN itself. This explains the initially counter-intuitive results with Eq and == in the examples below.

NaN is not comparable so inequalities raise a TypeError. This is in constrast with floating point nan where all inequalities are false.

NaN is a singleton, and can be accessed by S.NaN, or can be imported as nan.

Examples

>>> from .. import nan, S, oo, Eq
>>> nan is S.NaN
True
>>> oo - oo
nan
>>> nan + 1
nan
>>> Eq(nan, nan)   # mathematical equality
False
>>> nan == nan     # structural equality
True

References

ceiling()[source]
default_assumptions = {'algebraic': None, 'commutative': True, 'finite': None, 'integer': None, 'negative': None, 'positive': None, 'prime': None, 'rational': None, 'real': None, 'transcendental': None, 'zero': None}
floor()[source]
is_algebraic = None
is_commutative = True
is_comparable = False
is_finite = None
is_integer = None
is_negative = None
is_number = True
is_positive = None
is_prime = None
is_rational = None
is_real = None
is_transcendental = None
is_zero = None
class modelparameters.sympy.core.numbers.NegativeInfinity(*args, **kwargs)[source]

Bases: Number

Negative infinite quantity.

NegativeInfinity is a singleton, and can be accessed by S.NegativeInfinity.

See also

Infinity

ceiling()[source]
default_assumptions = {'commutative': True, 'complex': True, 'composite': False, 'finite': False, 'hermitian': True, 'imaginary': False, 'infinite': True, 'negative': True, 'nonnegative': False, 'nonpositive': True, 'nonzero': True, 'positive': False, 'prime': False, 'real': True, 'zero': False}
floor()[source]
is_commutative = True
is_complex = True
is_composite = False
is_finite = False
is_hermitian = True
is_imaginary = False
is_infinite = True
is_negative = True
is_nonnegative = False
is_nonpositive = True
is_nonzero = True
is_number = True
is_positive = False
is_prime = False
is_real = True
is_zero = False
class modelparameters.sympy.core.numbers.NegativeOne(*args, **kwargs)[source]

Bases: IntegerConstant

The number negative one.

NegativeOne is a singleton, and can be accessed by S.NegativeOne.

Examples

>>> from .. import S, Integer
>>> Integer(-1) is S.NegativeOne
True

See also

One

References

default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'integer': True, 'irrational': False, 'noninteger': False, 'rational': True, 'real': True, 'transcendental': False}
is_algebraic = True
is_commutative = True
is_complex = True
is_hermitian = True
is_imaginary = False
is_integer = True
is_irrational = False
is_noninteger = False
is_number = True
is_rational = True
is_real = True
is_transcendental = False
p = -1
q = 1
class modelparameters.sympy.core.numbers.Number(*obj)[source]

Bases: AtomicExpr

Represents any kind of number in sympy.

Floating point numbers are represented by the Float class. Integer numbers (of any size), together with rational numbers (again, there is no limit on their size) are represented by the Rational class.

If you want to represent, for example, 1+sqrt(2), then you need to do:

Rational(1) + sqrt(Rational(2))
as_coeff_Add(rational=False)[source]

Efficiently extract the coefficient of a summation.

as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)[source]

Return the tuple (c, args) where self is written as an Add, a.

c should be a Rational added to any terms of the Add that are independent of deps.

args should be a tuple of all other terms of a; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you don’t know if self is an Add or not but you want to treat self as an Add or if you want to process the individual arguments of the tail of self as an Add.

  • if you know self is an Add and want only the head, use self.args[0];

  • if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail.

  • if you want to split self into an independent and dependent parts use self.as_independent(*deps)

>>> from .. import S
>>> from ..abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x).as_coeff_add()
(3, (x,))
>>> (3 + x + y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_mul(*deps, **kwargs)[source]

Return the tuple (c, args) where self is written as a Mul, m.

c should be a Rational multiplied by any factors of the Mul that are independent of deps.

args should be a tuple of all other factors of m; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you don’t know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul.

  • if you know self is a Mul and want only the head, use self.args[0];

  • if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail;

  • if you want to split self into an independent and dependent parts use self.as_independent(*deps)

>>> from .. import S
>>> from ..abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())
ceiling()[source]
classmethod class_key()[source]

Nice order of classes.

cofactors(other)[source]

Compute GCD and cofactors of self and other.

default_assumptions = {'commutative': True}
floor()[source]
gcd(other)[source]

Compute GCD of self and other.

invert(other, *gens, **args)[source]

Return the multiplicative inverse of self mod g where self (and g) may be symbolic expressions).

See also

sympy.core.numbers.mod_inverse, sympy.polys.polytools.invert

is_Number = True
is_commutative = True
is_constant(*wrt, **flags)[source]

Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.

If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, two strategies are tried:

1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if wrt is different than the free symbols.

2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.

If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag failing_number is True – in that case the numerical value will be returned.

If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.

Examples

>>> from .. import cos, sin, Sum, S, pi
>>> from ..abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
is_number = True
lcm(other)[source]

Compute LCM of self and other.

sort_key(order=None)[source]

Return a sort key.

Examples

>>> from ..core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
class modelparameters.sympy.core.numbers.NumberSymbol[source]

Bases: AtomicExpr

approximation(number_cls)[source]

Return an interval with number_cls endpoints that contains the value of NumberSymbol. If not implemented, then return None.

default_assumptions = {'commutative': True, 'finite': True, 'infinite': False}
is_NumberSymbol = True
is_commutative = True
is_finite = True
is_infinite = False
is_number = True
class modelparameters.sympy.core.numbers.One(*args, **kwargs)[source]

Bases: IntegerConstant

The number one.

One is a singleton, and can be accessed by S.One.

Examples

>>> from .. import S, Integer
>>> Integer(1) is S.One
True

References

default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'hermitian': True, 'imaginary': False, 'integer': True, 'irrational': False, 'noninteger': False, 'rational': True, 'real': True, 'transcendental': False}
static factors(limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False)[source]

A wrapper to factorint which return factors of self that are smaller than limit (or cheap to compute). Special methods of factoring are disabled by default so that only trial division is used.

is_algebraic = True
is_commutative = True
is_complex = True
is_hermitian = True
is_imaginary = False
is_integer = True
is_irrational = False
is_noninteger = False
is_number = True
is_rational = True
is_real = True
is_transcendental = False
p = 1
q = 1
class modelparameters.sympy.core.numbers.Pi(*args, **kwargs)[source]

Bases: NumberSymbol

The pi constant.

The transcendental number pi = 3.141592654ldots represents the ratio of a circle’s circumference to its diameter, the area of the unit circle, the half-period of trigonometric functions, and many other things in mathematics.

Pi is a singleton, and can be accessed by S.Pi, or can be imported as pi.

Examples

>>> from .. import S, pi, oo, sin, exp, integrate, Symbol
>>> S.Pi
pi
>>> pi > 3
True
>>> pi.is_irrational
True
>>> x = Symbol('x')
>>> sin(x + 2*pi)
sin(x)
>>> integrate(exp(-x**2), (x, -oo, oo))
sqrt(pi)

References

approximation_interval(number_cls)[source]
default_assumptions = {'algebraic': False, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'integer': False, 'irrational': True, 'negative': False, 'noninteger': True, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'odd': False, 'positive': True, 'prime': False, 'rational': False, 'real': True, 'transcendental': True, 'zero': False}
is_algebraic = False
is_commutative = True
is_complex = True
is_composite = False
is_even = False
is_finite = True
is_hermitian = True
is_imaginary = False
is_infinite = False
is_integer = False
is_irrational = True
is_negative = False
is_noninteger = True
is_nonnegative = True
is_nonpositive = False
is_nonzero = True
is_number = True
is_odd = False
is_positive = True
is_prime = False
is_rational = False
is_real = True
is_transcendental = True
is_zero = False
class modelparameters.sympy.core.numbers.Rational(p, q=None, gcd=None)[source]

Bases: Number

Represents integers and rational numbers (p/q) of any size.

Examples

>>> from .. import Rational, nsimplify, S, pi
>>> Rational(3)
3
>>> Rational(1, 2)
1/2

Rational is unprejudiced in accepting input. If a float is passed, the underlying value of the binary representation will be returned:

>>> Rational(.5)
1/2
>>> Rational(.2)
3602879701896397/18014398509481984

If the simpler representation of the float is desired then consider limiting the denominator to the desired value or convert the float to a string (which is roughly equivalent to limiting the denominator to 10**12):

>>> Rational(str(.2))
1/5
>>> Rational(.2).limit_denominator(10**12)
1/5

An arbitrarily precise Rational is obtained when a string literal is passed:

>>> Rational("1.23")
123/100
>>> Rational('1e-2')
1/100
>>> Rational(".1")
1/10
>>> Rational('1e-2/3.2')
1/320

The conversion of other types of strings can be handled by the sympify() function, and conversion of floats to expressions or simple fractions can be handled with nsimplify:

>>> S('.[3]')  # repeating digits in brackets
1/3
>>> S('3**2/10')  # general expressions
9/10
>>> nsimplify(.3)  # numbers that have a simple form
3/10

But if the input does not reduce to a literal Rational, an error will be raised:

>>> Rational(pi)
Traceback (most recent call last):
...
TypeError: invalid input: pi

Low-level

Access numerator and denominator as .p and .q:

>>> r = Rational(3, 4)
>>> r
3/4
>>> r.p
3
>>> r.q
4

Note that p and q return integers (not SymPy Integers) so some care is needed when using them in expressions:

>>> r.p/r.q
0.75

See also

sympify, sympy.simplify.simplify.nsimplify

as_coeff_Add(rational=False)[source]

Efficiently extract the coefficient of a summation.

as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a product.

as_content_primitive(radical=False, clear=True)[source]

Return the tuple (R, self/R) where R is the positive Rational extracted from self.

Examples

>>> from .. import S
>>> (S(-3)/2).as_content_primitive()
(3/2, -1)

See docstring of Expr.as_content_primitive for more examples.

as_numer_denom()[source]

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

See also

normal

return a/b instead of a, b

ceiling()[source]
default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'hermitian': True, 'imaginary': False, 'integer': False, 'irrational': False, 'noninteger': True, 'nonzero': True, 'odd': False, 'prime': False, 'rational': True, 'real': True, 'transcendental': False, 'zero': False}
factors(limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False)[source]

A wrapper to factorint which return factors of self that are smaller than limit (or cheap to compute). Special methods of factoring are disabled by default so that only trial division is used.

floor()[source]
gcd(other)[source]

Compute GCD of self and other.

is_Rational = True
is_algebraic = True
is_commutative = True
is_complex = True
is_composite = False
is_even = False
is_hermitian = True
is_imaginary = False
is_integer = False
is_irrational = False
is_noninteger = True
is_nonzero = True
is_number = True
is_odd = False
is_prime = False
is_rational = True
is_real = True
is_transcendental = False
is_zero = False
lcm(other)[source]

Compute LCM of self and other.

limit_denominator(max_denominator=1000000)[source]

Closest Rational to self with denominator at most max_denominator.

>>> from .. import Rational
>>> Rational('3.141592653589793').limit_denominator(10)
22/7
>>> Rational('3.141592653589793').limit_denominator(100)
311/99
p
q
class modelparameters.sympy.core.numbers.RationalConstant[source]

Bases: Rational

Abstract base class for rationals with specific behaviors

Derived classes must define class attributes p and q and should probably all be singletons.

default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'hermitian': True, 'imaginary': False, 'integer': False, 'irrational': False, 'noninteger': True, 'nonzero': True, 'odd': False, 'prime': False, 'rational': True, 'real': True, 'transcendental': False, 'zero': False}
is_algebraic = True
is_commutative = True
is_complex = True
is_composite = False
is_even = False
is_hermitian = True
is_imaginary = False
is_integer = False
is_irrational = False
is_noninteger = True
is_nonzero = True
is_odd = False
is_prime = False
is_rational = True
is_real = True
is_transcendental = False
is_zero = False
modelparameters.sympy.core.numbers.RealNumber

alias of Float

class modelparameters.sympy.core.numbers.Zero(*args, **kwargs)[source]

Bases: IntegerConstant

The number zero.

Zero is a singleton, and can be accessed by S.Zero

Examples

>>> from .. import S, Integer, zoo
>>> Integer(0) is S.Zero
True
>>> 1/S.Zero
zoo

References

as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a summation.

default_assumptions = {'algebraic': True, 'commutative': True, 'complex': True, 'composite': False, 'even': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'integer': True, 'irrational': False, 'negative': False, 'noninteger': False, 'nonnegative': True, 'nonpositive': True, 'nonzero': False, 'odd': False, 'positive': False, 'prime': False, 'rational': True, 'real': True, 'transcendental': False, 'zero': True}
is_algebraic = True
is_commutative = True
is_complex = True
is_composite = False
is_even = True
is_finite = True
is_hermitian = True
is_imaginary = False
is_infinite = False
is_integer = True
is_irrational = False
is_negative = False
is_noninteger = False
is_nonnegative = True
is_nonpositive = True
is_nonzero = False
is_number = True
is_odd = False
is_positive = False
is_prime = False
is_rational = True
is_real = True
is_transcendental = False
is_zero = True
p = 0
q = 1
modelparameters.sympy.core.numbers.comp(z1, z2, tol=None)[source]

Return a bool indicating whether the error between z1 and z2 is <= tol.

If tol is None then True will be returned if there is a significant difference between the numbers: abs(z1 - z2)*10**p <= 1/2 where p is the lower of the precisions of the values. A comparison of strings will be made if z1 is a Number and a) z2 is a string or b) tol is ‘’ and z2 is a Number.

When tol is a nonzero value, if z2 is non-zero and |z1| > 1 the error is normalized by |z1|, so if you want to see if the absolute error between z1 and z2 is <= tol then call this as comp(z1 - z2, 0, tol).

modelparameters.sympy.core.numbers.igcd(*args)[source]

Computes nonnegative integer greatest common divisor.

The algorithm is based on the well known Euclid’s algorithm. To improve speed, igcd() has its own caching mechanism implemented.

Examples

>>> from .numbers import igcd
>>> igcd(2, 4)
2
>>> igcd(5, 10, 15)
5
modelparameters.sympy.core.numbers.igcd_lehmer(a, b)[source]

Computes greatest common divisor of two integers.

Euclid’s algorithm for the computation of the greatest common divisor gcd(a, b) of two (positive) integers a and b is based on the division identity

a = q*b + r,

where the quotient q and the remainder r are integers and 0 <= r < b. Then each common divisor of a and b divides r, and it follows that gcd(a, b) == gcd(b, r). The algorithm works by constructing the sequence r0, r1, r2, …, where r0 = a, r1 = b, and each rn is the remainder from the division of the two preceding elements.

In Python, q = a // b and r = a % b are obtained by the floor division and the remainder operations, respectively. These are the most expensive arithmetic operations, especially for large a and b.

Lehmer’s algorithm is based on the observation that the quotients qn = r(n-1) // rn are in general small integers even when a and b are very large. Hence the quotients can be usually determined from a relatively small number of most significant bits.

The efficiency of the algorithm is further enhanced by not computing each long remainder in Euclid’s sequence. The remainders are linear combinations of a and b with integer coefficients derived from the quotients. The coefficients can be computed as far as the quotients can be determined from the chosen most significant parts of a and b. Only then a new pair of consecutive remainders is computed and the algorithm starts anew with this pair.

References

modelparameters.sympy.core.numbers.igcdex(a, b)[source]

Returns x, y, g such that g = x*a + y*b = gcd(a, b).

>>> from .numbers import igcdex
>>> igcdex(2, 3)
(-1, 1, 1)
>>> igcdex(10, 12)
(-1, 1, 2)
>>> x, y, g = igcdex(100, 2004)
>>> x, y, g
(-20, 1, 4)
>>> x*100 + y*2004
4
modelparameters.sympy.core.numbers.ilcm(*args)[source]

Computes integer least common multiple.

Examples

>>> from .numbers import ilcm
>>> ilcm(5, 10)
10
>>> ilcm(7, 3)
21
>>> ilcm(5, 10, 15)
30
modelparameters.sympy.core.numbers.int_trace(f)[source]
modelparameters.sympy.core.numbers.mod_inverse(a, m)[source]

Return the number c such that, ( a * c ) % m == 1 where c has the same sign as a. If no such value exists, a ValueError is raised.

Examples

>>> from .. import S
>>> from .numbers import mod_inverse

Suppose we wish to find multiplicative inverse x of 3 modulo 11. This is the same as finding x such that 3 * x = 1 (mod 11). One value of x that satisfies this congruence is 4. Because 3 * 4 = 12 and 12 = 1 mod(11). This is the value return by mod_inverse:

>>> mod_inverse(3, 11)
4
>>> mod_inverse(-3, 11)
-4

When there is a common factor between the numerators of a and m the inverse does not exist:

>>> mod_inverse(2, 4)
Traceback (most recent call last):
...
ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2)
7/2

References

modelparameters.sympy.core.numbers.mpf_norm(mpf, prec)[source]

Return the mpf tuple normalized appropriately for the indicated precision after doing a check to see if zero should be returned or not when the mantissa is 0. mpf_normlize always assumes that this is zero, but it may not be since the mantissa for mpf’s values “+inf”, “-inf” and “nan” have a mantissa of zero, too.

Note: this is not intended to validate a given mpf tuple, so sending mpf tuples that were not created by mpmath may produce bad results. This is only a wrapper to mpf_normalize which provides the check for non- zero mpfs that have a 0 for the mantissa.

modelparameters.sympy.core.numbers.seterr(divide=False)[source]

Should sympy raise an exception on 0/0 or return a nan?

divide == True …. raise an exception divide == False … return nan

modelparameters.sympy.core.numbers.sympify_complex(a)[source]
modelparameters.sympy.core.numbers.sympify_fractions(f)[source]
modelparameters.sympy.core.numbers.sympify_mpmath(x)[source]

modelparameters.sympy.core.operations module

class modelparameters.sympy.core.operations.AssocOp(*args, **options)[source]

Bases: Basic

Associative operations, can separate noncommutative and commutative parts.

(a op b) op c == a op (b op c) == a op b op c.

Base class for Add and Mul.

This is an abstract base class, concrete derived classes must define the attribute identity.

default_assumptions = {}
classmethod flatten(seq)[source]

Return seq so that none of the elements are of type cls. This is the vanilla routine that will be used if a class derived from AssocOp does not define its own flatten routine.

is_commutative
classmethod make_args(expr)[source]

Return a sequence of elements args such that cls(*args) == expr

>>> from .. import Symbol, Mul, Add
>>> x, y = map(Symbol, 'xy')
>>> Mul.make_args(x*y)
(x, y)
>>> Add.make_args(x*y)
(x*y,)
>>> set(Add.make_args(x*y + y)) == set([y, x*y])
True
class modelparameters.sympy.core.operations.LatticeOp(*args, **options)[source]

Bases: AssocOp

Join/meet operations of an algebraic lattice[1].

These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))), commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a). Common examples are AND, OR, Union, Intersection, max or min. They have an identity element (op(identity, a) = a) and an absorbing element conventionally called zero (op(zero, a) = zero).

This is an abstract base class, concrete derived classes must declare attributes zero and identity. All defining properties are then respected.

>>> from .. import Integer
>>> from .operations import LatticeOp
>>> class my_join(LatticeOp):
...     zero = Integer(0)
...     identity = Integer(1)
>>> my_join(2, 3) == my_join(3, 2)
True
>>> my_join(2, my_join(3, 4)) == my_join(2, 3, 4)
True
>>> my_join(0, 1, 4, 2, 3, 4)
0
>>> my_join(1, 2)
2

References:

[1] - http://en.wikipedia.org/wiki/Lattice_%28order%29

property args

Returns a tuple of arguments of ‘self’.

Examples

>>> from .. import cot
>>> from ..abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y

Notes

Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

default_assumptions = {'commutative': True}
is_commutative
classmethod make_args(expr)[source]

Return a set of args such that cls(*arg_set) == expr.

exception modelparameters.sympy.core.operations.ShortCircuit[source]

Bases: Exception

modelparameters.sympy.core.power module

class modelparameters.sympy.core.power.Pow(b, e, evaluate=None)[source]

Bases: Expr

Defines the expression x**y as “x raised to a power y”

Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):

expr

value

reason

z**0

1

Although arguments over 0**0 exist, see [2].

z**1

z

(-oo)**(-1)

0

(-1)**-1

-1

S.Zero**-1

zoo

This is not strictly true, as 0**-1 may be undefined, but is convenient in some contexts where the base is assumed to be positive.

1**-1

1

oo**-1

0

0**oo

0

Because for all complex numbers z near 0, z**oo -> 0.

0**-oo

zoo

This is not strictly true, as 0**oo may be oscillating between positive and negative values or rotating in the complex plane. It is convenient, however, when the base is positive.

1**oo 1**-oo 1**zoo

nan

Because there are various cases where lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), but lim( x(t)**y(t), t) != 1. See [3].

(-1)**oo (-1)**(-oo)

nan

Because of oscillations in the limit.

oo**oo

oo

oo**-oo

0

(-oo)**oo (-oo)**-oo

nan

oo**I (-oo)**I

nan

oo**e could probably be best thought of as the limit of x**e for real x as x tends to oo. If e is I, then the limit does not exist and nan is used to indicate that.

oo**(1+I) (-oo)**(1+I)

zoo

If the real part of e is positive, then the limit of abs(x**e) is oo. So the limit value is zoo.

oo**(-1+I) -oo**(-1+I)

0

If the real part of e is negative, then the limit is 0.

Because symbolic computations are more flexible that floating point calculations and we prefer to never return an incorrect answer, we choose not to conform to all IEEE 754 conventions. This helps us avoid extra test-case code in the calculation of limits.

See also

sympy.core.numbers.Infinity, sympy.core.numbers.NegativeInfinity, sympy.core.numbers.NaN

References

as_base_exp()[source]

Return base and exp of self.

If base is 1/Integer, then return Integer, -exp. If this extra processing is not needed, the base and exp properties will give the raw arguments

Examples

>>> from .. import Pow, S
>>> p = Pow(S.Half, 2, evaluate=False)
>>> p.as_base_exp()
(2, -2)
>>> p.args
(1/2, 2)
as_content_primitive(radical=False, clear=True)[source]

Return the tuple (R, self/R) where R is the positive Rational extracted from self.

Examples

>>> from .. import sqrt
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
(2, sqrt(1 + sqrt(2)))
>>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
(1, sqrt(3)*sqrt(1 + sqrt(2)))
>>> from .. import expand_power_base, powsimp, Mul
>>> from ..abc import x, y
>>> ((2*x + 2)**2).as_content_primitive()
(4, (x + 1)**2)
>>> (4**((1 + y)/2)).as_content_primitive()
(2, 4**(y/2))
>>> (3**((1 + y)/2)).as_content_primitive()
(1, 3**((y + 1)/2))
>>> (3**((5 + y)/2)).as_content_primitive()
(9, 3**((y + 1)/2))
>>> eq = 3**(2 + 2*x)
>>> powsimp(eq) == eq
True
>>> eq.as_content_primitive()
(9, 3**(2*x))
>>> powsimp(Mul(*_))
3**(2*x + 2)
>>> eq = (2 + 2*x)**y
>>> s = expand_power_base(eq); s.is_Mul, s
(False, (2*x + 2)**y)
>>> eq.as_content_primitive()
(1, (2*(x + 1))**y)
>>> s = expand_power_base(_[1]); s.is_Mul, s
(True, 2**y*(x + 1)**y)

See docstring of Expr.as_content_primitive for more examples.

as_numer_denom()[source]

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

See also

normal

return a/b instead of a, b

as_real_imag(deep=True, **hints)[source]

Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method can’t be confused with re() and im() functions, which does not perform complex expansion at evaluation.

However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.

>>> from .. import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from ..abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
property base
classmethod class_key()[source]

Nice order of classes.

default_assumptions = {}
property exp
is_Pow = True
is_commutative
is_constant(*wrt, **flags)[source]

Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.

If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, two strategies are tried:

1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if wrt is different than the free symbols.

2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.

If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag failing_number is True – in that case the numerical value will be returned.

If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.

Examples

>>> from .. import cos, sin, Sum, S, pi
>>> from ..abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
matches(expr, repl_dict={}, old=False)[source]

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

Examples

>>> from .. import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
modelparameters.sympy.core.power.integer_nthroot(y, n)[source]

Return a tuple containing x = floor(y**(1/n)) and a boolean indicating whether the result is exact (that is, whether x**n == y).

Examples

>>> from .. import integer_nthroot
>>> integer_nthroot(16, 2)
(4, True)
>>> integer_nthroot(26, 2)
(5, False)

To simply determine if a number is a perfect square, the is_square function should be used:

>>> from ..ntheory.primetest import is_square
>>> is_square(26)
False

See also

sympy.ntheory.primetest.is_square

modelparameters.sympy.core.power.isqrt(n)[source]

Return the largest integer less than or equal to sqrt(n).

modelparameters.sympy.core.relational module

modelparameters.sympy.core.relational.Eq

alias of Equality

class modelparameters.sympy.core.relational.Equality(lhs, rhs=0, **options)[source]

Bases: Relational

An equal relation between two objects.

Represents that two objects are equal. If they can be easily shown to be definitively equal (or unequal), this will reduce to True (or False). Otherwise, the relation is maintained as an unevaluated Equality object. Use the simplify function on this object for more nontrivial evaluation of the equality relation.

As usual, the keyword argument evaluate=False can be used to prevent any evaluation.

Examples

>>> from .. import Eq, simplify, exp, cos
>>> from ..abc import x, y
>>> Eq(y, x + x**2)
Eq(y, x**2 + x)
>>> Eq(2, 5)
False
>>> Eq(2, 5, evaluate=False)
Eq(2, 5)
>>> _.doit()
False
>>> Eq(exp(x), exp(x).rewrite(cos))
Eq(exp(x), sinh(x) + cosh(x))
>>> simplify(_)
True

See also

sympy.logic.boolalg.Equivalent

for representing equality between two boolean expressions

Notes

This class is not the same as the == operator. The == operator tests for exact structural equality between two expressions; this class compares expressions mathematically.

If either object defines an _eval_Eq method, it can be used in place of the default algorithm. If lhs._eval_Eq(rhs) or rhs._eval_Eq(lhs) returns anything other than None, that return value will be substituted for the Equality. If None is returned by _eval_Eq, an Equality object will be created as usual.

default_assumptions = {}
is_Equality = True
rel_op = '=='
modelparameters.sympy.core.relational.Ge

alias of GreaterThan

class modelparameters.sympy.core.relational.GreaterThan(lhs, rhs, **options)[source]

Bases: _Greater

Class representations of inequalities.

Extended Summary

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name

Symbol

GreaterThan

(>=)

LessThan

(<=)

StrictGreaterThan

(>)

StrictLessThan

(<)

All classes take two arguments, lhs and rhs.

Signature Example

Math equivalent

GreaterThan(lhs, rhs)

lhs >= rhs

LessThan(lhs, rhs)

lhs <= rhs

StrictGreaterThan(lhs, rhs)

lhs > rhs

StrictLessThan(lhs, rhs)

lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from .. import GreaterThan, StrictGreaterThan
>>> from .. import LessThan,    StrictLessThan
>>> from .. import And, Ge, Gt, Le, Lt, Rel, S
>>> from ..abc import x, y, z
>>> from .relational import Relational
>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print(e1)
x >= 2
>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print('%s\n%s\n%s\n%s' % rels)
x >= 2
x > 2
x <= 2
x < 2

Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print(e2)
x >= 2
>>> print("e1: %s,    e2: %s" % (e1, e2))
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True

However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x >= 1
x >= 1
x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x > 1
x > 1
x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print("%s\n%s\n%s" % rels)
x <= 1
x <= 1
x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x < 1
x < 1
x < 1

Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1

If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x

The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z
Traceback (most recent call last):
...
TypeError: symbolic boolean expression has no truth value.

Due to an implementation detail or decision of Python [1]_, there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
(x < y) & (y < z)

Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [2]_):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z

Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

default_assumptions = {}
rel_op = '>='
modelparameters.sympy.core.relational.Gt

alias of StrictGreaterThan

modelparameters.sympy.core.relational.Le

alias of LessThan

class modelparameters.sympy.core.relational.LessThan(lhs, rhs, **options)[source]

Bases: _Less

Class representations of inequalities.

Extended Summary

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name

Symbol

GreaterThan

(>=)

LessThan

(<=)

StrictGreaterThan

(>)

StrictLessThan

(<)

All classes take two arguments, lhs and rhs.

Signature Example

Math equivalent

GreaterThan(lhs, rhs)

lhs >= rhs

LessThan(lhs, rhs)

lhs <= rhs

StrictGreaterThan(lhs, rhs)

lhs > rhs

StrictLessThan(lhs, rhs)

lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from .. import GreaterThan, StrictGreaterThan
>>> from .. import LessThan,    StrictLessThan
>>> from .. import And, Ge, Gt, Le, Lt, Rel, S
>>> from ..abc import x, y, z
>>> from .relational import Relational
>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print(e1)
x >= 2
>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print('%s\n%s\n%s\n%s' % rels)
x >= 2
x > 2
x <= 2
x < 2

Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print(e2)
x >= 2
>>> print("e1: %s,    e2: %s" % (e1, e2))
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True

However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x >= 1
x >= 1
x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x > 1
x > 1
x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print("%s\n%s\n%s" % rels)
x <= 1
x <= 1
x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x < 1
x < 1
x < 1

Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1

If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x

The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z
Traceback (most recent call last):
...
TypeError: symbolic boolean expression has no truth value.

Due to an implementation detail or decision of Python [1]_, there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
(x < y) & (y < z)

Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [2]_):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z

Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

default_assumptions = {}
rel_op = '<='
modelparameters.sympy.core.relational.Lt

alias of StrictLessThan

modelparameters.sympy.core.relational.Ne

alias of Unequality

modelparameters.sympy.core.relational.Rel

alias of Relational

class modelparameters.sympy.core.relational.Relational(lhs, rhs, rop=None, **assumptions)[source]

Bases: Boolean, Expr, EvalfMixin

Base class for all relation types.

Subclasses of Relational should generally be instantiated directly, but Relational can be instantiated with a valid rop value to dispatch to the appropriate subclass.

Parameters:

rop (str or None) – Indicates what subclass to instantiate. Valid values can be found in the keys of Relational.ValidRelationalOperator.

Examples

>>> from .. import Rel
>>> from ..abc import x, y
>>> Rel(y, x+x**2, '==')
Eq(y, x**2 + x)
ValidRelationOperator = {None: <class 'modelparameters.sympy.core.relational.Equality'>, '==': <class 'modelparameters.sympy.core.relational.Equality'>, 'eq': <class 'modelparameters.sympy.core.relational.Equality'>, '!=': <class 'modelparameters.sympy.core.relational.Unequality'>, '<>': <class 'modelparameters.sympy.core.relational.Unequality'>, 'ne': <class 'modelparameters.sympy.core.relational.Unequality'>, '>=': <class 'modelparameters.sympy.core.relational.GreaterThan'>, 'ge': <class 'modelparameters.sympy.core.relational.GreaterThan'>, '<=': <class 'modelparameters.sympy.core.relational.LessThan'>, 'le': <class 'modelparameters.sympy.core.relational.LessThan'>, '>': <class 'modelparameters.sympy.core.relational.StrictGreaterThan'>, 'gt': <class 'modelparameters.sympy.core.relational.StrictGreaterThan'>, '<': <class 'modelparameters.sympy.core.relational.StrictLessThan'>, 'lt': <class 'modelparameters.sympy.core.relational.StrictLessThan'>, ':=': <class 'modelparameters.sympy.codegen.ast.Assignment'>, '+=': <class 'modelparameters.sympy.codegen.ast.AddAugmentedAssignment'>, '-=': <class 'modelparameters.sympy.codegen.ast.SubAugmentedAssignment'>, '*=': <class 'modelparameters.sympy.codegen.ast.MulAugmentedAssignment'>, '/=': <class 'modelparameters.sympy.codegen.ast.DivAugmentedAssignment'>, '%=': <class 'modelparameters.sympy.codegen.ast.ModAugmentedAssignment'>}
as_set()[source]

Rewrites univariate inequality in terms of real sets

Examples

>>> from .. import Symbol, Eq
>>> x = Symbol('x', real=True)
>>> (x > 0).as_set()
Interval.open(0, oo)
>>> Eq(x, 0).as_set()
{0}
property canonical

Return a canonical form of the relational.

The rules for the canonical form, in order of decreasing priority are:
  1. Number on right if left is not a Number;

  2. Symbol on the left;

  3. Gt/Ge changed to Lt/Le;

  4. Lt/Le are unchanged;

  5. Eq and Ne get ordered args.

default_assumptions = {}
equals(other, failing_expression=False)[source]

Return True if the sides of the relationship are mathematically identical and the type of relationship is the same. If failing_expression is True, return the expression whose truth value was unknown.

is_Relational = True
property lhs

The left-hand side of the relation.

property reversed

Return the relationship with sides (and sign) reversed.

Examples

>>> from .. import Eq
>>> from ..abc import x
>>> Eq(x, 1)
Eq(x, 1)
>>> _.reversed
Eq(1, x)
>>> x < 1
x < 1
>>> _.reversed
1 > x
property rhs

The right-hand side of the relation.

class modelparameters.sympy.core.relational.StrictGreaterThan(lhs, rhs, **options)[source]

Bases: _Greater

Class representations of inequalities.

Extended Summary

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name

Symbol

GreaterThan

(>=)

LessThan

(<=)

StrictGreaterThan

(>)

StrictLessThan

(<)

All classes take two arguments, lhs and rhs.

Signature Example

Math equivalent

GreaterThan(lhs, rhs)

lhs >= rhs

LessThan(lhs, rhs)

lhs <= rhs

StrictGreaterThan(lhs, rhs)

lhs > rhs

StrictLessThan(lhs, rhs)

lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from .. import GreaterThan, StrictGreaterThan
>>> from .. import LessThan,    StrictLessThan
>>> from .. import And, Ge, Gt, Le, Lt, Rel, S
>>> from ..abc import x, y, z
>>> from .relational import Relational
>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print(e1)
x >= 2
>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print('%s\n%s\n%s\n%s' % rels)
x >= 2
x > 2
x <= 2
x < 2

Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print(e2)
x >= 2
>>> print("e1: %s,    e2: %s" % (e1, e2))
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True

However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x >= 1
x >= 1
x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x > 1
x > 1
x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print("%s\n%s\n%s" % rels)
x <= 1
x <= 1
x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x < 1
x < 1
x < 1

Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1

If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x

The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z
Traceback (most recent call last):
...
TypeError: symbolic boolean expression has no truth value.

Due to an implementation detail or decision of Python [1]_, there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
(x < y) & (y < z)

Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [2]_):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z

Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

default_assumptions = {}
rel_op = '>'
class modelparameters.sympy.core.relational.StrictLessThan(lhs, rhs, **options)[source]

Bases: _Less

Class representations of inequalities.

Extended Summary

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name

Symbol

GreaterThan

(>=)

LessThan

(<=)

StrictGreaterThan

(>)

StrictLessThan

(<)

All classes take two arguments, lhs and rhs.

Signature Example

Math equivalent

GreaterThan(lhs, rhs)

lhs >= rhs

LessThan(lhs, rhs)

lhs <= rhs

StrictGreaterThan(lhs, rhs)

lhs > rhs

StrictLessThan(lhs, rhs)

lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from .. import GreaterThan, StrictGreaterThan
>>> from .. import LessThan,    StrictLessThan
>>> from .. import And, Ge, Gt, Le, Lt, Rel, S
>>> from ..abc import x, y, z
>>> from .relational import Relational
>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print(e1)
x >= 2
>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print('%s\n%s\n%s\n%s' % rels)
x >= 2
x > 2
x <= 2
x < 2

Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print(e2)
x >= 2
>>> print("e1: %s,    e2: %s" % (e1, e2))
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True

However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x >= 1
x >= 1
x >= 1
>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x > 1
x > 1
x > 1
>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print("%s\n%s\n%s" % rels)
x <= 1
x <= 1
x <= 1
>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print('%s\n%s\n%s' % rels)
x < 1
x < 1
x < 1

Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1

If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print("%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8))
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x

The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z
Traceback (most recent call last):
...
TypeError: symbolic boolean expression has no truth value.

Due to an implementation detail or decision of Python [1]_, there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
(x < y) & (y < z)

Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [2]_):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z

Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

default_assumptions = {}
rel_op = '<'
class modelparameters.sympy.core.relational.Unequality(lhs, rhs, **options)[source]

Bases: Relational

An unequal relation between two objects.

Represents that two objects are not equal. If they can be shown to be definitively equal, this will reduce to False; if definitively unequal, this will reduce to True. Otherwise, the relation is maintained as an Unequality object.

Examples

>>> from .. import Ne
>>> from ..abc import x, y
>>> Ne(y, x+x**2)
Ne(y, x**2 + x)

See also

Equality

Notes

This class is not the same as the != operator. The != operator tests for exact structural equality between two expressions; this class compares expressions mathematically.

This class is effectively the inverse of Equality. As such, it uses the same algorithms, including any available _eval_Eq methods.

default_assumptions = {}
rel_op = '!='

modelparameters.sympy.core.rules module

Replacement rules.

class modelparameters.sympy.core.rules.Transform(transform, filter=<function Transform.<lambda>>)[source]

Bases: object

Immutable mapping that can be used as a generic transformation rule.

Parameters:
  • transform (callable) – Computes the value corresponding to any key.

  • filter (callable, optional) – If supplied, specifies which objects are in the mapping.

Examples

>>> from .rules import Transform
>>> from ..abc import x

This Transform will return, as a value, one more than the key:

>>> add1 = Transform(lambda x: x + 1)
>>> add1[1]
2
>>> add1[x]
x + 1

By default, all values are considered to be in the dictionary. If a filter is supplied, only the objects for which it returns True are considered as being in the dictionary:

>>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1)
>>> 2 in add1_odd
False
>>> add1_odd.get(2, 0)
0
>>> 3 in add1_odd
True
>>> add1_odd[3]
4
>>> add1_odd.get(3, 0)
4
get(item, default=None)[source]

modelparameters.sympy.core.singleton module

Singleton mechanism

class modelparameters.sympy.core.singleton.Singleton(*args, **kwargs)[source]

Bases: ManagedProperties

Metaclass for singleton classes.

A singleton class has only one instance which is returned every time the class is instantiated. Additionally, this instance can be accessed through the global registry object S as S.<class_name>.

Examples

>>> from .. import S, Basic
>>> from .singleton import Singleton
>>> from .compatibility import with_metaclass
>>> class MySingleton(with_metaclass(Singleton, Basic)):
...     pass
>>> Basic() is Basic()
False
>>> MySingleton() is MySingleton()
True
>>> S.MySingleton is MySingleton()
True

Notes

Instance creation is delayed until the first time the value is accessed. (SymPy versions before 1.0 would create the instance during class creation time, which would be prone to import cycles.)

This metaclass is a subclass of ManagedProperties because that is the metaclass of many classes that need to be Singletons (Python does not allow subclasses to have a different metaclass than the superclass, except the subclass may use a subclassed metaclass).

class modelparameters.sympy.core.singleton.SingletonRegistry[source]

Bases: Registry

The registry for the singleton classes (accessible as S).

This class serves as two separate things.

The first thing it is is the SingletonRegistry. Several classes in SymPy appear so often that they are singletonized, that is, using some metaprogramming they are made so that they can only be instantiated once (see the sympy.core.singleton.Singleton class for details). For instance, every time you create Integer(0), this will return the same instance, sympy.core.numbers.Zero. All singleton instances are attributes of the S object, so Integer(0) can also be accessed as S.Zero.

Singletonization offers two advantages: it saves memory, and it allows fast comparison. It saves memory because no matter how many times the singletonized objects appear in expressions in memory, they all point to the same single instance in memory. The fast comparison comes from the fact that you can use is to compare exact instances in Python (usually, you need to use == to compare things). is compares objects by memory address, and is very fast. For instance

>>> from .. import S, Integer
>>> a = Integer(0)
>>> a is S.Zero
True

For the most part, the fact that certain objects are singletonized is an implementation detail that users shouldn’t need to worry about. In SymPy library code, is comparison is often used for performance purposes The primary advantage of S for end users is the convenient access to certain instances that are otherwise difficult to type, like S.Half (instead of Rational(1, 2)).

When using is comparison, make sure the argument is sympified. For instance,

>>> 0 is S.Zero
False

This problem is not an issue when using ==, which is recommended for most use-cases:

>>> 0 == S.Zero
True

The second thing S is is a shortcut for sympy.core.sympify.sympify(). sympy.core.sympify.sympify() is the function that converts Python objects such as int(1) into SymPy objects such as Integer(1). It also converts the string form of an expression into a SymPy expression, like sympify("x**2") -> Symbol("x")**2. S(1) is the same thing as sympify(1) (basically, S.__call__ has been defined to call sympify).

This is for convenience, since S is a single letter. It’s mostly useful for defining rational numbers. Consider an expression like x + 1/2. If you enter this directly in Python, it will evaluate the 1/2 and give 0.5 (or just 0 in Python 2, because of integer division), because both arguments are ints (see also tutorial-gotchas-final-notes). However, in SymPy, you usually want the quotient of two integers to give an exact rational number. The way Python’s evaluation works, at least one side of an operator needs to be a SymPy object for the SymPy evaluation to take over. You could write this as x + Rational(1, 2), but this is a lot more typing. A shorter version is x + S(1)/2. Since S(1) returns Integer(1), the division will return a Rational type, since it will call Integer.__div__, which knows how to return a Rational.

Catalan = Catalan
ComplexInfinity = zoo
Complexes = S.Complexes
EulerGamma = EulerGamma
Exp1 = E
GoldenRatio = GoldenRatio
Half = 1/2
IdentityFunction = Lambda(_x, _x)
ImaginaryUnit = I
Infinity = oo
NaN = nan
NegativeInfinity = -oo
NegativeOne = -1
One = 1
Pi = pi
Reals = S.Reals
Zero = 0
false = False
register(cls)[source]
true = True

modelparameters.sympy.core.symbol module

class modelparameters.sympy.core.symbol.Dummy(name=None, dummy_index=None, **assumptions)[source]

Bases: Symbol

Dummy symbols are each unique, even if they have the same name:

>>> from .. import Dummy
>>> Dummy("x") == Dummy("x")
False

If a name is not supplied then a string value of an internal count will be used. This is useful when a temporary variable is needed and the name of the variable used in the expression is not important.

>>> Dummy() 
_Dummy_10
default_assumptions = {}
dummy_index
is_Dummy = True
sort_key(order=None)[source]

Return a sort key.

Examples

>>> from ..core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
class modelparameters.sympy.core.symbol.Symbol(name, **assumptions)[source]

Bases: AtomicExpr, Boolean

Assumptions:

commutative = True

You can override the default assumptions in the constructor:

>>> from .. import symbols
>>> A,B = symbols('A,B', commutative = False)
>>> bool(A*B != B*A)
True
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
True
as_dummy()[source]

Return a Dummy having the same name and same assumptions as self.

as_real_imag(deep=True, **hints)[source]

Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method can’t be confused with re() and im() functions, which does not perform complex expansion at evaluation.

However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.

>>> from .. import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from ..abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
property assumptions0

Return object type assumptions.

For example:

Symbol(‘x’, real=True) Symbol(‘x’, integer=True)

are different objects. In other words, besides Python type (Symbol in this case), the initial assumptions are also forming their typeinfo.

Examples

>>> from .. import Symbol
>>> from ..abc import x
>>> x.assumptions0
{'commutative': True}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'hermitian': True,
'imaginary': False, 'negative': False, 'nonnegative': True,
'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True,
'zero': False}
default_assumptions = {}
property free_symbols

Return from the atoms of self those which are free symbols.

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.

Any other method that uses bound variables should implement a free_symbols method.

is_Symbol = True
is_comparable = False
is_constant(*wrt, **flags)[source]

Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.

If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, two strategies are tried:

1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if wrt is different than the free symbols.

2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.

If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag failing_number is True – in that case the numerical value will be returned.

If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.

Examples

>>> from .. import cos, sin, Sum, S, pi
>>> from ..abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
is_symbol = True
name
sort_key(order=None)[source]

Return a sort key.

Examples

>>> from ..core import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
class modelparameters.sympy.core.symbol.Wild(name, exclude=(), properties=(), **assumptions)[source]

Bases: Symbol

A Wild symbol matches anything, or anything without whatever is explicitly excluded.

Examples

>>> from .. import Wild, WildFunction, cos, pi
>>> from ..abc import x, y, z
>>> a = Wild('a')
>>> x.match(a)
{a_: x}
>>> pi.match(a)
{a_: pi}
>>> (3*x**2).match(a*x)
{a_: 3*x}
>>> cos(x).match(a)
{a_: cos(x)}
>>> b = Wild('b', exclude=[x])
>>> (3*x**2).match(b*x)
>>> b.match(a)
{a_: b_}
>>> A = WildFunction('A')
>>> A.match(a)
{a_: A_}

Tips

When using Wild, be sure to use the exclude keyword to make the pattern more precise. Without the exclude pattern, you may get matches that are technically correct, but not what you wanted. For example, using the above without exclude:

>>> from .. import symbols
>>> a, b = symbols('a b', cls=Wild)
>>> (2 + 3*y).match(a*x + b*y)
{a_: 2/x, b_: 3}

This is technically correct, because (2/x)*x + 3*y == 2 + 3*y, but you probably wanted it to not match at all. The issue is that you really didn’t want a and b to include x and y, and the exclude parameter lets you specify exactly this. With the exclude parameter, the pattern will not match.

>>> a = Wild('a', exclude=[x, y])
>>> b = Wild('b', exclude=[x, y])
>>> (2 + 3*y).match(a*x + b*y)

Exclude also helps remove ambiguity from matches.

>>> E = 2*x**3*y*z
>>> a, b = symbols('a b', cls=Wild)
>>> E.match(a*b)
{a_: 2*y*z, b_: x**3}
>>> a = Wild('a', exclude=[x, y])
>>> E.match(a*b)
{a_: z, b_: 2*x**3*y}
>>> a = Wild('a', exclude=[x, y, z])
>>> E.match(a*b)
{a_: 2, b_: x**3*y*z}
default_assumptions = {}
exclude
is_Wild = True
matches(expr, repl_dict={}, old=False)[source]

Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.

Examples

>>> from .. import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
True
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
{x_: b + c}
properties
modelparameters.sympy.core.symbol.symbols(names, **args)[source]

Transform strings into instances of Symbol class.

symbols() function returns a sequence of symbols with names taken from names argument, which can be a comma or whitespace delimited string, or a sequence of strings:

>>> from .. import symbols, Function

>>> x, y, z = symbols('x,y,z')
>>> a, b, c = symbols('a b c')

The type of output is dependent on the properties of input arguments:

>>> symbols('x')
x
>>> symbols('x,')
(x,)
>>> symbols('x,y')
(x, y)
>>> symbols(('a', 'b', 'c'))
(a, b, c)
>>> symbols(['a', 'b', 'c'])
[a, b, c]
>>> symbols({'a', 'b', 'c'})
{a, b, c}

If an iterable container is needed for a single symbol, set the seq argument to True or terminate the symbol name with a comma:

>>> symbols('x', seq=True)
(x,)

To reduce typing, range syntax is supported to create indexed symbols. Ranges are indicated by a colon and the type of range is determined by the character to the right of the colon. If the character is a digit then all contiguous digits to the left are taken as the nonnegative starting value (or 0 if there is no digit left of the colon) and all contiguous digits to the right are taken as 1 greater than the ending value:

>>> symbols('x:10')
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)

>>> symbols('x5:10')
(x5, x6, x7, x8, x9)
>>> symbols('x5(:2)')
(x50, x51)

>>> symbols('x5:10,y:5')
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)

>>> symbols(('x5:10', 'y:5'))
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))

If the character to the right of the colon is a letter, then the single letter to the left (or ‘a’ if there is none) is taken as the start and all characters in the lexicographic range through the letter to the right are used as the range:

>>> symbols('x:z')
(x, y, z)
>>> symbols('x:c')  # null range
()
>>> symbols('x(:c)')
(xa, xb, xc)

>>> symbols(':c')
(a, b, c)

>>> symbols('a:d, x:z')
(a, b, c, d, x, y, z)

>>> symbols(('a:d', 'x:z'))
((a, b, c, d), (x, y, z))

Multiple ranges are supported; contiguous numerical ranges should be separated by parentheses to disambiguate the ending number of one range from the starting number of the next:

>>> symbols('x:2(1:3)')
(x01, x02, x11, x12)
>>> symbols(':3:2')  # parsing is from left to right
(00, 01, 10, 11, 20, 21)

Only one pair of parentheses surrounding ranges are removed, so to include parentheses around ranges, double them. And to include spaces, commas, or colons, escape them with a backslash:

>>> symbols('x((a:b))')
(x(a), x(b))
>>> symbols(r'x(:1\,:2)')  # or r'x((:1)\,(:2))'
(x(0,0), x(0,1))

All newly created symbols have assumptions set according to args:

>>> a = symbols('a', integer=True)
>>> a.is_integer
True

>>> x, y, z = symbols('x,y,z', real=True)
>>> x.is_real and y.is_real and z.is_real
True

Despite its name, symbols() can create symbol-like objects like instances of Function or Wild classes. To achieve this, set cls keyword argument to the desired type:

>>> symbols('f,g,h', cls=Function)
(f, g, h)

>>> type(_[0])
<class 'sympy.core.function.UndefinedFunction'>
modelparameters.sympy.core.symbol.var(names, **args)[source]

Create symbols and inject them into the global namespace.

This calls symbols() with the same arguments and puts the results into the global namespace. It’s recommended not to use var() in library code, where symbols() has to be used:

.. rubric:: Examples
>>> from .. import var
>>> var('x')
x
>>> x
x
>>> var('a,ab,abc')
(a, ab, abc)
>>> abc
abc
>>> var('x,y', real=True)
(x, y)
>>> x.is_real and y.is_real
True

See symbol() documentation for more details on what kinds of arguments can be passed to var().

modelparameters.sympy.core.sympify module

sympify – convert objects SymPy internal format

class modelparameters.sympy.core.sympify.CantSympify[source]

Bases: object

Mix in this trait to a class to disallow sympification of its instances.

Examples

>>> from .sympify import sympify, CantSympify
>>> class Something(dict):
...     pass
...
>>> sympify(Something())
{}
>>> class Something(dict, CantSympify):
...     pass
...
>>> sympify(Something())
Traceback (most recent call last):
...
SympifyError: SympifyError: {}
exception modelparameters.sympy.core.sympify.SympifyError(expr, base_exc=None)[source]

Bases: ValueError

modelparameters.sympy.core.sympify.kernS(s)[source]

Use a hack to try keep autosimplification from joining Integer or minus sign into an Add of a Mul; this modification doesn’t prevent the 2-arg Mul from becoming an Add, however.

Examples

>>> from .sympify import kernS
>>> from ..abc import x, y, z

The 2-arg Mul allows a leading Integer to be distributed but kernS will prevent that:

>>> 2*(x + y)
2*x + 2*y
>>> kernS('2*(x + y)')
2*(x + y)

If use of the hack fails, the un-hacked string will be passed to sympify… and you get what you get.

XXX This hack should not be necessary once issue 4596 has been resolved.

modelparameters.sympy.core.sympify.sympify(a, locals=None, convert_xor=True, strict=False, rational=False, evaluate=None)[source]

Converts an arbitrary expression to a type that can be used inside SymPy.

For example, it will convert Python ints into instance of sympy.Rational, floats into instances of sympy.Float, etc. It is also able to coerce symbolic expressions which inherit from Basic. This can be useful in cooperation with SAGE.

It currently accepts as arguments:
  • any object defined in sympy

  • standard numeric python types: int, long, float, Decimal

  • strings (like “0.09” or “2e-19”)

  • booleans, including None (will leave None unchanged)

  • lists, sets or tuples containing any of the above

Warning

Note that this function uses eval, and thus shouldn’t be used on unsanitized input.

If the argument is already a type that SymPy understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type.

>>> from .. import sympify
>>> sympify(2).is_integer
True
>>> sympify(2).is_real
True
>>> sympify(2.0).is_real
True
>>> sympify("2.0").is_real
True
>>> sympify("2e-45").is_real
True

If the expression could not be converted, a SympifyError is raised.

>>> sympify("x***2")
Traceback (most recent call last):
...
SympifyError: SympifyError: "could not parse u'x***2'"

Locals

The sympification happens with access to everything that is loaded by from .. import *; anything used in a string that is not defined by that import will be converted to a symbol. In the following, the bitcount function is treated as a symbol and the O is interpreted as the Order object (used with series) and it raises an error when used improperly:

>>> s = 'bitcount(42)'
>>> sympify(s)
bitcount(42)
>>> sympify("O(x)")
O(x)
>>> sympify("O + 1")
Traceback (most recent call last):
...
TypeError: unbound method...

In order to have bitcount be recognized it can be imported into a namespace dictionary and passed as locals:

>>> from .compatibility import exec_
>>> ns = {}
>>> exec_('from .evalf import bitcount', ns)
>>> sympify(s, locals=ns)
6

In order to have the O interpreted as a Symbol, identify it as such in the namespace dictionary. This can be done in a variety of ways; all three of the following are possibilities:

>>> from .. import Symbol
>>> ns["O"] = Symbol("O")  # method 1
>>> exec_('from ..abc import O', ns)  # method 2
>>> ns.update(dict(O=Symbol("O")))  # method 3
>>> sympify("O + 1", locals=ns)
O + 1

If you want all single-letter and Greek-letter variables to be symbols then you can use the clashing-symbols dictionaries that have been defined there as private variables: _clash1 (single-letter variables), _clash2 (the multi-letter Greek names) or _clash (both single and multi-letter names that are defined in abc).

>>> from ..abc import _clash1
>>> _clash1
{'C': C, 'E': E, 'I': I, 'N': N, 'O': O, 'Q': Q, 'S': S}
>>> sympify('I & Q', _clash1)
I & Q

Strict

If the option strict is set to True, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised.

>>> print(sympify(None))
None
>>> sympify(None, strict=True)
Traceback (most recent call last):
...
SympifyError: SympifyError: None

Evaluation

If the option evaluate is set to False, then arithmetic and operators will be converted into their SymPy equivalents and the evaluate=False option will be added. Nested Add or Mul will be denested first. This is done via an AST transformation that replaces operators with their SymPy equivalents, so if an operand redefines any of those operations, the redefined operators will not be used.

>>> sympify('2**2 / 3 + 5')
19/3
>>> sympify('2**2 / 3 + 5', evaluate=False)
2**2/3 + 5

Extending

To extend sympify to convert custom objects (not derived from Basic), just define a _sympy_ method to your class. You can do that even to classes that you do not own by subclassing or adding the method at runtime.

>>> from .. import Matrix
>>> class MyList1(object):
...     def __iter__(self):
...         yield 1
...         yield 2
...         return
...     def __getitem__(self, i): return list(self)[i]
...     def _sympy_(self): return Matrix(self)
>>> sympify(MyList1())
Matrix([
[1],
[2]])

If you do not have control over the class definition you could also use the converter global dictionary. The key is the class and the value is a function that takes a single argument and returns the desired SymPy object, e.g. converter[MyList] = lambda x: Matrix(x).

>>> class MyList2(object):   # XXX Do not do this if you control the class!
...     def __iter__(self):  #     Use _sympy_!
...         yield 1
...         yield 2
...         return
...     def __getitem__(self, i): return list(self)[i]
>>> from .sympify import converter
>>> converter[MyList2] = lambda x: Matrix(x)
>>> sympify(MyList2())
Matrix([
[1],
[2]])

Notes

Sometimes autosimplification during sympification results in expressions that are very different in structure than what was entered. Until such autosimplification is no longer done, the kernS function might be of some use. In the example below you can see how an expression reduces to -1 by autosimplification, but does not do so when kernS is used.

>>> from .sympify import kernS
>>> from ..abc import x
>>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
-1
>>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'
>>> sympify(s)
-1
>>> kernS(s)
-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1

modelparameters.sympy.core.trace module

class modelparameters.sympy.core.trace.Tr(*args)[source]

Bases: Expr

Generic Trace operation than can trace over:

  1. sympy matrix

  2. operators

  3. outer products

Parameters:
  • o (operator, matrix, expr) –

  • i (tuple/list indices (optional)) –

Examples

# TODO: Need to handle printing

  1. Trace(A+B) = Tr(A) + Tr(B)

  2. Trace(scalar*Operator) = scalar*Trace(Operator)

>>> from .trace import Tr
>>> from .. import symbols, Matrix
>>> a, b = symbols('a b', commutative=True)
>>> A, B = symbols('A B', commutative=False)
>>> Tr(a*A,[2])
a*Tr(A)
>>> m = Matrix([[1,2],[1,1]])
>>> Tr(m)
2
default_assumptions = {}
doit(**kwargs)[source]

Perform the trace operation.

#TODO: Current version ignores the indices set for partial trace.

>>> from .trace import Tr
>>> from ..physics.quantum.operator import OuterProduct
>>> from ..physics.quantum.spin import JzKet, JzBra
>>> t = Tr(OuterProduct(JzKet(1,1), JzBra(1,1)))
>>> t.doit()
1
property is_number

Returns True if self has no free symbols. It will be faster than if not self.free_symbols, however, since is_number will fail as soon as it hits a free symbol.

Examples

>>> from .. import log, Integral
>>> from ..abc import x
>>> x.is_number
False
>>> (2*x).is_number
False
>>> (2 + log(2)).is_number
True
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True
permute(pos)[source]

Permute the arguments cyclically.

Parameters:

pos (integer, if positive, shift-right, else shift-left) –

Examples

>>> from .trace import Tr
>>> from .. import symbols
>>> A, B, C, D = symbols('A B C D', commutative=False)
>>> t = Tr(A*B*C*D)
>>> t.permute(2)
Tr(C*D*A*B)
>>> t.permute(-2)
Tr(C*D*A*B)

Module contents

Core module. Provides the basic operations needed in sympy.