def __new__(cls, *args, **options): if len(args) == 0: return cls.identity args = map(_sympify, args) if len(args) == 1: return args[0] if not options.pop('evaluate', True): obj = Expr.__new__(cls, *args) obj.is_commutative = all(a.is_commutative for a in args) return obj c_part, nc_part, order_symbols = cls.flatten(args) if len(c_part) + len(nc_part) <= 1: if c_part: obj = c_part[0] elif nc_part: obj = nc_part[0] else: obj = cls.identity else: obj = Expr.__new__(cls, *(c_part + nc_part)) obj.is_commutative = not nc_part if order_symbols is not None: obj = C.Order(obj, *order_symbols) return obj
def __new__(cls, expr, *symbols, **assumptions): expr = sympify(expr) if not symbols: return expr symbols = Derivative._symbolgen(*symbols) if expr.is_commutative: assumptions['commutative'] = True evaluate = assumptions.pop('evaluate', False) if not evaluate and not isinstance(expr, Derivative): symbols = list(symbols) if len(symbols) == 0: # We make a special case for 0th derivative, because there # is no good way to unambiguously print this. return expr obj = Expr.__new__(cls, expr, *symbols, **assumptions) return obj unevaluated_symbols = [] for s in symbols: s = sympify(s) if not isinstance(s, C.Symbol): raise ValueError( 'Invalid literal: %s is not a valid variable' % s) obj = expr._eval_derivative(s) if obj is None: unevaluated_symbols.append(s) elif obj is S.Zero: return S.Zero else: expr = obj if not unevaluated_symbols: return expr return Expr.__new__(cls, expr, *unevaluated_symbols, **assumptions)
def __new__(cls, *args, **assumptions): if assumptions.get('evaluate') is False: args = map(_sympify, args) obj = Expr.__new__(cls, *args, **assumptions) obj.is_commutative = all(arg.is_commutative for arg in args) return obj if len(args)==0: return cls.identity if len(args)==1: return _sympify(args[0]) c_part, nc_part, order_symbols = cls.flatten(map(_sympify, args)) if len(c_part) + len(nc_part) <= 1: if c_part: obj = c_part[0] elif nc_part: obj = nc_part[0] else: obj = cls.identity else: obj = Expr.__new__(cls, *(c_part + nc_part), **assumptions) obj.is_commutative = not nc_part if order_symbols is not None: obj = C.Order(obj, *order_symbols) return obj
def __new__(cls, expr, *symbols, **assumptions): expr = sympify(expr) if not symbols: return expr symbols = Derivative._symbolgen(*symbols) if expr.is_commutative: assumptions['commutative'] = True evaluate = assumptions.pop('evaluate', False) if not evaluate and not isinstance(expr, Derivative): symbols = list(symbols) if len(symbols) == 0: # We make a special case for 0th derivative, because there # is no good way to unambiguously print this. return expr obj = Expr.__new__(cls, expr, *symbols, **assumptions) return obj unevaluated_symbols = [] for s in symbols: s = sympify(s) if not isinstance(s, C.Symbol): raise ValueError('Invalid literal: %s is not a valid variable' % s) obj = expr._eval_derivative(s) if obj is None: unevaluated_symbols.append(s) elif obj is S.Zero: return S.Zero else: expr = obj if not unevaluated_symbols: return expr return Expr.__new__(cls, expr, *unevaluated_symbols, **assumptions)
def __new__(cls, *args, **assumptions): if len(args) == 0: return cls.identity args = map(_sympify, args) if len(args) == 1: return args[0] if not assumptions.pop('evaluate', True): obj = Expr.__new__(cls, *args, **assumptions) obj.is_commutative = all(a.is_commutative for a in args) return obj c_part, nc_part, order_symbols = cls.flatten(args) if len(c_part) + len(nc_part) <= 1: if c_part: obj = c_part[0] elif nc_part: obj = nc_part[0] else: obj = cls.identity else: obj = Expr.__new__(cls, *(c_part + nc_part), **assumptions) obj.is_commutative = not nc_part if order_symbols is not None: obj = C.Order(obj, *order_symbols) return obj
def __new__(cls, p, q = None): if q is None: if isinstance(p, basestring): p, q = _parse_rational(p) elif isinstance(p, Rational): return p else: return Integer(p) q = int(q) p = int(p) if q==0: if p==0: if _errdict["divide"]: raise ValueError("Indeterminate 0/0") else: return S.NaN if p<0: return S.NegativeInfinity return S.Infinity if q<0: q = -q p = -p n = igcd(abs(p), q) if n>1: p //= n q //= n if q==1: return Integer(p) if p==1 and q==2: return S.Half obj = Expr.__new__(cls) obj.p = p obj.q = q #obj._args = (p, q) return obj
def __new_stage2__(cls, name, **assumptions): if not isinstance(name, basestring): raise TypeError("name should be a string, not %s" % repr(type(name))) obj = Expr.__new__(cls) obj.name = name obj._assumptions = StdFactKB(assumptions) return obj
def _new(cls, _mpf_, _prec): if _mpf_ == mlib.fzero: return S.Zero obj = Expr.__new__(cls) obj._mpf_ = _mpf_ obj._prec = _prec return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: try: rop_cls = Relational.ValidRelationOperator[rop] except KeyError: msg = "Invalid relational operator symbol: '%r'" raise ValueError(msg % repr(rop)) if lhs.is_number and rhs.is_number and (rop_cls in (Equality, Unequality) or lhs.is_real and rhs.is_real): diff = lhs - rhs know = diff.equals(0, failing_expression=True) if know is True: # exclude failing expression case Nlhs = S.Zero elif know is False: from sympy import sign Nlhs = sign(diff.n(1)) else: Nlhs = None lhs = know rhs = S.Zero if Nlhs is not None: return rop_cls._eval_relation(Nlhs, S.Zero) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, p, q=None): if q is None: if isinstance(p, basestring): p, q = _parse_rational(p) elif isinstance(p, Rational): return p else: return Integer(p) q = int(q) p = int(p) if q == 0: if p == 0: if _errdict["divide"]: raise ValueError("Indeterminate 0/0") else: return S.NaN if p < 0: return S.NegativeInfinity return S.Infinity if q < 0: q = -q p = -p n = igcd(abs(p), q) if n > 1: p //= n q //= n if q == 1: return Integer(p) if p == 1 and q == 2: return S.Half obj = Expr.__new__(cls) obj.p = p obj.q = q #obj._args = (p, q) return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: try: rop_cls = Relational.ValidRelationOperator[rop] except KeyError: msg = "Invalid relational operator symbol: '%r'" raise ValueError(msg % repr(rop)) if (lhs.is_number and rhs.is_number and (rop_cls in (Equality, Unequality) or lhs.is_real and rhs.is_real)): diff = lhs - rhs know = diff.equals(0, failing_expression=True) if know is True: # exclude failing expression case Nlhs = S.Zero elif know is False: from sympy import sign Nlhs = sign(diff.n(2)) else: Nlhs = None lhs = know rhs = S.Zero if Nlhs is not None: return rop_cls._eval_relation(Nlhs, S.Zero) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, expr, variables, point, **assumptions): if not ordered_iter(variables, Tuple): variables = [variables] variables = Tuple(*sympify(variables)) if uniq(variables) != variables: repeated = repeated = [ v for v in set(variables) if list(variables).count(v) > 1 ] raise ValueError('cannot substitute expressions %s more than ' 'once.' % repeated) if not ordered_iter(point, Tuple): point = [point] point = Tuple(*sympify(point)) if len(point) != len(variables): raise ValueError('Number of point values must be the same as ' 'the number of variables.') # it's necessary to use dummy variables internally new_variables = Tuple(*[ arg.as_dummy() if arg.is_Symbol else C.Dummy(str(arg)) for arg in variables ]) expr = sympify(expr).subs(tuple(zip(variables, new_variables))) if expr.is_commutative: assumptions['commutative'] = True obj = Expr.__new__(cls, expr, new_variables, point, **assumptions) return obj
def __new__(cls, p, q=None): if q is None: if isinstance(p, Rational): return p if isinstance(p, basestring): try: # we might have a Real neg_pow, digits, expt = decimal.Decimal(p).as_tuple() p = [1, -1][neg_pow] * int("".join(str(x) for x in digits)) if expt > 0: rv = Rational(p*Pow(10, expt), 1) return Rational(p, Pow(10, -expt)) except decimal.InvalidOperation: import re f = re.match(' *([-+]? *[0-9]+)( */ *)([0-9]+)', p) if f: p, _, q = f.groups() return Rational(int(p), int(q)) else: raise ValueError('invalid literal: %s' % p) elif not isinstance(p, Basic): return Rational(S(p)) q = S.One if isinstance(q, Rational): p *= q.q q = q.p if isinstance(p, Rational): q *= p.q p = p.p p = int(p) q = int(q) if q == 0: if p == 0: if _errdict["divide"]: raise ValueError("Indeterminate 0/0") else: return S.NaN if p < 0: return S.NegativeInfinity return S.Infinity if q < 0: q = -q p = -p n = igcd(abs(p), q) if n > 1: p //= n q //= n if q == 1: return Integer(p) if p == 1 and q == 2: return S.Half obj = Expr.__new__(cls) obj.p = p obj.q = q #obj._args = (p, q) return obj
def _from_args(cls, args, is_commutative=None): """Create new instance with already-processed args""" if len(args) == 0: return cls.identity elif len(args) == 1: return args[0] obj = Expr.__new__(cls, *args) if is_commutative is None: is_commutative = all(a.is_commutative for a in args) obj.is_commutative = is_commutative return obj
def _from_args(cls, args, is_commutative=None): """Create new instance with already-processed args""" if len(args) == 0: return cls.identity elif len(args) == 1: return args[0] obj = Expr.__new__(cls, *args) if is_commutative is None: is_commutative = fuzzy_and(a.is_commutative for a in args) obj.is_commutative = is_commutative return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: rop_cls, swap = Relational.get_relational_class(rop) if swap: lhs, rhs = rhs, lhs if lhs.is_real and lhs.is_number and rhs.is_real and rhs.is_number: return rop_cls._eval_relation(lhs.evalf(), rhs.evalf()) else: obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, *args, **assumptions): if assumptions.get('evaluate') is False: args = map(_sympify, args) obj = Expr.__new__(cls, *args, **assumptions) obj.is_commutative = all(arg.is_commutative for arg in args) return obj if len(args) == 0: return cls.identity() if len(args) == 1: return _sympify(args[0]) c_part, nc_part, order_symbols = cls.flatten(map(_sympify, args)) if len(c_part) + len(nc_part) <= 1: if c_part: obj = c_part[0] elif nc_part: obj = nc_part[0] else: obj = cls.identity() else: obj = Expr.__new__(cls, *(c_part + nc_part), **assumptions) obj.is_commutative = not nc_part if order_symbols is not None: obj = C.Order(obj, *order_symbols) return obj
def __new__(cls, *args, **options): if len(args) == 0: return cls.identity args = map(_sympify, args) try: args = [a for a in args if a is not cls.identity] except AttributeError: pass if len(args) == 0: # recheck after filtering return cls.identity if len(args) == 1: return args[0] if not options.pop('evaluate', True): obj = Expr.__new__(cls, *args) obj.is_commutative = all(a.is_commutative for a in args) return obj c_part, nc_part, order_symbols = cls.flatten(args) if len(c_part) + len(nc_part) <= 1: if c_part: obj = c_part[0] elif nc_part: obj = nc_part[0] else: obj = cls.identity else: obj = Expr.__new__(cls, *(c_part + nc_part)) obj.is_commutative = not nc_part if order_symbols is not None: obj = C.Order(obj, *order_symbols) return obj
def __new__(cls, *args, **options): if len(args) == 0: return cls.identity args = map(_sympify, args) try: args = [a for a in args if a is not cls.identity] except AttributeError: pass if len(args) == 0: # recheck after filtering return cls.identity if len(args) == 1: return args[0] if not options.pop("evaluate", True): obj = Expr.__new__(cls, *args) obj.is_commutative = all(a.is_commutative for a in args) return obj c_part, nc_part, order_symbols = cls.flatten(args) if len(c_part) + len(nc_part) <= 1: if c_part: obj = c_part[0] elif nc_part: obj = nc_part[0] else: obj = cls.identity else: obj = Expr.__new__(cls, *(c_part + nc_part)) obj.is_commutative = not nc_part if order_symbols is not None: obj = C.Order(obj, *order_symbols) return obj
def __new__(cls, variables, expr): try: variables = Tuple(*variables) except TypeError: variables = Tuple(variables) if len(variables) == 1 and variables[0] == expr: return S.IdentityFunction #use dummy variables internally, just to be sure new_variables = [C.Dummy(arg.name) for arg in variables] expr = sympify(expr).subs(tuple(zip(variables, new_variables))) obj = Expr.__new__(cls, Tuple(*new_variables), expr) return obj
def __new__(cls, *args, **assumptions): args = (sympify(arg) for arg in args) try: _args = frozenset(cls._new_args_filter(args)) except ShortCircuit: return cls.zero if not _args: return cls.identity elif len(_args) == 1: return set(_args).pop() else: obj = Expr.__new__(cls, _args, **assumptions) obj._argset = _args return obj
def eval(cls,*args): obj = Expr.__new__(cls, *args) #use dummy variables internally, just to be sure nargs = len(args)-1 expression = args[nargs] funargs = [C.Symbol(arg.name, dummy=True) for arg in args[:nargs]] #probably could use something like foldl here for arg,funarg in zip(args[:nargs],funargs): expression = expression.subs(arg,funarg) funargs.append(expression) obj._args = tuple(funargs) return obj
def eval(cls, *args): obj = Expr.__new__(cls, *args) #use dummy variables internally, just to be sure nargs = len(args) - 1 expression = args[nargs] funargs = [C.Dummy(arg.name) for arg in args[:nargs]] #probably could use something like foldl here for arg, funarg in zip(args[:nargs], funargs): expression = expression.subs(arg, funarg) funargs.append(expression) obj._args = tuple(funargs) return obj
def __new__(cls, b, e, evaluate=True): b = _sympify(b) e = _sympify(e) if evaluate: if e is S.Zero: return S.One elif e is S.One: return b else: obj = b._eval_power(e) if obj is not None: return obj obj = Expr.__new__(cls, b, e) obj.is_commutative = (b.is_commutative and e.is_commutative) return obj
def __new__(cls, i): try: return _intcache[i] except KeyError: # We only work with well-behaved integer types. This converts, for # example, numpy.int32 instances. ival = int(i) try: obj = _intcache[ival] except KeyError: obj = Expr.__new__(cls) obj.p = ival _intcache[i] = obj return obj
def __new__(cls, b, e, **assumptions): b = _sympify(b) e = _sympify(e) if assumptions.pop('evaluate', True): if e is S.Zero: return S.One elif e is S.One: return b else: obj = b._eval_power(e) if obj is not None: return obj obj = Expr.__new__(cls, b, e, **assumptions) obj.is_commutative = (b.is_commutative and e.is_commutative) return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: try: rop_cls = Relational.ValidRelationOperator[ rop ] except KeyError: msg = "Invalid relational operator symbol: '%r'" raise ValueError(msg % repr(rop)) diff = S.NaN if isinstance(lhs, Expr) and isinstance(rhs, Expr): diff = lhs - rhs if not (diff is S.NaN or diff.has(Symbol)): know = diff.equals(0, failing_expression=True) if know is True: # exclude failing expression case diff = S.Zero elif know is False: diff = diff.n() if rop_cls is Equality: if (lhs == rhs) is True or (diff == S.Zero) is True: return True elif diff is S.NaN: pass elif diff.is_Number or diff.is_Float: return False elif lhs.is_real is not rhs.is_real and \ lhs.is_real is not None and \ rhs.is_real is not None: return False elif rop_cls is Unequality: if (lhs == rhs) is True or (diff == S.Zero) is True: return False elif diff is S.NaN: pass elif diff.is_Number or diff.is_Float: return True elif lhs.is_real is not rhs.is_real and \ lhs.is_real is not None and \ rhs.is_real is not None: return True elif diff.is_Number and diff.is_real: return rop_cls._eval_relation(diff, S.Zero) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: try: rop_cls = cls.ValidRelationOperator[ rop ] except KeyError: msg = "Invalid relational operator symbol: '%r'" raise ValueError(msg % repr(rop)) diff = S.NaN if isinstance(lhs, Expr) and isinstance(rhs, Expr): diff = lhs - rhs if not (diff is S.NaN or diff.has(Symbol)): know = diff.equals(0, failing_expression=True) if know is True: # exclude failing expression case diff = S.Zero elif know is False: diff = diff.n() if rop_cls is Equality: if (lhs == rhs) is True or (diff == S.Zero) is True: return True elif diff is S.NaN: pass elif diff.is_Number or diff.is_Float: return False elif lhs.is_real is not rhs.is_real and \ lhs.is_real is not None and \ rhs.is_real is not None: return False elif rop_cls is Unequality: if (lhs == rhs) is True or (diff == S.Zero) is True: return False elif diff is S.NaN: pass elif diff.is_Number or diff.is_Float: return True elif lhs.is_real is not rhs.is_real and \ lhs.is_real is not None and \ rhs.is_real is not None: return True elif diff.is_Number and diff.is_real: return rop_cls._eval_relation(diff, S.Zero) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, i): try: return _intcache[i] except KeyError: # We only work with well-behaved integer types. This converts, for # example, numpy.int32 instances. ival = int(i) if ival == 0: obj = S.Zero elif ival == 1: obj = S.One elif ival == -1: obj = S.NegativeOne else: obj = Expr.__new__(cls) obj.p = ival _intcache[i] = obj return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: rop_cls, swap = Relational.get_relational_class(rop) if swap: lhs, rhs = rhs, lhs if lhs.is_number and rhs.is_number and lhs.is_real and rhs.is_real: # Just becase something is a number, doesn't mean you can evalf it. Nlhs = lhs.evalf() if Nlhs.is_Number: # S.Zero.evalf() returns S.Zero, so test Number instead of Float Nrhs = rhs.evalf() if Nrhs.is_Number: return rop_cls._eval_relation(Nlhs, Nrhs) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: rop_cls, swap = Relational.get_relational_class(rop) if swap: lhs, rhs = rhs, lhs if lhs.is_real and lhs.is_number and rhs.is_real and rhs.is_number: # Just becase something is a number, doesn't mean you can evalf it. Nlhs = lhs.evalf() if Nlhs.is_Number: # S.Zero.evalf() returns S.Zero, so test Number instead of Float Nrhs = rhs.evalf() if Nrhs.is_Number: return rop_cls._eval_relation(Nlhs, Nrhs) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def _new_rawargs(self, *args): """create new instance of own class with args exactly as provided by caller This is handy when we want to optimize things, e.g. >>> from sympy import Mul, symbols >>> from sympy.abc import x, y >>> e = Mul(3,x,y) >>> e.args (3, x, y) >>> Mul(*e.args[1:]) x*y >>> e._new_rawargs(*e.args[1:]) # the same as above, but faster x*y """ obj = Expr.__new__(type(self), *args) # NB no assumptions for Add/Mul obj.is_commutative = self.is_commutative return obj
def __new__(cls, b, e, evaluate=True): # don't optimize "if e==0; return 1" here; it's better to handle that # in the calling routine so this doesn't get called b = _sympify(b) e = _sympify(e) if evaluate: if e is S.Zero: return S.One elif e is S.One: return b elif S.NaN in (b, e): if b is S.One: # already handled e == 0 above return S.One return S.NaN else: obj = b._eval_power(e) if obj is not None: return obj obj = Expr.__new__(cls, b, e) obj.is_commutative = (b.is_commutative and e.is_commutative) return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: try: rop_cls = Relational.ValidRelationOperator[ rop ] except KeyError: msg = "Invalid relational operator symbol: '%r'" raise ValueError(msg % repr(rop)) if lhs.is_number and rhs.is_number and lhs.is_real and rhs.is_real: # Just becase something is a number, doesn't mean you can evalf it. Nlhs = lhs.evalf() if Nlhs.is_Number: # S.Zero.evalf() returns S.Zero, so test Number instead of Float Nrhs = rhs.evalf() if Nrhs.is_Number: return rop_cls._eval_relation(Nlhs, Nrhs) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = _sympify(lhs) rhs = _sympify(rhs) if cls is not Relational: rop_cls = cls else: try: rop_cls = Relational.ValidRelationOperator[ rop ] except KeyError: msg = "Invalid relational operator symbol: '%r'" raise ValueError(msg % repr(rop)) if lhs.is_number and rhs.is_number and (rop in ('==', '!=' ) or lhs.is_real and rhs.is_real): # Just because something is a number, doesn't mean you can evalf it. Nlhs = lhs.evalf() if not lhs.is_Atom else lhs if Nlhs.is_Atom: Nrhs = rhs.evalf() if not rhs.is_Atom else rhs if Nrhs.is_Atom: return rop_cls._eval_relation(Nlhs, Nrhs) obj = Expr.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def __new__(cls, num, prec=15): prec = mlib.libmpf.dps_to_prec(prec) if isinstance(num, (int, long)): return Integer(num) if isinstance(num, (str, decimal.Decimal)): _mpf_ = mlib.from_str(str(num), prec, rnd) elif isinstance(num, tuple) and len(num) == 4: if type(num[1]) is str: # it's a hexadecimal (coming from a pickled object) # assume that it is in standard form num = list(num) num[1] = long(num[1], 16) _mpf_ = tuple(num) else: _mpf_ = mpmath.mpf( S.NegativeOne ** num[0] * num[1] * 2 ** num[2])._mpf_ else: _mpf_ = mpmath.mpf(num)._mpf_ if not num: return C.Zero() obj = Expr.__new__(cls) obj._mpf_ = _mpf_ obj._prec = prec return obj
def __new__(cls, b, e, evaluate=True): from sympy.functions.elementary.exponential import exp_polar # don't optimize "if e==0; return 1" here; it's better to handle that # in the calling routine so this doesn't get called b = _sympify(b) e = _sympify(e) if evaluate: if e is S.Zero: return S.One elif e is S.One: return b elif S.NaN in (b, e): if b is S.One: # already handled e == 0 above return S.One return S.NaN else: # recognize base as E if not e.is_Atom and b is not S.Exp1 and b.func is not exp_polar: from sympy import numer, denom, log, sign, im, factor_terms c, ex = factor_terms(e, sign=False).as_coeff_Mul() den = denom(ex) if den.func is log and den.args[0] == b: return S.Exp1**(c * numer(ex)) elif den.is_Add: s = sign(im(b)) if s.is_Number and s and den == \ log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi: return S.Exp1**(c * numer(ex)) obj = b._eval_power(e) if obj is not None: return obj obj = Expr.__new__(cls, b, e) obj.is_commutative = (b.is_commutative and e.is_commutative) return obj
def __new__(cls, b, e, evaluate=True): from sympy.functions.elementary.exponential import exp_polar # don't optimize "if e==0; return 1" here; it's better to handle that # in the calling routine so this doesn't get called b = _sympify(b) e = _sympify(e) if evaluate: if e is S.Zero: return S.One elif e is S.One: return b elif S.NaN in (b, e): if b is S.One: # already handled e == 0 above return S.One return S.NaN else: # recognize base as E if not e.is_Atom and b is not S.Exp1 and b.func is not exp_polar: from sympy import numer, denom, log, sign, im, factor_terms c, ex = factor_terms(e).as_coeff_Mul() den = denom(ex) if den.func is log and den.args[0] == b: return S.Exp1**(c*numer(ex)) elif den.is_Add: s = sign(im(b)) if s.is_Number and s and den == \ log(-b) + s*S.ImaginaryUnit*S.Pi: return S.Exp1**(c*numer(ex)) obj = b._eval_power(e) if obj is not None: return obj obj = Expr.__new__(cls, b, e) obj.is_commutative = (b.is_commutative and e.is_commutative) return obj
def __new_stage2__(cls, name, commutative=True, **assumptions): assert isinstance(name, str), repr(type(name)) obj = Expr.__new__(cls, **assumptions) obj.is_commutative = commutative obj.name = name return obj
def __new_stage2__(cls, name, commutative=True, **assumptions): assert isinstance(name, str),`type(name)` obj = Expr.__new__(cls, **assumptions) obj.is_commutative = commutative obj.name = name return obj
def __new_stage2__(cls, name, **assumptions): assert isinstance(name, str), repr(type(name)) obj = Expr.__new__(cls) obj.name = name obj._assumptions = StdFactKB(assumptions) return obj
def _new_rawargs(self, *args, **kwargs): """create new instance of own class with args exactly as provided by caller but returning the self class identity if args is empty. This is handy when we want to optimize things, e.g. >>> from sympy import Mul, symbols, S >>> from sympy.abc import x, y >>> e = Mul(3, x, y) >>> e.args (3, x, y) >>> Mul(*e.args[1:]) x*y >>> e._new_rawargs(*e.args[1:]) # the same as above, but faster x*y Note: use this with caution. There is no checking of arguments at all. This is best used when you are rebuilding an Add or Mul after simply removing one or more terms. If modification which result, for example, in extra 1s being inserted (as when collecting an expression's numerators and denominators) they will not show up in the result but a Mul will be returned nonetheless: >>> m = (x*y)._new_rawargs(S.One, x); m x >>> m == x False >>> m.is_Mul True Another issue to be aware of is that the commutativity of the result is based on the commutativity of self. If you are rebuilding the terms that came from a commutative object then there will be no problem, but if self was non-commutative then what you are rebuilding may now be commutative. Although this routine tries to do as little as possible with the input, getting the commutativity right is important, so this level of safety is enforced: commutativity will always be recomputed if either a) self has no is_commutate attribute or b) self is non-commutative and kwarg `reeval=False` has not been passed. If you don't have an existing Add or Mul and need one quickly, try the following. >>> m = object.__new__(Mul) >>> m._new_rawargs(x, y) x*y Note that the commutativity is always computed in this case since m doesn't have an is_commutative attribute; reeval is ignored: >>> _.is_commutative True >>> hasattr(m, 'is_commutative') False >>> m._new_rawargs(x, y, reeval=False).is_commutative True It is possible to define the commutativity of m. If it's False then the new Mul's commutivity will be re-evaluated: >>> m.is_commutative = False >>> m._new_rawargs(x, y).is_commutative True But if reeval=False then a non-commutative self can pass along its non-commutativity to the result (but at least you have to *work* to get this wrong): >>> m._new_rawargs(x, y, reeval=False).is_commutative False """ if len(args) > 1: obj = Expr.__new__(type(self), *args) # NB no assumptions for Add/Mul if (hasattr(self, 'is_commutative') and (self.is_commutative or not kwargs.pop('reeval', True))): obj.is_commutative = self.is_commutative else: obj.is_commutative = all(a.is_commutative for a in args) elif len(args) == 1: obj = args[0] else: obj = self.identity return obj
def __new__(cls, expr, *symbols, **assumptions): expr = sympify(expr) if not symbols: return expr # standardize symbols symbols = list(sympify(symbols)) if not symbols[-1].is_Integer or len(symbols) == 1: symbols.append(S.One) symbol_count = [] all_zero = True i = 0 while i < len(symbols) - 1: # process up to final Integer s, count = symbols[i:i + 2] iwas = i if s.is_Symbol: if count.is_Symbol: count = 1 i += 1 elif count.is_Integer: count = int(count) i += 2 if i == iwas: # didn't get an update because of bad input raise ValueError( 'Derivative expects Symbol [, Integer] args but got %s, %s' % (s, count)) symbol_count.append((s, count)) if all_zero and not count == 0: all_zero = False # We make a special case for 0th derivative, because there # is no good way to unambiguously print this. if all_zero: return expr evaluate = assumptions.pop('evaluate', False) # look for a quick exit if there are symbols that are not in the free symbols if evaluate: if set(sc[0] for sc in symbol_count).difference(expr.free_symbols): return S.Zero # We make a generator so as to only generate a symbol when necessary. # If a high order of derivative is requested and the expr becomes 0 # after a few differentiations, then we won't need the other symbols symbolgen = (s for s, count in symbol_count for i in xrange(count)) if expr.is_commutative: assumptions['commutative'] = True if (not (hasattr(expr, '_eval_derivative') and evaluate) and not isinstance(expr, Derivative)): symbols = list(symbolgen) obj = Expr.__new__(cls, expr, *symbols, **assumptions) return obj # compute the derivative now unevaluated_symbols = [] for s in symbolgen: obj = expr._eval_derivative(s) if obj is None: unevaluated_symbols.append(s) elif obj is S.Zero: return S.Zero else: expr = obj if not unevaluated_symbols: return expr return Expr.__new__(cls, expr, *unevaluated_symbols, **assumptions)
def __new__(cls, *args, **options): args = map(sympify, args) result = Expr.__new__(cls, *args, **options) result.nargs = len(args) return result
def __new__(cls, expr, *symbols, **assumptions): expr = sympify(expr) if not symbols: symbols = expr.free_symbols if len(symbols) != 1: raise ValueError("specify differentiation variables to differentiate %s" % expr) # standardize symbols symbols = list(sympify(symbols)) if not symbols[-1].is_Integer or len(symbols) == 1: symbols.append(S.One) symbol_count = [] all_zero = True i = 0 while i < len(symbols) - 1: # process up to final Integer s, count = symbols[i: i+2] iwas = i if s.is_Symbol: if count.is_Symbol: count = 1 i += 1 elif count.is_Integer: count = int(count) i += 2 if i == iwas: # didn't get an update because of bad input raise ValueError('Derivative expects Symbol [, Integer] args but got %s, %s' % (s, count)) symbol_count.append((s, count)) if all_zero and not count == 0: all_zero = False # We make a special case for 0th derivative, because there # is no good way to unambiguously print this. if all_zero: return expr evaluate = assumptions.pop('evaluate', False) # look for a quick exit if there are symbols that are not in the free symbols if evaluate: if set(sc[0] for sc in symbol_count ).difference(expr.free_symbols): return S.Zero # We make a generator so as to only generate a symbol when necessary. # If a high order of derivative is requested and the expr becomes 0 # after a few differentiations, then we won't need the other symbols symbolgen = (s for s, count in symbol_count for i in xrange(count)) if expr.is_commutative: assumptions['commutative'] = True if (not (hasattr(expr, '_eval_derivative') and evaluate) and not isinstance(expr, Derivative)): symbols = list(symbolgen) obj = Expr.__new__(cls, expr, *symbols, **assumptions) return obj # compute the derivative now unevaluated_symbols = [] for s in symbolgen: obj = expr._eval_derivative(s) if obj is None: unevaluated_symbols.append(s) elif obj is S.Zero: return S.Zero else: expr = obj if not unevaluated_symbols: return expr return Expr.__new__(cls, expr, *unevaluated_symbols, **assumptions)