Inheritance diagram for nipy.algorithms.statistics.formula.formulae:
A formula is basically a sympy expression for the mean of something of the form:
mean = sum([Beta(e)*e for e in expr])
Or, a linear combination of sympy expressions, with each one multiplied by its own “Beta”. The elements of expr can be instances of Term (for a linear regression formula, they would all be instances of Term). But, in general, there might be some other parameters (i.e. sympy.Symbol instances) that are not Terms.
The design matrix is made up of columns that are the derivatives of mean with respect to everything that is not a Term, evaluted at a recarray that has field names given by [str(t) for t in self.terms].
For those familiar with R’s formula syntax, if we wanted a design matrix like the following:
> s.table = read.table("http://www-stat.stanford.edu/~jtaylo/courses/stats191/data/supervisor.table", header=T)
> d = model.matrix(lm(Y ~ X1*X3, s.table)
)
> d
(Intercept) X1 X3 X1:X3
1 1 51 39 1989
2 1 64 54 3456
3 1 70 69 4830
4 1 63 47 2961
5 1 78 66 5148
6 1 55 44 2420
7 1 67 56 3752
8 1 75 55 4125
9 1 82 67 5494
10 1 61 47 2867
11 1 53 58 3074
12 1 60 39 2340
13 1 62 42 2604
14 1 83 45 3735
15 1 77 72 5544
16 1 90 72 6480
17 1 85 69 5865
18 1 60 75 4500
19 1 70 57 3990
20 1 58 54 3132
21 1 40 34 1360
22 1 61 62 3782
23 1 66 50 3300
24 1 37 58 2146
25 1 54 48 2592
26 1 77 63 4851
27 1 75 74 5550
28 1 57 45 2565
29 1 85 71 6035
30 1 82 59 4838
attr(,"assign")
[1] 0 1 2 3
>
With the Formula, it looks like this:
>>> r = np.rec.array([
... (43, 51, 30, 39, 61, 92, 45), (63, 64, 51, 54, 63, 73, 47),
... (71, 70, 68, 69, 76, 86, 48), (61, 63, 45, 47, 54, 84, 35),
... (81, 78, 56, 66, 71, 83, 47), (43, 55, 49, 44, 54, 49, 34),
... (58, 67, 42, 56, 66, 68, 35), (71, 75, 50, 55, 70, 66, 41),
... (72, 82, 72, 67, 71, 83, 31), (67, 61, 45, 47, 62, 80, 41),
... (64, 53, 53, 58, 58, 67, 34), (67, 60, 47, 39, 59, 74, 41),
... (69, 62, 57, 42, 55, 63, 25), (68, 83, 83, 45, 59, 77, 35),
... (77, 77, 54, 72, 79, 77, 46), (81, 90, 50, 72, 60, 54, 36),
... (74, 85, 64, 69, 79, 79, 63), (65, 60, 65, 75, 55, 80, 60),
... (65, 70, 46, 57, 75, 85, 46), (50, 58, 68, 54, 64, 78, 52),
... (50, 40, 33, 34, 43, 64, 33), (64, 61, 52, 62, 66, 80, 41),
... (53, 66, 52, 50, 63, 80, 37), (40, 37, 42, 58, 50, 57, 49),
... (63, 54, 42, 48, 66, 75, 33), (66, 77, 66, 63, 88, 76, 72),
... (78, 75, 58, 74, 80, 78, 49), (48, 57, 44, 45, 51, 83, 38),
... (85, 85, 71, 71, 77, 74, 55), (82, 82, 39, 59, 64, 78, 39)],
... dtype=[('y', '<i8'), ('x1', '<i8'), ('x2', '<i8'),
... ('x3', '<i8'), ('x4', '<i8'), ('x5', '<i8'),
... ('x6', '<i8')])
>>> x1 = Term('x1'); x3 = Term('x3')
>>> f = Formula([x1, x3, x1*x3]) + I
>>> f.mean
_b0*x1 + _b1*x3 + _b2*x1*x3 + _b3
The I is the “intercept” term, I have explicity not used R’s default of adding it to everything.
>>> f.design(r)
array([(51.0, 39.0, 1989.0, 1.0), (64.0, 54.0, 3456.0, 1.0),
(70.0, 69.0, 4830.0, 1.0), (63.0, 47.0, 2961.0, 1.0),
(78.0, 66.0, 5148.0, 1.0), (55.0, 44.0, 2420.0, 1.0),
(67.0, 56.0, 3752.0, 1.0), (75.0, 55.0, 4125.0, 1.0),
(82.0, 67.0, 5494.0, 1.0), (61.0, 47.0, 2867.0, 1.0),
(53.0, 58.0, 3074.0, 1.0), (60.0, 39.0, 2340.0, 1.0),
(62.0, 42.0, 2604.0, 1.0), (83.0, 45.0, 3735.0, 1.0),
(77.0, 72.0, 5544.0, 1.0), (90.0, 72.0, 6480.0, 1.0),
(85.0, 69.0, 5865.0, 1.0), (60.0, 75.0, 4500.0, 1.0),
(70.0, 57.0, 3990.0, 1.0), (58.0, 54.0, 3132.0, 1.0),
(40.0, 34.0, 1360.0, 1.0), (61.0, 62.0, 3782.0, 1.0),
(66.0, 50.0, 3300.0, 1.0), (37.0, 58.0, 2146.0, 1.0),
(54.0, 48.0, 2592.0, 1.0), (77.0, 63.0, 4851.0, 1.0),
(75.0, 74.0, 5550.0, 1.0), (57.0, 45.0, 2565.0, 1.0),
(85.0, 71.0, 6035.0, 1.0), (82.0, 59.0, 4838.0, 1.0)],
dtype=[('x1', '<f8'), ('x3', '<f8'), ('x1*x3', '<f8'), ('1', '<f8')])
Bases: sympy.core.symbol.Dummy
A symbol tied to a Term term
Methods
__call__(*args) | |
apart([x]) | See the apart function in sympy.polys |
args_cnc() | treat self as Mul and split it into tuple (set, list) |
as_base_exp() | |
as_coeff_Mul() | Efficiently extract the coefficient of a product. |
as_coeff_add(*deps) | Return the tuple (c, args) where self is written as an Add, a. |
as_coeff_exponent(x) | c*x**e -> c,e where x can be any symbolic expression. |
as_coeff_factors(*deps) | |
as_coeff_mul(*deps) | Return the tuple (c, args) where self is written as a Mul, m. |
as_coeff_terms(*deps) | |
as_coefficient(expr) | Extracts symbolic coefficient at the given expression. |
as_dummy() | |
as_expr(*gens) | Convert a polynomial to a SymPy expression. |
as_independent(*deps, **hint) | A mostly naive separation of a Mul or Add into arguments that are not |
as_leading_term(*args, **kw_args) | Returns the leading term. |
as_numer_denom() | |
as_ordered_factors([order]) | Transform an expression to an ordered list of factors. |
as_ordered_terms([order, data]) | Transform an expression to an ordered list of terms. |
as_poly(*gens, **args) | Converts self to a polynomial or returns None. |
as_powers_dict() | |
as_real_imag([deep]) | |
as_terms() | Transform an expression to a list of terms. |
atoms(*types) | Returns the atoms that form the current object. |
cancel(*gens, **args) | See the cancel function in sympy.polys |
class_key() | |
coeff(x[, right]) | Returns the coefficient of the exact term “x” or None if there is no “x”. |
collect(syms[, evaluate, exact]) | See the collect function in sympy.simplify |
combsimp() | See the combsimp function in sympy.simplify |
compare(other) | Return -1,0,1 if the object is smaller, equal, or greater than other. |
compare_pretty(a, b) | Is a > b in the sense of ordering in printing? :: yes ..... |
compute_leading_term(x[, skip_abs, logx]) | as_leading_term is only allowed for results of .series() |
conjugate() | |
could_extract_minus_sign() | Canonical way to choose an element in the set {e, -e} where e is any expression. |
count(query) | Count the number of matching subexpressions. |
count_ops([visual]) | wrapper for count_ops that returns the operation count. |
diff(*symbols, **assumptions) | |
doit(**hints) | |
dummy_eq(other[, symbol]) | Compare two expressions and handle dummy symbols. |
evalf([n, subs, maxn, chop, strict, quad, ...]) | Evaluate the given formula to an accuracy of n digits. |
expand([deep, modulus, power_base, ...]) | Expand an expression using hints. |
extract_additively(c) | Return None if it’s not possible to make self in the form |
extract_multiplicatively(c) | Return None if it’s not possible to make self in the form |
factor(*gens, **args) | See the factor() function in sympy.polys.polytools |
find(query[, group]) | Find all subexpressions matching a query. |
fromiter(args, **assumptions) | Create a new object from an iterable. |
getO() | Returns the additive O(..) symbol if there is one, else None. |
getn() | Returns the order of the expression. |
has(*args, **kw_args) | Test whether any subexpression matches any of the patterns. |
integrate(*args, **kwargs) | See the integrate function in sympy.integrals |
invert(g) | See the invert function in sympy.polys |
is_hypergeometric(k) | |
is_polynomial(*syms) | Return True if self is a polynomial in syms and False otherwise. |
is_rational_function(*syms) | Test whether function is a ratio of two polynomials in the given symbols, syms. |
iter_basic_args() | Iterates arguments of ‘self’. |
leadterm(x) | Returns the leading term a*x**b as a tuple (a, b). |
limit(x, xlim[, dir]) | Compute limit x->xlim. |
lseries([x, x0, dir]) | Wrapper for series yielding an iterator of the terms of the series. |
match(pattern) | Pattern matching. |
matches(expr[, repl_dict, evaluate]) | |
n([n, subs, maxn, chop, strict, quad, verbose]) | Evaluate the given formula to an accuracy of n digits. |
normal() | |
nseries([x, x0, n, dir, logx]) | Wrapper to _eval_nseries if assumptions allow, else to series. |
nsimplify([constants, tolerance, full]) | See the nsimplify function in sympy.simplify |
powsimp([deep, combine]) | See the powsimp function in sympy.simplify |
radsimp() | See the radsimp function in sympy.simplify |
ratsimp() | See the ratsimp function in sympy.simplify |
refine([assumption]) | See the refine function in sympy.assumptions |
removeO() | Removes the additive O(..) symbol if there is one |
replace(query, value[, map]) | Replace matching subexpressions of self with value. |
rewrite(*args, **hints) | Rewrites expression containing applications of functions of one kind in terms of functions of different kind. |
separate([deep, force]) | See the separate function in sympy.simplify |
series([x, x0, n, dir]) | Series expansion of “self” around x = x0 yielding either terms of |
simplify() | See the simplify function in sympy.simplify |
sort_key([order]) | |
subs(*args) | Substitutes an expression. |
together(*args, **kwargs) | See the together function in sympy.polys |
trigsimp([deep, recursive]) | See the trigsimp function in sympy.simplify |
x.__init__(...) initializes x; see help(type(x)) for signature
See the apart function in sympy.polys
Returns a tuple of arguments of ‘self’.
Example:
>>> from sympy import symbols, cot
>>> from sympy.abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).
treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.
A special treatment is that -1 is separated from a Rational:
>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]
The arg is treated as a Mul:
>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
Efficiently extract the coefficient of a product.
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.
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
c*x**e -> c,e where x can be any symbolic expression.
Return the tuple (c, args) where self is written as a Mul, m.
c should be a Rational multiplied by any terms of the Mul that are independent of deps.
args should be a tuple of all other terms 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.
>>> from sympy import S
>>> from sympy.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, ())
Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.
>>> from sympy import E, pi, sin, I, symbols
>>> from sympy.abc import x, y
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)
>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> (2*E*x + x).as_coefficient(E)
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)
Convert a polynomial to a SymPy expression.
Examples
>>> from sympy import sin
>>> from sympy.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)
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.:
The only non-naive thing that is done here is to respect noncommutative ordering of variables.
The returned tuple (i, d) has the following interpretation:
To force the expression to be treated as an Add, use the hint as_Add=True
Examples:
– self is an Add
>>> from sympy import sin, cos, exp
>>> from sympy.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 sympy 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=1)
(0, 3*x)
– force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)
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 sympy 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))
Returns the leading term.
Example:
>>> from sympy.abc import x
>>> (1+x+x**2).as_leading_term(x)
1
>>> (1/x**2+x+x**2).as_leading_term(x)
x**(-2)
Note:
self is assumed to be the result returned by Basic.series().
Transform an expression to an ordered list of factors.
Examples
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
[2, x, y, sin(x), cos(x)]
Transform an expression to an ordered list of terms.
Examples
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
Converts self to a polynomial or returns None.
>>> from sympy import Poly, sin
>>> from sympy.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
Transform an expression to a list of terms.
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.
Example:
>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
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 sympy import I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])
If one or more types are given, the results will contain only those types of atoms.
Examples:
>>> from sympy import Number, NumberSymbol, Symbol
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
set([x, y])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
set([1, 2])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
set([1, 2, pi])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
set([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
set([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 sympy import S
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
set([1])
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
set([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 sympy import Function, Mul
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
See the cancel function in sympy.polys
Returns the coefficient of the exact term “x” or None if there is no “x”.
When x is noncommutative, the coeff to the left (default) or right of x can be returned. The keyword ‘right’ is ignored when x is commutative.
Examples:
>>> from sympy import symbols
>>> from sympy.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)
You can select terms that have a numerical term in front of them:
>>> (-x-2*y).coeff(2)
-y
>>> from sympy 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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)
In addition, no factoring is done, so 2 + y is not obtained from the following:
>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:
>>> (n*m + m*n).coeff(n)
If there is only one possible coefficient, it is returned:
>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
See the collect function in sympy.simplify
See the combsimp function in sympy.simplify
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.
Example:
>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
Is a > b in the sense of ordering in printing?
yes ..... return 1
no ...... return -1
equal ... return 0
Strategy:
It uses Basic.compare as a fallback, but improves it in many cases, like x**3, x**4, O(x**3) etc. In those simple cases, it just parses the expression and returns the “sane” ordering such as:
1 < x < x**2 < x**3 < O(x**4) etc.
Example:
>>> from sympy.abc import x
>>> from sympy import Basic, Number
>>> Basic._compare_pretty(x, x**2)
-1
>>> Basic._compare_pretty(x**2, x**2)
0
>>> Basic._compare_pretty(x**3, x**2)
1
>>> Basic._compare_pretty(Number(1, 2), Number(1, 3))
1
>>> Basic._compare_pretty(Number(0), Number(-1))
1
as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first. If skip_abs is true, the absolute term is assumed to be zero. (This is necessary because sometimes it cannot be simplified
to zero without a lot of work, but is still known to be zero. See log._eval_nseries for an example.)
If skip_log is true, log(x) is treated as an independent symbol. (This is needed for the gruntz algorithm.)
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 sympy.abc import x, y
>>> (x-y).could_extract_minus_sign() != (y-x).could_extract_minus_sign()
True
Count the number of matching subexpressions.
wrapper for count_ops that returns the operation count.
Compare two expressions and handle dummy symbols.
Examples
>>> from sympy import Dummy
>>> from sympy.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
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}.
- 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)
Expand an expression using hints.
See the docstring in function.expand for more information.
Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.
>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
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 sympy 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
See the factor() function in sympy.polys.polytools
Find all subexpressions matching a query.
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.
Example:
>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
The top-level function in an expression.
The following should hold for all objects:
>> x == x.func(*x.args)
Example:
>>> from sympy.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
Returns the additive O(..) symbol if there is one, else None.
Returns the order of the expression.
The order is determined either from the O(...) term. If there is no O(...) term, it returns None.
Example:
>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
Test whether any subexpression matches any of the patterns.
Examples:
>>> from sympy import sin, S
>>> from sympy.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 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
See the integrate function in sympy.integrals
See the invert function in sympy.polys
Deprecated alias for is_Float
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 only 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 sympy 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 sympy 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()
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).
Example:
>>> from sympy import Symbol, sin
>>> from sympy.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 sympy import sqrt, factor, cancel
>>> 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_rational_function().
Iterates arguments of ‘self’.
Example:
>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
Returns the leading term a*x**b as a tuple (a, b).
Example:
>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
Note:
self is assumed to be the result returned by Basic.series().
Compute limit x->xlim.
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().
Pattern matching.
Wild symbols match all.
Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:
pattern.subs(self.match(pattern)) == self
Example:
>>> from sympy import symbols, Wild
>>> from sympy.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).subs(e.match(p*q**r))
4*x**2
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}.
- 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)
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.
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().
See the nsimplify function in sympy.simplify
See the powsimp function in sympy.simplify
See the radsimp function in sympy.simplify
See the ratsimp function in sympy.simplify
See the refine function in sympy.assumptions
Removes the additive O(..) symbol if there is one
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.
Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The list of possible combinations of queries and replacement values is listed below:
Examples:
>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('a')
>>> f.replace(sin(a), cos(a))
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin(a), lambda a: sin(2*a))
log(sin(2*x)) + tan(sin(2*x**2))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
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 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.
>>> from sympy import sin, exp, I
>>> from sympy.abc import x, y
>>> sin(x).rewrite(sin, exp)
-I*(exp(I*x) - exp(-I*x))/2
See the separate function in sympy.simplify
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.
Note: when n != None, if an O() term is returned then the x in the in it and the entire expression represents x - x0, the displacement from x0. (If there is no O() term then the series was exact and x has it’s normal meaning.) This is currently necessary since sympy’s O() can only represent terms at x0=0. So instead of:
cos(x).series(x0=1, n=2) --> (1 - x)*sin(1) + cos(1) + O((x - 1)**2)
which graphically looks like this:
|
.|. . .
. | \ . .
---+----------------------
| . . . .
| x=0
the following is returned instead:
-x*sin(1) + cos(1) + O(x**2)
whose graph is this:
\ |
. .| . .
. \ . .
-----+\------------------.
| . . . .
| x=0
which is identical to cos(x + 1).series(n=2).
Returns the series expansion of “self” around the point x = x0 with respect to x up to O(x**n) (default n is 6).
If x=None and self is univariate, the univariate symbol will be supplied, otherwise an error will be raised.
>>> from sympy import cos, exp
>>> from sympy.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)
>>> 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 an iterator of the series terms will be returned.
>>> term=cos(x).series(n=None)
>>> [term.next() 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
See the simplify function in sympy.simplify
Substitutes an expression.
Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.
Examples:
>>> from sympy import pi
>>> from sympy.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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
See the together function in sympy.polys
See the trigsimp function in sympy.simplify
Bases: nipy.algorithms.statistics.formula.formulae.Formula
A qualitative variable in a regression model
A Factor is similar to R’s factor. The levels of the Factor can be either strings or ints.
Methods
design(input[, param, return_float, contrasts]) | Construct the design matrix, and optional contrast matrices. |
fromcol(col, name) | Create a Factor from a column array. |
fromrec(rec[, keep, drop]) | Construct Formula from recarray |
get_term(level) | Retrieve a term of the Factor... |
stratify(variable) | Create a new variable, stratified by the levels of a Factor. |
subs(old, new) | Perform a sympy substitution on all terms in the Formula |
Initialize Factor
Parameters : | name : str levels : [str or int]
char : str, optional
|
---|
Coefficients in the linear regression formula.
Construct the design matrix, and optional contrast matrices.
Parameters : | input : np.recarray
param : None or np.recarray
return_float : bool, optional
contrasts : None or dict, optional
|
---|---|
Returns : | des : 2D array
cmatrices : dict, optional
|
The dtype of the design matrix of the Formula.
Create a Factor from a column array.
Parameters : | col : ndarray
name : str
|
---|---|
Returns : | factor : Factor |
Examples
>>> data = np.array([(3,'a'),(4,'a'),(5,'b'),(3,'b')], np.dtype([('x', np.float), ('y', 'S1')]))
>>> f1 = Factor.fromcol(data['y'], 'y')
>>> f2 = Factor.fromcol(data['x'], 'x')
>>> d = f1.design(data)
>>> print(d.dtype.descr)
[('y_a', '<f8'), ('y_b', '<f8')]
>>> d = f2.design(data)
>>> print(d.dtype.descr)
[('x_3', '<f8'), ('x_4', '<f8'), ('x_5', '<f8')]
Construct Formula from recarray
For fields with a string-dtype, it is assumed that these are qualtiatitve regressors, i.e. Factors.
Parameters : | rec: recarray :
keep: [] :
drop: [] :
|
---|
Retrieve a term of the Factor...
Expression for the mean, expressed as a linear combination of terms, each with dummy variables in front.
The parameters in the Formula.
Create a new variable, stratified by the levels of a Factor.
Parameters : | variable : str or simple sympy expression
|
---|---|
Returns : | formula : Formula
|
Examples
>>> f = Factor('a', ['x','y'])
>>> sf = f.stratify('theta')
>>> sf.mean
_theta0*a_x + _theta1*a_y
Perform a sympy substitution on all terms in the Formula
Returns a new instance of the same class
Parameters : | old : sympy.Basic
new : sympy.Basic
|
---|---|
Returns : | newf : Formula |
Examples
>>> s, t = [Term(l) for l in 'st']
>>> f, g = [sympy.Function(l) for l in 'fg']
>>> form = Formula([f(t),g(s)])
>>> newform = form.subs(g, sympy.Function('h'))
>>> newform.terms
array([f(t), h(s)], dtype=object)
>>> form.terms
array([f(t), g(s)], dtype=object)
Terms in the linear regression formula.
Bases: nipy.algorithms.statistics.formula.formulae.Term
Boolean Term derived from a Factor.
Its properties are the same as a Term except that its product with itself is itself.
Methods
__call__(*args) | |
apart([x]) | See the apart function in sympy.polys |
args_cnc() | treat self as Mul and split it into tuple (set, list) |
as_base_exp() | |
as_coeff_Mul() | Efficiently extract the coefficient of a product. |
as_coeff_add(*deps) | Return the tuple (c, args) where self is written as an Add, a. |
as_coeff_exponent(x) | c*x**e -> c,e where x can be any symbolic expression. |
as_coeff_factors(*deps) | |
as_coeff_mul(*deps) | Return the tuple (c, args) where self is written as a Mul, m. |
as_coeff_terms(*deps) | |
as_coefficient(expr) | Extracts symbolic coefficient at the given expression. |
as_dummy() | |
as_expr(*gens) | Convert a polynomial to a SymPy expression. |
as_independent(*deps, **hint) | A mostly naive separation of a Mul or Add into arguments that are not |
as_leading_term(*args, **kw_args) | Returns the leading term. |
as_numer_denom() | |
as_ordered_factors([order]) | Transform an expression to an ordered list of factors. |
as_ordered_terms([order, data]) | Transform an expression to an ordered list of terms. |
as_poly(*gens, **args) | Converts self to a polynomial or returns None. |
as_powers_dict() | |
as_real_imag([deep]) | |
as_terms() | Transform an expression to a list of terms. |
atoms(*types) | Returns the atoms that form the current object. |
cancel(*gens, **args) | See the cancel function in sympy.polys |
class_key() | |
coeff(x[, right]) | Returns the coefficient of the exact term “x” or None if there is no “x”. |
collect(syms[, evaluate, exact]) | See the collect function in sympy.simplify |
combsimp() | See the combsimp function in sympy.simplify |
compare(other) | Return -1,0,1 if the object is smaller, equal, or greater than other. |
compare_pretty(a, b) | Is a > b in the sense of ordering in printing? :: yes ..... |
compute_leading_term(x[, skip_abs, logx]) | as_leading_term is only allowed for results of .series() |
conjugate() | |
could_extract_minus_sign() | Canonical way to choose an element in the set {e, -e} where e is any expression. |
count(query) | Count the number of matching subexpressions. |
count_ops([visual]) | wrapper for count_ops that returns the operation count. |
diff(*symbols, **assumptions) | |
doit(**hints) | |
dummy_eq(other[, symbol]) | Compare two expressions and handle dummy symbols. |
evalf([n, subs, maxn, chop, strict, quad, ...]) | Evaluate the given formula to an accuracy of n digits. |
expand([deep, modulus, power_base, ...]) | Expand an expression using hints. |
extract_additively(c) | Return None if it’s not possible to make self in the form |
extract_multiplicatively(c) | Return None if it’s not possible to make self in the form |
factor(*gens, **args) | See the factor() function in sympy.polys.polytools |
find(query[, group]) | Find all subexpressions matching a query. |
fromiter(args, **assumptions) | Create a new object from an iterable. |
getO() | Returns the additive O(..) symbol if there is one, else None. |
getn() | Returns the order of the expression. |
has(*args, **kw_args) | Test whether any subexpression matches any of the patterns. |
integrate(*args, **kwargs) | See the integrate function in sympy.integrals |
invert(g) | See the invert function in sympy.polys |
is_hypergeometric(k) | |
is_polynomial(*syms) | Return True if self is a polynomial in syms and False otherwise. |
is_rational_function(*syms) | Test whether function is a ratio of two polynomials in the given symbols, syms. |
iter_basic_args() | Iterates arguments of ‘self’. |
leadterm(x) | Returns the leading term a*x**b as a tuple (a, b). |
limit(x, xlim[, dir]) | Compute limit x->xlim. |
lseries([x, x0, dir]) | Wrapper for series yielding an iterator of the terms of the series. |
match(pattern) | Pattern matching. |
matches(expr[, repl_dict, evaluate]) | |
n([n, subs, maxn, chop, strict, quad, verbose]) | Evaluate the given formula to an accuracy of n digits. |
normal() | |
nseries([x, x0, n, dir, logx]) | Wrapper to _eval_nseries if assumptions allow, else to series. |
nsimplify([constants, tolerance, full]) | See the nsimplify function in sympy.simplify |
powsimp([deep, combine]) | See the powsimp function in sympy.simplify |
radsimp() | See the radsimp function in sympy.simplify |
ratsimp() | See the ratsimp function in sympy.simplify |
refine([assumption]) | See the refine function in sympy.assumptions |
removeO() | Removes the additive O(..) symbol if there is one |
replace(query, value[, map]) | Replace matching subexpressions of self with value. |
rewrite(*args, **hints) | Rewrites expression containing applications of functions of one kind in terms of functions of different kind. |
separate([deep, force]) | See the separate function in sympy.simplify |
series([x, x0, n, dir]) | Series expansion of “self” around x = x0 yielding either terms of |
simplify() | See the simplify function in sympy.simplify |
sort_key([order]) | |
subs(*args) | Substitutes an expression. |
together(*args, **kwargs) | See the together function in sympy.polys |
trigsimp([deep, recursive]) | See the trigsimp function in sympy.simplify |
x.__init__(...) initializes x; see help(type(x)) for signature
See the apart function in sympy.polys
Returns a tuple of arguments of ‘self’.
Example:
>>> from sympy import symbols, cot
>>> from sympy.abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).
treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.
A special treatment is that -1 is separated from a Rational:
>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]
The arg is treated as a Mul:
>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
Efficiently extract the coefficient of a product.
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.
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
c*x**e -> c,e where x can be any symbolic expression.
Return the tuple (c, args) where self is written as a Mul, m.
c should be a Rational multiplied by any terms of the Mul that are independent of deps.
args should be a tuple of all other terms 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.
>>> from sympy import S
>>> from sympy.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, ())
Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.
>>> from sympy import E, pi, sin, I, symbols
>>> from sympy.abc import x, y
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)
>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> (2*E*x + x).as_coefficient(E)
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)
Convert a polynomial to a SymPy expression.
Examples
>>> from sympy import sin
>>> from sympy.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)
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.:
The only non-naive thing that is done here is to respect noncommutative ordering of variables.
The returned tuple (i, d) has the following interpretation:
To force the expression to be treated as an Add, use the hint as_Add=True
Examples:
– self is an Add
>>> from sympy import sin, cos, exp
>>> from sympy.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 sympy 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=1)
(0, 3*x)
– force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)
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 sympy 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))
Returns the leading term.
Example:
>>> from sympy.abc import x
>>> (1+x+x**2).as_leading_term(x)
1
>>> (1/x**2+x+x**2).as_leading_term(x)
x**(-2)
Note:
self is assumed to be the result returned by Basic.series().
Transform an expression to an ordered list of factors.
Examples
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
[2, x, y, sin(x), cos(x)]
Transform an expression to an ordered list of terms.
Examples
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
Converts self to a polynomial or returns None.
>>> from sympy import Poly, sin
>>> from sympy.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
Transform an expression to a list of terms.
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.
Example:
>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
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 sympy import I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])
If one or more types are given, the results will contain only those types of atoms.
Examples:
>>> from sympy import Number, NumberSymbol, Symbol
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
set([x, y])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
set([1, 2])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
set([1, 2, pi])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
set([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
set([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 sympy import S
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
set([1])
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
set([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 sympy import Function, Mul
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
See the cancel function in sympy.polys
Returns the coefficient of the exact term “x” or None if there is no “x”.
When x is noncommutative, the coeff to the left (default) or right of x can be returned. The keyword ‘right’ is ignored when x is commutative.
Examples:
>>> from sympy import symbols
>>> from sympy.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)
You can select terms that have a numerical term in front of them:
>>> (-x-2*y).coeff(2)
-y
>>> from sympy 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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)
In addition, no factoring is done, so 2 + y is not obtained from the following:
>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:
>>> (n*m + m*n).coeff(n)
If there is only one possible coefficient, it is returned:
>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
See the collect function in sympy.simplify
See the combsimp function in sympy.simplify
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.
Example:
>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
Is a > b in the sense of ordering in printing?
yes ..... return 1
no ...... return -1
equal ... return 0
Strategy:
It uses Basic.compare as a fallback, but improves it in many cases, like x**3, x**4, O(x**3) etc. In those simple cases, it just parses the expression and returns the “sane” ordering such as:
1 < x < x**2 < x**3 < O(x**4) etc.
Example:
>>> from sympy.abc import x
>>> from sympy import Basic, Number
>>> Basic._compare_pretty(x, x**2)
-1
>>> Basic._compare_pretty(x**2, x**2)
0
>>> Basic._compare_pretty(x**3, x**2)
1
>>> Basic._compare_pretty(Number(1, 2), Number(1, 3))
1
>>> Basic._compare_pretty(Number(0), Number(-1))
1
as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first. If skip_abs is true, the absolute term is assumed to be zero. (This is necessary because sometimes it cannot be simplified
to zero without a lot of work, but is still known to be zero. See log._eval_nseries for an example.)
If skip_log is true, log(x) is treated as an independent symbol. (This is needed for the gruntz algorithm.)
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 sympy.abc import x, y
>>> (x-y).could_extract_minus_sign() != (y-x).could_extract_minus_sign()
True
Count the number of matching subexpressions.
wrapper for count_ops that returns the operation count.
Compare two expressions and handle dummy symbols.
Examples
>>> from sympy import Dummy
>>> from sympy.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
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}.
- 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)
Expand an expression using hints.
See the docstring in function.expand for more information.
Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.
>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
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 sympy 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
See the factor() function in sympy.polys.polytools
Find all subexpressions matching a query.
Return a Formula with only terms=[self].
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.
Example:
>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
The top-level function in an expression.
The following should hold for all objects:
>> x == x.func(*x.args)
Example:
>>> from sympy.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
Returns the additive O(..) symbol if there is one, else None.
Returns the order of the expression.
The order is determined either from the O(...) term. If there is no O(...) term, it returns None.
Example:
>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
Test whether any subexpression matches any of the patterns.
Examples:
>>> from sympy import sin, S
>>> from sympy.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 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
See the integrate function in sympy.integrals
See the invert function in sympy.polys
Deprecated alias for is_Float
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 only 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 sympy 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 sympy 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()
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).
Example:
>>> from sympy import Symbol, sin
>>> from sympy.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 sympy import sqrt, factor, cancel
>>> 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_rational_function().
Iterates arguments of ‘self’.
Example:
>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
Returns the leading term a*x**b as a tuple (a, b).
Example:
>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
Note:
self is assumed to be the result returned by Basic.series().
Compute limit x->xlim.
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().
Pattern matching.
Wild symbols match all.
Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:
pattern.subs(self.match(pattern)) == self
Example:
>>> from sympy import symbols, Wild
>>> from sympy.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).subs(e.match(p*q**r))
4*x**2
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}.
- 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)
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.
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().
See the nsimplify function in sympy.simplify
See the powsimp function in sympy.simplify
See the radsimp function in sympy.simplify
See the ratsimp function in sympy.simplify
See the refine function in sympy.assumptions
Removes the additive O(..) symbol if there is one
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.
Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The list of possible combinations of queries and replacement values is listed below:
Examples:
>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('a')
>>> f.replace(sin(a), cos(a))
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin(a), lambda a: sin(2*a))
log(sin(2*x)) + tan(sin(2*x**2))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
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 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.
>>> from sympy import sin, exp, I
>>> from sympy.abc import x, y
>>> sin(x).rewrite(sin, exp)
-I*(exp(I*x) - exp(-I*x))/2
See the separate function in sympy.simplify
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.
Note: when n != None, if an O() term is returned then the x in the in it and the entire expression represents x - x0, the displacement from x0. (If there is no O() term then the series was exact and x has it’s normal meaning.) This is currently necessary since sympy’s O() can only represent terms at x0=0. So instead of:
cos(x).series(x0=1, n=2) --> (1 - x)*sin(1) + cos(1) + O((x - 1)**2)
which graphically looks like this:
|
.|. . .
. | \ . .
---+----------------------
| . . . .
| x=0
the following is returned instead:
-x*sin(1) + cos(1) + O(x**2)
whose graph is this:
\ |
. .| . .
. \ . .
-----+\------------------.
| . . . .
| x=0
which is identical to cos(x + 1).series(n=2).
Returns the series expansion of “self” around the point x = x0 with respect to x up to O(x**n) (default n is 6).
If x=None and self is univariate, the univariate symbol will be supplied, otherwise an error will be raised.
>>> from sympy import cos, exp
>>> from sympy.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)
>>> 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 an iterator of the series terms will be returned.
>>> term=cos(x).series(n=None)
>>> [term.next() 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
See the simplify function in sympy.simplify
Substitutes an expression.
Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.
Examples:
>>> from sympy import pi
>>> from sympy.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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
See the together function in sympy.polys
See the trigsimp function in sympy.simplify
Bases: object
A Formula is a model for a mean in a regression model.
It is often given by a sequence of sympy expressions, with the mean model being the sum of each term multiplied by a linear regression coefficient.
The expressions may depend on additional Symbol instances, giving a non-linear regression model.
Methods
design(input[, param, return_float, contrasts]) | Construct the design matrix, and optional contrast matrices. |
fromrec(rec[, keep, drop]) | Construct Formula from recarray |
subs(old, new) | Perform a sympy substitution on all terms in the Formula |
Parameters : | seq : sequence of sympy.Basic char : str, optional
|
---|
Coefficients in the linear regression formula.
Construct the design matrix, and optional contrast matrices.
Parameters : | input : np.recarray
param : None or np.recarray
return_float : bool, optional
contrasts : None or dict, optional
|
---|---|
Returns : | des : 2D array
cmatrices : dict, optional
|
The dtype of the design matrix of the Formula.
Construct Formula from recarray
For fields with a string-dtype, it is assumed that these are qualtiatitve regressors, i.e. Factors.
Parameters : | rec: recarray :
keep: [] :
drop: [] :
|
---|
Expression for the mean, expressed as a linear combination of terms, each with dummy variables in front.
The parameters in the Formula.
Perform a sympy substitution on all terms in the Formula
Returns a new instance of the same class
Parameters : | old : sympy.Basic
new : sympy.Basic
|
---|---|
Returns : | newf : Formula |
Examples
>>> s, t = [Term(l) for l in 'st']
>>> f, g = [sympy.Function(l) for l in 'fg']
>>> form = Formula([f(t),g(s)])
>>> newform = form.subs(g, sympy.Function('h'))
>>> newform.terms
array([f(t), h(s)], dtype=object)
>>> form.terms
array([f(t), g(s)], dtype=object)
Terms in the linear regression formula.
Bases: nipy.algorithms.statistics.formula.formulae.Formula
Covariance matrices for common random effects analyses.
Examples
Two subjects (here named 2 and 3):
>>> subj = make_recarray([2,2,2,3,3], 's')
>>> subj_factor = Factor('s', [2,3])
By default the covariance matrix is symbolic. The display differs a little between sympy versions (hence we don’t check it in the doctests):
>>> c = RandomEffects(subj_factor.terms)
>>> c.cov(subj)
array([[_s2_0, _s2_0, _s2_0, 0, 0],
[_s2_0, _s2_0, _s2_0, 0, 0],
[_s2_0, _s2_0, _s2_0, 0, 0],
[0, 0, 0, _s2_1, _s2_1],
[0, 0, 0, _s2_1, _s2_1]], dtype=object)
With a numeric sigma, you get a numeric array:
>>> c = RandomEffects(subj_factor.terms, sigma=np.array([[4,1],[1,6]]))
>>> c.cov(subj)
array([[ 4., 4., 4., 1., 1.],
[ 4., 4., 4., 1., 1.],
[ 4., 4., 4., 1., 1.],
[ 1., 1., 1., 6., 6.],
[ 1., 1., 1., 6., 6.]])
Methods
cov(term[, param]) | Compute the covariance matrix for some given data. |
design(input[, param, return_float, contrasts]) | Construct the design matrix, and optional contrast matrices. |
fromrec(rec[, keep, drop]) | Construct Formula from recarray |
subs(old, new) | Perform a sympy substitution on all terms in the Formula |
Initialize random effects instance
Parameters : | seq : [sympy.Basic] sigma : ndarray
char : character for regression coefficient |
---|
Coefficients in the linear regression formula.
Compute the covariance matrix for some given data.
Parameters : | term : np.recarray
param : np.recarray
|
---|---|
Returns : | C : ndarray
|
Construct the design matrix, and optional contrast matrices.
Parameters : | input : np.recarray
param : None or np.recarray
return_float : bool, optional
contrasts : None or dict, optional
|
---|---|
Returns : | des : 2D array
cmatrices : dict, optional
|
The dtype of the design matrix of the Formula.
Construct Formula from recarray
For fields with a string-dtype, it is assumed that these are qualtiatitve regressors, i.e. Factors.
Parameters : | rec: recarray :
keep: [] :
drop: [] :
|
---|
Expression for the mean, expressed as a linear combination of terms, each with dummy variables in front.
The parameters in the Formula.
Perform a sympy substitution on all terms in the Formula
Returns a new instance of the same class
Parameters : | old : sympy.Basic
new : sympy.Basic
|
---|---|
Returns : | newf : Formula |
Examples
>>> s, t = [Term(l) for l in 'st']
>>> f, g = [sympy.Function(l) for l in 'fg']
>>> form = Formula([f(t),g(s)])
>>> newform = form.subs(g, sympy.Function('h'))
>>> newform.terms
array([f(t), h(s)], dtype=object)
>>> form.terms
array([f(t), g(s)], dtype=object)
Terms in the linear regression formula.
Bases: sympy.core.symbol.Symbol
A sympy.Symbol type to represent a term an a regression model
Terms can be added to other sympy expressions with the single convention that a term plus itself returns itself.
It is meant to emulate something on the right hand side of a formula in R. In particular, its name can be the name of a field in a recarray used to create a design matrix.
>>> t = Term('x')
>>> xval = np.array([(3,),(4,),(5,)], np.dtype([('x', np.float)]))
>>> f = t.formula
>>> d = f.design(xval)
>>> print(d.dtype.descr)
[('x', '<f8')]
>>> f.design(xval, return_float=True)
array([ 3., 4., 5.])
Methods
__call__(*args) | |
apart([x]) | See the apart function in sympy.polys |
args_cnc() | treat self as Mul and split it into tuple (set, list) |
as_base_exp() | |
as_coeff_Mul() | Efficiently extract the coefficient of a product. |
as_coeff_add(*deps) | Return the tuple (c, args) where self is written as an Add, a. |
as_coeff_exponent(x) | c*x**e -> c,e where x can be any symbolic expression. |
as_coeff_factors(*deps) | |
as_coeff_mul(*deps) | Return the tuple (c, args) where self is written as a Mul, m. |
as_coeff_terms(*deps) | |
as_coefficient(expr) | Extracts symbolic coefficient at the given expression. |
as_dummy() | |
as_expr(*gens) | Convert a polynomial to a SymPy expression. |
as_independent(*deps, **hint) | A mostly naive separation of a Mul or Add into arguments that are not |
as_leading_term(*args, **kw_args) | Returns the leading term. |
as_numer_denom() | |
as_ordered_factors([order]) | Transform an expression to an ordered list of factors. |
as_ordered_terms([order, data]) | Transform an expression to an ordered list of terms. |
as_poly(*gens, **args) | Converts self to a polynomial or returns None. |
as_powers_dict() | |
as_real_imag([deep]) | |
as_terms() | Transform an expression to a list of terms. |
atoms(*types) | Returns the atoms that form the current object. |
cancel(*gens, **args) | See the cancel function in sympy.polys |
class_key() | |
coeff(x[, right]) | Returns the coefficient of the exact term “x” or None if there is no “x”. |
collect(syms[, evaluate, exact]) | See the collect function in sympy.simplify |
combsimp() | See the combsimp function in sympy.simplify |
compare(other) | Return -1,0,1 if the object is smaller, equal, or greater than other. |
compare_pretty(a, b) | Is a > b in the sense of ordering in printing? :: yes ..... |
compute_leading_term(x[, skip_abs, logx]) | as_leading_term is only allowed for results of .series() |
conjugate() | |
could_extract_minus_sign() | Canonical way to choose an element in the set {e, -e} where e is any expression. |
count(query) | Count the number of matching subexpressions. |
count_ops([visual]) | wrapper for count_ops that returns the operation count. |
diff(*symbols, **assumptions) | |
doit(**hints) | |
dummy_eq(other[, symbol]) | Compare two expressions and handle dummy symbols. |
evalf([n, subs, maxn, chop, strict, quad, ...]) | Evaluate the given formula to an accuracy of n digits. |
expand([deep, modulus, power_base, ...]) | Expand an expression using hints. |
extract_additively(c) | Return None if it’s not possible to make self in the form |
extract_multiplicatively(c) | Return None if it’s not possible to make self in the form |
factor(*gens, **args) | See the factor() function in sympy.polys.polytools |
find(query[, group]) | Find all subexpressions matching a query. |
fromiter(args, **assumptions) | Create a new object from an iterable. |
getO() | Returns the additive O(..) symbol if there is one, else None. |
getn() | Returns the order of the expression. |
has(*args, **kw_args) | Test whether any subexpression matches any of the patterns. |
integrate(*args, **kwargs) | See the integrate function in sympy.integrals |
invert(g) | See the invert function in sympy.polys |
is_hypergeometric(k) | |
is_polynomial(*syms) | Return True if self is a polynomial in syms and False otherwise. |
is_rational_function(*syms) | Test whether function is a ratio of two polynomials in the given symbols, syms. |
iter_basic_args() | Iterates arguments of ‘self’. |
leadterm(x) | Returns the leading term a*x**b as a tuple (a, b). |
limit(x, xlim[, dir]) | Compute limit x->xlim. |
lseries([x, x0, dir]) | Wrapper for series yielding an iterator of the terms of the series. |
match(pattern) | Pattern matching. |
matches(expr[, repl_dict, evaluate]) | |
n([n, subs, maxn, chop, strict, quad, verbose]) | Evaluate the given formula to an accuracy of n digits. |
normal() | |
nseries([x, x0, n, dir, logx]) | Wrapper to _eval_nseries if assumptions allow, else to series. |
nsimplify([constants, tolerance, full]) | See the nsimplify function in sympy.simplify |
powsimp([deep, combine]) | See the powsimp function in sympy.simplify |
radsimp() | See the radsimp function in sympy.simplify |
ratsimp() | See the ratsimp function in sympy.simplify |
refine([assumption]) | See the refine function in sympy.assumptions |
removeO() | Removes the additive O(..) symbol if there is one |
replace(query, value[, map]) | Replace matching subexpressions of self with value. |
rewrite(*args, **hints) | Rewrites expression containing applications of functions of one kind in terms of functions of different kind. |
separate([deep, force]) | See the separate function in sympy.simplify |
series([x, x0, n, dir]) | Series expansion of “self” around x = x0 yielding either terms of |
simplify() | See the simplify function in sympy.simplify |
sort_key([order]) | |
subs(*args) | Substitutes an expression. |
together(*args, **kwargs) | See the together function in sympy.polys |
trigsimp([deep, recursive]) | See the trigsimp function in sympy.simplify |
x.__init__(...) initializes x; see help(type(x)) for signature
See the apart function in sympy.polys
Returns a tuple of arguments of ‘self’.
Example:
>>> from sympy import symbols, cot
>>> from sympy.abc import x, y
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).
treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.
A special treatment is that -1 is separated from a Rational:
>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]
The arg is treated as a Mul:
>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
Efficiently extract the coefficient of a product.
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.
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
c*x**e -> c,e where x can be any symbolic expression.
Return the tuple (c, args) where self is written as a Mul, m.
c should be a Rational multiplied by any terms of the Mul that are independent of deps.
args should be a tuple of all other terms 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.
>>> from sympy import S
>>> from sympy.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, ())
Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.
>>> from sympy import E, pi, sin, I, symbols
>>> from sympy.abc import x, y
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)
>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> (2*E*x + x).as_coefficient(E)
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)
Convert a polynomial to a SymPy expression.
Examples
>>> from sympy import sin
>>> from sympy.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)
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.:
The only non-naive thing that is done here is to respect noncommutative ordering of variables.
The returned tuple (i, d) has the following interpretation:
To force the expression to be treated as an Add, use the hint as_Add=True
Examples:
– self is an Add
>>> from sympy import sin, cos, exp
>>> from sympy.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 sympy 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=1)
(0, 3*x)
– force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)
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 sympy 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))
Returns the leading term.
Example:
>>> from sympy.abc import x
>>> (1+x+x**2).as_leading_term(x)
1
>>> (1/x**2+x+x**2).as_leading_term(x)
x**(-2)
Note:
self is assumed to be the result returned by Basic.series().
Transform an expression to an ordered list of factors.
Examples
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
[2, x, y, sin(x), cos(x)]
Transform an expression to an ordered list of terms.
Examples
>>> from sympy import sin, cos
>>> from sympy.abc import x, y
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
Converts self to a polynomial or returns None.
>>> from sympy import Poly, sin
>>> from sympy.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
Transform an expression to a list of terms.
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.
Example:
>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
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 sympy import I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])
If one or more types are given, the results will contain only those types of atoms.
Examples:
>>> from sympy import Number, NumberSymbol, Symbol
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
set([x, y])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
set([1, 2])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
set([1, 2, pi])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
set([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
set([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 sympy import S
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
set([1])
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
set([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 sympy import Function, Mul
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
See the cancel function in sympy.polys
Returns the coefficient of the exact term “x” or None if there is no “x”.
When x is noncommutative, the coeff to the left (default) or right of x can be returned. The keyword ‘right’ is ignored when x is commutative.
Examples:
>>> from sympy import symbols
>>> from sympy.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)
You can select terms that have a numerical term in front of them:
>>> (-x-2*y).coeff(2)
-y
>>> from sympy 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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)
In addition, no factoring is done, so 2 + y is not obtained from the following:
>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:
>>> (n*m + m*n).coeff(n)
If there is only one possible coefficient, it is returned:
>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
See the collect function in sympy.simplify
See the combsimp function in sympy.simplify
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.
Example:
>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
Is a > b in the sense of ordering in printing?
yes ..... return 1
no ...... return -1
equal ... return 0
Strategy:
It uses Basic.compare as a fallback, but improves it in many cases, like x**3, x**4, O(x**3) etc. In those simple cases, it just parses the expression and returns the “sane” ordering such as:
1 < x < x**2 < x**3 < O(x**4) etc.
Example:
>>> from sympy.abc import x
>>> from sympy import Basic, Number
>>> Basic._compare_pretty(x, x**2)
-1
>>> Basic._compare_pretty(x**2, x**2)
0
>>> Basic._compare_pretty(x**3, x**2)
1
>>> Basic._compare_pretty(Number(1, 2), Number(1, 3))
1
>>> Basic._compare_pretty(Number(0), Number(-1))
1
as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first. If skip_abs is true, the absolute term is assumed to be zero. (This is necessary because sometimes it cannot be simplified
to zero without a lot of work, but is still known to be zero. See log._eval_nseries for an example.)
If skip_log is true, log(x) is treated as an independent symbol. (This is needed for the gruntz algorithm.)
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 sympy.abc import x, y
>>> (x-y).could_extract_minus_sign() != (y-x).could_extract_minus_sign()
True
Count the number of matching subexpressions.
wrapper for count_ops that returns the operation count.
Compare two expressions and handle dummy symbols.
Examples
>>> from sympy import Dummy
>>> from sympy.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
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}.
- 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)
Expand an expression using hints.
See the docstring in function.expand for more information.
Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.
>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
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 sympy 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
See the factor() function in sympy.polys.polytools
Find all subexpressions matching a query.
Return a Formula with only terms=[self].
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.
Example:
>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
The top-level function in an expression.
The following should hold for all objects:
>> x == x.func(*x.args)
Example:
>>> from sympy.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
Returns the additive O(..) symbol if there is one, else None.
Returns the order of the expression.
The order is determined either from the O(...) term. If there is no O(...) term, it returns None.
Example:
>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
Test whether any subexpression matches any of the patterns.
Examples:
>>> from sympy import sin, S
>>> from sympy.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 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
See the integrate function in sympy.integrals
See the invert function in sympy.polys
Deprecated alias for is_Float
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 only 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 sympy 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 sympy 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()
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).
Example:
>>> from sympy import Symbol, sin
>>> from sympy.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 sympy import sqrt, factor, cancel
>>> 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_rational_function().
Iterates arguments of ‘self’.
Example:
>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
Returns the leading term a*x**b as a tuple (a, b).
Example:
>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
Note:
self is assumed to be the result returned by Basic.series().
Compute limit x->xlim.
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().
Pattern matching.
Wild symbols match all.
Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:
pattern.subs(self.match(pattern)) == self
Example:
>>> from sympy import symbols, Wild
>>> from sympy.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).subs(e.match(p*q**r))
4*x**2
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}.
- 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)
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.
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().
See the nsimplify function in sympy.simplify
See the powsimp function in sympy.simplify
See the radsimp function in sympy.simplify
See the ratsimp function in sympy.simplify
See the refine function in sympy.assumptions
Removes the additive O(..) symbol if there is one
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.
Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The list of possible combinations of queries and replacement values is listed below:
Examples:
>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('a')
>>> f.replace(sin(a), cos(a))
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin(a), lambda a: sin(2*a))
log(sin(2*x)) + tan(sin(2*x**2))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
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 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.
>>> from sympy import sin, exp, I
>>> from sympy.abc import x, y
>>> sin(x).rewrite(sin, exp)
-I*(exp(I*x) - exp(-I*x))/2
See the separate function in sympy.simplify
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.
Note: when n != None, if an O() term is returned then the x in the in it and the entire expression represents x - x0, the displacement from x0. (If there is no O() term then the series was exact and x has it’s normal meaning.) This is currently necessary since sympy’s O() can only represent terms at x0=0. So instead of:
cos(x).series(x0=1, n=2) --> (1 - x)*sin(1) + cos(1) + O((x - 1)**2)
which graphically looks like this:
|
.|. . .
. | \ . .
---+----------------------
| . . . .
| x=0
the following is returned instead:
-x*sin(1) + cos(1) + O(x**2)
whose graph is this:
\ |
. .| . .
. \ . .
-----+\------------------.
| . . . .
| x=0
which is identical to cos(x + 1).series(n=2).
Returns the series expansion of “self” around the point x = x0 with respect to x up to O(x**n) (default n is 6).
If x=None and self is univariate, the univariate symbol will be supplied, otherwise an error will be raised.
>>> from sympy import cos, exp
>>> from sympy.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)
>>> 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 an iterator of the series terms will be returned.
>>> term=cos(x).series(n=None)
>>> [term.next() 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
See the simplify function in sympy.simplify
Substitutes an expression.
Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.
Examples:
>>> from sympy import pi
>>> from sympy.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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
See the together function in sympy.polys
See the trigsimp function in sympy.simplify
Construct a contrast matrix from a design matrix D
(possibly with its pseudo inverse already computed) and a matrix L that either specifies something in the column space of D or the row space of D.
Parameters : | L : ndarray
D : ndarray
pseudo : None or array-like, optional
|
---|---|
Returns : | C : ndarray
|
Notes
From an n x p design matrix D and a matrix L, tries to determine a p x q contrast matrix C which determines a contrast of full rank, i.e. the n x q matrix
dot(transpose(C), pinv(D))
is full rank.
L must satisfy either L.shape[0] == n or L.shape[1] == p.
If L.shape[0] == n, then L is thought of as representing columns in the column space of D.
If L.shape[1] == p, then L is thought of as what is known as a contrast matrix. In this case, this function returns an estimable contrast corresponding to the dot(D, L.T)
This always produces a meaningful contrast, not always with the intended properties because q is always non-zero unless L is identically 0. That is, it produces a contrast that spans the column space of L (after projection onto the column space of D).
Return the parameters of an expression that are not Term instances but are instances of sympy.Symbol.
Examples
>>> x, y, z = [Term(l) for l in 'xyz']
>>> f = Formula([x,y,z])
>>> getparams(f)
[]
>>> f.mean
_b0*x + _b1*y + _b2*z
>>> getparams(f.mean)
[_b0, _b1, _b2]
>>> th = sympy.Symbol('theta')
>>> f.mean*sympy.exp(th)
(_b0*x + _b1*y + _b2*z)*exp(theta)
>>> getparams(f.mean*sympy.exp(th))
[_b0, _b1, _b2, theta]
Return the all instances of Term in an expression.
Examples
>>> x, y, z = [Term(l) for l in 'xyz']
>>> f = Formula([x,y,z])
>>> getterms(f)
[x, y, z]
>>> getterms(f.mean)
[x, y, z]
Is obj a Factor?
Is obj a FactorTerm?
Is obj a Formula?
Is obj a Term?
make_dummy is deprecated! Please use sympy.Dummy instead of this function
Make dummy variable of given name
Parameters : | name : str
|
---|---|
Returns : | dum : Dummy instance |
Notes
The interface to Dummy changed between 0.6.7 and 0.7.0, and we used this function to keep compatibility. Now we depend on sympy 0.7.0 and this function is obsolete.
Create recarray from rows with field names names
Create a recarray with named columns from a list or ndarray of rows and sequence of names for the columns. If rows is an ndarray, dtypes must be None, otherwise we raise a ValueError. Otherwise, if dtypes is None, we cast the data in all columns in rows as np.float. If dtypes is not None, the routine uses dtypes as a dtype specifier for the output structured array.
Parameters : | rows: list or array :
names: sequence :
dtypes: None or sequence of str or sequence of np.dtype :
|
---|---|
Returns : | v : np.ndarray
|
Examples
The following tests depend on machine byte order for their exact output.
>>> arr = np.array([[3, 4], [4, 6], [6, 8]])
>>> make_recarray(arr, ['x', 'y'])
array([[(3, 4)],
[(4, 6)],
[(6, 8)]],
dtype=[('x', '...'), ('y', '...')])
>>> r = make_recarray(arr, ['w', 'u'])
>>> make_recarray(r, ['x', 'y'])
array([[(3, 4)],
[(4, 6)],
[(6, 8)]],
dtype=[('x', '...'), ('y', '...')])
>>> make_recarray([[3, 4], [4, 6], [7, 9]], 'wv', [np.float, np.int])
array([(3.0, 4), (4.0, 6), (7.0, 9)],
dtype=[('w', '...'), ('v', '...')])
Return a Formula containing a natural spline
Spline for a Term with specified knots and order.
Parameters : | t : Term knots : None or sequence, optional
order : int, optional
intercept : bool, optional
|
---|---|
Returns : | formula : Formula
|
Examples
>>> x = Term('x')
>>> n = natural_spline(x, knots=[1,3,4], order=3)
>>> xval = np.array([3,5,7.]).view(np.dtype([('x', np.float)]))
>>> n.design(xval, return_float=True)
array([[ 3., 9., 27., 8., 0., -0.],
[ 5., 25., 125., 64., 8., 1.],
[ 7., 49., 343., 216., 64., 27.]])
>>> d = n.design(xval)
>>> print(d.dtype.descr)
[('ns_1(x)', '<f8'), ('ns_2(x)', '<f8'), ('ns_3(x)', '<f8'), ('ns_4(x)', '<f8'), ('ns_5(x)', '<f8'), ('ns_6(x)', '<f8')]
Return list of terms with names given by names
This is just a convenience in defining a set of terms, and is the equivalent of sympy.symbols for defining symbols in sympy.
We enforce the sympy 0.7.0 behavior of returning symbol “abc” from input “abc”, rthan than 3 symbols “a”, “b”, “c”.
Parameters : | names : str or sequence of str
**kwargs : keyword arguments
|
---|---|
Returns : | ts : Term or tuple
|
Examples
>>> terms(('a', 'b', 'c'))
(a, b, c)
>>> terms('a, b, c')
(a, b, c)
>>> terms('abc')
abc