本文整理汇总了Python中sympy.functions.elementary.piecewise.piecewise_fold函数的典型用法代码示例。如果您正苦于以下问题:Python piecewise_fold函数的具体用法?Python piecewise_fold怎么用?Python piecewise_fold使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了piecewise_fold函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __new__
def __new__(cls, function, *symbols, **assumptions):
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
function = piecewise_fold(sympify(function))
if function is S.NaN:
return S.NaN
if symbols:
limits, sign = _process_limits(*symbols)
else:
# no symbols provided -- let's compute full anti-derivative
limits, sign = [Tuple(s) for s in function.free_symbols], 1
if len(limits) != 1:
raise ValueError("specify integration variables to integrate %s" % function)
while isinstance(function, Integral):
# denest the integrand
limits = list(function.limits) + limits
function = function.function
obj = Expr.__new__(cls, **assumptions)
arglist = [sign*function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = all(s.is_commutative for s in obj.free_symbols)
return obj
示例2: __new__
def __new__(cls, function, *symbols, **assumptions):
from sympy.integrals.integrals import _process_limits
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
function = piecewise_fold(sympify(function))
if function is S.NaN:
return S.NaN
if not symbols:
raise ValueError("Summation variables must be given")
limits, sign = _process_limits(*symbols)
# Only limits with lower and upper bounds are supported; the indefinite Sum
# is not supported
if any(len(l) != 3 or None in l for l in limits):
raise ValueError('Sum requires values for lower and upper bounds.')
obj = Expr.__new__(cls, **assumptions)
arglist = [sign*function]
arglist.extend(limits)
obj._args = tuple(arglist)
return obj
示例3: __new__
def __new__(cls, function, *symbols, **assumptions):
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
#
# This constructor only differs from ExprWithLimits
# in the application of the orientation variable. Perhaps merge?
function = piecewise_fold(sympify(function))
if function is S.NaN:
return S.NaN
if symbols:
limits, orientation = _process_limits(*symbols)
else:
# symbol not provided -- we can still try to compute a general form
free = function.free_symbols
if len(free) != 1:
raise ValueError(
"specify dummy variables for %s" % function)
limits, orientation = [Tuple(s) for s in free], 1
# denest any nested calls
while cls == type(function):
limits = list(function.limits) + limits
function = function.function
obj = Expr.__new__(cls, **assumptions)
arglist = [orientation*function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
示例4: __new__
def __new__(cls, function, *symbols, **assumptions):
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
function = piecewise_fold(sympify(function))
if function is S.NaN:
return S.NaN
symbols = list(symbols)
if not symbols:
# no symbols provided -- let's compute full anti-derivative
symbols = sorted(function.free_symbols, Basic.compare)
if not symbols:
raise ValueError('An integration variable is required.')
while isinstance(function, Integral):
# denest the integrand
symbols = list(function.limits) + symbols
function = function.function
limits = []
for V in symbols:
if isinstance(V, Symbol):
limits.append(Tuple(V))
continue
elif isinstance(V, (tuple, list, Tuple)):
V = sympify(flatten(V))
if V[0].is_Symbol:
newsymbol = V[0]
if len(V) == 3:
if V[1] is None and V[2] is not None:
nlim = [V[2]]
elif V[1] is not None and V[2] is None:
function = -function
nlim = [V[1]]
elif V[1] is None and V[2] is None:
nlim = []
else:
nlim = V[1:]
limits.append(Tuple(newsymbol, *nlim ))
continue
elif len(V) == 1 or (len(V) == 2 and V[1] is None):
limits.append(Tuple(newsymbol))
continue
elif len(V) == 2:
limits.append(Tuple(newsymbol, V[1]))
continue
raise ValueError("Invalid integration variable or limits: %s" % str(symbols))
obj = Expr.__new__(cls, **assumptions)
obj._args = tuple([function] + limits)
obj.is_commutative = all(s.is_commutative for s in obj.free_symbols)
return obj
示例5: __new__
def __new__(cls, function, *symbols, **assumptions):
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
#
# This constructor only differs from ExprWithLimits
# in the application of the orientation variable. Perhaps merge?
function = piecewise_fold(sympify(function))
if function is S.NaN:
return S.NaN
# delete dx, dy, dx, etc.
free = function.free_symbols
for f in free:
if len(f.name) > 1 and f.name[0] == "d":
function = function.subs(f, 1)
if symbols:
limits, orientation = _process_limits(*symbols)
else:
# symbol not provided -- we can still try to compute a general form
new_free = set()
limits = []
# if f is dx, then the variable is x
for f in free:
if len(f.name) > 1 and f.name[0] == "d":
limits.append((Symbol(f.name[1:]),))
else:
new_free.add(f)
free = new_free
del new_free
if len(limits) == 0:
if len(free) != 1:
raise ValueError(
"specify dummy variables for %s" % function)
limits = [Tuple(s) for s in free]
orientation = 1
# denest any nested calls
while cls == type(function):
limits = list(function.limits) + limits
function = function.function
obj = Expr.__new__(cls, **assumptions)
arglist = [orientation*function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
示例6: _common_new
def _common_new(cls, function, *symbols, **assumptions):
"""Return either a special return value or the tuple,
(function, limits, orientation). This code is common to
both ExprWithLimits and AddWithLimits."""
function = sympify(function)
if hasattr(function, 'func') and isinstance(function, Equality):
lhs = function.lhs
rhs = function.rhs
return Equality(cls(lhs, *symbols, **assumptions), \
cls(rhs, *symbols, **assumptions))
if function is S.NaN:
return S.NaN
if symbols:
limits, orientation = _process_limits(*symbols)
for i, li in enumerate(limits):
if len(li) == 4:
function = function.subs(li[0], li[-1])
limits[i] = tuple(li[:-1])
else:
# symbol not provided -- we can still try to compute a general form
free = function.free_symbols
if len(free) != 1:
raise ValueError(
"specify dummy variables for %s" % function)
limits, orientation = [Tuple(s) for s in free], 1
# denest any nested calls
while cls == type(function):
limits = list(function.limits) + limits
function = function.function
# Any embedded piecewise functions need to be brought out to the
# top level. We only fold Piecewise that contain the integration
# variable.
reps = {}
symbols_of_integration = set([i[0] for i in limits])
for p in function.atoms(Piecewise):
if not p.has(*symbols_of_integration):
reps[p] = Dummy()
# mask off those that don't
function = function.xreplace(reps)
# do the fold
function = piecewise_fold(function)
# remove the masking
function = function.xreplace({v: k for k, v in reps.items()})
return function, limits, orientation
示例7: __new__
def __new__(cls, function, *symbols, **assumptions):
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
#
# This constructor only differs from ExprWithLimits
# in the application of the orientation variable. Perhaps merge?
function = sympify(function)
if hasattr(function, 'func') and function.func is Equality:
lhs = function.lhs
rhs = function.rhs
return Equality(cls(lhs, *symbols, **assumptions), \
cls(rhs, *symbols, **assumptions))
function = piecewise_fold(function)
if function is S.NaN:
return S.NaN
if symbols:
limits, orientation = _process_limits(*symbols)
else:
# symbol not provided -- we can still try to compute a general form
free = function.free_symbols
if len(free) != 1:
raise ValueError(
" specify dummy variables for %s. If the integrand contains"
" more than one free symbol, an integration variable should"
" be supplied explicitly e.g., integrate(f(x, y), x)"
% function)
limits, orientation = [Tuple(s) for s in free], 1
# denest any nested calls
while cls == type(function):
limits = list(function.limits) + limits
function = function.function
obj = Expr.__new__(cls, **assumptions)
arglist = [orientation*function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
示例8: __new__
def __new__(cls, function, *symbols, **assumptions):
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
function = sympify(function)
if hasattr(function, 'func') and function.func is C.Equality:
lhs = function.lhs
rhs = function.rhs
return C.Equality(cls(lhs, *symbols, **assumptions), \
cls(rhs, *symbols, **assumptions))
function = piecewise_fold(function)
if function is S.NaN:
return S.NaN
if symbols:
limits, orientation = _process_limits(*symbols)
else:
# symbol not provided -- we can still try to compute a general form
free = function.free_symbols
if len(free) != 1:
raise ValueError(
"specify dummy variables for %s" % function)
limits, orientation = [Tuple(s) for s in free], 1
# denest any nested calls
while cls == type(function):
limits = list(function.limits) + limits
function = function.function
# Only limits with lower and upper bounds are supported; the indefinite form
# is not supported
if any(len(l) != 3 or None in l for l in limits):
raise ValueError('ExprWithLimits requires values for lower and upper bounds.')
obj = Expr.__new__(cls, **assumptions)
arglist = [function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
示例9: solve
#.........这里部分代码省略.........
symbols_new = []
symbol_swapped = False
symbols_passed = list(symbols)
for i, s in enumerate(symbols):
if s.is_Symbol:
s_new = s
elif s.is_Function:
symbol_swapped = True
s_new = Dummy("F%d" % i)
elif s.is_Derivative:
symbol_swapped = True
s_new = Dummy("D%d" % i)
else:
raise TypeError("not a Symbol or a Function")
symbols_new.append(s_new)
if symbol_swapped:
swap_back_dict = dict(zip(symbols_new, symbols))
# End code for handling of Function and Derivative instances
if not isinstance(f, (tuple, list, set)):
# Create a swap dictionary for storing the passed symbols to be solved
# for, so that they may be swapped back.
if symbol_swapped:
swap_dict = zip(symbols, symbols_new)
f = f.subs(swap_dict)
symbols = symbols_new
# Any embedded piecewise functions need to be brought out to the
# top level so that the appropriate strategy gets selected.
f = piecewise_fold(f)
if len(symbols) != 1:
result = {}
for s in symbols:
result[s] = solve(f, s, **flags)
if flags.get("simplified", True):
for s, r in result.items():
result[s] = map(simplify, r)
return result
symbol = symbols[0]
strategy = guess_solve_strategy(f, symbol)
if strategy == GS_POLY:
poly = f.as_poly(symbol)
if poly is None:
raise NotImplementedError("Cannot solve equation " + str(f) + " for " + str(symbol))
# for cubics and quartics, if the flag wasn't set, DON'T do it
# by default since the results are quite long. Perhaps one could
# base this decision on a certain crtical length of the roots.
if poly.degree > 2:
flags["simplified"] = flags.get("simplified", False)
result = roots(poly, cubics=True, quartics=True).keys()
elif strategy == GS_RATIONAL:
P, Q = f.as_numer_denom()
# TODO: check for Q != 0
result = solve(P, symbol, **flags)
elif strategy == GS_POLY_CV_1:
args = list(f.args)
if isinstance(f, Add):
示例10: solve
#.........这里部分代码省略.........
involves relationals or bools.
See also:
rsolve() for solving recurrence relationships
dsolve() for solving differential equations
"""
# make f and symbols into lists of sympified quantities
# keeping track of how f was passed since if it is a list
# a dictionary of results will be returned.
###########################################################################
def sympified_list(w):
return map(sympify, w if iterable(w) else [w])
bare_f = not iterable(f)
ordered_symbols = (symbols and
symbols[0] and
(isinstance(symbols[0], Symbol) or
is_sequence(symbols[0], include=GeneratorType)
)
)
f, symbols = (sympified_list(w) for w in [f, symbols])
# preprocess equation(s)
###########################################################################
for i, fi in enumerate(f):
if isinstance(fi, Equality):
f[i] = fi.lhs - fi.rhs
elif isinstance(fi, Poly):
f[i] = fi.as_expr()
elif isinstance(fi, bool) or fi.is_Relational:
return reduce_inequalities(f, assume=flags.get('assume'))
# Any embedded piecewise functions need to be brought out to the
# top level so that the appropriate strategy gets selected.
f[i] = piecewise_fold(f[i])
# preprocess symbol(s)
###########################################################################
if not symbols:
# get symbols from equations or supply dummy symbols so solve(3) behaves
# like solve(3, x).
symbols = set([])
for fi in f:
symbols |= fi.free_symbols or set([Dummy()])
ordered_symbols = False
elif len(symbols) == 1 and iterable(symbols[0]):
symbols = symbols[0]
if not ordered_symbols:
# we do this to make the results returned canonical in case f
# contains a system of nonlinear equations; all other cases should
# be unambiguous
symbols = sorted(symbols, key=lambda i: i.sort_key())
# we can solve for Function and Derivative instances by replacing them
# with Dummy symbols
symbols_new = []
symbol_swapped = False
symbols_passed = list(symbols)
for i, s in enumerate(symbols):
if s.is_Symbol:
s_new = s
elif s.is_Function:
symbol_swapped = True
s_new = Dummy('F%d' % i)
elif s.is_Derivative:
symbol_swapped = True
示例11: __new__
def __new__(cls, function, *symbols, **assumptions):
"""Create an unevaluated integral.
Arguments are an integrand followed by one or more limits.
If no limits are given and there is only one free symbol in the
expression, that symbol will be used, otherwise an error will be
raised.
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x)
Integral(x, x)
>>> Integral(y)
Integral(y, y)
When limits are provided, they are interpreted as follows (using
``x`` as though it were the variable of integration):
(x,) or x - indefinite integral
(x, a) - "evaluate at" integral
(x, a, b) - definite integral
Although the same integral will be obtained from an indefinite
integral and an "evaluate at" integral when ``a == x``, they
respond differently to substitution:
>>> i = Integral(x, x)
>>> at = Integral(x, (x, x))
>>> i.doit() == at.doit()
True
>>> i.subs(x, 1)
Integral(1, x)
>>> at.subs(x, 1)
Integral(x, (x, 1))
The ``as_dummy`` method can be used to see which symbols cannot be
targeted by subs: those with a preppended underscore cannot be
changed with ``subs``. (Also, the integration variables themselves --
the first element of a limit -- can never be changed by subs.)
>>> i.as_dummy()
Integral(x, x)
>>> at.as_dummy()
Integral(_x, (_x, x))
"""
# Any embedded piecewise functions need to be brought out to the
# top level so that integration can go into piecewise mode at the
# earliest possible moment.
function = piecewise_fold(sympify(function))
if function is S.NaN:
return S.NaN
if symbols:
limits, sign = _process_limits(*symbols)
else:
# no symbols provided -- let's compute full anti-derivative
free = function.free_symbols
if len(free) != 1:
raise ValueError("specify variables of integration for %s" % function)
limits, sign = [Tuple(s) for s in free], 1
while isinstance(function, Integral):
# denest the integrand
limits = list(function.limits) + limits
function = function.function
obj = Expr.__new__(cls, **assumptions)
arglist = [sign*function]
arglist.extend(limits)
obj._args = tuple(arglist)
obj.is_commutative = function.is_commutative # limits already checked
return obj
示例12: _solve
#.........这里部分代码省略.........
symbol_swapped = False
symbols_passed = list(symbols)
for i, s in enumerate(symbols):
if s.is_Symbol:
s_new = s
elif s.is_Function:
symbol_swapped = True
s_new = Dummy('F%d' % i)
elif s.is_Derivative:
symbol_swapped = True
s_new = Dummy('D%d' % i)
else:
raise TypeError('not a Symbol or a Function')
symbols_new.append(s_new)
if symbol_swapped:
swap_back_dict = dict(zip(symbols_new, symbols))
# End code for handling of Function and Derivative instances
if bare_f:
f = f[0]
# Create a swap dictionary for storing the passed symbols to be solved
# for, so that they may be swapped back.
if symbol_swapped:
swap_dict = zip(symbols, symbols_new)
f = f.subs(swap_dict)
symbols = symbols_new
# Any embedded piecewise functions need to be brought out to the
# top level so that the appropriate strategy gets selected.
f = piecewise_fold(f)
if len(symbols) != 1:
soln = None
free = f.free_symbols
ex = free - set(symbols)
if len(ex) == 1:
ex = ex.pop()
try:
# may come back as dict or list (if non-linear)
soln = solve_undetermined_coeffs(f, symbols, ex)
except NotImplementedError:
pass
if soln is None:
n, d = solve_linear(f, x=symbols)
if n.is_Symbol:
soln = {n: cancel(d)}
if soln:
if symbol_swapped and isinstance(soln, dict):
return dict([(swap_back_dict[k],
v.subs(swap_back_dict))
for k, v in soln.iteritems()])
return soln
symbol = symbols[0]
# first see if it really depends on symbol and whether there
# is a linear solution
f_num, sol = solve_linear(f, x=symbols)
if not symbol in f_num.free_symbols:
return []
elif f_num.is_Symbol:
return [cancel(sol)]