def __new__(cls, arg): arg = sympify(arg) r = cls.canonize(arg) if isinstance(r, Basic): return r obj = Basic.__new__(cls, arg) return obj
def __new__(cls, dimension): dimension = sympify(dimension) r = cls.eval(dimension) if isinstance(r, Basic): return r obj = Basic.__new__(cls, dimension, **{'commutative': False}) return obj
def __new__ (cls, arg, **options): # print "Inverse(", arg, ")" # print INVERTIBLE if isinstance(arg, Inverse): return arg.args[0] if arg.is_Number: return 1 / arg arg_rank = expr_rank(arg) if arg_rank == 1: raise NotInvertibleError if is_one(arg): return arg if is_zero(arg): raise NotInvertibleError # FIXME: Funky case trying to catch lower triangular or diagonal # muls like T(P_0)*A*P_0 if arg in INVERTIBLE: pass elif isinstance(arg, TensorExpr) and not arg.has_inverse: raise NotInvertibleError elif isinstance(arg, Mul): if arg.args[0] == S(-1): return - Inverse(reduce(operator.mul, arg.args[1:])) if not expr_invertible(arg): raise NotInvertibleError options['commutative'] = arg.is_commutative return Basic.__new__(cls, arg, **options)
def _new(cls, *args, **kwargs): if len(args)==1 and isinstance(args[0], ImmutableMatrix): return args[0] rows, cols, mat = MatrixBase._handle_creation_inputs(*args, **kwargs) shape = Tuple(rows, cols) mat = Tuple(*mat) return Basic.__new__(cls, shape, mat)
def __new__(cls, arg0, arg1, **options): new_args = [arg0, arg1] #check for T(x)*y and T(x)*A*y arg_list = list(arg0.args) + list(arg1.args) if len(arg_list) < 3 and \ all(map(lambda x: isinstance(x, TensorExpr), arg_list)): txy = None A = None if isinstance(arg0, Transpose): if isinstance(arg1, Mul) and len(arg1.args) <= 2: txy = [arg0.args[0]] + [arg1.args[-1]] if len(arg1.args) == 2: A = arg1.args[0] elif isinstance(arg0, Mul) and len(arg1.args) <= 2: if isinstance(arg0.args[0], Transpose) and isinstance(arg1, Tensor): txy = [arg0.args[0].args[0], arg1] if len(arg0.args) == 2: A = arg0.args[1] if txy: stxy = sorted(txy, Basic.compare) if txy != stxy: if not A: return Inner(Transpose(stxy[0]), stxy[1]) if A and A.is_symmetric: return Inner(Transpose(stxy[0]) * A, stxy[1]) # if expr_rank(arg0) != 1 and expr_rank(arg1) != 1: # return Mul(arg0, arg1) # for n in xrange(len(new_args)): # if isinstance(new_args[n], Transpose): # new_args[n] = new_args[n].args[0] return Basic.__new__(cls, *new_args, **options)
def __new__(cls, sym, dist): sym = sympify(sym) if isinstance(dist, SingleContinuousDistribution): return SingleContinuousPSpace(sym, dist) if isinstance(dist, SingleDiscreteDistribution): return SingleDiscretePSpace(sym, dist) return Basic.__new__(cls, sym, dist)
def __new__(cls, i, j): i, j = map(sympify, (i, j)) r = cls.canonize(i, j) if isinstance(r, Basic): return r obj = Basic.__new__(cls, i, j, commutative=True) return obj
def __new__(cls, iterable=None, shape=None, **kwargs): from sympy.utilities.iterables import flatten shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) shape = Tuple(*map(_sympify, shape)) loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0 # Sparse array: if isinstance(flat_list, (dict, Dict)): sparse_array = Dict(flat_list) else: sparse_array = {} for i, el in enumerate(flatten(flat_list)): if el != 0: sparse_array[i] = _sympify(el) sparse_array = Dict(sparse_array) self = Basic.__new__(cls, sparse_array, shape, **kwargs) self._shape = shape self._rank = len(shape) self._loop_size = loop_size self._sparse_array = sparse_array return self
def __new__(cls, dimension): dimension = sympify(dimension) r = cls.eval(dimension) if isinstance(r, Basic): return r obj = Basic.__new__(cls, dimension) return obj
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, M): if not isinstance(M, Matrix): M = Matrix(M) data = Tuple(*M._mat) shape = Tuple(*sympify(M.shape)) obj = Basic.__new__(cls, data, shape) obj._mat = M return obj
def __new__(cls, mat): if not mat.is_Matrix: raise TypeError("input to Trace, %s, is not a matrix" % str(mat)) if not mat.is_square: raise ShapeError("Trace of a non-square matrix") return Basic.__new__(cls, mat)
def __new__(cls, bra, ket): assert isinstance(bra, FockStateBra), 'must be a bra' assert isinstance(ket, FockStateKet), 'must be a key' r = cls.canonize(bra, ket) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *(bra, ket), **dict(commutative=True)) return obj
def __new__(cls, mat): if not mat.is_Matrix: raise TypeError("Input to Determinant, %s, not a matrix" % str(mat)) if not mat.is_square: raise ShapeError("Det of a non-square matrix") return Basic.__new__(cls, mat)
def __new__(cls, mat): if not isinstance(mat, Matrix): mat = Matrix(mat) data = Tuple(*mat.mat) shape = Tuple(*sympify(mat.shape)) obj = Basic.__new__(cls, data, shape) obj.mat = mat return obj
def _new(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], ImmutableMatrix): return args[0] rows, cols, flat_list = MatrixBase._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, num, denom=None): obj = Basic.__new__(cls) if denom is None: if isinstance(num, str): obj.p, obj.q = parse_rational(num) else: obj.p = num obj.q = denom return obj
def __new__(cls, dist): if not isinstance(dist, (ContinuousDistribution, DiscreteDistribution)): raise ValueError(filldedent('''CompoundDistribution can only be initialized from ContinuousDistribution or DiscreteDistribution ''')) _args = dist.args if not any([isinstance(i, RandomSymbol) for i in _args]): return dist return Basic.__new__(cls, dist)
def __new__(cls,dist, rvs): if not all([isinstance(rv, (Indexed, RandomSymbol))] for rv in rvs): raise ValueError(filldedent('''Marginal distribution can be intitialised only in terms of random variables or indexed random variables''')) rvs = Tuple.fromiter(rv for rv in rvs) if not isinstance(dist, JointDistribution) and len(random_symbols(dist)) == 0: return dist return Basic.__new__(cls, dist, rvs)
def __new__(cls, mat): if not mat.is_Matrix: return mat try: return mat._eval_transpose() except (AttributeError, NotImplementedError): return Basic.__new__(cls, mat)
def __new__(cls, pspace, symbol=None): if symbol is None: # Allow single arg, representing pspace == PSpace() pspace, symbol = PSpace(), pspace if not isinstance(symbol, Symbol): raise TypeError("symbol should be of type Symbol") if not isinstance(pspace, PSpace): raise TypeError("pspace variable should be of type PSpace") return Basic.__new__(cls, pspace, symbol)
def test_expr_fns(): from sympy.strategies.rl import rebuild from sympy import Add x, y = map(Symbol, 'xy') expr = x + y**3 e = bottom_up(lambda x: x + 1, expr_fns)(expr) b = bottom_up(lambda x: Basic.__new__(Add, x, 1), basic_fns)(expr) assert rebuild(b) == e
def __new__(cls, mat): try: return mat._eval_adjoint() except (AttributeError, NotImplementedError): pass try: return mat.adjoint() except (AttributeError, NotImplementedError): pass return Basic.__new__(cls, mat)
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, sym, dist): if isinstance(dist, SingleContinuousDistribution): return SingleContinuousPSpace(sym, dist) if isinstance(dist, SingleDiscreteDistribution): return SingleDiscretePSpace(sym, dist) if isinstance(sym, string_types): sym = Symbol(sym) if not isinstance(sym, Symbol): raise TypeError("s should have been string or Symbol") return Basic.__new__(cls, sym, dist)
def __new__(cls, density): density = Dict(density) for k in density.values(): k_sym = sympify(k) if fuzzy_not(fuzzy_and((k_sym.is_nonnegative, (k_sym - 1).is_nonpositive))): raise ValueError("Probability at a point must be between 0 and 1.") sum_sym = sum(density.values()) if sum_sym != 1: raise ValueError("Total Probability must be equal to 1.") return Basic.__new__(cls, density)
def _new(cls, *args, **kwargs): shape, flat_list = cls._handle_ndarray_creation_inputs(*args, **kwargs) shape = Tuple(*map(_sympify, shape)) flat_list = flatten(flat_list) flat_list = Tuple(*flat_list) self = Basic.__new__(cls, flat_list, shape, **kwargs) self._shape = shape self._array = list(flat_list) self._rank = len(shape) self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0 return self
def __new__(cls, mat): if not mat.is_Matrix: raise TypeError("input to Det, %s, is not a matrix" % str(mat)) if not mat.is_square: raise ShapeError("Det of a non-square matrix") try: return mat.det() except (AttributeError, NotImplementedError): return Basic.__new__(cls, mat)
def __new__(cls, parent, rowslice, colslice): rowslice = normalize(rowslice, parent.shape[0]) colslice = normalize(colslice, parent.shape[1]) if not (len(rowslice) == len(colslice) == 3): raise IndexError() if ((0 > rowslice[0]) == True or (parent.shape[0] < rowslice[1]) == True or (0 > colslice[0]) == True or (parent.shape[1] < colslice[1]) == True): raise IndexError() return Basic.__new__(cls, parent, Tuple(*rowslice), Tuple(*colslice))
def __new__(cls, symbol, pspace=None): from sympy.stats.joint_rv import JointRandomSymbol if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() if not isinstance(symbol, Symbol): raise TypeError("symbol should be of type Symbol") if not isinstance(pspace, PSpace): raise TypeError("pspace variable should be of type PSpace") if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace): cls = RandomSymbol return Basic.__new__(cls, symbol, pspace)
def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj
def __new__(cls, rows, cols, lamda): rows, cols = sympify(rows), sympify(cols) return Basic.__new__(cls, rows, cols, lamda)
def __new__(cls): obj = Basic.__new__(cls) return obj
def __new__(cls, density): density = Dict(density) return Basic.__new__(cls, density)
def __new__(cls, sym, state_space=S.Reals, **kwargs): sym = _symbol_converter(sym) state_space = _set_converter(state_space) return Basic.__new__(cls, sym, state_space)
def __new__(cls, process, matrix): if not isinstance(process, DiscreteMarkovChain): raise ValueError("Currently only DiscreteMarkovChain " "support TransitionMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix)
def __new__(cls, pdf, set=Interval(-oo, oo)): return Basic.__new__(cls, pdf, set)
def __new__(cls, symbol, n, m, pspace=None): n, m = _sympify(n), _sympify(m) symbol = _symbol_converter(symbol) return Basic.__new__(cls, symbol, n, m, pspace)
def __new__(cls, symbols, *args): symbols = FiniteSet(*symbols) return Basic.__new__(cls, symbols, *args)
def __new__(cls, s, distribution): if isinstance(s, string_types): s = Symbol(s) if not isinstance(s, Symbol): raise TypeError("s should have been string or Symbol") return Basic.__new__(cls, s, distribution)
def __new__(cls, idx_obj, pspace=None): if not isinstance(idx_obj, (Indexed, Function)): raise TypeError( "An Function or Indexed object is expected not %s" % (idx_obj)) return Basic.__new__(cls, idx_obj, pspace)
def __new__(cls, fulldomain, condition): condition = condition.xreplace( dict((rs, rs.symbol) for rs in random_symbols(condition))) return Basic.__new__(cls, fulldomain, condition)
def test_rebuild(): from sympy import Add expr = Basic.__new__(Add, S(1), S(2)) assert rebuild(expr) == 3
def __new__(cls, pspace, symbol): assert isinstance(symbol, Symbol) assert isinstance(pspace, PSpace) return Basic.__new__(cls, pspace, symbol)
def __new__(cls, interval): if not isinstance(interval, Interval): raise TypeError('L2 interval must be an Interval instance: %r' % interval) obj = Basic.__new__(cls, interval) return obj
def __new__(cls, base, exp): return Basic.__new__(cls, _sympify(base), _sympify(exp))
def __new__(cls, pdf, set=S.Integers): return Basic.__new__(cls, pdf, set)
def __new__(cls, sym, state_space=S.Reals, trans_probs=None): sym = _symbol_converter(sym) state_space = _set_converter(state_space) if trans_probs != None: trans_probs = _matrix_checks(trans_probs) return Basic.__new__(cls, sym, state_space, trans_probs)
def __new__(cls, pspace, symbol): if not isinstance(symbol, Symbol): raise TypeError("symbol should be of type Symbol") if not isinstance(pspace, PSpace): raise TypeError("pspace variable should be of type PSpace") return Basic.__new__(cls, pspace, symbol)
def __new__(cls, symbol, set): if not isinstance(set, FiniteSet) and \ not isinstance(set, Intersection): set = FiniteSet(*set) return Basic.__new__(cls, symbol, set)
def __new__(cls, base_dims, derived_dims=[], dimensional_dependencies={}, name=None, descr=None): dimensional_dependencies = dict(dimensional_dependencies) if (name is not None) or (descr is not None): SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, useinstead="do not define a `name` or `descr`", ).warn() def parse_dim(dim): if isinstance(dim, str): dim = Dimension(Symbol(dim)) elif isinstance(dim, Dimension): pass elif isinstance(dim, Symbol): dim = Dimension(dim) else: raise TypeError("%s wrong type" % dim) return dim base_dims = [parse_dim(i) for i in base_dims] derived_dims = [parse_dim(i) for i in derived_dims] for dim in base_dims: dim = dim.name if (dim in dimensional_dependencies and (len(dimensional_dependencies[dim]) != 1 or dimensional_dependencies[dim].get(dim, None) != 1)): raise IndexError("Repeated value in base dimensions") dimensional_dependencies[dim] = Dict({dim: 1}) def parse_dim_name(dim): if isinstance(dim, Dimension): return dim.name elif isinstance(dim, str): return Symbol(dim) elif isinstance(dim, Symbol): return dim else: raise TypeError("unrecognized type %s for %s" % (type(dim), dim)) for dim in dimensional_dependencies.keys(): dim = parse_dim(dim) if (dim not in derived_dims) and (dim not in base_dims): derived_dims.append(dim) def parse_dict(d): return Dict({parse_dim_name(i): j for i, j in d.items()}) # Make sure everything is a SymPy type: dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in dimensional_dependencies.items()} for dim in derived_dims: if dim in base_dims: raise ValueError("Dimension %s both in base and derived" % dim) if dim.name not in dimensional_dependencies: # TODO: should this raise a warning? dimensional_dependencies[dim.name] = Dict({dim.name: 1}) base_dims.sort(key=default_sort_key) derived_dims.sort(key=default_sort_key) base_dims = Tuple(*base_dims) derived_dims = Tuple(*derived_dims) dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()}) obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies) return obj
def __new__(cls, process, state_space): if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)): raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain " "support StochasticStateSpaceOf.") state_space = _set_converter(state_space) return Basic.__new__(cls, process, state_space)
def __new__(cls, sym, dim=None): sym, dim = _symbol_converter(sym), _sympify(dim) if dim.is_integer == False: raise ValueError("Dimension of the random matrices must be " "integers, received %s instead." % (dim)) return Basic.__new__(cls, sym, dim)
def __new__(cls, process, matrix): if not isinstance(process, ContinuousMarkovChain): raise ValueError("Currently only ContinuousMarkovChain " "support GeneratorMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix)
def __new__(cls, symbol, set): assert symbol.is_Symbol return Basic.__new__(cls, symbol, set)
def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r return Basic.__new__(cls, *r)
def __new__(cls, *args): args = map(sympify, args) return Basic.__new__(cls, *args)
def __new__(cls, symbol, set): if not isinstance(set, FiniteSet): set = FiniteSet(*set) return Basic.__new__(cls, symbol, set)
def __new__(cls, sym, state_space=S.Reals, gen_mat=None): sym = _symbol_converter(sym) state_space = _set_converter(state_space) if gen_mat != None: gen_mat = _matrix_checks(gen_mat) return Basic.__new__(cls, sym, state_space, gen_mat)
def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set)