本文整理汇总了Python中expr.Expr类的典型用法代码示例。如果您正苦于以下问题:Python Expr类的具体用法?Python Expr怎么用?Python Expr使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Expr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __new__
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
示例2: __new__
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)
示例3: row_select
def row_select(self, vec):
"""
Boolean column select lookup
:param vec: An H2OVec.
:return: A new H2OVec.
"""
e = Expr("[", self, vec)
j = h2o.frame(e.eager())
e.set_len(j['frames'][0]['rows'])
return H2OVec(self._name, e)
示例4: _new
def _new(cls, _mpf_, _prec):
if _mpf_ == mlib.fzero:
return S.Zero
obj = Expr.__new__(cls)
obj._mpf_ = _mpf_
obj._prec = _prec
return obj
示例5: __new__
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
示例6: __new_stage2__
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
示例7: __new__
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
示例8: _eval_evalf
def _eval_evalf(self, prec):
# Lookup mpmath function based on name
fname = self.func.__name__
try:
if not hasattr(mpmath, fname):
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
fname = MPMATH_TRANSLATIONS[fname]
func = getattr(mpmath, fname)
except (AttributeError, KeyError):
try:
return C.Real(self._imp_(*self.args), prec)
except (AttributeError, TypeError):
return
# Convert all args to mpf or mpc
try:
args = [arg._to_mpmath(prec) for arg in self.args]
except ValueError:
return
# Set mpmath precision and apply. Make sure precision is restored
# afterwards
orig = mpmath.mp.prec
try:
mpmath.mp.prec = prec
v = func(*args)
finally:
mpmath.mp.prec = orig
return Expr._from_mpmath(v, prec)
示例9: __new__
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
示例10: matches
def matches(self, expr, repl_dict={}, evaluate=False):
if self in repl_dict:
if repl_dict[self] == expr:
return repl_dict
elif isinstance(expr, Derivative):
if len(expr.variables) == len(self.variables):
return Expr.matches(self, expr, repl_dict, evaluate)
示例11: matches
def matches(self, expr, repl_dict={}, old=False):
expr = _sympify(expr)
# special case, pattern = 1 and expr.exp can match to 0
if expr is S.One:
d = repl_dict.copy()
d = self.exp.matches(S.Zero, d)
if d is not None:
return d
b, e = expr.as_base_exp()
# special case number
sb, se = self.as_base_exp()
if sb.is_Symbol and se.is_Integer and expr:
if e.is_rational:
return sb.matches(b**(e/se), repl_dict)
return sb.matches(expr**(1/se), repl_dict)
d = repl_dict.copy()
d = self.base.matches(b, d)
if d is None:
return None
d = self.exp.xreplace(d).matches(e, d)
if d is None:
return Expr.matches(self, expr, repl_dict)
return d
示例12: __new__
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
示例13: __le__
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
return False # sympy > other --> not <=
if self is other: return True
if other.is_comparable: other = other.evalf()
if isinstance(other, Number):
return self.evalf()<=other
return Expr.__le__(self, other)
示例14: __getitem__
def __getitem__(self, i):
"""
Column selection via integer, string(name)
Column selection via slice returns a subset of the H2OFrame
:param i: An int, str, slice, H2OVec, or list/tuple
:return: An H2OVec, an H2OFrame, or scalar depending on the input slice.
"""
if self._vecs is None or self._vecs == []:
raise ValueError("Frame Removed")
if isinstance(i, int): return self._vecs[i]
if isinstance(i, str): return self._find(i)
# Slice; return a Frame not a Vec
if isinstance(i, slice): return H2OFrame(vecs=self._vecs[i])
# Row selection from a boolean Vec
if isinstance(i, H2OVec):
self._len_check(i)
return H2OFrame(vecs=[x.row_select(i) for x in self._vecs])
# have a list/tuple of numbers or strings
if isinstance(i, list) or (isinstance(i, tuple) and len(i) != 2):
vecs = []
for it in i:
if isinstance(it, int): vecs.append(self._vecs[it])
elif isinstance(it, str): vecs.append(self._find(it))
else: raise NotImplementedError
return H2OFrame(vecs=vecs)
# multi-dimensional slicing via 2-tuple
if isinstance(i, tuple):
veckeys = [str(v._expr._data) for v in self._vecs]
left = Expr(veckeys)
rite = Expr((i[0], i[1]))
res = Expr("[", left, rite, length=2)
if not isinstance(i[0], int) or not isinstance(i[1], int): return res # possible big data
# small data (single value)
res.eager()
if res.is_local(): return res._data
j = h2o.frame(res._data) # data is remote
return map(list, zip(*[c['data'] for c in j['frames'][0]['columns'][:]]))[0][0]
raise NotImplementedError("Slicing by unknown type: "+str(type(i)))
示例15: _from_args
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