本文整理汇总了Python中sympy.core.basic.Basic.__new__方法的典型用法代码示例。如果您正苦于以下问题:Python Basic.__new__方法的具体用法?Python Basic.__new__怎么用?Python Basic.__new__使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy.core.basic.Basic
的用法示例。
在下文中一共展示了Basic.__new__方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, *args):
if len(args) == 2:
low, high = args
return Basic.__new__(cls, sympify(low), sympify(high))
elif len(args) == 0 or (len(args) == 1 and args[0] in (':', None)):
return Basic.__new__(cls) # assumed shape
else:
raise ValueError("Expected 0 or 2 args (or one argument == None or ':')")
示例2: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, sym, condition, base_set=S.UniversalSet):
# nonlinsolve uses ConditionSet to return an unsolved system
# of equations (see _return_conditionset in solveset) so until
# that is changed we do minimal checking of the args
if isinstance(sym, (Tuple, tuple)): # unsolved eqns syntax
sym = Tuple(*sym)
condition = FiniteSet(*condition)
return Basic.__new__(cls, sym, condition, base_set)
condition = as_Boolean(condition)
if isinstance(base_set, set):
base_set = FiniteSet(*base_set)
elif not isinstance(base_set, Set):
raise TypeError('expecting set for base_set')
if condition is S.false:
return S.EmptySet
if condition is S.true:
return base_set
if isinstance(base_set, EmptySet):
return base_set
know = None
if isinstance(base_set, FiniteSet):
sifted = sift(
base_set, lambda _: fuzzy_bool(
condition.subs(sym, _)))
if sifted[None]:
know = FiniteSet(*sifted[True])
base_set = FiniteSet(*sifted[None])
else:
return FiniteSet(*sifted[True])
if isinstance(base_set, cls):
s, c, base_set = base_set.args
if sym == s:
condition = And(condition, c)
elif sym not in c.free_symbols:
condition = And(condition, c.xreplace({s: sym}))
elif s not in condition.free_symbols:
condition = And(condition.xreplace({sym: s}), c)
sym = s
else:
# user will have to use cls.sym to get symbol
dum = Symbol('lambda')
if dum in condition.free_symbols or \
dum in c.free_symbols:
dum = Dummy(str(dum))
condition = And(
condition.xreplace({sym: dum}),
c.xreplace({s: dum}))
sym = dum
if not isinstance(sym, Symbol):
s = Dummy('lambda')
if s not in condition.xreplace({sym: s}).free_symbols:
raise ValueError(
'non-symbol dummy not recognized in condition')
rv = Basic.__new__(cls, sym, condition, base_set)
return rv if know is None else Union(know, rv)
示例3: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, sym, condition, base_set):
if condition == S.false:
return S.EmptySet
if condition == S.true:
return base_set
if isinstance(base_set, EmptySet):
return base_set
if isinstance(base_set, FiniteSet):
sifted = sift(base_set, lambda _: fuzzy_bool(condition.subs(sym, _)))
if sifted[None]:
return Union(FiniteSet(*sifted[True]),
Basic.__new__(cls, sym, condition, FiniteSet(*sifted[None])))
else:
return FiniteSet(*sifted[True])
return Basic.__new__(cls, sym, condition, base_set)
示例4: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, lhs, op, rhs):
lhs = _sympify(lhs)
rhs = _sympify(rhs)
# Tuple of things that can be on the lhs of an assignment
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed)
if not isinstance(lhs, assignable):
raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
# Indexed types implement shape, but don't define it until later. This
# causes issues in assignment validation. For now, matrices are defined
# as anything with a shape that is not an Indexed
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
# If lhs and rhs have same structure, then this assignment is ok
if lhs_is_mat:
if not rhs_is_mat:
raise ValueError("Cannot assign a scalar to a matrix.")
elif lhs.shape != rhs.shape:
raise ValueError("Dimensions of lhs and rhs don't align.")
elif rhs_is_mat and not lhs_is_mat:
raise ValueError("Cannot assign a matrix to a scalar.")
if isinstance(op, str):
op = operator(op)
elif op not in op_registry.values():
raise TypeError("Unrecognized Operator")
return Basic.__new__(cls, lhs, op, rhs)
示例5: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, expr, *contraction_indices, **kwargs):
contraction_indices = _sort_contraction_indices(contraction_indices)
expr = _sympify(expr)
if len(contraction_indices) == 0:
return expr
if isinstance(expr, CodegenArrayContraction):
return cls._flatten(expr, *contraction_indices)
obj = Basic.__new__(cls, expr, *contraction_indices)
obj._subranks = _get_subranks(expr)
obj._mapping = _get_mapping_from_subranks(obj._subranks)
free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all([i not in cind for cind in contraction_indices])}
obj._free_indices_to_position = free_indices_to_position
shape = expr.shape
if shape:
# Check that no contraction happens when the shape is mismatched:
for i in contraction_indices:
if len(set(shape[j] for j in i)) != 1:
raise ValueError("contracting indices of different dimensions")
shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
obj._shape = shape
return obj
示例6: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, name, abbrev, **assumptions):
obj = Basic.__new__(cls, **assumptions)
assert isinstance(name, str),`type(name)`
assert isinstance(abbrev, str),`type(abbrev)`
obj.name = name
obj.abbrev = abbrev
return obj
示例7: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, symbol, attrs=FiniteSet(), type_=None):
args = (_sympify(symbol), attrs if isinstance(attrs, FiniteSet) else FiniteSet(*attrs))
if type_ is not None:
if not isinstance(type_, Type):
raise TypeError("type_ argument should be an instance of Type")
args += (type_,)
return Basic.__new__(cls, *args)
示例8: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, expr, x, xlim, direction='<', **assumptions):
expr = Basic.sympify(expr)
x = Basic.sympify(x)
xlim = Basic.sympify(xlim)
if not isinstance(x, Basic.Symbol):
raise ValueError("Limit 2nd argument must be Symbol instance (got %s)" % (x))
assert isinstance(x, Basic.Symbol),`x`
if not expr.has(x):
return expr
if isinstance(xlim, Basic.NegativeInfinity):
xoo = InfLimit.limit_process_symbol()
if expr.has(xoo):
xoo = Basic.Symbol(x.name + '_oo',dummy=True,positive=True,unbounded=True)
return InfLimit(expr.subs(x,-xoo), xoo)
if isinstance(xlim, Basic.Infinity):
return InfLimit(expr, x)
else:
xoo = InfLimit.limit_process_symbol()
if expr.has(xoo):
xoo = Basic.Symbol(x.name + '_oo',dummy=True,positive=True,unbounded=True)
if direction=='<':
return InfLimit(expr.subs(x, xlim+1/xoo), xoo)
elif direction=='>':
return InfLimit(expr.subs(x, xlim-1/xoo), xoo)
else:
raise ValueError("Limit direction must be < or > (got %s)" % (direction))
# XXX This code is currently unreachable
obj = Basic.__new__(cls, expr, x, xlim, **assumptions)
obj.direction = direction
return obj
示例9: eval
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def eval(cls, *args):
"""
Equivalence relation.
Returns True if all of the arguments are logically equivalent.
Returns False otherwise.
Examples
========
>>> from sympy.logic.boolalg import Equivalent, And
>>> from sympy.abc import x
>>> Equivalent(False, False, False)
True
>>> Equivalent(True, False, False)
False
>>> Equivalent(x, And(x, True))
True
"""
argset = set(args)
if len(argset) <= 1:
return True
if True in argset:
argset.discard(True)
return And(*argset)
if False in argset:
argset.discard(False)
return Nor(*argset)
return Basic.__new__(cls, *set(args))
示例10: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get("evaluate", True)
# flatten inputs to merge intersections and iterables
args = list(args)
def flatten(arg):
if isinstance(arg, Set):
if arg.is_Intersection:
return sum(map(flatten, arg.args), [])
else:
return [arg]
if iterable(arg): # and not isinstance(arg, Set) (implicit)
return sum(map(flatten, arg), [])
raise TypeError("Input must be Sets or iterables of Sets")
args = flatten(args)
# Intersection of no sets is everything
if len(args) == 0:
return S.UniversalSet
args = sorted(args, key=set_sort_fn)
# Reduce sets using known rules
if evaluate:
return Intersection.reduce(args)
return Basic.__new__(cls, *args)
示例11: matrixify
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def matrixify(expr):
"""
Recursively walks down an expression tree changing Expr's to MatExpr's
i.e. Add -> MatAdd
Mul -> MatMul
Only changes those Exprs which contain MatrixSymbols
This function is useful when traditional SymPy functions which use Mul and
Add are called on MatrixExpressions. Examples flatten, expand, simplify...
Calling matrixify after calling these functions will reset classes back to
their matrix equivalents
"""
class_dict = {Mul:MatMul, Add:MatAdd, MatMul:MatMul, MatAdd:MatAdd,
Pow:MatPow, MatPow:MatPow}
if expr.__class__ not in class_dict:
return expr
args = map(matrixify, expr.args) # Recursively call down the tree
if not any(arg.is_Matrix for arg in args):
return expr
else:
return Basic.__new__(class_dict[expr.__class__], *args)
示例12: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, periodical, limits=None):
x, start, stop = None, None, None
if limits is None:
x, start, stop = Dummy("k"), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = Dummy("k")
start, stop = limits
if not isinstance(x, Symbol) or start is None or stop is None:
raise ValueError("Invalid limits given: %s" % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value" " cannot be unbounded")
limits = sympify((x, start, stop))
if is_sequence(periodical, Tuple):
periodical = sympify(tuple(flatten(periodical)))
else:
raise ValueError("invalid period %s should be something " "like e.g (1, 2) " % periodical)
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, periodical, limits)
示例13: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, *args):
from sympy.functions.elementary.integers import ceiling
# expand range
slc = slice(*args)
start, stop, step = slc.start or 0, slc.stop, slc.step or 1
try:
start, stop, step = [w if w in [S.NegativeInfinity, S.Infinity] else S(as_int(w))
for w in (start, stop, step)]
except ValueError:
raise ValueError("Inputs to Range must be Integer Valued\n" +
"Use ImageSets of Ranges for other cases")
if not step.is_finite:
raise ValueError("Infinite step is not allowed")
if start == stop:
return S.EmptySet
n = ceiling((stop - start)/step)
if n <= 0:
return S.EmptySet
# normalize args: regardless of how they are entered they will show
# canonically as Range(inf, sup, step) with step > 0
if n.is_finite:
start, stop = sorted((start, start + (n - 1)*step))
else:
start, stop = sorted((start, stop - step))
step = abs(step)
if (start, stop) == (S.NegativeInfinity, S.Infinity):
raise ValueError("Both the start and end value of "
"Range cannot be unbounded")
else:
return Basic.__new__(cls, start, stop + step, step)
示例14: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_evaluate[0])
# flatten inputs to merge intersections and iterables
args = list(args)
def flatten(arg):
if isinstance(arg, Set):
if arg.is_Intersection:
return sum(map(flatten, arg.args), [])
else:
return [arg]
if iterable(arg): # and not isinstance(arg, Set) (implicit)
return sum(map(flatten, arg), [])
raise TypeError("Input must be Sets or iterables of Sets")
args = flatten(args)
if len(args) == 0:
raise TypeError("Intersection expected at least one argument")
# Reduce sets using known rules
if evaluate:
return Intersection.reduce(args)
args = list(ordered(args, Set._infimum_key))
return Basic.__new__(cls, *args)
示例15: __new__
# 需要导入模块: from sympy.core.basic import Basic [as 别名]
# 或者: from sympy.core.basic.Basic import __new__ [as 别名]
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get("evaluate", global_evaluate[0])
# flatten inputs to merge intersections and iterables
args = list(args)
def flatten(arg):
if isinstance(arg, Set):
if arg.is_Union:
return sum(map(flatten, arg.args), [])
else:
return [arg]
if iterable(arg): # and not isinstance(arg, Set) (implicit)
return sum(map(flatten, arg), [])
raise TypeError("Input must be Sets or iterables of Sets")
args = flatten(args)
# Union of no sets is EmptySet
if len(args) == 0:
return S.EmptySet
args = sorted(args, key=default_sort_key)
# Reduce sets using known rules
if evaluate:
return Union.reduce(args)
return Basic.__new__(cls, *args)