def test_euler_pendulum():
x = Function('x')
t = Symbol('t')
L = D(x(t), t)**2/2 + cos(x(t))
assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t))]
python类Eq()的实例源码
def test_euler_sineg():
psi = Function('psi')
t = Symbol('t')
x = Symbol('x')
L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x))
assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) -
D(psi(t, x), t, t) +
D(psi(t, x), x, x))]
def test_preview_latex_construct_in_expr():
# see PR 9801
x = Symbol('x')
pw = Piecewise((1, Eq(x, 0)), (0, True))
obj = BytesIO()
try:
preview(pw, output='png', viewer='BytesIO', outputbuffer=obj)
except RuntimeError:
pass # latex not installed on CI server
def test_ccode_Relational():
from sympy import Eq, Ne, Le, Lt, Gt, Ge
assert ccode(Eq(x, y)) == "x == y"
assert ccode(Ne(x, y)) == "x != y"
assert ccode(Le(x, y)) == "x <= y"
assert ccode(Lt(x, y)) == "x < y"
assert ccode(Gt(x, y)) == "x > y"
assert ccode(Ge(x, y)) == "x >= y"
def test_rcode_Relational():
from sympy import Eq, Ne, Le, Lt, Gt, Ge
assert rcode(Eq(x, y)) == "x == y"
assert rcode(Ne(x, y)) == "x != y"
assert rcode(Le(x, y)) == "x <= y"
assert rcode(Lt(x, y)) == "x < y"
assert rcode(Gt(x, y)) == "x > y"
assert rcode(Ge(x, y)) == "x >= y"
def test_rcode_Indexed_without_looking_for_contraction():
len_y = 5
y = IndexedBase('y', shape=(len_y,))
x = IndexedBase('x', shape=(len_y,))
Dy = IndexedBase('Dy', shape=(len_y-1,))
i = Idx('i', len_y-1)
e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
code0 = rcode(e.rhs, assign_to=e.lhs, contract=False)
assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1)
def runtest_autowrap_matrix_vector(language, backend):
has_module('numpy')
x, y = symbols('x y', cls=IndexedBase)
expr = Eq(y[i], A[i, j]*x[j])
mv = autowrap(expr, language, backend)
# compare with numpy's dot product
M = numpy.random.rand(10, 20)
x = numpy.random.rand(20)
y = numpy.dot(M, x)
assert numpy.sum(numpy.abs(y - mv(M, x))) < 1e-13
def runtest_autowrap_matrix_matrix(language, backend):
has_module('numpy')
expr = Eq(C[i, j], A[i, k]*B[k, j])
matmat = autowrap(expr, language, backend)
# compare with numpy's dot product
M1 = numpy.random.rand(10, 20)
M2 = numpy.random.rand(20, 15)
M3 = numpy.dot(M1, M2)
assert numpy.sum(numpy.abs(M3 - matmat(M1, M2))) < 1e-13
def solveEquation(expr):
expr = expr.replace('^', '**')
members = expr.split('=')
if len(members) != 2:
raise BadFormatException('Bad number of equals.')
from sympy.abc import *
eq = sympy.Eq(*map(eval, members))
return [{repr(j): repr(k) for j, k in i.items()} for i in _ensureList(sympy.solve(eq, dict=1))]
def test_one_variable(self):
"""
It can eliminate ``x`` from the system ``(a = x, b = x)``.
"""
equations = [sympy.Eq(a, x), sympy.Eq(b, x)]
new_equations = vadouvan.symbolic_utils.eliminate(equations, [x])
assert len(new_equations) == 1
assert new_equations[0].free_symbols == {a, b}
def test_two_variables(self):
"""
It can eliminate ``x, y`` from the system
``(a = 3x - 4y, b = 4x + 5y, c = 6x + 2y)``.
"""
equations = [
sympy.Eq(a, 3 * x - 4 * y),
sympy.Eq(b, 4 * x + 5 * y),
sympy.Eq(c, 6 * x + 2 * y),
]
new_equations = vadouvan.symbolic_utils.eliminate(equations, [x, y])
assert len(new_equations) == 1
assert new_equations[0].free_symbols == {a, b, c}
def test_many_variables(self):
"""
It can eliminate all x's from the chain
``(a = x0, x0 = x1, ..., x19 = x20, x20 = b)``.
"""
symbols = list(itertools.islice(sympy.numbered_symbols("x"), 20))
equations = [sympy.Eq(symbols[i], symbols[i + 1])
for i in range(len(symbols) - 1)]
equations.append(sympy.Eq(a, symbols[0]))
equations.append(sympy.Eq(b, symbols[-1]))
new_equations = vadouvan.symbolic_utils.eliminate(equations, symbols)
assert len(new_equations) == 1
assert new_equations[0].free_symbols == {a, b}
def test_underconstrained_2(self):
"""
Underconstrained system returns an empty collection.
"""
equations = [sympy.Eq(x, y)]
new_equations = vadouvan.symbolic_utils.eliminate(equations, [x, y])
assert len(new_equations) == 0
def odes(self):
"""Return a list of differential equations describing the
evolution of the species concentrations in time."""
t = sp.Symbol('t', real = True)
x = [sp.Function(s) for s in self.species]
derivs = self.equations()
return [sp.Eq(sp.Derivative(x[j](t), t),
derivs[j].subs([(sp.Symbol(self.species[i]), x[i](t)) for i in range(self.n_species)]))
for j in range(self.n_species)]
def __new__(cls, *args, **kwargs):
kwargs['evaluate'] = False
obj = sympy.Eq.__new__(cls, *args, **kwargs)
return obj
def ccode(expr, **settings):
"""Generate C++ code from an expression calling CodePrinter class
:param expr: The expression
:param settings: A dictionary of settings for code printing
:returns: The resulting code as a string. If it fails, then it returns the expr
"""
if isinstance(expr, Eq):
return ccode_eq(expr)
try:
return CodePrinter(settings).doprint(expr, None)
except:
return expr
def first_touch(array):
"""
Uses an Operator to initialize the given array in the same pattern that
would later be used to access it.
"""
devito.Operator(Eq(array, 0.))()
def execute_lambdify(ui, spacing=0.01, a=0.5, timesteps=500):
"""Execute diffusion stencil using vectorised numpy array accesses."""
nx, ny = ui.shape
dx2, dy2 = spacing**2, spacing**2
dt = dx2 * dy2 / (2 * a * (dx2 + dy2))
u = np.concatenate((ui, np.zeros_like(ui))).reshape((2, nx, ny))
def diffusion_stencil():
"""Create stencil and substitutions for the diffusion equation"""
p = sympy.Function('p')
x, y, t, h, s = sympy.symbols('x y t h s')
dx2 = p(x, y, t).diff(x, x).as_finite_difference([x - h, x, x + h])
dy2 = p(x, y, t).diff(y, y).as_finite_difference([y - h, y, y + h])
dt = p(x, y, t).diff(t).as_finite_difference([t, t + s])
eqn = sympy.Eq(dt, a * (dx2 + dy2))
stencil = sympy.solve(eqn, p(x, y, t + s))[0]
return stencil, (p(x, y, t), p(x + h, y, t), p(x - h, y, t),
p(x, y + h, t), p(x, y - h, t), s, h)
stencil, subs = diffusion_stencil()
kernel = sympy.lambdify(subs, stencil, 'numpy')
# Execute timestepping loop with alternating buffers
tstart = time.time()
for ti in range(timesteps):
t0 = ti % 2
t1 = (ti + 1) % 2
u[t1, 1:-1, 1:-1] = kernel(u[t0, 1:-1, 1:-1], u[t0, 2:, 1:-1],
u[t0, :-2, 1:-1], u[t0, 1:-1, 2:],
u[t0, 1:-1, :-2], dt, spacing)
runtime = time.time() - tstart
log("Lambdify: Diffusion with dx=%0.4f, dy=%0.4f, executed %d timesteps in %f seconds"
% (spacing, spacing, timesteps, runtime))
return u[ti % 2, :, :], runtime
def test_unpolarify():
from sympy import (exp_polar, polar_lift, exp, unpolarify, sin,
principal_branch)
from sympy import gamma, erf, sin, tanh, uppergamma, Eq, Ne
from sympy.abc import x
p = exp_polar(7*I) + 1
u = exp(7*I) + 1
assert unpolarify(1) == 1
assert unpolarify(p) == u
assert unpolarify(p**2) == u**2
assert unpolarify(p**x) == p**x
assert unpolarify(p*x) == u*x
assert unpolarify(p + x) == u + x
assert unpolarify(sqrt(sin(p))) == sqrt(sin(u))
# Test reduction to principal branch 2*pi.
t = principal_branch(x, 2*pi)
assert unpolarify(t) == x
assert unpolarify(sqrt(t)) == sqrt(t)
# Test exponents_only.
assert unpolarify(p**p, exponents_only=True) == p**u
assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u)
# Test functions.
assert unpolarify(sin(p)) == sin(u)
assert unpolarify(tanh(p)) == tanh(u)
assert unpolarify(gamma(p)) == gamma(u)
assert unpolarify(erf(p)) == erf(u)
assert unpolarify(uppergamma(x, p)) == uppergamma(x, p)
assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \
uppergamma(sin(u), sin(u + 1))
assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \
uppergamma(0, 2)
assert unpolarify(Eq(p, 0)) == Eq(u, 0)
assert unpolarify(Ne(p, 0)) == Ne(u, 0)
assert unpolarify(polar_lift(x) > 0) == (x > 0)
# Test bools
assert unpolarify(True) is True
def substitution_rule(integral):
integrand, symbol = integral
u_var = sympy.Dummy("u")
substitutions = find_substitutions(integrand, symbol, u_var)
if substitutions:
ways = []
for u_func, c, substituted in substitutions:
subrule = integral_steps(substituted, u_var)
if contains_dont_know(subrule):
continue
if sympy.simplify(c - 1) != 0:
_, denom = c.as_numer_denom()
subrule = ConstantTimesRule(c, substituted, subrule, substituted, u_var)
if denom.free_symbols:
piecewise = []
could_be_zero = []
if isinstance(denom, sympy.Mul):
could_be_zero = denom.args
else:
could_be_zero.append(denom)
for expr in could_be_zero:
if not sympy.ask(~sympy.Q.zero(expr)):
substep = integral_steps(integrand.subs(expr, 0), symbol)
if substep:
piecewise.append((
substep,
sympy.Eq(expr, 0)
))
piecewise.append((subrule, True))
subrule = PiecewiseRule(piecewise, substituted, symbol)
ways.append(URule(u_var, u_func, c,
subrule,
integrand, symbol))
if len(ways) > 1:
return AlternativeRule(ways, integrand, symbol)
elif ways:
return ways[0]
elif integrand.has(sympy.exp):
u_func = sympy.exp(symbol)
c = 1
substituted = integrand / u_func.diff(symbol)
substituted = substituted.subs(u_func, u_var)
if symbol not in substituted.free_symbols:
return URule(u_var, u_func, c,
integral_steps(substituted, u_var),
integrand, symbol)