def __new__(cls, name, objects=EmptySet(), commutative_diagrams=EmptySet()): if not name: raise ValueError("A Category cannot have an empty name.") new_category = Basic.__new__(cls, Symbol(name), Class(objects), FiniteSet(*commutative_diagrams)) return new_category
def __new__(cls, radius=1, center=[0,0,0], direction=[0,0,1], closed=False, **kwargs): """ >>> from sympy import * >>> from symplus.strplus import init_mprinting >>> init_mprinting() >>> InfiniteCylinder() InfiniteCylinder(1, [0 0 0]', [0 0 1]', False) >>> InfiniteCylinder(2, [0,0,0], [0,1,1]) InfiniteCylinder(2, [0 0 0]', [0 -sqrt(2)/2 -sqrt(2)/2]', False) >>> InfiniteCylinder().contains((1,1,1)) False >>> InfiniteCylinder(2, [0,0,0], [0,1,1]).contains((1,1,1)) True """ normalization = kwargs.pop("normalization", True) radius = sympify(abs(radius)) direction = Mat(direction) if normalization: if norm(direction) == 0: raise ValueError direction = simplify(normalize(direction)) direction = max(direction, -direction, key=hash) center = Mat(center) if normalization: center = simplify(center - project(center, direction)) closed = sympify(bool(closed)) return Basic.__new__(cls, radius, center, direction, closed)
def __new__(cls, *args, **kw_args): """ Constructor for the Permutation object. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0,1,2]) >>> p Permutation([0, 1, 2]) >>> q = Permutation([[0,1],[2]]) >>> q Permutation([[0, 1], [2]]) """ if not args or not is_sequence(args[0]) or len(args) > 1 or \ len(set(is_sequence(a) for a in args[0])) > 1: raise ValueError('Permutation argument must be a list of ints or a list of lists.') # 0, 1, ..., n-1 should all be present temp = [int(i) for i in flatten(args[0])] if set(range(len(temp))) != set(temp): raise ValueError("Integers 0 through %s must be present." % len(temp)) cform = aform = None if args[0] and is_sequence(args[0][0]): cform = [list(a) for a in args[0]] else: aform = list(args[0]) ret_obj = Basic.__new__(cls, (cform or aform), **kw_args) ret_obj._cyclic_form, ret_obj._array_form = cform, aform return ret_obj
def __new__(cls, *args, **kwargs): check = kwargs.get('check', True) obj = Basic.__new__(cls, *args) if check: validate(*args) return obj
def __new__(cls, *args, **kw_args): """ The constructor for the Prufer object. Examples ======== >>> from sympy.combinatorics.prufer import Prufer A Prufer object can be constructed from a list of node connections and the number of nodes: >>> a = Prufer([[0, 1], [0, 2], [0, 3]], 4) >>> a.prufer_repr [0, 0] A Prufer object can be constructed from a Prufer sequence: >>> b = Prufer([1, 3]) >>> b.tree_repr [[2, 1], [1, 3], [3, 0]] """ ret_obj = Basic.__new__(cls, *args, **kw_args) if isinstance(args[0][0], list): ret_obj._tree_repr = args[0] ret_obj._nodes = args[1] else: ret_obj._prufer_repr = args[0] ret_obj._nodes = len(ret_obj._prufer_repr) + 2 return ret_obj
def __new__(cls, func, center=[0,0,0], direction=[0,0,1], **kwargs): center = Mat(center) direction = Mat(direction) if norm(direction) == 0: raise ValueError direction = normalize(direction) return Basic.__new__(cls, func, center, direction)
def __new__(cls, *components): if components and not isinstance(components[0], Morphism): # Maybe the user has explicitly supplied a list of # morphisms. return CompositeMorphism.__new__(cls, *components[0]) normalised_components = Tuple() for current, following in zip(components, components[1:]): if not isinstance(current, Morphism) or \ not isinstance(following, Morphism): raise TypeError("All components must be morphisms.") if current.codomain != following.domain: raise ValueError("Uncomposable morphisms.") normalised_components = CompositeMorphism._add_morphism( normalised_components, current) # We haven't added the last morphism to the list of normalised # components. Add it now. normalised_components = CompositeMorphism._add_morphism( normalised_components, components[-1]) if not normalised_components: # If ``normalised_components`` is empty, only identities # were supplied. Since they all were composable, they are # all the same identities. return components[0] elif len(normalised_components) == 1: # No sense to construct a whole CompositeMorphism. return normalised_components[0] return Basic.__new__(cls, normalised_components)
def __new__(cls, *args): from sympy.matrices.immutable import ImmutableDenseMatrix args = map(sympify, args) mat = ImmutableDenseMatrix(*args) obj = Basic.__new__(cls, mat) return obj
def __new__(cls, arg, expr): if not isinstance(arg, Argument): raise TypeError("arg must be of type `Argument`") expr = _sympify(expr) if not isinstance(expr, (Expr, MatrixExpr)): raise TypeError("Unsupported expression type %s." % type(expr)) return Basic.__new__(cls, arg, expr)
def __new__(cls, mat): mat = _sympify(mat) if not mat.is_Matrix: raise TypeError("mat should be a matrix") if not mat.is_square: raise ShapeError("Inverse of non-square matrix %s" % mat) return Basic.__new__(cls, mat)
def __new__(cls, e, z, z0, dir="+"): e = sympify(e) z = sympify(z) z0 = sympify(z0) obj = Basic.__new__(cls) obj._args = (e, z, z0, dir) return obj
def __new__(cls, *args, **options): # (Try to) sympify args first newargs = [] for ec in args: pair = ExprCondPair(*ec) cond = pair.cond if cond == false: continue if not isinstance(cond, (bool, Relational, Boolean)): raise TypeError( "Cond %s is of type %s, but must be a Relational," " Boolean, or a built-in bool." % (cond, type(cond))) newargs.append(pair) if cond == True: break if options.pop('evaluate', True): r = cls.eval(*newargs) else: r = None if r is None: return Basic.__new__(cls, *newargs, **options) else: return r
def __new__(cls, subset, superset): """ Default constructor. It takes the subset and its superset as its parameters. Examples: >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c','d'], ['a','b','c','d']) >>> a.subset ['c', 'd'] >>> a.superset ['a', 'b', 'c', 'd'] >>> a.size 2 """ if len(subset) > len(superset): raise ValueError("Invalid arguments have been provided. The superset must be larger than the subset.") for elem in subset: if elem not in superset: raise ValueError("The superset provided is invalid as it does not contain the element %i" % elem) obj = Basic.__new__(cls) obj._subset = subset obj._superset = superset return obj
def __new__(cls, partition, integer=None): """ Generates a new IntegerPartition object from a list or dictionary. The partition can be given as a list of positive integers or a dictionary of (integer, multiplicity) items. If the partition is preceeded by an integer an error will be raised if the partition does not sum to that given integer. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([5, 4, 3, 1, 1]) >>> a IntegerPartition(14, (5, 4, 3, 1, 1)) >>> print a [5, 4, 3, 1, 1] >>> IntegerPartition({1:3, 2:1}) IntegerPartition(5, (2, 1, 1, 1)) If the value that the partion should sum to is given first, a check will be made to see n error will be raised if there is a discrepancy: >>> IntegerPartition(10, [5, 4, 3, 1]) Traceback (most recent call last): ... ValueError: The partition is not valid """ from sympy.ntheory.residue_ntheory import int_tested if integer is not None: integer, partition = partition, integer if isinstance(partition, (dict, Dict)): _ = [] for k, v in sorted(partition.items(), reverse=True): if not v: continue k, v = int_tested(k, v) _.extend([k]*v) partition = tuple(_) else: partition = tuple(sorted(int_tested(partition), reverse=True)) sum_ok = False if integer is None: integer = sum(partition) sum_ok = True else: integer = int_tested(integer) if not sum_ok and sum(partition) != integer: raise ValueError("Partition did not add to %s" % integer) if any(i < 1 for i in partition): raise ValueError("The summands must all be positive.") obj = Basic.__new__(cls, integer, partition) obj.partition = list(partition) obj.integer = integer return obj
def __new__(cls, *args, **kwargs): args = list(map(sympify, args)) check = kwargs.get('check', True) obj = Basic.__new__(cls, *args) if check: validate(*args) return obj
def _new(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], ImmutableMatrix): return args[0] rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) rows = Integer(rows) cols = Integer(cols) mat = Tuple(*flat_list) return Basic.__new__(cls, rows, cols, mat)
def __new__(cls, mat, exp=S(-1)): # exp is there to make it consistent with # inverse.func(*inverse.args) == inverse mat = _sympify(mat) if not mat.is_Matrix: raise TypeError("mat should be a matrix") if not mat.is_square: raise ShapeError("Inverse of non-square matrix %s" % mat) return Basic.__new__(cls, mat, exp)
def __new__(cls, *args, **kwargs): check = kwargs.get('check', True) args = map(sympify, args) obj = Basic.__new__(cls, *args) factor, matrices = obj.as_coeff_matrices() if check: validate(*matrices) return obj
def __new__(cls, dtype, expr): if isinstance(dtype, str): dtype = datatype(dtype) elif not isinstance(dtype, DataType): raise TypeError("datatype must be an instance of DataType.") expr = _sympify(expr) if not isinstance(expr, (Expr, MatrixExpr)): raise TypeError("Unsupported expression type %s." % type(expr)) return Basic.__new__(cls, dtype, expr)
def _new(cls, *args, **kwargs): # same as sympy version, only always creates new class # even if passed in a matrix from sympy.core import Basic, Integer rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) rows = Integer(rows) cols = Integer(cols) mat = Tuple(*flat_list) return Basic.__new__(cls, rows, cols, mat)
def __new__(cls, routine, args): if not isinstance(routine, Routine): raise TypeError("routine must be of type Routine") if len(routine.arguments) != len(args): raise ValueError("Incorrect number of arguments") for n, (a, p) in enumerate(zip(args, routine.arguments)): cls._validate_arg(a, p) args = Tuple(*args) return Basic.__new__(cls, routine, args)
def __new__(cls, a, b): if isinstance(b, int): b = Integer(b) if not isinstance(b, Integer) or b <= 0: raise TypeError("multiplicity must be a positive integer") if not isinstance(a, Ordinal): a = Ordinal.convert(a) return Basic.__new__(cls, a, b)
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, *args, **kwargs): args = list(map(sympify, args)) check = kwargs.get('check', False) obj = Basic.__new__(cls, *args) if check: if all(not isinstance(i, MatrixExpr) for i in args): return Add.fromiter(args) validate(*args) return obj
def _new(cls, *args, **kwargs): s = MutableSparseMatrix(*args) rows = Integer(s.rows) cols = Integer(s.cols) mat = Dict(s._smat) obj = Basic.__new__(cls, rows, cols, mat) obj.rows = s.rows obj.cols = s.cols obj._smat = s._smat return obj
def __new__(cls, f, z, **assumptions): f = Basic.sympify(f) if not f.is_polynomial(z): return f obj = Basic.__new__(cls, **assumptions) obj._args = (f.as_polynomial(z), z) return obj
def eval(cls, *args): out_args = [] for arg in args: # we iterate over a copy or args if isinstance(arg, bool): if arg: return True else: continue out_args.append(arg) if len(out_args) == 0: return False if len(out_args) == 1: return out_args[0] sargs = sorted(flatten(out_args, cls=cls)) return Basic.__new__(cls, *sargs)
def __new__(cls, cartantype): """ Creates a new RootSystem object. This method assigns an attribute called cartan_type to each instance of a RootSystem object. When an instance of RootSystem is called, it needs an argument, which should be an instance of a simple Lie algebra. We then take the CartanType of this argument and set it as the cartan_type attribute of the RootSystem instance. """ obj = Basic.__new__(cls, cartantype) obj.cartan_type = CartanType(cartantype) return obj
def construct(t): """ Turn a Compound into a SymPy object """ if isinstance(t, (Variable, CondVariable)): return t.arg if not isinstance(t, Compound): return t if any(issubclass(t.op, cls) for cls in eval_false_legal): return t.op(*map(construct, t.args), evaluate=False) elif any(issubclass(t.op, cls) for cls in basic_new_legal): return Basic.__new__(t.op, *map(construct, t.args)) else: return t.op(*map(construct, t.args))
def __new__(cls, *args, **kwargs): evaluate = kwargs.get("evaluate", True) check = kwargs.get("check", True) args = map(sympify, args) obj = Basic.__new__(cls, *args) factor, matrices = obj.as_coeff_matrices() if check: validate(*matrices) if evaluate: return canonicalize(obj) return obj
def _new(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], ImmutableDenseMatrix): return args[0] if kwargs.get('copy', True) is False: if len(args) != 3: raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]") rows, cols, flat_list = args else: rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) flat_list = list(flat_list) # create a shallow copy rows = Integer(rows) cols = Integer(cols) if not isinstance(flat_list, Tuple): flat_list = Tuple(*flat_list) return Basic.__new__(cls, rows, cols, flat_list)
def __new__(cls, function, *symbols, **assumptions): if any(len(l) != 3 or None for l in symbols): raise ValueError('ArrayComprehension requires values lower and upper bound' ' for the expression') if not isLambda(function): raise ValueError('Data type not supported') arglist = cls._check_limits_validity(function, symbols) obj = Basic.__new__(cls, *arglist, **assumptions) obj._limits = obj._args obj._shape = cls._calculate_shape_from_limits(obj._limits) obj._rank = len(obj._shape) obj._loop_size = cls._calculate_loop_size(obj._shape) obj._lambda = function return obj
def __new__(cls, *args, **kwargs): if not args: return GenericZeroMatrix() # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericZeroMatrix().shape args = filter(lambda i: GenericZeroMatrix() != i, args) args = list(map(sympify, args)) check = kwargs.get('check', False) obj = Basic.__new__(cls, *args) if check: if all(not isinstance(i, MatrixExpr) for i in args): return Add.fromiter(args) validate(*args) return obj
def __new__(cls, arg1, arg2): arg1, arg2 = _sympify((arg1, arg2)) if not arg1.is_Matrix: raise TypeError("Argument 1 of DotProduct is not a matrix") if not arg2.is_Matrix: raise TypeError("Argument 2 of DotProduct is not a matrix") if not (1 in arg1.shape): raise TypeError("Argument 1 of DotProduct is not a vector") if not (1 in arg2.shape): raise TypeError("Argument 2 of DotProduct is not a vector") if set(arg1.shape) != set(arg2.shape): raise TypeError("DotProduct arguments are not the same length") return Basic.__new__(cls, arg1, arg2)
def __new__(cls, n, *args, **kw_args): """ Default constructor. It takes a single argument ``n`` which gives the dimension of the Gray code. The starting Gray code string (``start``) or the starting ``rank`` may also be given; the default is to start at rank = 0 ('0...0'). Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3) >>> a GrayCode(3) >>> a.n 3 >>> a = GrayCode(3, start='100') >>> a.current '100' >>> a = GrayCode(4, rank=4) >>> a.current '0110' >>> a.rank 4 """ if n < 1 or int(n) != n: raise ValueError( 'Gray code dimension must be a positive integer, not %i' % n) n = int(n) args = (n,) + args obj = Basic.__new__(cls, *args) if 'start' in kw_args: obj._current = kw_args["start"] if len(obj._current) > n: raise ValueError('Gray code start has length %i but ' 'should not be greater than %i' % (len(obj._current), n)) elif 'rank' in kw_args: if int(kw_args["rank"]) != kw_args["rank"]: raise ValueError('Gray code rank must be a positive integer, ' 'not %i' % kw_args["rank"]) obj._rank = int(kw_args["rank"]) % obj.selections obj._current = obj.unrank(n, obj._rank) return obj
def __new__(cls, *args, **options): # (Try to) sympify args first name = options.pop('name', None) if options.pop('evaluate', True): r = cls.eval(*args) else: r = None if r is None: obj = Basic.__new__(cls, *args, **options) obj._name = name return obj else: r._name = name return r
def __new__(cls, f, *symbols, **assumptions): f = sympify(f) if f.is_Number: if f is S.NaN: return S.NaN elif f is S.Zero: return S.Zero if not symbols: limits = f.atoms(Symbol) if not limits: return f else: limits = [] for V in symbols: if isinstance(V, Symbol): limits.append(V) continue elif isinstance(V, Equality): if isinstance(V.lhs, Symbol): if isinstance(V.rhs, Interval): limits.append((V.lhs, V.rhs.start, V.rhs.end)) else: limits.append((V.lhs, V.rhs)) continue elif isinstance(V, (tuple, list)): if len(V) == 1: if isinstance(V[0], Symbol): limits.append(V[0]) continue elif len(V) in (2, 3): if isinstance(V[0], Symbol): limits.append(tuple(map(sympify, V))) continue raise ValueError("Invalid summation variable or limits") obj = Basic.__new__(cls, **assumptions) obj._args = (f, tuple(limits)) return obj
def __new__(cls, name, bnd_minus, bnd_plus, mapping=None, logical_domain=None): if not isinstance(name , str ): raise TypeError(name) if not isinstance(bnd_minus, Boundary): raise TypeError(bnd_minus) if not isinstance(bnd_plus , Boundary): raise TypeError(bnd_plus) if bnd_minus.dim != bnd_plus.dim: raise TypeError('Dimension mismatch: {} != {}'.format( bnd_minus.dim, bnd_plus.dim)) assert mapping is None and logical_domain is None or\ mapping is not None and logical_domain is not None assert bnd_minus.axis == bnd_plus.axis obj = Basic.__new__(cls, name, bnd_minus, bnd_plus) obj._mapping = mapping obj._logical_domain = logical_domain return obj
def __new__(cls, name, args, results): # name if isinstance(name, str): name = Symbol(name) elif not isinstance(name, Symbol): raise TypeError("name must be Symbol or string") # args if not iterable(args): raise TypeError("args must be an iterable") if not all(isinstance(a, Argument) for a in args): raise TypeError("All args must be of type Argument") args = Tuple(*args) # results if not iterable(results): raise TypeError("results must be an iterable") if not all(isinstance(i, RoutineResult) for i in results): raise TypeError("All results must be of type RoutineResult") results = Tuple(*results) return Basic.__new__(cls, name, args, results)
def __new__(cls, name, domain, axis=None, ext=None, mapping=None, logical_domain=None): if axis is not None: assert isinstance(axis, int) if ext is not None: assert isinstance(ext, int) obj = Basic.__new__(cls, name, domain, axis, ext) obj._mapping = mapping obj._logical_domain = logical_domain return obj
def __new__(cls, *args, **options): # (Try to) sympify args first newargs = [] for ec in args: pair = ExprCondPair(*ec) cond_type = type(pair.cond) if not (cond_type is bool or issubclass(cond_type, Relational) or \ issubclass(cond_type, Number) or issubclass(cond_type, Set)): raise TypeError, \ "Cond %s is of type %s, but must be a bool," \ " Relational, Number or Set" % (pair.cond, cond_type) newargs.append(pair) r = cls.eval(*newargs) if r is None: return Basic.__new__(cls, *newargs, **options) else: return r
def _new_from_array_form(perm): """ factory function to produce a Permutation object from a list; the list is bound to the _array_form attribute, so it must not be modified; this method is meant for internal use only; the list a is supposed to be generated as a temporary value in a method, so p = _new_from_array_form(a) is the only object to hold a reference to a:: >>> from sympy.combinatorics.permutations import _new_from_array_form >>> a = [2,1,3,0] >>> p = _new_from_array_form(a) >>> p Permutation([2, 1, 3, 0]) """ p = Basic.__new__(Permutation, perm) p._array_form = perm return p
def __new__(cls, name, domain, shape, kind): if not isinstance(domain, BasicDomain): raise TypeError('> Expecting a BasicDomain object for domain') obj = Basic.__new__(cls) obj._name = name obj._domain = domain obj._shape = shape # ... if kind is None: kind = 'undefined' if isinstance(kind, str): kind_str = kind.lower() assert (kind_str in ['h1', 'hcurl', 'hdiv', 'l2', 'undefined']) kind = dtype_space_registry[kind_str] elif not isinstance(kind, SpaceType): raise TypeError('Expecting kind to be of SpaceType') kind_str = kind.name obj._kind = kind # ... if not (kind_str == 'undefined'): obj._regularity = dtype_regularity_registry[kind_str] # ... # ... # TODO remove this if => bug in tensor form if isinstance(domain, Interval): is_broken = False else: is_broken = len(domain) > 1 obj._is_broken = is_broken # ... return obj
def __new__(cls, function, *symbols, **assumptions): function = sympify(function) if function.is_Number: if function is S.NaN: return S.NaN elif function is S.Infinity: return S.Infinity elif function is S.NegativeInfinity: return S.NegativeInfinity if symbols: limits = [] for V in symbols: if isinstance(V, Symbol): limits.append((V, None)) continue elif isinstance(V, (tuple, list)): if len(V) == 3: if isinstance(V[0], Symbol): nlim = map(sympify, V[1:]) limits.append((V[0], tuple(nlim))) continue elif len(V) == 1 or (len(V) == 2 and V[1] is None): if isinstance(V[0], Symbol): limits.append((V[0], None)) continue raise ValueError("Invalid integration variable or limits: %s" % str(symbols)) else: # no symbols provided -- let's compute full antiderivative limits = [(symb, None) for symb in function.atoms(Symbol)] if not limits: return function obj = Basic.__new__(cls, **assumptions) obj._args = (function, tuple(limits)) return obj
def __new__(cls, arg1, arg2): if not arg1.is_Matrix: raise TypeError("Input to Dot Product, %s, not a matrix" % str(arg1)) if not arg2.is_Matrix: raise TypeError("Input to Dot Product, %s, not a matrix" % str(arg2)) if not (1 in arg1.shape): raise TypeError("Input to Dot Product, %s, not a vector" % str(arg1)) if not (1 in arg2.shape): raise TypeError("Input to Dot Product, %s, not a vector" % str(arg1)) if arg1.shape != arg2.shape: raise TypeError( "Input to Dot Product, %s and %s, are not of same dimensions" % (str(arg1), str(arg2))) return Basic.__new__(cls, arg1, arg2)
def __new__(cls, *args, **kwargs): check = kwargs.get('check', True) if not args: return GenericIdentity() # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericIdentity().shape args = filter(lambda i: GenericIdentity() != i, args) args = list(map(sympify, args)) obj = Basic.__new__(cls, *args) factor, matrices = obj.as_coeff_matrices() if check: validate(*matrices) if not matrices: # Should it be # # return Basic.__neq__(cls, factor, GenericIdentity()) ? return factor return obj
def __new__(cls, name, dim=None, dtype=None, mapping=None, logical_domain=None): target = None if not isinstance(name, str): target = name name = name.name if not( target is None ): dim = target.dim assert mapping is None and logical_domain is None or \ mapping is not None and logical_domain is not None obj = Basic.__new__(cls, name) obj._dim = dim obj._target = target obj._dtype = dtype obj._mapping = mapping obj._logical_domain = logical_domain return obj
def __new__(cls, *args, **kw_args): """ The constructor for the Prufer object. Examples: >>> from sympy.combinatorics.prufer import Prufer >>> a = Prufer([[0, 1], [0, 2], [0, 3]], 4) >>> a.prufer_repr [0, 0] >>> b = Prufer([1, 3]) >>> b.tree_repr [[2, 1], [1, 3], [3, 0]] """ ret_obj = Basic.__new__(cls, *args, **kw_args) if isinstance(args[0][0], list): ret_obj._tree_repr = args[0] ret_obj._nodes = args[1] else: ret_obj._prufer_repr = args[0] ret_obj._nodes = len(ret_obj._prufer_repr) + 2 return ret_obj
def __new__(cls, *args, evaluate=False, check=False, _sympify=True): if not args: return cls.identity # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericZeroMatrix().shape args = list(filter(lambda i: cls.identity != i, args)) if _sympify: args = list(map(sympify, args)) obj = Basic.__new__(cls, *args) if check: if not any(isinstance(i, MatrixExpr) for i in args): return Add.fromiter(args) validate(*args) if evaluate: obj = cls._evaluate(obj) return obj
def __new__(cls, term, *symbols, **assumptions): term = sympify(term) if term.is_Number: if term is S.NaN: return S.NaN elif term is S.Infinity: return S.NaN elif term is S.NegativeInfinity: return S.NaN elif term is S.Zero: return S.Zero elif term is S.One: return S.One if len(symbols) == 1: symbol = symbols[0] if isinstance(symbol, C.Equality): k = symbol.lhs a = symbol.rhs.start n = symbol.rhs.end elif isinstance(symbol, (tuple, list)): k, a, n = symbol else: raise ValueError("Invalid arguments") k, a, n = map(sympify, (k, a, n)) if isinstance(a, C.Number) and isinstance(n, C.Number): return Mul( *[term.subs(k, i) for i in xrange(int(a), int(n) + 1)]) else: raise NotImplementedError obj = Basic.__new__(cls, **assumptions) obj._args = (term, k, a, n) return obj
def __new__(cls, expr, domain, eval=True): if eval: expr = Integral(expr, domain) obj = Basic.__new__(cls, expr, domain) # compute dim from fields if available ls = list(expr.atoms((ScalarField, VectorField))) if ls: F = ls[0] space = F.space else: tag = random_string( 3 ) space_name = 'space_{}'.format(tag) space = ScalarFunctionSpace(space_name, domain) # TODO vector case obj._ldim = domain.dim obj._space = space return obj
def __new__(cls, *args, **options): # (Try to) sympify args first newargs = [] for ec in args: # ec could be a ExprCondPair or a tuple pair = ExprCondPair(*getattr(ec, 'args', ec)) cond = pair.cond if cond is false: continue newargs.append(pair) if cond is true: break if options.pop('evaluate', True): r = cls.eval(*newargs) else: r = None if r is None: return Basic.__new__(cls, *newargs, **options) else: return r
def __new__(cls, *components): if components and not isinstance(components[0], Morphism): # Maybe the user has explicitly supplied a list of # morphisms. return CompositeMorphism.__new__(cls, *components[0]) normalised_components = Tuple() # TODO: Fix the unpythonicity. for i in xrange(len(components) - 1): current = components[i] following = components[i + 1] if not isinstance(current, Morphism) or \ not isinstance(following, Morphism): raise TypeError("All components must be morphisms.") if current.codomain != following.domain: raise ValueError("Uncomposable morphisms.") normalised_components = CompositeMorphism._add_morphism( normalised_components, current) # We haven't added the last morphism to the list of normalised # components. Add it now. normalised_components = CompositeMorphism._add_morphism( normalised_components, components[-1]) if not normalised_components: # If ``normalised_components`` is empty, only identities # were supplied. Since they all were composable, they are # all the same identities. return components[0] elif len(normalised_components) == 1: # No sense to construct a whole CompositeMorphism. return normalised_components[0] return Basic.__new__(cls, normalised_components)
def __new__(cls, arguments, expr, check=False): # ... if expr.atoms(DomainIntegral, BoundaryIntegral): raise TypeError('') # ... # ... if not isinstance(arguments, (tuple, list, Tuple)): raise TypeError('(trial, test) must be a tuple, list or Tuple') if not(len(arguments) == 2): raise ValueError('Expecting a couple (trial, test)') # ... # ... if check and not is_bilinear_form(expr, arguments): msg = '> Expression is not bilinear' raise UnconsistentLinearExpressionError(msg) # ... args = _sanitize_arguments(arguments, is_bilinear=True) return Basic.__new__(cls, args, expr)
def __new__(cls, *args, **kw_args): """ The default constructor. """ obj = Basic.__new__(cls, *args, **kw_args) obj._generators = args[0] obj._order = None obj._center = [] obj._is_abelian = None size = len(args[0][0].array_form) obj._r = len(obj._generators) if not all( len(args[0][i].array_form) == size for i in xrange(1, len(args[0]))): raise ValueError("Permutation group size is not correct") obj._degree = size # these attributes are assigned after running schreier_sims obj._base = [] obj._coset_repr = [] obj._coset_repr_n = [] obj._stabilizers_gens = [] return obj
def __new__(cls, arguments, expr, **options): # Trivial case: null expression if expr == 0: return sy_Zero() # Check that integral expression is given if not expr.atoms(Integral): raise ValueError('Expecting integral Expression') # TODO: why do we 'sanitize' here? args = _sanitize_arguments(arguments, is_bilinear=True) # Distinguish between trial and test functions trial_functions, test_functions = args # Check linearity with respect to trial functions if not is_linear_expression(expr, trial_functions): msg = ' Expression is not linear w.r.t trial functions {}'\ .format(trial_functions) raise UnconsistentLinearExpressionError(msg) # Check linearity with respect to test functions if not is_linear_expression(expr, test_functions): msg = ' Expression is not linear w.r.t test functions {}'\ .format(test_functions) raise UnconsistentLinearExpressionError(msg) # Create new object of type BilinearForm obj = Basic.__new__(cls, args, expr) # Compute 'domain' property (scalar or tuple) # TODO: is this is useful? obj._domain = _get_domain(expr) return obj
def __new__(cls, *args, **kw_args): """ Constructor for the Permutation object. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0,1,2]) >>> p Permutation([0, 1, 2]) >>> q = Permutation([[0,1],[2]]) >>> q Permutation([[0, 1], [2]]) """ if not args or not is_sequence(args[0]) or len(args) > 1 or \ len(set(is_sequence(a) for a in args[0])) > 1: raise ValueError("Permutation argument must be a list of ints " "or a list of lists.") # 0, 1, ..., n-1 should all be present temp = [int(i) for i in flatten(args[0])] if set(range(len(temp))) != set(temp): # XXX allow arbitrary elements like Partition does raise ValueError("Integers 0 through %s must be present." % len(temp)) cform = aform = None if args[0] and is_sequence(args[0][0]): cform = [list(a) for a in args[0]] else: aform = list(args[0]) ret_obj = Basic.__new__(cls, (cform or aform), **kw_args) ret_obj._cyclic_form, ret_obj._array_form = cform, aform return ret_obj
def __new__(cls, *args): # Check that the shape of the args is consistent matrices = [arg for arg in args if arg.is_Matrix] for i in range(len(matrices) - 1): A, B = matrices[i:i + 2] if A.cols != B.rows: raise ShapeError("Matrices %s and %s are not aligned" % (A, B)) if any(arg.is_zero for arg in args): return ZeroMatrix(matrices[0].rows, matrices[-1].cols) expr = matrixify(Mul.__new__(cls, *args)) if expr.is_Add: return MatAdd(*expr.args) if expr.is_Pow: assert expr.exp.is_Integer expr = Basic.__new__(MatMul, *[expr.base for i in range(expr.exp)]) if not expr.is_Mul: return expr if any(arg.is_Matrix and arg.is_ZeroMatrix for arg in expr.args): return ZeroMatrix(*expr.shape) # Clear out Identities nonmats = [M for M in expr.args if not M.is_Matrix] # scalars mats = [M for M in expr.args if M.is_Matrix] # matrices if any(M.is_Identity for M in mats): # Any identities around? newmats = [M for M in mats if not M.is_Identity] # clear out if len(newmats) == 0: # Did we lose everything? newmats = [Identity(expr.rows)] # put just one back in if mats != newmats: # Removed some I's but not everything? return MatMul(*(nonmats + newmats)) # Repeat with simpler expr return expr
def __new__(cls, *args, **kw_args): """ Constructor for the Permutation object. Examples: >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0,1,2]) >>> p Permutation([0, 1, 2]) >>> q = Permutation([[0,1],[2]]) >>> q Permutation([[0, 1], [2]]) """ ret_obj = Basic.__new__(cls, *args, **kw_args) temp = args[0][:] if type(temp[0]) is list: ret_obj._cyclic_form = args[0] temp = reduce(lambda x, y: x + y, temp, []) else: ret_obj._array_form = args[0] temp.sort() if temp != list(xrange(len(temp))): raise ValueError("Invalid permutation.") return ret_obj
def __new__(cls, *args): # Discard empty Unions (represented as None) from args args = Tuple(*[a for a in args if a is not None]) # Verify types if not all(isinstance(a, BasicDomain) for a in args): raise TypeError('arguments must be of BasicDomain type') # Verify dimensionality if len({a.dim for a in args}) > 1: dims = ', '.join(str(a.dim) for a in args) msg = 'arguments must have the same dimension, '\ 'given [{}] instead'.format(dims) raise ValueError(msg) # Flatten arguments into a single list of domains unions = [a for a in args if isinstance(a, Union)] args = [a for a in args if not isinstance(a, Union)] for union in unions: args += list(union.as_tuple()) # remove duplicates and sort domains by their string representation args = sorted(set(args), key=str) # a. If the required Union contains no domains, return None; # b. If it contains a single domain, return the domain itself; # c. If it contains multiple domains, create a Union object. if not args: obj = None elif len(args) == 1: obj = args[0] else: obj = Basic.__new__(cls, *args) obj.index = 0 return obj