def my_compare(a, b): main_var = s p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3") r_a = a.match(p1 * s**p3) r_b = b.match(p1 * s**p3) if r_a is not None and r_b is not None: c = Basic.compare(r_a[p3], r_b[p3]) if c!=0: return c return Basic._compare_pretty(a,b)
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, dimension): dimension = sympify(dimension) r = cls.eval(dimension) if isinstance(r, Basic): return r obj = Basic.__new__(cls, dimension) return obj
def sample2d(f, x_args): """ Samples a 2d function f over specified intervals and returns two arrays (X, Y) suitable for plotting with matlab (matplotlib) syntax. See examples\mplot2d.py. f is a function of one variable, such as x**2. x_args is an interval given in the form (var, min, max, n) """ try: f = Basic.sympify(f) except: raise ValueError("f could not be interpretted as a SymPy function") try: x, x_min, x_max, x_n = x_args except: raise ValueError("x_args must be a tuple of the form (var, min, max, n)") x_l = float(x_max - x_min) x_d = x_l/float(x_n) X = arange(float(x_min), float(x_max)+x_d, x_d) Y = empty(len(X)) for i in range(len(X)): try: Y[i] = float(f.subs(x, X[i])) except: Y[i] = None return X, Y
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, 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, 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, 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, *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, arg): arg = sympify(arg) r = cls.canonize(arg) if isinstance(r, Basic): return r obj = Basic.__new__(cls, arg) 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, 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, 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, *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, 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 set_v_max(self, v_max): if v_max is None: self._v_max = None return try: self._v_max = Basic.sympify(v_max) float(self._v_max.evalf()) except: raise ValueError("v_max could not be interpreted as a number.")
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 set_v_min(self, v_min): if v_min is None: self._v_min = None return try: self._v_min = Basic.sympify(v_min) float(self._v_min.evalf()) except: raise ValueError("v_min could not be interpreted as a number.")
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, 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, 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, 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, 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, s, distribution): if isinstance(s, str): 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, base, exp): return Basic.__new__(cls, _sympify(base), _sympify(exp))
def __new__(cls, rows, cols, lamda): rows, cols = sympify(rows), sympify(cols) return Basic.__new__(cls, rows, cols, lamda)
def test_zero_ints(): expr = Basic(2, Basic(5, 3), 8) expected = set([Basic(0, Basic(0, 0), 0)]) brl = canon(posdec) assert set(brl(expr)) == expected
def test_top_down_big_tree(): expr = Basic(1, Basic(2), Basic(3, Basic(4), 5)) expected = Basic(2, Basic(3), Basic(4, Basic(5), 6)) brl = top_down(inc) assert set(brl(expr)) == set([expected])
def test_top_down_easy(): expr = Basic(1, 2) expected = Basic(2, 3) brl = top_down(inc) assert set(brl(expr)) == set([expected])
def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set)
def __new__(cls, pdf, set=S.Integers): return Basic.__new__(cls, pdf, set)
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, symbol, set): if not isinstance(set, FiniteSet): set = FiniteSet(*set) return Basic.__new__(cls, symbol, set)
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 __new__(cls, symbol, set): assert symbol.is_Symbol return Basic.__new__(cls, symbol, set)
def __hash__(self): return Basic.__hash__(self)
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, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj
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 _eval_derivative_n_times(self, s, n): return Basic._eval_derivative_n_times(self, s, n)
def __new__(cls): obj = Basic.__new__(cls) return obj
def test_arguments(): """Functions accepting `Point` objects in `geometry` should also accept tuples and lists and automatically convert them to points.""" singles2d = ((1, 2), [1, 2], Point(1, 2)) singles2d2 = ((1, 3), [1, 3], Point(1, 3)) doubles2d = cartes(singles2d, singles2d2) p2d = Point2D(1, 2) singles3d = ((1, 2, 3), [1, 2, 3], Point(1, 2, 3)) doubles3d = subsets(singles3d, 2) p3d = Point3D(1, 2, 3) singles4d = ((1, 2, 3, 4), [1, 2, 3, 4], Point(1, 2, 3, 4)) doubles4d = subsets(singles4d, 2) p4d = Point(1, 2, 3, 4) # test 2D test_single = [ 'distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__' ] test_double = ['is_concyclic', 'is_collinear'] for p in singles2d: Point2D(p) for func in test_single: for p in singles2d: getattr(p2d, func)(p) for func in test_double: for p in doubles2d: getattr(p2d, func)(*p) # test 3D test_double = ['is_collinear'] for p in singles3d: Point3D(p) for func in test_single: for p in singles3d: getattr(p3d, func)(p) for func in test_double: for p in doubles3d: getattr(p3d, func)(*p) # test 4D test_double = ['is_collinear'] for p in singles4d: Point(p) for func in test_single: for p in singles4d: getattr(p4d, func)(p) for func in test_double: for p in doubles4d: getattr(p4d, func)(*p) # test evaluate=False for ops x = Symbol('x') a = Point(0, 1) assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False) a = Point(0, 1) assert a / 10.0 == Point(0, 0.1, evaluate=False) a = Point(0, 1) assert a * 10.0 == Point(0.0, 10.0, evaluate=False) # test evaluate=False when changing dimensions u = Point(.1, .2, evaluate=False) u4 = Point(u, dim=4, on_morph='ignore') assert u4.args == (.1, .2, 0, 0) assert all(i.is_Float for i in u4.args[:2]) # and even when *not* changing dimensions assert all(i.is_Float for i in Point(u).args) # never raise error if creating an origin assert Point(dim=3, on_morph='error') # raise error with unmatched dimension raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error')) # test unknown on_morph raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown')) # test invalid expressions raises(TypeError, lambda: Point(Basic(), Basic()))
def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r return Basic.__new__(cls, *r)
def __new__(cls, *args): args = list(map(sympify, args)) return Basic.__new__(cls, *args)
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, density): density = Dict(density) return Basic.__new__(cls, density)
def test_construct(): expr = Compound(Basic, (1, 2, 3)) expected = Basic(1, 2, 3) assert construct(expr) == expected
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 xlog(y: Basic, x: Symbol, base: Basic = 10): "For log plots on the x axis" return y.subs(x, 10**x)
def test_sort_variable(): vsort = Derivative._sort_variable_count def vsort0(*v, **kw): reverse = kw.get('reverse', False) return [ i[0] for i in vsort([(i, 0) for i in (reversed(v) if reverse else v)]) ] for R in range(2): assert vsort0(y, x, reverse=R) == [x, y] assert vsort0(f(x), x, reverse=R) == [x, f(x)] assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)] assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)] assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)] fx = f(x).diff(x) assert vsort0(fx, y, reverse=R) == [y, fx] fy = f(y).diff(y) assert vsort0(fy, fx, reverse=R) == [fx, fy] fxx = fx.diff(x) assert vsort0(fxx, fx, reverse=R) == [fx, fxx] assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)] assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)] assert vsort0(Basic(y, z), Basic(x), reverse=R) == [Basic(x), Basic(y, z)] assert vsort0(fx, x, reverse=R) == [x, fx] if R else [fx, x] assert vsort0(Basic(x), x, reverse=R) == [x, Basic(x) ] if R else [Basic(x), x] assert vsort0(Basic(f(x)), f(x), reverse=R) == [ f(x), Basic(f(x)) ] if R else [Basic(f(x)), f(x)] assert vsort0(Basic(x, z), Basic(x), reverse=R) == [ Basic(x), Basic(x, z) ] if R else [Basic(x, z), Basic(x)] assert vsort([]) == [] assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)]) assert vsort([(x, y), (x, z)]) == [(x, y + z)] assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)] # coverage complete; legacy tests below assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [(f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1), (f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1), (y, 1), (f(x), 1), (f(y), 1)] assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1), (h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)] assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3), (z, 4), (f(x), 3), (g(x), 1)] assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)] assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple) assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)] assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [(f(x), 1), (g(x), 1), (h(y), 1)] assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)] assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [(f(x), 2), (f(y), 1)] dfx = f(x).diff(x) self = [(dfx, 1), (x, 1)] assert vsort(self) == self assert vsort([(dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [(y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)] dfy = f(y).diff(y) assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)] d2fx = dfx.diff(x) assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)]
def __new__(cls, pdf, set=Interval(-oo, oo)): return Basic.__new__(cls, pdf, set)
def __new__(cls, symbols, *args): symbols = FiniteSet(*symbols) return Basic.__new__(cls, symbols, *args)
def test_simple_variables(): rl = rewriterule(Basic(x, 1), Basic(x, 2), variables=(x, )) assert list(rl(Basic(3, 1))) == [Basic(3, 2)] rl = rewriterule(x**2, x**3, variables=(x, )) assert list(rl(y**2)) == [y**3]