本文整理汇总了Python中sympy.core.compatibility.reduce函数的典型用法代码示例。如果您正苦于以下问题:Python reduce函数的具体用法?Python reduce怎么用?Python reduce使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了reduce函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _rebuild
def _rebuild(expr):
generator = mapping.get(expr)
if generator is not None:
return generator
elif expr.is_Add:
return reduce(add, list(map(_rebuild, expr.args)))
elif expr.is_Mul:
return reduce(mul, list(map(_rebuild, expr.args)))
elif expr.is_Pow or isinstance(expr, (ExpBase, Exp1)):
b, e = expr.as_base_exp()
# look for bg**eg whose integer power may be b**e
for gen, (bg, eg) in powers:
if bg == b and Mod(e, eg) == 0:
return mapping.get(gen)**int(e/eg)
if e.is_Integer and e is not S.One:
return _rebuild(b)**int(e)
try:
return domain.convert(expr)
except CoercionFailed:
if not domain.is_Field and domain.has_assoc_Field:
return domain.get_field().convert(expr)
else:
raise
示例2: dynamicsymbols
def dynamicsymbols(names, level=0):
"""Uses symbols and Function for functions of time.
Creates a SymPy UndefinedFunction, which is then initialized as a function
of a variable, the default being Symbol('t').
Parameters
==========
names : str
Names of the dynamic symbols you want to create; works the same way as
inputs to symbols
level : int
Level of differentiation of the returned function; d/dt once of t,
twice of t, etc.
Examples
========
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy import diff, Symbol
>>> q1 = dynamicsymbols('q1')
>>> q1
q1(t)
>>> diff(q1, Symbol('t'))
Derivative(q1(t), t)
"""
esses = symbols(names, cls=Function)
t = dynamicsymbols._t
if iterable(esses):
esses = [reduce(diff, [t] * level, e(t)) for e in esses]
return esses
else:
return reduce(diff, [t] * level, esses(t))
示例3: eval
def eval(cls, x, k):
x = sympify(x)
k = sympify(k)
if x is S.NaN:
return S.NaN
elif k.is_Integer:
if k is S.NaN:
return S.NaN
elif k is S.Zero:
return S.One
else:
if k.is_positive:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
if k.is_odd:
return S.NegativeInfinity
else:
return S.Infinity
else:
return reduce(lambda r, i: r*(x - i), xrange(0, int(k)), 1)
else:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
return S.Infinity
else:
return 1/reduce(lambda r, i: r*(x + i), xrange(1, abs(int(k)) + 1), 1)
示例4: dim_simplify
def dim_simplify(expr):
"""
Simplify expression by recursively evaluating the dimension arguments.
This function proceeds to a very rough dimensional analysis. It tries to
simplify expression with dimensions, and it deletes all what multiplies a
dimension without being a dimension. This is necessary to avoid strange
behavior when Add(L, L) be transformed into Mul(2, L).
"""
args = []
for arg in expr.args:
if isinstance(arg, (Mul, Pow, Add)):
arg = dim_simplify(arg)
args.append(arg)
if isinstance(expr, Pow):
return args[0].pow(args[1])
elif isinstance(expr, Add):
args = [arg for arg in args if isinstance(arg, Dimension)]
return reduce(lambda x, y: x.add(y), args)
elif isinstance(expr, Mul):
args = [arg for arg in args if isinstance(arg, Dimension)]
return reduce(lambda x, y: x.mul(y), args)
else:
return expr
示例5: qsimplify
def qsimplify(cls, expr):
"""
Simplify expression by recursively evaluating the quantity arguments.
If units are encountered, as it can be when using Constant, they are
converted to quantity.
"""
def redmul(x, y):
"""
Function used to combine args in multiplications.
This is necessary because the previous computation was not commutative,
and Mul(3, u) was not simplified; but Mul(u, 3) was.
"""
if isinstance(x, Quantity):
return x.mul(y)
elif isinstance(y, Quantity):
return y.mul(x)
else:
return x*y
args = []
for arg in expr.args:
arg = arg.evalf()
if isinstance(arg, (Mul, Pow, Add)):
arg = cls.qsimplify(arg)
args.append(arg)
q_args, o_args = [], []
for arg in args:
if isinstance(arg, Quantity):
q_args.append(arg)
elif isinstance(arg, Unit):
# replace unit by a quantity to make the simplification
q_args.append(arg.as_quantity)
else:
o_args.append(arg)
if isinstance(expr, Pow):
return args[0].pow(args[1])
elif isinstance(expr, Add):
if q_args != []:
quantities = reduce(lambda x, y: x.add(y), q_args)
else:
quantities = []
return reduce(lambda x, y: x+y, o_args, quantities)
elif isinstance(expr, Mul):
if q_args != []:
quantities = reduce(lambda x, y: x.mul(y), q_args)
else:
quantities = []
return reduce(redmul, o_args, quantities)
else:
return expr
示例6: eval
def eval(cls, x, k):
x = sympify(x)
k = sympify(k)
if x is S.NaN or k is S.NaN:
return S.NaN
elif x is S.One:
return factorial(k)
elif k.is_Integer:
if k is S.Zero:
return S.One
else:
if k.is_positive:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
if k.is_odd:
return S.NegativeInfinity
else:
return S.Infinity
else:
if isinstance(x, Poly):
gens = x.gens
if len(gens)!= 1:
raise ValueError("rf only defined for "
"polynomials on one generator")
else:
return reduce(lambda r, i:
r*(x.shift(i).expand()),
range(0, int(k)), 1)
else:
return reduce(lambda r, i: r*(x + i),
range(0, int(k)), 1)
else:
if x is S.Infinity:
return S.Infinity
elif x is S.NegativeInfinity:
return S.Infinity
else:
if isinstance(x, Poly):
gens = x.gens
if len(gens)!= 1:
raise ValueError("rf only defined for "
"polynomials on one generator")
else:
return 1/reduce(lambda r, i:
r*(x.shift(-i).expand()),
range(1, abs(int(k)) + 1), 1)
else:
return 1/reduce(lambda r, i:
r*(x - i),
range(1, abs(int(k)) + 1), 1)
示例7: dim_simplify
def dim_simplify(expr):
"""
NOTE: this function could be deprecated in the future.
Simplify expression by recursively evaluating the dimension arguments.
This function proceeds to a very rough dimensional analysis. It tries to
simplify expression with dimensions, and it deletes all what multiplies a
dimension without being a dimension. This is necessary to avoid strange
behavior when Add(L, L) be transformed into Mul(2, L).
"""
if isinstance(expr, Dimension):
return expr
if isinstance(expr, Pow):
return dim_simplify(expr.base)**dim_simplify(expr.exp)
elif isinstance(expr, Function):
return dim_simplify(expr.args[0])
elif isinstance(expr, Add):
if (all(isinstance(arg, Dimension) for arg in expr.args) or
all(arg.is_dimensionless for arg in expr.args if isinstance(arg, Dimension))):
return reduce(lambda x, y: x.add(y), expr.args)
else:
raise ValueError("Dimensions cannot be added: %s" % expr)
elif isinstance(expr, Mul):
return Dimension(Mul(*[dim_simplify(i).name for i in expr.args if isinstance(i, Dimension)]))
raise ValueError("Cannot be simplifed: %s", expr)
示例8: merge_explicit
def merge_explicit(matadd):
""" Merge explicit MatrixBase arguments
Examples
========
>>> from sympy import MatrixSymbol, eye, Matrix, MatAdd, pprint
>>> from sympy.matrices.expressions.matadd import merge_explicit
>>> A = MatrixSymbol('A', 2, 2)
>>> B = eye(2)
>>> C = Matrix([[1, 2], [3, 4]])
>>> X = MatAdd(A, B, C)
>>> pprint(X)
[1 0] [1 2]
A + [ ] + [ ]
[0 1] [3 4]
>>> pprint(merge_explicit(X))
[2 2]
A + [ ]
[3 5]
"""
groups = sift(matadd.args, lambda arg: isinstance(arg, MatrixBase))
if len(groups[True]) > 1:
return MatAdd(*(groups[False] + [reduce(add, groups[True])]))
else:
return matadd
示例9: test_treeapply
def test_treeapply():
tree = ([3, 3], [4, 1], 2)
assert treeapply(tree, {list: min, tuple: max}) == 3
add = lambda *args: sum(args)
mul = lambda *args: reduce(lambda a, b: a*b, args, 1)
assert treeapply(tree, {list: add, tuple: mul}) == 60
示例10: _module_quotient
def _module_quotient(self, other, relations=False):
# See: [SCA, section 2.8.4]
if relations and len(other.gens) != 1:
raise NotImplementedError
if len(other.gens) == 0:
return self.ring.ideal(1)
elif len(other.gens) == 1:
# We do some trickery. Let f be the (vector!) generating ``other``
# and f1, .., fn be the (vectors) generating self.
# Consider the submodule of R^{r+1} generated by (f, 1) and
# {(fi, 0) | i}. Then the intersection with the last module
# component yields the quotient.
g1 = list(other.gens[0]) + [1]
gi = [list(x) + [0] for x in self.gens]
# NOTE: We *need* to use an elimination order
M = self.ring.free_module(self.rank + 1).submodule(*([g1] + gi),
order='ilex', TOP=False)
if not relations:
return self.ring.ideal(*[x[-1] for x in M._groebner_vec() if
all(y == self.ring.zero for y in x[:-1])])
else:
G, R = M._groebner_vec(extended=True)
indices = [i for i, x in enumerate(G) if
all(y == self.ring.zero for y in x[:-1])]
return (self.ring.ideal(*[G[i][-1] for i in indices]),
[[-x for x in R[i][1:]] for i in indices])
# For more generators, we use I : <h1, .., hn> = intersection of
# {I : <hi> | i}
# TODO this can be done more efficiently
return reduce(lambda x, y: x.intersect(y),
(self._module_quotient(self.container.submodule(x)) for x in other.gens))
示例11: prde_linear_constraints
def prde_linear_constraints(a, b, G, DE):
"""
Parametric Risch Differential Equation - Generate linear constraints on the constants.
Given a derivation D on k[t], a, b, in k[t] with gcd(a, b) == 1, and
G = [g1, ..., gm] in k(t)^m, return Q = [q1, ..., qm] in k[t]^m and a
matrix M with entries in k(t) such that for any solution c1, ..., cm in
Const(k) and p in k[t] of a*Dp + b*p == Sum(ci*gi, (i, 1, m)),
(c1, ..., cm) is a solution of Mx == 0, and p and the ci satisfy
a*Dp + b*p == Sum(ci*qi, (i, 1, m)).
Because M has entries in k(t), and because Matrix doesn't play well with
Poly, M will be a Matrix of Basic expressions.
"""
m = len(G)
Gns, Gds = list(zip(*G))
d = reduce(lambda i, j: i.lcm(j), Gds)
d = Poly(d, field=True)
Q = [(ga*(d).quo(gd)).div(d) for ga, gd in G]
if not all([ri.is_zero for _, ri in Q]):
N = max([ri.degree(DE.t) for _, ri in Q])
M = Matrix(N + 1, m, lambda i, j: Q[j][1].nth(i))
else:
M = Matrix() # No constraints, return the empty matrix.
qs, _ = list(zip(*Q))
return (qs, M)
示例12: pull_out_u_rl
def pull_out_u_rl(integrand):
if any([integrand.has(f) for f in functions]):
args = [arg for arg in integrand.args if any(isinstance(arg, cls) for cls in functions)]
if args:
u = reduce(lambda a, b: a * b, args)
dv = integrand / u
return u, dv
示例13: _eval_matrix_mul
def _eval_matrix_mul(self, other):
from sympy import Add
# cache attributes for faster access
self_rows, self_cols = self.rows, self.cols
other_rows, other_cols = other.rows, other.cols
other_len = other_rows * other_cols
new_mat_rows = self.rows
new_mat_cols = other.cols
# preallocate the array
new_mat = [S.Zero]*new_mat_rows*new_mat_cols
# if we multiply an n x 0 with a 0 x m, the
# expected behavior is to produce an n x m matrix of zeros
if self.cols != 0 and other.rows != 0:
# cache self._mat and other._mat for performance
mat = self._mat
other_mat = other._mat
for i in range(len(new_mat)):
row, col = i // new_mat_cols, i % new_mat_cols
row_indices = range(self_cols*row, self_cols*(row+1))
col_indices = range(col, other_len, other_cols)
vec = (mat[a]*other_mat[b] for a,b in zip(row_indices, col_indices))
try:
new_mat[i] = Add(*vec)
except (TypeError, SympifyError):
# Block matrices don't work with `sum` or `Add` (ISSUE #11599)
# They don't work with `sum` because `sum` tries to add `0`
# initially, and for a matrix, that is a mix of a scalar and
# a matrix, which raises a TypeError. Fall back to a
# block-matrix-safe way to multiply if the `sum` fails.
vec = (mat[a]*other_mat[b] for a,b in zip(row_indices, col_indices))
new_mat[i] = reduce(lambda a,b: a + b, vec)
return classof(self, other)._new(new_mat_rows, new_mat_cols, new_mat, copy=False)
示例14: _get_indices_Mul
def _get_indices_Mul(expr, return_dummies=False):
"""Determine the outer indices of a Mul object.
>>> from sympy.tensor.index_methods import _get_indices_Mul
>>> from sympy.tensor.indexed import IndexedBase, Idx
>>> i, j, k = map(Idx, ['i', 'j', 'k'])
>>> x = IndexedBase('x')
>>> y = IndexedBase('y')
>>> _get_indices_Mul(x[i, k]*y[j, k])
(set([i, j]), {})
>>> _get_indices_Mul(x[i, k]*y[j, k], return_dummies=True)
(set([i, j]), {}, (k,))
"""
inds = list(map(get_indices, expr.args))
inds, syms = list(zip(*inds))
inds = list(map(list, inds))
inds = list(reduce(lambda x, y: x + y, inds))
inds, dummies = _remove_repeated(inds)
symmetry = {}
for s in syms:
for pair in s:
if pair in symmetry:
symmetry[pair] *= s[pair]
else:
symmetry[pair] = s[pair]
if return_dummies:
return inds, symmetry, dummies
else:
return inds, symmetry
示例15: prde_normal_denom
def prde_normal_denom(fa, fd, G, DE):
"""
Parametric Risch Differential Equation - Normal part of the denominator.
Given a derivation D on k[t] and f, g1, ..., gm in k(t) with f weakly
normalized with respect to t, return the tuple (a, b, G, h) such that
a, h in k[t], b in k<t>, G = [g1, ..., gm] in k(t)^m, and for any solution
c1, ..., cm in Const(k) and y in k(t) of Dy + f*y == Sum(ci*gi, (i, 1, m)),
q == y*h in k<t> satisfies a*Dq + b*q == Sum(ci*Gi, (i, 1, m)).
"""
dn, ds = splitfactor(fd, DE)
Gas, Gds = list(zip(*G))
gd = reduce(lambda i, j: i.lcm(j), Gds, Poly(1, DE.t))
en, es = splitfactor(gd, DE)
p = dn.gcd(en)
h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t)))
a = dn*h
c = a*h
ba = a*fa - dn*derivation(h, DE)*fd
ba, bd = ba.cancel(fd, include=True)
G = [(c*A).cancel(D, include=True) for A, D in G]
return (a, (ba, bd), G, h)