def test_K(): assert K(0) == pi / 2 assert K(S(1) / 2) == 8 * pi ** (S(3) / 2) / gamma(-S(1) / 4) ** 2 assert K(1) == zoo assert K(-1) == gamma(S(1) / 4) ** 2 / (4 * sqrt(2 * pi)) assert K(oo) == 0 assert K(-oo) == 0 assert K(I * oo) == 0 assert K(-I * oo) == 0 assert K(zoo) == 0 assert K(z).diff(z) == (E(z) - (1 - z) * K(z)) / (2 * z * (1 - z)) assert td(K(z), z) zi = Symbol("z", real=False) assert K(zi).conjugate() == K(zi.conjugate()) zr = Symbol("z", real=True, negative=True) assert K(zr).conjugate() == K(zr) assert K(z).rewrite(hyper) == (pi / 2) * hyper((S.Half, S.Half), (S.One,), z) assert tn(K(z), (pi / 2) * hyper((S.Half, S.Half), (S.One,), z)) assert K(z).rewrite(meijerg) == meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z) / 2 assert tn(K(z), meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z) / 2) assert K(z).series( z ) == pi / 2 + pi * z / 8 + 9 * pi * z ** 2 / 128 + 25 * pi * z ** 3 / 512 + 1225 * pi * z ** 4 / 32768 + 3969 * pi * z ** 5 / 131072 + O( z ** 6 )
def test_diff(): x = Symbol('x') assert Rational(1, 3).diff(x) is S.Zero assert I.diff(x) is S.Zero assert pi.diff(x) is S.Zero assert x.diff(x, 0) == x assert (x**2).diff(x, 2, x) == 0 raises(ValueError, 'x.diff(1, x)') a = Symbol("a") b = Symbol("b") c = Symbol("c") p = Rational(5) e = a*b + b**p assert e.diff(a) == b assert e.diff(b) == a + 5*b**4 assert e.diff(b).diff(a) == Rational(1) e = a*(b + c) assert e.diff(a) == b + c assert e.diff(b) == a assert e.diff(b).diff(a) == Rational(1) e = c**p assert e.diff(c, 6) == Rational(0) assert e.diff(c, 5) == Rational(120) e = c**Rational(2) assert e.diff(c) == 2*c e = a*b*c assert e.diff(c) == a*b
def get_dim(self, dim): """ Find a specific dimension which is part of the system. dim can be a string or a dimension object. If no dimension is found, then return None. """ #TODO: if the argument is a list, return a list of all matching dims found_dim = None #TODO: use copy instead of direct assignment for found_dim? if isinstance(dim, string_types): dim = Symbol(dim) if dim.is_Symbol: for d in self._dims: if dim in (d.name, d.symbol): found_dim = d break elif isinstance(dim, Dimension): for i, idim in enumerate(self._dims): if dim.get_dimensional_dependencies() == idim.get_dimensional_dependencies(): return idim return found_dim
def test_as_coeff_factors(): x = Symbol("x") assert x.as_coeff_factors() == (0, (x,)) assert (-1 + x).as_coeff_factors() == (-1, (x,)) assert (2 + x).as_coeff_factors() == (2, (x,)) assert (1 + x).as_coeff_factors() == (1, (x,))
def test_E(): assert E(z, 0) == z assert E(0, m) == 0 assert E(i*pi/2, m) == i*E(m) assert E(z, oo) == zoo assert E(z, -oo) == zoo assert E(0) == pi/2 assert E(1) == 1 assert E(oo) == I*oo assert E(-oo) == oo assert E(zoo) == zoo assert E(-z, m) == -E(z, m) assert E(z, m).diff(z) == sqrt(1 - m*sin(z)**2) assert E(z, m).diff(m) == (E(z, m) - F(z, m))/(2*m) assert E(z).diff(z) == (E(z) - K(z))/(2*z) r = randcplx() assert td(E(r, m), m) assert td(E(z, r), z) assert td(E(z), z) mi = Symbol('m', real=False) assert E(z, mi).conjugate() == E(z.conjugate(), mi.conjugate()) mr = Symbol('m', real=True, negative=True) assert E(z, mr).conjugate() == E(z.conjugate(), mr) assert E(z).rewrite(hyper) == (pi/2)*hyper((-S.Half, S.Half), (S.One,), z) assert tn(E(z), (pi/2)*hyper((-S.Half, S.Half), (S.One,), z)) assert E(z).rewrite(meijerg) == \ -meijerg(((S.Half, S(3)/2), []), ((S.Zero,), (S.Zero,)), -z)/4 assert tn(E(z), -meijerg(((S.Half, S(3)/2), []), ((S.Zero,), (S.Zero,)), -z)/4)
def test_Dummy_from_Symbol(): # should not get the full dictionary of assumptions n = Symbol('n', integer=True) d = n.as_dummy() s1 = "Dummy('n', dummy_index=%s, integer=True)" % str(d.dummy_index) s2 = "Dummy('n', integer=True, dummy_index=%s)" % str(d.dummy_index) assert srepr(d) in (s1, s2)
def test_K(): assert K(0) == pi/2 assert K(S(1)/2) == 8*pi**(S(3)/2)/gamma(-S(1)/4)**2 assert K(1) == zoo assert K(-1) == gamma(S(1)/4)**2/(4*sqrt(2*pi)) assert K(oo) == 0 assert K(-oo) == 0 assert K(I*oo) == 0 assert K(-I*oo) == 0 assert K(zoo) == 0 assert K(z).diff(z) == (E(z) - (1 - z)*K(z))/(2*z*(1 - z)) assert td(K(z), z) zi = Symbol('z', real=False) assert K(zi).conjugate() == K(zi.conjugate()) zr = Symbol('z', real=True, negative=True) assert K(zr).conjugate() == K(zr) assert K(z).rewrite(hyper) == \ (pi/2)*hyper((S.Half, S.Half), (S.One,), z) assert tn(K(z), (pi/2)*hyper((S.Half, S.Half), (S.One,), z)) assert K(z).rewrite(meijerg) == \ meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2 assert tn(K(z), meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2)
def __init__(self, data, step_size=1.0): """A continuous scalar data source from a discrete time series. Time series data points are linearly interpolated in order to generate values for points not present in the time series. The time series is wrapped in order to generate an infinite sequence. :param data: iterable of scalar values :param step_size: number of LB iterations corresponding to one unit in the time series (i.e. time distance between two neighboring points). """ Symbol.__init__("unused") if type(data) is list or type(data) is tuple: data = np.float64(data) # Copy here is necessary so that the caller doesn't accidentally change # the underlying array later. Also, we need the array to be C-contiguous # (for __hash__ below), which might not be the case if it's a view. self._data = data.copy() self._step_size = step_size # To be set later by the geometry encoder class. This is necessary due # to how the printing system in Sympy works (see _ccode below). self._offset = None
def GeneralizedCoordinate(s, constant=False): gc = Symbol(s)(Symbol("t")) gc.is_gc = True if constant == True: gc.fdiff = lambda argindex: 0 gc.__repr__ = lambda self: PyDyStrPrinter().doprint(self) gc.__str__ = lambda self: PyDyStrPrinter().doprint(self) return gc
def test_atoms(): x = Symbol('x') y = Symbol('y') assert list((1+x).atoms()) == [1,x] assert list(x.atoms()) == [x] assert list((1+2*cos(x)).atoms(type=Symbol)) == [x] assert list((2*(x**(y**x))).atoms()) == [2,x,y] assert list(Rational(1,2).atoms()) == [Rational(1,2)] assert list(Rational(1,2).atoms(type=type(oo))) == []
def test_as_dummy(): x = Symbol('x') x1 = x.as_dummy() assert x1 != x assert x1 != x.as_dummy() x = Symbol('x', commutative=False) x1 = x.as_dummy() assert x1 != x assert x1.is_commutative is False
def test_as_dummy_nondummy(): x = Symbol('x') x1 = x.as_dummy() assert x1 != x assert x1 != x.as_dummy() # assert x == x1.as_nondummy() x = Symbol('x', commutative = False) x1 = x.as_dummy() assert x1 != x assert x1.is_commutative == False
def __init__(self, val): if not Expr.initialized: Expr.initialized = True Expr.init() if isinstance(val, int) or isinstance(val, long): self.expr = Integer(val) elif isinstance(val, basestring): self.expr = Symbol(val) elif isinstance(val, bool) or isinstance(val, BooleanAtom): self.expr = S.One if val else S.Zero else: assert isinstance(val, SymPyExpr) or isinstance(val, BooleanFunction) \ or (val == S.Infinity) or (val == -S.Infinity) self.expr = val
def test_as_coeff_add(): x = Symbol("x") y = Symbol("y") assert S(2).as_coeff_add() == (2, ()) assert S(3.0).as_coeff_add() == (0, (S(3.0),)) assert S(-3.0).as_coeff_add() == (0, (S(-3.0),)) assert x.as_coeff_add() == (0, (x,)) assert (-1 + x).as_coeff_add() == (-1, (x,)) assert (2 + x).as_coeff_add() == (2, (x,)) assert (1 + x).as_coeff_add() == (1, (x,)) assert (x + y).as_coeff_add(y) == (x, (y,)) assert (3 * x).as_coeff_add(y) == (3 * x, ()) # don't do expansion e = (x + y) ** 2 assert e.as_coeff_add(y) == (0, (e,))
def __new__(cls, i, label="sigma"): if not i in [1, 2, 3]: raise IndexError("Invalid Pauli index") obj = Symbol.__new__(cls, "%s%d" %(label,i), commutative=False, hermitian=True) obj.i = i obj.label = label return obj
def __new__(cls, name, dim=None): obj = Symbol.__new__(cls, name) obj.dim = dim obj._fields = None obj._field_names = None obj._constant_fields = None return obj
def test_dict_set(): x = Symbol('x') a, b, c = map(Wild, 'abc') f = 3*cos(4*x) r = f.match(a*cos(b*x)) assert r == {a: 3, b: 4} e = a/b*sin(b*x) assert e.subs(r) == r[a]/r[b]*sin(r[b]*x) assert e.subs(r) == 3*sin(4*x) / 4 s = set(r.items()) assert e.subs(s) == r[a]/r[b]*sin(r[b]*x) assert e.subs(s) == 3*sin(4*x) / 4 assert e.subs(r) == r[a]/r[b]*sin(r[b]*x) assert e.subs(r) == 3*sin(4*x) / 4 assert x.subs(Dict((x, 1))) == 1
def test_as_coeff_mul(): x = Symbol("x") y = Symbol("y") assert S(2).as_coeff_mul() == (2, ()) assert S(3.0).as_coeff_mul() == (1, (S(3.0),)) assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),)) assert x.as_coeff_mul() == (1, (x,)) assert (-x).as_coeff_mul() == (-1, (x,)) assert (2 * x).as_coeff_mul() == (2, (x,)) assert (x * y).as_coeff_mul(y) == (x, (y,)) assert (3 + x).as_coeff_mul(y) == (3 + x, ()) # don't do expansion e = exp(x + y) assert e.as_coeff_mul(y) == (1, (e,)) e = 2 ** (x + y) assert e.as_coeff_mul(y) == (1, (e,))
def test_P(): assert P(0, z, m) == F(z, m) assert P(1, z, m) == F(z, m) + (sqrt(1 - m * sin(z) ** 2) * tan(z) - E(z, m)) / (1 - m) assert P(n, i * pi / 2, m) == i * P(n, m) assert P(n, z, 0) == atanh(sqrt(n - 1) * tan(z)) / sqrt(n - 1) assert P(n, z, n) == F(z, n) - P(1, z, n) + tan(z) / sqrt(1 - n * sin(z) ** 2) assert P(oo, z, m) == 0 assert P(-oo, z, m) == 0 assert P(n, z, oo) == 0 assert P(n, z, -oo) == 0 assert P(0, m) == K(m) assert P(1, m) == zoo assert P(n, 0) == pi / (2 * sqrt(1 - n)) assert P(2, 1) == -oo assert P(-1, 1) == oo assert P(n, n) == E(n) / (1 - n) assert P(n, -z, m) == -P(n, z, m) ni, mi = Symbol("n", real=False), Symbol("m", real=False) assert P(ni, z, mi).conjugate() == P(ni.conjugate(), z.conjugate(), mi.conjugate()) nr, mr = Symbol("n", real=True, negative=True), Symbol("m", real=True, negative=True) assert P(nr, z, mr).conjugate() == P(nr, z.conjugate(), mr) assert P(n, m).conjugate() == P(n.conjugate(), m.conjugate()) assert P(n, z, m).diff(n) == ( E(z, m) + (m - n) * F(z, m) / n + (n ** 2 - m) * P(n, z, m) / n - n * sqrt(1 - m * sin(z) ** 2) * sin(2 * z) / (2 * (1 - n * sin(z) ** 2)) ) / (2 * (m - n) * (n - 1)) assert P(n, z, m).diff(z) == 1 / (sqrt(1 - m * sin(z) ** 2) * (1 - n * sin(z) ** 2)) assert P(n, z, m).diff(m) == ( E(z, m) / (m - 1) + P(n, z, m) - m * sin(2 * z) / (2 * (m - 1) * sqrt(1 - m * sin(z) ** 2)) ) / (2 * (n - m)) assert P(n, m).diff(n) == (E(m) + (m - n) * K(m) / n + (n ** 2 - m) * P(n, m) / n) / (2 * (m - n) * (n - 1)) assert P(n, m).diff(m) == (E(m) / (m - 1) + P(n, m)) / (2 * (n - m)) rx, ry = randcplx(), randcplx() assert td(P(n, rx, ry), n) assert td(P(rx, z, ry), z) assert td(P(rx, ry, m), m) assert P(n, z, m).series(z) == z + z ** 3 * (m / 6 + n / 3) + z ** 5 * ( 3 * m ** 2 / 40 + m * n / 10 - m / 30 + n ** 2 / 5 - n / 15 ) + O(z ** 6)
def test_F(): assert F(z, 0) == z assert F(0, m) == 0 assert F(pi*i/2, m) == i*K(m) assert F(z, oo) == 0 assert F(z, -oo) == 0 assert F(-z, m) == -F(z, m) assert F(z, m).diff(z) == 1/sqrt(1 - m*sin(z)**2) assert F(z, m).diff(m) == E(z, m)/(2*m*(1 - m)) - F(z, m)/(2*m) - \ sin(2*z)/(4*(1 - m)*sqrt(1 - m*sin(z)**2)) r = randcplx() assert td(F(z, r), z) assert td(F(r, m), m) mi = Symbol('m', real=False) assert F(z, mi).conjugate() == F(z.conjugate(), mi.conjugate()) mr = Symbol('m', real=True, negative=True) assert F(z, mr).conjugate() == F(z.conjugate(), mr)
def test_E(): assert E(z, 0) == z assert E(0, m) == 0 assert E(i * pi / 2, m) == i * E(m) assert E(z, oo) == zoo assert E(z, -oo) == zoo assert E(0) == pi / 2 assert E(1) == 1 assert E(oo) == I * oo assert E(-oo) == oo assert E(zoo) == zoo assert E(-z, m) == -E(z, m) assert E(z, m).diff(z) == sqrt(1 - m * sin(z) ** 2) assert E(z, m).diff(m) == (E(z, m) - F(z, m)) / (2 * m) assert E(z).diff(z) == (E(z) - K(z)) / (2 * z) r = randcplx() assert td(E(r, m), m) assert td(E(z, r), z) assert td(E(z), z) mi = Symbol("m", real=False) assert E(z, mi).conjugate() == E(z.conjugate(), mi.conjugate()) assert E(mi).conjugate() == E(mi.conjugate()) mr = Symbol("m", real=True, negative=True) assert E(z, mr).conjugate() == E(z.conjugate(), mr) assert E(mr).conjugate() == E(mr) assert E(z).rewrite(hyper) == (pi / 2) * hyper((-S.Half, S.Half), (S.One,), z) assert tn(E(z), (pi / 2) * hyper((-S.Half, S.Half), (S.One,), z)) assert E(z).rewrite(meijerg) == -meijerg(((S.Half, S(3) / 2), []), ((S.Zero,), (S.Zero,)), -z) / 4 assert tn(E(z), -meijerg(((S.Half, S(3) / 2), []), ((S.Zero,), (S.Zero,)), -z) / 4) assert E(z, m).series(z) == z + z ** 5 * (-m ** 2 / 40 + m / 30) - m * z ** 3 / 6 + O(z ** 6) assert E(z).series( z ) == pi / 2 - pi * z / 8 - 3 * pi * z ** 2 / 128 - 5 * pi * z ** 3 / 512 - 175 * pi * z ** 4 / 32768 - 441 * pi * z ** 5 / 131072 + O( z ** 6 )
def test_issue_1460(): x = Symbol('x') e = Symbol('e') w = Wild('w', exclude=[x]) y = Wild('y') # this is as it should be assert (3/x).match(w/y) == {w: 3, y: x} assert (3*x).match(w*y) == {w: 3, y: x} assert (x/3).match(y/w) == {w: 3, y: x} assert (3*x).match(y/w) == {w: S(1)/3, y: x} # these could be allowed to fail assert (x/3).match(w/y) == {w: S(1)/3, y: 1/x} assert (3*x).match(w/y) == {w: 3, y: 1/x} assert (3/x).match(w*y) == {w: 3, y: 1/x} # Note that solve will give # multiple roots but match only gives one: # # >>> solve(x**r-y**2,y) # [-x**(r/2), x**(r/2)] r = Symbol('r', rational=True) assert (x**r).match(y**2) == {y: x**(r/2)} assert (x**e).match(y**2) == {y: sqrt(x**e)} # since (x**i = y) -> x = y**(1/i) where i is an integer # the following should also be valid as long as y is not # zero when i is negative. a = Wild('a') e = S(0) assert e.match(a) == {a: e} assert e.match(1/a) is None assert e.match(a**.3) is None e = S(3) assert e.match(1/a) == {a: 1/e} assert e.match(1/a**2) == {a: 1/sqrt(e)} e = pi assert e.match(1/a) == {a: 1/e} assert e.match(1/a**2) == {a: 1/sqrt(e)} assert (-e).match(sqrt(a)) is None assert (-e).match(a**2) == {a: I*sqrt(pi)}
def test_F(): assert F(z, 0) == z assert F(0, m) == 0 assert F(pi * i / 2, m) == i * K(m) assert F(z, oo) == 0 assert F(z, -oo) == 0 assert F(-z, m) == -F(z, m) assert F(z, m).diff(z) == 1 / sqrt(1 - m * sin(z) ** 2) assert F(z, m).diff(m) == E(z, m) / (2 * m * (1 - m)) - F(z, m) / (2 * m) - sin(2 * z) / ( 4 * (1 - m) * sqrt(1 - m * sin(z) ** 2) ) r = randcplx() assert td(F(z, r), z) assert td(F(r, m), m) mi = Symbol("m", real=False) assert F(z, mi).conjugate() == F(z.conjugate(), mi.conjugate()) mr = Symbol("m", real=True, negative=True) assert F(z, mr).conjugate() == F(z.conjugate(), mr) assert F(z, m).series(z) == z + z ** 5 * (3 * m ** 2 / 40 - m / 30) + m * z ** 3 / 6 + O(z ** 6)
def __new__ (cls, ten, rank=None, shape=None, has_inv=None, transposed=None, **kws): # Handle either str or change the behavior if isinstance(ten, str): name = ten if rank is None: raise ValueError("Must give rank with string arg.") if name in ['0', '1']: name = "%s_%d" % (name, rank) if name.startswith('0'): has_inv = False elif name.startswith('1') and rank in [0, 2]: has_inv = True elif rank == 0: has_inv = True elif has_inv is None: has_inv = False elif isinstance(ten, Tensor): name = ten.name if has_inv is None: has_inv = ten.has_inverse if not rank is None and rank != ten.rank: raise ValueError("Given rank and rank of ten don't match") if shape is None and transposed is None: shape = ten.shape if transposed is None: transposed = ten.transposed rank = ten.rank else: raise ValueError("Unable to create Tensor from a %s" \ % type(ten)) if rank > 0 and not kws.has_key("commutative"): kws['commutative'] = False if transposed is None: transposed = False if transposed: name += "'" obj = Symbol.__new__(cls, name, **kws) obj.rank = rank obj.has_inverse = has_inv obj.transposed = transposed obj._set_default_shape(shape) return obj
def test_as_dummy(): x = Symbol('x') x1 = x.as_dummy() assert x1 != x assert x1 != x.as_dummy() x = Symbol('x', commutative = False) x1 = x.as_dummy() assert x1 != x assert x1.is_commutative == False # issue 2446 x = Symbol('x', real=True, commutative=False) assert x.as_dummy().assumptions0 == x.assumptions0
def __new__(cls, name=None, longname=None): if name is None or name == "": name = "NoName_"+str(Quantity.dummy_count) Quantity.dummy_count += 1 self = Dummy.__new__(cls, name) else: self = Symbol.__new__(cls, name) self.count = Quantity.quantity_count Quantity.quantity_count += 1 self.abbrev = name self.name = name self.longname = longname self.value = None self.value_formula = None self.error = None self.error_formula = None self.prefer_unit = None self.dim = None return self
Base dimensions """ #----------------------------------------------------------------------------- # Copyright (c) 2013, yt Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- from sympy import Symbol, sympify, Rational mass = Symbol("(mass)", positive=True) length = Symbol("(length)", positive=True) time = Symbol("(time)", positive=True) temperature = Symbol("(temperature)", positive=True) angle = Symbol("(angle)", positive=True) current_mks = Symbol("(current_mks)", positive=True) dimensionless = sympify(1) base_dimensions = [ mass, length, time, temperature, angle, current_mks, dimensionless ] # # Derived dimensions #
def test_issue536(): y = Symbol('y') assert integrate(x**2, y) == x**2 * y assert integrate(x**2, (y, -1, 1)) == 2 * x**2
from sympy.sets import (ConditionSet, Intersection, FiniteSet, EmptySet, Union) from sympy import (Symbol, Eq, Lt, S, Abs, sin, pi, Lambda, Interval, And, Mod, oo, Function) from sympy.utilities.pytest import raises w = Symbol('w') x = Symbol('x') y = Symbol('y') z = Symbol('z') L = Symbol('lambda') f = Function('f') def test_CondSet(): sin_sols_principal = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi, False, True)) assert pi in sin_sols_principal assert pi/2 not in sin_sols_principal assert 3*pi not in sin_sols_principal assert 5 in ConditionSet(x, x**2 > 4, S.Reals) assert 1 not in ConditionSet(x, x**2 > 4, S.Reals) # in this case, 0 is not part of the base set so # it can't be in any subset selected by the condition assert 0 not in ConditionSet(x, y > 5, Interval(1, 7)) # since 'in' requires a true/false, the following raises # an error because the given value provides no information # for the condition to evaluate (since the condition does # not depend on the dummy symbol): the result is `y > 5`. # In this case, ConditionSet is just acting like
def _sympy_(self): return Symbol("x")
def step(self, action): execute_action = False execute_sell = False execute_buy = False ask_price = self.ask_price_history[-1] bid_price = self.bid_price_history[-1] reward = 0 #reward is the profit value_in_stock = 0 for position in self.positions: value_in_stock += position['quantity'] * bid_price #the action is an integer anywhere between 0 and max_position if action != self.last_action: self.last_action = action x = Symbol('x') r = solve( (value_in_stock + x) / (value_in_stock + x + self.cash - x) - (action / self.max_position), x) r = float(r[0]) if r > 0: #buy if r > self.cash: r = self.cash num_new_position = action - len(self.positions) if num_new_position > 0: per_position_value = r / num_new_position for _ in range(0, int(num_new_position)): new_position = {} new_position['quantity'] = np.floor( per_position_value / ask_price) new_position['price'] = ask_price self.cash -= new_position['quantity'] * new_position[ 'price'] self.positions.append(new_position) execute_action = True execute_buy = True self.positions = sorted(self.positions, key=lambda k: k['price']) elif r < 0: #sell num_sell_position = len(self.positions) - action for _ in range(0, int(num_sell_position)): sold_position = self.positions.pop( 0) #sell the cheapest first self.cash += sold_position['quantity'] * bid_price execute_action = True execute_sell = True reward += sold_position['quantity'] * ( sold_position['price'] - bid_price) self.current_time_index += 1 self.ask_price_history.pop(0) self.ask_price_history.append( self.ask_price_list[self.current_time_index]) self.bid_price_history.pop(0) self.bid_price_history.append( self.bid_price_list[self.current_time_index]) self.middle_price_history.pop(0) self.middle_price_history.append( self.middle_price_list[self.current_time_index]) ask_price = self.ask_price_history[-1] bid_price = self.bid_price_history[-1] value_in_stock = 0 for position in self.positions: value_in_stock += position['quantity'] * bid_price self.current_portfolio_value = self.cash + value_in_stock current_stock_portfolio_ratio = value_in_stock / self.current_portfolio_value observation_dict = {} price_for_percentage_computation = self.middle_price_history[ -1 * self.min_history_length:] observed_price_history = [ 100.0 * a1 / a2 - 100 for a1, a2 in zip(price_for_percentage_computation[1:], price_for_percentage_computation) ] observation_dict['price_history'] = observed_price_history observation_dict['current_stock_ratio'] = current_stock_portfolio_ratio observation_dict[ 'current_portfolio_value'] = self.current_portfolio_value observation_dict['action'] = action observation_dict['raw_price'] = price_for_percentage_computation return observation_dict, reward, execute_action
def wrap_symbol(obj): if isinstance(obj, Symbol): return obj else: return Symbol(obj)
from sympy import sympify, Symbol x = Symbol('x') #Se comvierte la variable a simbolico #Funcion principal del metodo def metodo_nuevo(x_0, f, tol, iter_max): if tol <= 0: raise ValueError( 'Tolerancia no debe ser cero.' ) #Error al ingresar una tolerancia con las condiones no aptas f = sympify(f) k = 0 x_k = x_0 error = tol + 1 D = [] A = [] # Cliclo de iteraciones segun tolerancia o maximo de iteraciones while error > tol and k < iter_max: x_k = calc_sgte(x_k, f) error = calc_error(x_k, f) D.append(k) A.append(error) k += 1 return [x_k, error, k, D, A]
from sympy import (binomial, Catalan, cos, Derivative, E, exp, EulerGamma, factorial, Function, harmonic, Integral, log, nan, oo, pi, Product, product, Rational, S, sqrt, Sum, summation, Symbol, sympify, zeta) from sympy.abc import a, b, c, d, k, m, x, y, z from sympy.concrete.summations import telescopic from sympy.utilities.pytest import XFAIL, raises n = Symbol('n', integer=True) def test_arithmetic_sums(): assert summation(1, (n, a, b)) == b - a + 1 assert Sum(S.NaN, (n, a, b)) is S.NaN assert Sum(x, (n, a, a)).doit() == x assert Sum(x, (x, a, a)).doit() == a assert Sum(x, (n, 1, a)).doit() == a * x lo, hi = 1, 2 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == s2.doit() == 3 lo, hi = x, x + 1 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == s2.doit() == 2 * x + 1 assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \ y**2 + 2 assert summation(1, (n, 1, 10)) == 10 assert summation(2 * n, (n, 0, 10**10)) == 100000000010000000000
from functools import singledispatch from typing import Tuple as tTuple from sympy import (Basic, S, Expr, Symbol, Tuple, And, Add, Eq, lambdify, Or, Equality, Lambda, sympify, Dummy, Ne, KroneckerDelta, DiracDelta, Mul, Indexed, MatrixSymbol, Function) from sympy.core.relational import Relational from sympy.core.sympify import _sympify from sympy.sets.sets import FiniteSet, ProductSet, Intersection from sympy.solvers.solveset import solveset from sympy.external import import_module from sympy.utilities.misc import filldedent import warnings x = Symbol('x') @singledispatch def is_random(x): return False @is_random.register(Basic) def _(x): atoms = x.free_symbols return any([is_random(i) for i in atoms]) class RandomDomain(Basic): """
def test_ndim_array_initiation(): arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0, )) assert len(arr_with_no_elements) == 0 assert arr_with_no_elements.rank() == 1 raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0, ))) raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0, ))) raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=())) raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0, ))) raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0, ))) raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=())) arr_with_one_element = ImmutableDenseNDimArray([23]) assert len(arr_with_one_element) == 1 assert arr_with_one_element[0] == 23 assert arr_with_one_element[:] == ImmutableDenseNDimArray([23]) assert arr_with_one_element.rank() == 1 arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')]) assert len(arr_with_symbol_element) == 1 assert arr_with_symbol_element[0] == Symbol('x') assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')]) assert arr_with_symbol_element.rank() == 1 number5 = 5 vector = ImmutableDenseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5, ) assert vector.rank() == 1 vector = ImmutableSparseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5, ) assert vector._sparse_array == Dict() assert vector.rank() == 1 n_dim_array = ImmutableDenseNDimArray(range(3**4), ( 3, 3, 3, 3, )) assert len(n_dim_array) == 3 * 3 * 3 * 3 assert n_dim_array.shape == (3, 3, 3, 3) assert n_dim_array.rank() == 4 array_shape = (3, 3, 3, 3) sparse_array = ImmutableSparseNDimArray.zeros(*array_shape) assert len(sparse_array._sparse_array) == 0 assert len(sparse_array) == 3 * 3 * 3 * 3 assert n_dim_array.shape == array_shape assert n_dim_array.rank() == 4 one_dim_array = ImmutableDenseNDimArray([2, 3, 1]) assert len(one_dim_array) == 3 assert one_dim_array.shape == (3, ) assert one_dim_array.rank() == 1 assert one_dim_array.tolist() == [2, 3, 1] shape = (3, 3) array_with_many_args = ImmutableSparseNDimArray.zeros(*shape) assert len(array_with_many_args) == 3 * 3 assert array_with_many_args.shape == shape assert array_with_many_args[0, 0] == 0 assert array_with_many_args.rank() == 2 shape = (int(3), int(3)) array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape) assert len(array_with_long_shape) == 3 * 3 assert array_with_long_shape.shape == shape assert array_with_long_shape[int(0), int(0)] == 0 assert array_with_long_shape.rank() == 2 vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5)) assert len(vector_with_long_shape) == 5 assert vector_with_long_shape.shape == (int(5), ) assert vector_with_long_shape.rank() == 1 raises(ValueError, lambda: vector_with_long_shape[int(5)]) from sympy.abc import x for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: rank_zero_array = ArrayType(x) assert len(rank_zero_array) == 1 assert rank_zero_array.shape == () assert rank_zero_array.rank() == 0 assert rank_zero_array[()] == x raises(ValueError, lambda: rank_zero_array[0])
# print(solve(expr, dict=True)) # from sympy import Symbol, solve # x=Symbol('x') # expr = x**2 + x + 1 # print(solve(expr, dict=True)) # from sympy import Symbol, solve # x = Symbol('x') # a = Symbol('a') # b = Symbol('b') # c = Symbol('c') # expr = a*x*x + b*x + c # print(solve(expr, x, dict=True)) # from sympy import Symbol, solve, pprint # s = Symbol('s') # u = Symbol('u') # t = Symbol('t') # a = Symbol('a') # expr = u*t + (1/2)*a*t*t - s # t_expr = solve(expr,t, dict=True) # pprint(t_expr) from sympy import Symbol, solve x = Symbol('x') y = Symbol('y') expr1 = 2 * x + 3 * y - 6 expr2 = 3 * x + 2 * y - 12 print(solve((expr1, expr2), dict=True))
def gen_kargs(self): kargs = [] if len(self._indexes) == 3: argspaces = { tuple(): "KerArgSpace(1, KER_ITER_TILE0)", (0, ): "KerArgSpace(1, KER_ITER_D0)", (1, ): "KerArgSpace(1, KER_ITER_TILE0)", (2, ): "KerArgSpace(1, KER_ITER_TILE0)", (0, 1): "KerArgSpace(2, KER_ITER_D0, KER_ITER_TILE0)", (0, 2): "KerArgSpace(2, KER_ITER_D0, KER_ITER_TILE0)", (1, 2): "KerArgSpace(1, KER_ITER_TILE0)", (0, 1, 2): "KerArgSpace(2, KER_ITER_D0, KER_ITER_TILE0)", } out_argspace = "KerArgSpace(2, KER_ITER_D0, KER_ITER_TILE0)" dim_w = 2 dim_h = 1 elif len(self._indexes) == 2: argspaces = { tuple(): "KerArgSpace(1, KER_ITER_TILE0)", (0, ): "KerArgSpace(1, KER_ITER_TILE0)", (1, ): "KerArgSpace(1, KER_ITER_TILE0)", (0, 1): "KerArgSpace(1, KER_ITER_TILE0)", } out_argspace = "KerArgSpace(1, KER_ITER_TILE0)" dim_w = 1 dim_h = 0 elif len(self._indexes) == 1: argspaces = { tuple(): "KerArgSpace(1, KER_ITER_TILE0)", (0, ): "KerArgSpace(1, KER_ITER_TILE0)", } out_argspace = "KerArgSpace(1, KER_ITER_TILE0)" dim_w = -1 dim_h = 0 else: raise NotImplementedError() for input_node in self._inputs: sym = Symbol(input_node.name) arg_indexes = self._symbol_indexes[sym] argspace = argspaces[arg_indexes] constraints = "O_IN|O_DB|O_CONST" if self._constant_inputs[ input_node.idx] else "O_IN|O_DB" dims = [ index[1] if idx in arg_indexes else 1 for idx, index in enumerate(self._indexes) ] width = dims[dim_w] if dim_w > -1 else 1 height = dims[dim_h] if dim_h > -1 else 1 kargs.append( "KerArg(\"{0}\", {1}, {2}, {3}, {4}, 1, 0, 0, 0, \"{0}\")". format(sym.name, argspace, constraints, height, width)) dims = [index[1] for index in self._indexes] for output_node in self._outputs: name = output_node.name constraints = "O_OUT|O_DB" width = dims[dim_w] if dim_w > -1 else 1 height = dims[dim_h] if dim_h > -1 else 1 kargs.append( "KerArg(\"{0}\", {1}, {2}, {3}, {4}, 1, 0, 0, 0, \"{0}\")". format(name, out_argspace, constraints, height, width)) return kargs
def test_issue_4099(): a = Symbol('a') assert limit(a/x, x, 0) == oo*sign(a) assert limit(-a/x, x, 0) == -oo*sign(a) assert limit(-a*x, x, oo) == -oo*sign(a) assert limit(a*x, x, oo) == oo*sign(a)
def __new__(cls, name, *args, **assumptions): return Symbol.__new__(cls, name.upper(), real=True, **assumptions)
def test_issue_6366(): n = Symbol('n', integer=True, positive=True) r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1) assert limit(r, x, 1).simplify() == n/2
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)
""" Show that Guayan-Reduction of a single element result in rigid body modes """ import numpy as np import sympy from sympy import Symbol from sympy import Matrix from sympy.abc import * from fem.frame3d import frame3d_KeMe display = lambda x: sympy.pprint(x, use_unicode=False, wrap_line=False) Kv = Symbol('Kv') Ix = Symbol('Ix') Iy = Symbol('Iy') Iz = Symbol('Iz') Mass = Symbol('M') Ke, Me = frame3d_KeMe(E, G, Kv, E * A, E * Ix, E * Iy, E * Iz, L, A, Mass) Ke = Matrix(Ke) Me = Matrix(Me) Kmm = Ke[:6, :6] Ksm = Ke[6:, :6] Kss = Ke[6:, 6:] Kssm1 = Kss.inv() print( '-----------------------------------------------------------------------------------------' )
def test_issue_6364(): a = Symbol('a') e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2) assert limit(e, z, 0).simplify() == 2/cos(2*a)
def test_integrate_omit_var(): y = Symbol('y') raises(ValueError, "integrate(2)") assert integrate(x) == x**2 / 2 assert integrate(x * y) == x**2 * y**2 / 4
def test_issue_7088(): a = Symbol('a') assert limit(sqrt(x/(x + a)), x, oo) == 1
def test_order_oo(): x = Symbol('x', positive=True, finite=True) assert Order(x)*oo != Order(1, x) assert limit(oo/(x**2 - 4), x, oo) == oo
def func(block, idx): return [ VarFor(Declaration(Variable(Symbol(idx[0]), type=uint32)), VarRange(idx[2][0], idx[2][1], Integer(1)), block) ]
combinations of noncommutative SymPy symbols. also contains "half_angle_reduce" which is probably not needed any more due to the improvements in trigsimp. """ from sympy import expand, Mul, Add, Symbol, S, Pow, diff, trigsimp, \ simplify, sin, cos, symbols try: from numpy import matrix numpy_loaded = True except ImportError: numpy_loaded = False ONE_NC = Symbol('ONE', commutative=False) def get_commutative_coef(expr): if isinstance(expr, Mul): (coefs, bases) = expr.args_cnc() return Mul(*coefs) return S.One def half_angle_reduce(expr, theta): s, c = symbols('s c') sub_dict = {sin(theta / 2): s, cos(theta / 2): c} new_expr = expr.subs(sub_dict) sub_dict = { s * c: sin(theta) / 2,
# -*- coding: utf-8 -*- """ Created on Fri Jul 31 09:39:18 2020 @author: andfg """ # ============================================================================= # RESUMEN SOBRE SYMPY # ============================================================================= # ============================================================================= # 1. Definir simbolos from sympy import Symbol x=Symbol("x") #Atribuye a x el valor del simbolo "x" from sympy import symbols #permite declarar multiples simbolos en una linea x,y,z = symbols("x, y, z") # ============================================================================= # ============================================================================= # 2. Factorizar y expandir expreciones from sympy import factor, expand expr1= x**2 - y**2 factor(expr1) ##factor factoriza un expresion en la medida de lo posible expr2=(x+2)**3 expand(expr2) ## expand expande expresiones # =============================================================================
def test_issue_5939(): a = Symbol('a') b = Symbol('b') assert sympify('''a+\nb''') == a + b
def test_values(): assert set(PropertiesOnlyMatrix(2, 2, [0, 1, 2, 3]).values()) == set([1, 2, 3]) x = Symbol('x', real=True) assert set(PropertiesOnlyMatrix(2, 2, [x, 0, 0, 1]).values()) == set([x, 1])
def __new__(cls, name, constant=None, fundamental=None, substitution=None, substitution_atoms=None, datatype=None, **assumptions) : from sympy import Symbol return Symbol.__new__(cls, name, **assumptions)
def test_multiplication(): a = ArithmeticOnlyMatrix(( (1, 2), (3, 1), (0, 6), )) b = ArithmeticOnlyMatrix(( (1, 2), (3, 0), )) raises(ShapeError, lambda: b * a) raises(TypeError, lambda: a * {}) c = a * b assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 try: eval('c = a @ b') except SyntaxError: pass else: assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 h = a.multiply_elementwise(c) assert h == matrix_multiply_elementwise(a, c) assert h[0, 0] == 7 assert h[0, 1] == 4 assert h[1, 0] == 18 assert h[1, 1] == 6 assert h[2, 0] == 0 assert h[2, 1] == 0 raises(ShapeError, lambda: a.multiply_elementwise(b)) c = b * Symbol("x") assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == x assert c[0, 1] == 2 * x assert c[1, 0] == 3 * x assert c[1, 1] == 0 c2 = x * b assert c == c2 c = 5 * b assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == 5 assert c[0, 1] == 2 * 5 assert c[1, 0] == 3 * 5 assert c[1, 1] == 0 try: eval('c = 5 @ b') except SyntaxError: pass else: assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == 5 assert c[0, 1] == 2 * 5 assert c[1, 0] == 3 * 5 assert c[1, 1] == 0
def test_issue_3595(): assert sympify("a_") == Symbol("a_") assert sympify("_a") == Symbol("_a")
def test_issue_4503(): dx = Symbol('dx') assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \ exp(x)/(2*sqrt(exp(x) + 1))
def __new__(cls, data, step_size=1.0): return Symbol.__new__(cls, "lits%s_%s" % (hashlib.sha1(np.array(data)).hexdigest(), step_size))
def test_lambda(): x = Symbol('x') assert sympify('lambda: 1') == Lambda((), 1) assert sympify('lambda x: x') == Lambda(x, x) assert sympify('lambda x: 2*x') == Lambda(x, 2 * x) assert sympify('lambda x, y: 2*x+y') == Lambda([x, y], 2 * x + y)
def __new__(cls, i): if not i in [1, 2, 3]: raise IndexError("Invalid Pauli index") obj = Symbol.__new__(cls, "sigma%d" % i, commutative=False) obj.i = i return obj
def test_sympify_set(): n = Symbol('n') assert sympify({n}) == FiniteSet(n) assert sympify(set()) == EmptySet()