Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
from __future__ import print_function, division
from collections import defaultdict from functools import cmp_to_key
from .basic import Basic from .compatibility import reduce, is_sequence, range from .logic import _fuzzy_group, fuzzy_or, fuzzy_not from .singleton import S from .operations import AssocOp from .cache import cacheit from .numbers import ilcm, igcd from .expr import Expr
# Key for sorting commutative args in canonical order _args_sortkey = cmp_to_key(Basic.compare) def _addsort(args): # in-place sorting of args
def _unevaluated_Add(*args): """Return a well-formed unevaluated Add: Numbers are collected and put in slot 0 and args are sorted. Use this when args have changed but you still want to return an unevaluated Add.
Examples ========
>>> from sympy.core.add import _unevaluated_Add as uAdd >>> from sympy import S, Add >>> from sympy.abc import x, y >>> a = uAdd(*[S(1.0), x, S(2)]) >>> a.args[0] 3.00000000000000 >>> a.args[1] x
Beyond the Number being in slot 0, there is no other assurance of order for the arguments since they are hash sorted. So, for testing purposes, output produced by this in some other function can only be tested against the output of this function or as one of several options:
>>> opts = (Add(x, y, evaluated=False), Add(y, x, evaluated=False)) >>> a = uAdd(x, y) >>> assert a in opts and a == uAdd(x, y)
""" # this will keep nesting from building up # so that x + (x + 1) -> x + x + 1 (3 args) else:
class Add(Expr, AssocOp):
__slots__ = []
is_Add = True
@classmethod def flatten(cls, seq): """ Takes the sequence "seq" of nested Adds and returns a flatten list.
Returns: (commutative_part, noncommutative_part, order_symbols)
Applies associativity, all terms are commutable with respect to addition.
NB: the removal of 0 is already handled by AssocOp.__new__
See also ========
sympy.core.mul.Mul.flatten
""" return [], rv[0], None
# e.g. x**2 -> 5 for ... + 5*x**2 + ...
# e.g. 3 + ...
# O(x) if o1.contains(o): o = None break continue o1 for o1 in order_factors if not o.contains(o1)]
# 3 or NaN o.is_finite is False): # we know for sure the result will be nan return [S.NaN], [], None # we know for sure the result will be nan return [S.NaN], [], None
coeff = o.__add__(coeff) continue
# we know for sure the result will be nan
# Add([...]) # NB: here we assume Add is always commutative
# Mul([...])
# check for unevaluated Pow, e.g. 2**3 or 2**(-1/2) (e.is_Rational and e.is_negative)): seq.append(b**e) continue
else: # everything else
# now we have: # o = c*s, where # # c is a Number # s is an expression with number factor extracted # let's collect terms with the same s, so e.g. # 2*x**2 + 3*x**2 -> 5*x**2 # we know for sure the result will be nan return [S.NaN], [], None else:
# now let's construct new args: # [2*x**2, x**3, 7*x**4, pi, ...] # 0*s # 1*s # c*s else: # Mul, already keeps its arguments in perfect order. # so we can simply put c in slot0 and go the fast way. # we just re-create the unevaluated Mul newseq.append(Mul(c, s, evaluate=False)) else: # alternatively we have to call all Mul's machinery (slow)
# oo, -oo (f.is_nonnegative or f.is_real and f.is_finite)]
(f.is_nonpositive or f.is_real and f.is_finite)]
# zoo might be # infinite_real + finite_im # finite_real + infinite_im # infinite_real + infinite_im # addition of a finite real or imaginary number won't be able to # change the zoo nature; adding an infinite qualtity would result # in a NaN condition if it had sign opposite of the infinite # portion of zoo, e.g., infinite_real - infinite_real. c.is_real is not None)]
# process O(x) # x + O(x) -> O(x) # x + O(x**2) -> x + O(x**2) # 1 + O(1) -> O(1)
# order args canonically
# current code expects coeff to be first
# we are done return [], newseq, None else:
@classmethod def class_key(cls): """Nice order of classes"""
def as_coefficients_dict(a): """Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. If an expression is not an Add it is considered to have a single term.
Examples ========
>>> from sympy.abc import a, x >>> (3*x + a*x + 4).as_coefficients_dict() {1: 4, x: 3, a*x: 1} >>> _[a] 0 >>> (3*a*x).as_coefficients_dict() {a*x: 3} """
else: d[k] = Add(*v)
@cacheit def as_coeff_add(self, *deps): """ Returns a tuple (coeff, args) where self is treated as an Add and coeff is the Number term and args is a tuple of all other terms.
Examples ========
>>> from sympy.abc import x >>> (7 + 3*x).as_coeff_add() (7, (3*x,)) >>> (7*x).as_coeff_add() (0, (7*x,)) """ else: return coeff, notrat + self.args[1:]
def as_coeff_Add(self, rational=False): """Efficiently extract the coefficient of a summation. """
# Note, we intentionally do not implement Add.as_coeff_mul(). Rather, we # let Expr.as_coeff_mul() just always return (S.One, self) for an Add. See # issue 5524.
@cacheit def _eval_derivative(self, s):
def _eval_nseries(self, x, n, logx):
def _matches_simple(self, expr, repl_dict): # handle (w+3).matches('x+5') -> {w: x+2} return terms[0].matches(expr - coeff, repl_dict)
def matches(self, expr, repl_dict={}, old=False):
@staticmethod def _combine_inverse(lhs, rhs): """ Returns lhs - rhs, but treats arguments like symbols, so things like oo - oo return 0, instead of a nan. """ return S.Zero
@cacheit def as_two_terms(self): """Return head and tail of self.
This is the most efficient way to get the head and tail of an expression.
- if you want only the head, use self.args[0]; - if you want to process the arguments of the tail then use self.as_coef_add() which gives the head and a tuple containing the arguments of the tail when treated as an Add. - if you want the coefficient when self is treated as a Mul then use self.as_coeff_mul()[0]
>>> from sympy.abc import x, y >>> (3*x*y).as_two_terms() (3, x*y) """ return S.Zero, self
def as_numer_denom(self):
# clear rational denominator
# collect numerators and denominators of the terms # put infinity in the numerator n = nd.pop(S.Zero) assert len(n) == 1 n = n[0] nd[S.One].append(n/S.Zero)
# check for quick exit *[_keep_coeff(ncon, ni) for ni in n]), _keep_coeff(dcon, d)
# sum up the terms having a common denominator else:
# assemble single numerator and denominator for i in range(len(numers))]), Mul(*denoms)
def _eval_is_polynomial(self, syms):
def _eval_is_rational_function(self, syms):
def _eval_is_algebraic_expr(self, syms): return all(term._eval_is_algebraic_expr(syms) for term in self.args)
# assumption methods (a.is_real for a in self.args), quick_exit=True) (a.is_complex for a in self.args), quick_exit=True) (a.is_antihermitian for a in self.args), quick_exit=True) (a.is_finite for a in self.args), quick_exit=True) (a.is_hermitian for a in self.args), quick_exit=True) (a.is_integer for a in self.args), quick_exit=True) (a.is_rational for a in self.args), quick_exit=True) (a.is_algebraic for a in self.args), quick_exit=True) a.is_commutative for a in self.args)
def _eval_is_imaginary(self): pass else: else:
def _eval_is_zero(self): # issue 10528: there is no way to know if a nc symbol # is zero or not return z += 1 else: else: return True
def _eval_is_odd(self): return False
def _eval_is_irrational(self):
def _eval_is_positive(self): return False return
return
def _eval_is_nonnegative(self):
def _eval_is_nonpositive(self): return True return True
def _eval_is_negative(self): return False return
return return True
def _eval_subs(self, old, new):
coeff_self, terms_self = self.as_coeff_Add() coeff_old, terms_old = old.as_coeff_Add()
if coeff_self.is_Rational and coeff_old.is_Rational: if terms_self == terms_old: # (2 + a).subs( 3 + a, y) -> -1 + y return self.func(new, coeff_self, -coeff_old) if terms_self == -terms_old: # (2 + a).subs(-3 - a, y) -> -1 - y return self.func(-new, coeff_self, coeff_old)
if coeff_self.is_Rational and coeff_old.is_Rational \ or coeff_self == coeff_old: args_old, args_self = self.func.make_args( terms_old), self.func.make_args(terms_self) if len(args_old) < len(args_self): # (a+b+c).subs(b+c,x) -> a+x self_set = set(args_self) old_set = set(args_old)
if old_set < self_set: ret_set = self_set - old_set return self.func(new, coeff_self, -coeff_old, *[s._subs(old, new) for s in ret_set])
args_old = self.func.make_args( -terms_old) # (a+b+c+d).subs(-b-c,x) -> a-x+d old_set = set(args_old) if old_set < self_set: ret_set = self_set - old_set return self.func(-new, coeff_self, coeff_old, *[s._subs(old, new) for s in ret_set])
def removeO(self):
def getO(self): return self._new_rawargs(*args)
@cacheit def extract_leading_order(self, symbols, point=None): """ Returns the leading term and its order.
Examples ========
>>> from sympy.abc import x >>> (x + 1 + 1/x**5).extract_leading_order(x) ((x**(-5), O(x**(-5))),) >>> (1 + x).extract_leading_order(x) ((1, O(1)),) >>> (x + x**2).extract_leading_order(x) ((x, O(x)),)
""" new_lst.append((e, o))
def as_real_imag(self, deep=True, **hints): """ returns a tuple representing a complex number
Examples ========
>>> from sympy import I >>> (7 + 9*I).as_real_imag() (7, 9) >>> ((1 + I)/(1 - I)).as_real_imag() (0, 1) >>> ((1 + 2*I)*(1 + 3*I)).as_real_imag() (-5, 5) """
def _eval_as_leading_term(self, x): from sympy import expand_mul, factor_terms
old = self
expr = expand_mul(self) if not expr.is_Add: return expr.as_leading_term(x)
infinite = [t for t in expr.args if t.is_infinite]
expr = expr.func(*[t.as_leading_term(x) for t in expr.args]).removeO() if not expr: # simple leading term analysis gave us 0 but we have to send # back a term, so compute the leading term (via series) return old.compute_leading_term(x) elif expr is S.NaN: return old.func._from_args(infinite) elif not expr.is_Add: return expr else: plain = expr.func(*[s for s, _ in expr.extract_leading_order(x)]) rv = factor_terms(plain, fraction=False) rv_simplify = rv.simplify() # if it simplifies to an x-free expression, return that; # tests don't fail if we don't but it seems nicer to do this if x not in rv_simplify.free_symbols: if rv_simplify.is_zero and plain.is_zero is not True: return (expr - plain)._eval_as_leading_term(x) return rv_simplify return rv
def _eval_adjoint(self): return self.func(*[t.adjoint() for t in self.args])
def _eval_conjugate(self):
def _eval_transpose(self): return self.func(*[t.transpose() for t in self.args])
def __neg__(self):
def _sage_(self): s = 0 for x in self.args: s += x._sage_() return s
def primitive(self): """ Return ``(R, self/R)`` where ``R``` is the Rational GCD of ``self```.
``R`` is collected only from the leading coefficient of each term.
Examples ========
>>> from sympy.abc import x, y
>>> (2*x + 4*y).primitive() (2, x + 2*y)
>>> (2*x/3 + 4*y/9).primitive() (2/9, 3*x + 2*y)
>>> (2*x/3 + 4.2*y).primitive() (1/3, 2*x + 12.6*y)
No subprocessing of term factors is performed:
>>> ((2 + 2*x)*x + 2).primitive() (1, x*(2*x + 2) + 2)
Recursive subprocessing can be done with the as_content_primitive() method:
>>> ((2 + 2*x)*x + 2).as_content_primitive() (2, x*(x + 1) + 1)
See also: primitive() function in polytools.py
"""
else: ngcd = reduce(igcd, [t[0] for t in terms if t[1]], 0) dlcm = reduce(ilcm, [t[1] for t in terms if t[1]], 1)
else: for i, (p, q, term) in enumerate(terms): if q: terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term) else: terms[i] = _keep_coeff(Rational(p, q), term)
# we don't need a complete re-flattening since no new terms will join # so we just use the same sort as is used in Add.flatten. When the # coefficient changes, the ordering of terms may change, e.g. # (3*x, 6*y) -> (2*y, x) # # We do need to make sure that term[0] stays in position 0, however. # else:
def as_content_primitive(self, radical=False, clear=True): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. If radical is True (default is False) then common radicals will be removed and included as a factor of the primitive expression.
Examples ========
>>> from sympy import sqrt >>> (3 + 3*sqrt(2)).as_content_primitive() (3, 1 + sqrt(2))
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5)))
See docstring of Expr.as_content_primitive for more examples. """ radical=radical, clear=clear)) for a in self.args]).primitive() else: # look for common radicals that can be removed else: break else: # process rads # keep only those in common_q r.pop(q) # find the gcd of bases for each q
@property def _sorted_args(self): from sympy.core.compatibility import default_sort_key return tuple(sorted(self.args, key=lambda w: default_sort_key(w)))
def _eval_difference_delta(self, n, step): from sympy.series.limitseq import difference_delta as dd return self.func(*[dd(a, n, step) for a in self.args])
from .mul import Mul, _keep_coeff, prod from sympy.core.numbers import Rational |