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 ':')")
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)
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)
def __new__(cls, start, end, left_open=False, right_open=False): start = _sympify(start) end = _sympify(end) left_open = _sympify(left_open) right_open = _sympify(right_open) if not all(isinstance(a, (type(true), type(false))) for a in [left_open, right_open]): raise NotImplementedError( "left_open and right_open can have only true/false values, " "got %s and %s" % (left_open, right_open)) inftys = [S.Infinity, S.NegativeInfinity] # Only allow real intervals (use symbols with 'is_real=True'). if not (start.is_real or start in inftys) or not (end.is_real or end in inftys): raise ValueError("Only real intervals are supported") # Make sure that the created interval will be valid. if end.is_comparable and start.is_comparable: if end < start: return S.EmptySet if end == start and (left_open or right_open): return S.EmptySet if end == start and not (left_open or right_open): return FiniteSet(end) # Make sure infinite interval end points are open. if start == S.NegativeInfinity: left_open = true if end == S.Infinity: right_open = true return Basic.__new__(cls, start, end, left_open, right_open)
def __new__(cls, flambda, *sets): if not isinstance(flambda, Lambda): raise ValueError('First argument must be a Lambda') signature = flambda.signature if len(signature) != len(sets): raise ValueError('Incompatible signature') sets = [_sympify(s) for s in sets] if not all(isinstance(s, Set) for s in sets): raise TypeError("Set arguments to ImageSet should of type Set") if not all(cls._check_sig(sg, st) for sg, st in zip(signature, sets)): raise ValueError("Signature %s does not match sets %s" % (signature, sets)) if flambda is S.IdentityFunction and len(sets) == 1: return sets[0] if not set(flambda.variables) & flambda.expr.free_symbols: is_empty = fuzzy_or(s.is_empty for s in sets) if is_empty == True: return S.EmptySet elif is_empty == False: return FiniteSet(flambda.expr) return Basic.__new__(cls, flambda, *sets)
def __new__(cls, *args): if len(args) > 4: raise ValueError( "Range is defined by (top), (start, stop) or (start, stop, step)" ) # for a in args: # print(type(a)) # if not isinstance(a, (int, Symbol, Add)): # raise TypeError("args in Range must be integer or SymPy Idx") # expand range label = args[0] slc = slice(*args[1:]) if slc.step == 0: raise ValueError("step cannot be 0") start, stop, step = slc.start or 0, slc.stop, slc.step or 1 start = sympify(start) stop = sympify(stop) step = sympify(step) return Basic.__new__(cls, label, start, stop, step)
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)
def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_evaluate[0]) # flatten inputs args = list(args) # adapted from sympy.sets.sets.Union def _flatten(arg): if isinstance(arg, SeqBase): if isinstance(arg, SeqMul): return sum(map(_flatten, arg.args), []) else: return [arg] elif iterable(arg): return sum(map(_flatten, arg), []) raise TypeError("Input must be Sequences or " " iterables of Sequences") args = _flatten(args) # Multiplication of no sequences is EmptySequence if not args: return S.EmptySequence if Intersection(*(a.interval for a in args)) is S.EmptySet: return S.EmptySequence # reduce using known rules if evaluate: return SeqMul.reduce(args) args = list(ordered(args, SeqBase._start_key)) return Basic.__new__(cls, *args)
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))
def eval(cls, *args): """ Logical implication. Accepts two Boolean arguments; A and B. Returns False if A is True and B is False Returns True otherwise. Examples ======== >>> from sympy.logic.boolalg import Implies >>> Implies(True, False) False >>> Implies(False, False) True >>> Implies(True, True) True >>> Implies(False, True) True """ try: A, B = args except ValueError: raise ValueError( "%d operand(s) used for an Implies (pairs are required): %s" % (len(args), str(args))) if A is True or A is False or B is True or B is False: return Or(Not(A), B) else: return Basic.__new__(cls, *args)
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=default_sort_key) # Reduce sets using known rules if evaluate: return Intersection.reduce(args) return Basic.__new__(cls, *args)
def __new__(cls, start, end, left_open=False, right_open=False): start = _sympify(start) end = _sympify(end) inftys = [S.Infinity, S.NegativeInfinity] # Only allow real intervals (use symbols with 'is_real=True'). if not (start.is_real or start in inftys) or not (end.is_real or end in inftys): raise ValueError("Only real intervals are supported") # Make sure that the created interval will be valid. if end.is_comparable and start.is_comparable: if end < start: return S.EmptySet if end == start and (left_open or right_open): return S.EmptySet if end == start and not (left_open or right_open): return FiniteSet(end) # Make sure infinite interval end points are open. if start == S.NegativeInfinity: left_open = True if end == S.Infinity: right_open = True return Basic.__new__(cls, start, end, left_open, right_open)
def __new__(cls, amplitude, frequency=None, phase=S.Zero, time_period=None, n=Symbol('n')): if time_period is not None: time_period = _sympify(time_period) _frequency = S.One / time_period if frequency is not None: frequency = _sympify(frequency) _time_period = S.One / frequency if time_period is not None: if frequency != S.One / time_period: raise ValueError( "frequency and time_period should be consistent.") if frequency is None and time_period is None: raise ValueError("Either frequency or time period is needed.") if frequency is None: frequency = _frequency if time_period is None: time_period = _time_period amplitude = _sympify(amplitude) phase = _sympify(phase) n = sympify(n) obj = Basic.__new__(cls, amplitude, frequency, phase, time_period, n) return obj
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)
def __new__(cls, start, end, left_open=False, right_open=False): start = _sympify(start) end = _sympify(end) # Only allow real intervals (use symbols with 'is_real=True'). if not start.is_real or not end.is_real: raise ValueError("Only real intervals are supported") # Make sure that the created interval will be valid. if end.is_comparable and start.is_comparable: if end < start: return S.EmptySet if end == start and (left_open or right_open): return S.EmptySet if end == start and not (left_open or right_open): return FiniteSet(end) # Make sure infinite interval end points are open. if start == S.NegativeInfinity: left_open = True if end == S.Infinity: right_open = True return Basic.__new__(cls, start, end, left_open, right_open)
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
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
def __new__(cls, *args): args = [_sympify(arg) for arg in args] args = cls._flatten(args) ranks = [get_rank(arg) for arg in args] if len(args) == 1: return args[0] # If there are contraction objects inside, transform the whole # expression into `CodegenArrayContraction`: contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, CodegenArrayContraction)} if contractions: cumulative_ranks = list(accumulate([0] + ranks))[:-1] tp = cls(*[arg.expr if isinstance(arg, CodegenArrayContraction) else arg for arg in args]) contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices] return CodegenArrayContraction(tp, *contraction_indices) #newargs = [i for i in args if hasattr(i, "shape")] #coeff = reduce(lambda x, y: x*y, [i for i in args if not hasattr(i, "shape")], S.One) #newargs[0] *= coeff obj = Basic.__new__(cls, *args) obj._subranks = ranks shapes = [get_shape(i) for i in args] if any(i is None for i in shapes): obj._shape = None else: obj._shape = tuple(j for i in shapes for j in i) return obj
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
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)
def __new__(cls, *args, **kwargs): evaluate = kwargs.get("evaluate", global_evaluate[0]) # flatten inputs args = list(args) # adapted from sympy.sets.sets.Union def _flatten(arg): if isinstance(arg, SeqBase): if isinstance(arg, SeqMul): return sum(map(_flatten, arg.args), []) else: return [arg] elif iterable(arg): return sum(map(_flatten, arg), []) raise TypeError("Input must be Sequences or " " iterables of Sequences") args = _flatten(args) # Multiplication of no sequences is EmptySequence if not args: return S.EmptySequence if Intersection(a.interval for a in args) is S.EmptySet: return S.EmptySequence # reduce using known rules if evaluate: return SeqMul.reduce(args) args = list(ordered(args, SeqBase._start_key)) return Basic.__new__(cls, *args)
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)
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)
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)
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))
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)
def eval(cls, *args): """ Logical implication. Accepts two Boolean arguments; A and B. Returns False if A is True and B is False Returns True otherwise. Examples ======== >>> from sympy.logic.boolalg import Implies >>> Implies(True, False) False >>> Implies(False, False) True >>> Implies(True, True) True >>> Implies(False, True) True """ try: A, B = args except ValueError: raise ValueError( "%d operand(s) used for an Implies " "(pairs are required): %s" % (len(args), str(args))) if A is True or A is False or B is True or B is False: return Or(Not(A), B) else: return Basic.__new__(cls, *args)
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)
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)
def __new__(cls, sym, process, distribution=None): sym = _symbol_converter(sym) from sympy.stats.stochastic_process_types import StochasticProcess if not isinstance(process, StochasticProcess): raise TypeError("`process` must be an instance of StochasticProcess.") if distribution is None: distribution = Distribution() return Basic.__new__(cls, sym, process, distribution)
def __new__(cls, *args): obj = Basic.__new__(cls, *args) assumptions = {'integer': True} ass_copy = assumptions.copy() obj._assumptions = StdFactKB(assumptions) obj._assumptions._generator = ass_copy return obj
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)
def __new__(cls, *args, **kwargs): if len(args) == 1 and not kwargs and isinstance(args[0], cls): return args[0] args = args + tuple([kwargs[k] for k in cls.__slots__[len(args):]]) obj = Basic.__new__(cls) for attr, arg in zip(cls.__slots__, args): setattr(obj, attr, arg) return obj
def __new__(cls, domain, condition): """ Create a new instance of ConditionalFiniteDomain class """ if condition is True: return domain cond = rv_subs(condition) return Basic.__new__(cls, domain, cond)
def __new__(cls, *args): # args should be a tuple - a variable length argument list obj = Basic.__new__(cls, *args) obj._circuit = Mul(*args) obj._rules = generate_gate_rules(args) obj._eq_ids = generate_equivalent_ids(args) return obj
def __new__(cls, name, dtype): if not isinstance(name, (Symbol, MatrixSymbol)): raise TypeError("Only Symbols and MatrixSymbols can be Variables.") if isinstance(dtype, str): dtype = datatype(dtype) elif not isinstance(dtype, DataType): raise TypeError("datatype must be an instance of DataType.") return Basic.__new__(cls, name, dtype)
def __new__(cls, *args, **kwargs): if len(args) == 1 and not kwargs and isinstance(args[0], cls): return args[0] args = args + tuple([kwargs[k] for k in cls.__slots__[len(args):]]) obj = Basic.__new__(cls) for attr, arg in zip(cls.__slots__, args): setattr(obj, attr, arg) return obj
def __new__(cls, *args): # Flatten out Iterators and Unions to form one list of sets args = list(args) def flatten(arg): if arg == S.EmptySet: return [] if isinstance(arg, Set): if arg.is_Union: return sum(map(flatten, arg.args), []) else: return [arg] if is_flattenable(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: return S.EmptySet # Only real parts? Return a RealUnion if all(arg.is_real for arg in args): return RealUnion(args) # Lets find and merge real elements if we have them # Separate into finite, real and other sets finite_set = sum([s for s in args if s.is_FiniteSet], S.EmptySet) real_sets = [s for s in args if s.is_real] other_sets = [s for s in args if not s.is_FiniteSet and not s.is_real] # Separate finite_set into real and other part real_finite = RealFiniteSet(i for i in finite_set if i.is_real) other_finite = FiniteSet(i for i in finite_set if not i.is_real) # Merge real part of set real_union = RealUnion(real_sets+[real_finite]) if not real_union: # Real part was empty sets = other_sets + [other_finite] elif real_union.is_FiniteSet: # Real part was just a FiniteSet sets = other_sets + [real_union+other_finite] elif real_union.is_Interval: # Real part was just an Interval sets = [real_union] + other_sets + [other_finite] # If is_RealUnion then separate elif real_union.is_Union and real_union.is_real: intervals = [s for s in real_union.args if s.is_Interval] finite_set = sum([s for s in real_union.args if s.is_FiniteSet] + [other_finite], S.EmptySet) # Join FiniteSet back together sets = intervals + [finite_set] + other_sets # Clear out Empty Sets sets = [set for set in sets if set != S.EmptySet] # If a single set is left over, don't create a new Union object but # rather return the single set. if len(sets) == 1: return sets[0] return Basic.__new__(cls, *sets)
def __new__(cls, shape, *args): args = list(args) args_ = {'dtype': 'real', 'order': 'C'} prec = 0 val_args = [] for i in range(len(args)): if isinstance(args[i], ValuedArgument): val_args = args[i:] args[i:] = [] break if len(args) == 1: args_['dtype'] = str(args[0]) elif len(args) == 2: args_['dtype'] = str(args[0]) args_['order'] = str(args[1]) for i in val_args: val = str(i.value).replace('\'', '') args_[str(i.argument.name)] = val dtype = args_['dtype'] order = args_['order'] if isinstance(shape, Tuple): shape = list(shape) if isinstance(shape, list): if order == 'C': shape.reverse() # this is a correction. otherwise it is not working on LRZ if isinstance(shape[0], list): shape = Tuple(*(sympify(i, locals=local_sympify) for i in shape[0])) else: shape = Tuple(*(sympify(i, locals=local_sympify) for i in shape)) elif isinstance(shape, (int, sp_Integer, Symbol)): shape = Tuple(sympify(shape, locals=local_sympify)) else: shape = shape if isinstance(dtype, str): dtype = dtype.replace('\'', '') dtype, prec = dtype_registry[dtype] dtype = datatype('ndarray' + dtype) elif not isinstance(dtype, DataType): raise TypeError('datatype must be an instance of DataType.') if not prec: prec = default_precision[str(dtype)] return Basic.__new__(cls, shape, dtype, order, prec)
def __new__(cls, target, iter, body): target = _sympify(target) if not iterable(iter): raise TypeError("iter must be an iterable") iter = _sympify(iter) if not iterable(body): raise TypeError("body must be an iterable") body = Tuple(*(_sympify(i) for i in body)) return Basic.__new__(cls, target, iter, body)
def __new__(cls, name, body): if not isinstance(name, str): raise TypeError("Module name must be string") name = Symbol(name) # body if not iterable(body): raise TypeError("body must be an iterable") body = Tuple(*body) return Basic.__new__(cls, name, body)
def __new__(cls, lamda, base_set): if not isinstance(lamda, Lambda): raise ValueError('first argument must be a Lambda') if lamda is S.IdentityFunction: return base_set if not lamda.expr.free_symbols or not lamda.expr.args: return FiniteSet(lamda.expr) return Basic.__new__(cls, lamda, base_set)
def eval(cls, *args): try: A, B = args except ValueError: raise ValueError("%d operand(s) used for an Implies (pairs are required): %s" % (len(args), str(args))) if A is True or A is False or B is True or B is False: return Or(Not(A), B) else: return Basic.__new__(cls, *args)
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)
def __new__(cls, flambda, *sets): if not isinstance(flambda, Lambda): raise ValueError('first argument must be a Lambda') if flambda is S.IdentityFunction and len(sets) == 1: return sets[0] if not flambda.expr.free_symbols or not flambda.expr.args: return FiniteSet(flambda.expr) return Basic.__new__(cls, flambda, *sets)
def eval(cls, *args): try: A, B = args except ValueError: raise ValueError("%d operand(s) used for an Implies (pairs are required): %s" % (len(args), str(args))) if A is True or A is False or B is True or B is False: return Or(Not(A), B) else: return Basic.__new__(cls, *args)
def __new__(cls, arg, index=None): if not isinstance(arg, (list, tuple, Tuple, List, Array, Variable, IndexedElement, IndexedBase)): raise TypeError('Uknown type of %s.' % type(arg)) # TODO add check on index: must be Integer or Variable with dtype=int # TODO [YG, 09.10.2018]: Verify why index should be passed at all (not in Numpy!) return Basic.__new__(cls, arg, index)
def __new__(cls, lamda, base_set): if not isinstance(lamda, Lambda): raise ValueError('first argument must be a Lambda') if lamda is S.IdentityFunction: return base_set if not lamda.expr.free_symbols or not lamda.expr.args: return FiniteSet(lamda.expr) return Basic.__new__(cls, lamda, base_set)
def __new__(cls, flambda, *sets): if not isinstance(flambda, Lambda): raise ValueError('first argument must be a Lambda') if flambda is S.IdentityFunction and len(sets) == 1: return sets[0] if not flambda.expr.free_symbols or not flambda.expr.args: return FiniteSet(flambda.expr) return Basic.__new__(cls, flambda, *sets)
def __new__(cls, f, x=None): if not isinstance(f, Poly): f = Poly(f, x) elif x is not None: raise SymbolsError("Redundant symbols were given") if f.is_multivariate: raise MultivariatePolyError(f) return Basic.__new__(cls, f)
def __new__(cls, module, parents): if not isinstance(module, Module): raise TypeError('Expecting a Module') if not isinstance(parents, dict): raise TypeError('Expecting a dict') obj = Basic.__new__(cls, module) obj._parents = parents return obj
def __new__(cls, dtype, name): if isinstance(dtype, str): dtype = datatype(dtype) elif not isinstance(dtype, DataType): raise TypeError("datatype must be an instance of DataType.") if isinstance(name, str): name = Symbol(name) elif not isinstance(name, (Symbol, MatrixSymbol)): raise TypeError("Only Symbols and MatrixSymbols can be Variables.") return Basic.__new__(cls, dtype, name)
def __new__(cls, *args, **assumptions): if isinstance(args[0], cls): expr = args[0].expr cond = args[0].cond elif len(args) == 2: expr = sympify(args[0]) cond = sympify(args[1]) else: raise TypeError("args must be a (expr, cond) pair") return Basic.__new__(cls, expr, cond, **assumptions)
def __new__(cls, mat): mat = sympify(mat) if not mat.is_Matrix: raise TypeError("input to Trace, %s, is not a matrix" % str(mat)) if not mat.is_square: raise NonSquareMatrixError("Trace of a non-square matrix") return Basic.__new__(cls, mat)
def __new__(cls, symbol, type_=None, value_const=False, pointer_const=False, restrict=False): if type_ is None: type_ = _type_from_expr(symbol) return Basic.__new__(cls, symbol, type_, value_const, pointer_const, restrict)
def __new__(cls, var, val=None, cast=False): if not isinstance(var, Variable): raise TypeError("var argument should be an instance of Variable") args = var, if val is not None: if cast: args += (var.type.cast_check(val), ) else: args += (_sympify(val), ) return Basic.__new__(cls, *args)
def __new__(cls, dist): if not isinstance(dist, (ContinuousDistribution, SingleFiniteDistribution, DiscreteDistribution)): message = "Compound Distribution for %s is not implemeted yet" % str( dist) raise NotImplementedError(message) if not cls._compound_check(dist): return dist return Basic.__new__(cls, dist)
def __new__(cls, f, x=None): if not isinstance(f, Poly): f = Poly(f, x) elif x is not None: raise SymbolsError("Redundant symbols were given") if f.is_multivariate: raise MultivariatePolyError(f) return Basic.__new__(cls, f)
def __new__(cls, mat): mat = sympify(mat) if not mat.is_Matrix: raise TypeError("Input to Determinant, %s, not a matrix" % str(mat)) if not mat.is_square: raise NonSquareMatrixError("Det of a non-square matrix") return Basic.__new__(cls, mat)
def __new__(cls, var, val=None, cast=False): if not isinstance(var, Variable): raise TypeError("var argument should be an instance of Variable") args = var, if val is not None: if cast: args += (var.type.cast_check(val),) else: args += (_sympify(val),) return Basic.__new__(cls, *args)