Exemple #1
0
 def probability(self, condition, **kwargs):
     cond_inv = False
     if isinstance(condition, Ne):
         condition = Eq(condition.args[0], condition.args[1])
         cond_inv = True
     expr = condition.lhs - condition.rhs
     rvs = random_symbols(expr)
     z = Dummy('z', real=True, Finite=True)
     dens = self.compute_density(expr)
     if any([pspace(rv).is_Continuous for rv in rvs]):
         from sympy.stats.crv import (ContinuousDistributionHandmade,
             SingleContinuousPSpace)
         if expr in self.values:
             # Marginalize all other random symbols out of the density
             randomsymbols = tuple(set(self.values) - frozenset([expr]))
             symbols = tuple(rs.symbol for rs in randomsymbols)
             pdf = self.domain.integrate(self.pdf, symbols, **kwargs)
             return Lambda(expr.symbol, pdf)
         dens = ContinuousDistributionHandmade(dens)
         space = SingleContinuousPSpace(z, dens)
         result = space.probability(condition.__class__(space.value, 0))
     else:
         from sympy.stats.drv import (DiscreteDistributionHandmade,
             SingleDiscretePSpace)
         dens = DiscreteDistributionHandmade(dens)
         space = SingleDiscretePSpace(z, dens)
         result = space.probability(condition.__class__(space.value, 0))
     return result if not cond_inv else S.One - result
Exemple #2
0
    def probability(self, condition, **kwargs):
        z = Dummy('z', real=True, finite=True)
        cond_inv = False
        if isinstance(condition, Ne):
            condition = Eq(condition.args[0], condition.args[1])
            cond_inv = True
        # Univariate case can be handled by where
        try:
            domain = self.where(condition)
            rv = [rv for rv in self.values if rv.symbol == domain.symbol][0]
            # Integrate out all other random variables
            pdf = self.compute_density(rv, **kwargs)
            # return S.Zero if `domain` is empty set
            if domain.set is S.EmptySet or isinstance(domain.set, FiniteSet):
                return S.Zero if not cond_inv else S.One
            if isinstance(domain.set, Union):
                return sum(
                     Integral(pdf(z), (z, subset), **kwargs) for subset in
                     domain.set.args if isinstance(subset, Interval))
            # Integrate out the last variable over the special domain
            return Integral(pdf(z), (z, domain.set), **kwargs)

        # Other cases can be turned into univariate case
        # by computing a density handled by density computation
        except NotImplementedError:
            from sympy.stats.rv import density
            expr = condition.lhs - condition.rhs
            dens = density(expr, **kwargs)
            if not isinstance(dens, ContinuousDistribution):
                dens = ContinuousDistributionHandmade(dens)
            # Turn problem into univariate case
            space = SingleContinuousPSpace(z, dens)
            result = space.probability(condition.__class__(space.value, 0))
            return result if not cond_inv else S.One - result
def solver():
    vals = {i: base_eq(i) for i in range(1, 12)}
    coefficients = a, b, c, d, e, f, g, h, i, j, k = symbols(','.join('abcdefghijk'))
    (x, n), lhs = symbols('x n'), a
    answer = 1

    for i, element in enumerate(coefficients[1:]):
        lhs = lhs * n + element
        equation = Eq(x, lhs)
        results = solve([equation.subs(dict(n=t, x=vals[t])) for
                         t in range(1, i+3)])
        results[n] = i + 3
        if element != k:
            answer += equation.subs(results).args[1]
    return answer
Exemple #4
0
def solve_it(eqn, knowns, x):
    LHS, RHS = eqn['sympy'].split('=')
    e = Eq(sympify(LHS), sympify(RHS))

    voi = Symbol(x['symbol']) # upgrade sympy to 0.7.6 if this throws a unicode error

    vals = dict()
    for k in knowns:
        vals[Symbol(k['symbol'])] = k['value']
    for c in eqn['constants']:
        vals[Symbol(c['symbol'])] = c['value']

    answers = solve(e.subs(vals),voi)
    answer = answers[0]

    return answer.evalf()
Exemple #5
0
 def probability(self, condition):
     complement = isinstance(condition, Ne)
     if complement:
         condition = Eq(condition.args[0], condition.args[1])
     try:
         _domain = self.where(condition).set
         if condition == False or _domain is S.EmptySet:
             return S.Zero
         if condition == True or _domain == self.domain.set:
             return S.One
         prob = self.eval_prob(_domain)
     except NotImplementedError:
         from sympy.stats.rv import density
         expr = condition.lhs - condition.rhs
         dens = density(expr)
         if not isinstance(dens, DiscreteDistribution):
             dens = DiscreteDistributionHandmade(dens)
         z = Dummy('z', real = True)
         space = SingleDiscretePSpace(z, dens)
         prob = space.probability(condition.__class__(space.value, 0))
     if (prob == None):
         prob = Probability(condition)
     return prob if not complement else S.One - prob
def test_issue_9849():
    assert ConditionSet(x, Eq(x, x), S.Naturals) == S.Naturals
    assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals) == S.EmptySet
Exemple #7
0
#!/usr/bin/python

from sympy import latex
from sympy import solve
from sympy import symbols

from sympy import Eq
from sympy import Rational

a, d, t, v, v0 = symbols('a d t v v0')

kin1 = Eq(d, v0 * t + Rational(1,2) * a * t**2)
kin2 = Eq(v, v0 + a * t)

print ""
print "The basic equations for one-dimensional motion are:"
print ""
print "    {}".format(latex(kin1))
print "    {}".format(latex(kin2))
print ""
print "How long does it take an object released from rest to fall five meters?"
print ""

values = dict()
values[d] = -5
values[v0] = 0
values[a] = -9.81

print "The parameters for this problem are:"
print ""
for param, value in values.iteritems():
Exemple #8
0
def test_Equality_rewrite_as_Add():
    eq = Eq(x + y, y - x)
    assert eq.rewrite(Add) == 2*x
    assert eq.rewrite(Add, evaluate=None).args == (x, x, y, -y)
    assert eq.rewrite(Add, evaluate=False).args == (x, y, x, -y)
Exemple #9
0
def given(expr, condition=None, **kwargs):
    r""" Conditional Random Expression
    From a random expression and a condition on that expression creates a new
    probability space from the condition and returns the same expression on that
    conditional probability space.

    Examples
    ========

    >>> from sympy.stats import given, density, Die
    >>> X = Die('X', 6)
    >>> Y = given(X, X > 3)
    >>> density(Y).dict
    {4: 1/3, 5: 1/3, 6: 1/3}

    Following convention, if the condition is a random symbol then that symbol
    is considered fixed.

    >>> from sympy.stats import Normal
    >>> from sympy import pprint
    >>> from sympy.abc import z

    >>> X = Normal('X', 0, 1)
    >>> Y = Normal('Y', 0, 1)
    >>> pprint(density(X + Y, Y)(z), use_unicode=False)
                    2
           -(-Y + z)
           -----------
      ___       2
    \/ 2 *e
    ------------------
             ____
         2*\/ pi
    """

    if not is_random(condition) or pspace_independent(expr, condition):
        return expr

    if isinstance(condition, RandomSymbol):
        condition = Eq(condition, condition.symbol)

    condsymbols = random_symbols(condition)
    if (isinstance(condition, Equality) and len(condsymbols) == 1
            and not isinstance(pspace(expr).domain, ConditionalDomain)):
        rv = tuple(condsymbols)[0]

        results = solveset(condition, rv)
        if isinstance(results, Intersection) and S.Reals in results.args:
            results = list(results.args[1])

        sums = 0
        for res in results:
            temp = expr.subs(rv, res)
            if temp == True:
                return True
            if temp != False:
                # XXX: This seems nonsensical but preserves existing behaviour
                # after the change that Relational is no longer a subclass of
                # Expr. Here expr is sometimes Relational and sometimes Expr
                # but we are trying to add them with +=. This needs to be
                # fixed somehow.
                if sums == 0 and isinstance(expr, Relational):
                    sums = expr.subs(rv, res)
                else:
                    sums += expr.subs(rv, res)
        if sums == 0:
            return False
        return sums

    # Get full probability space of both the expression and the condition
    fullspace = pspace(Tuple(expr, condition))
    # Build new space given the condition
    space = fullspace.conditional_space(condition, **kwargs)
    # Dictionary to swap out RandomSymbols in expr with new RandomSymbols
    # That point to the new conditional space
    swapdict = rs_swap(fullspace.values, space.values)
    # Swap random variables in the expression
    expr = expr.xreplace(swapdict)
    return expr
Exemple #10
0
def test_rsolve():
    f = y(n + 2) - y(n + 1) - y(n)
    h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
        - sqrt(5)*(S.Half - S.Half*sqrt(5))**n

    assert rsolve(f, y(n)) in [
        C0 * (S.Half - S.Half * sqrt(5))**n + C1 *
        (S.Half + S.Half * sqrt(5))**n,
        C1 * (S.Half - S.Half * sqrt(5))**n + C0 *
        (S.Half + S.Half * sqrt(5))**n,
    ]

    assert rsolve(f, y(n), [0, 5]) == h
    assert rsolve(f, y(n), {0: 0, 1: 5}) == h
    assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h
    assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h
    assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = (n - 1) * y(n + 2) - (n**2 + 3 * n - 2) * y(n + 1) + 2 * n * (n +
                                                                      1) * y(n)
    g = C1 * factorial(n) + C0 * 2**n
    h = -3 * factorial(n) + 3 * 2**n

    assert rsolve(f, y(n)) == g
    assert rsolve(f, y(n), []) == g
    assert rsolve(f, y(n), {}) == g

    assert rsolve(f, y(n), [0, 3]) == h
    assert rsolve(f, y(n), {0: 0, 1: 3}) == h
    assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - y(n - 1) - 2

    assert rsolve(f, y(n), {y(0): 0}) == 2 * n
    assert rsolve(f, y(n), {y(0): 1}) == 2 * n + 1
    assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = 3 * y(n - 1) - y(n) - 1

    assert rsolve(f, y(n), {y(0): 0}) == -3**n / 2 + S.Half
    assert rsolve(f, y(n), {y(0): 1}) == 3**n / 2 + S.Half
    assert rsolve(f, y(n), {y(0): 2}) == 3 * 3**n / 2 + S.Half

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - 1 / n * y(n - 1)
    assert rsolve(f, y(n)) == C0 / factorial(n)
    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = y(n) - 1 / n * y(n - 1) - 1
    assert rsolve(f, y(n)) is None

    f = 2 * y(n - 1) + (1 - n) * y(n) / n

    assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1) * n
    assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1) * n * 2
    assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1) * n * 3

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    f = (n - 1) * (n - 2) * y(n + 2) - (n + 1) * (n + 2) * y(n)

    assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n * (n - 1) * (n - 2)
    assert rsolve(f, y(n), {
        y(3): 6,
        y(4): -24
    }) == -n * (n - 1) * (n - 2) * (-1)**(n)

    assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0

    assert rsolve(Eq(y(n + 1), a * y(n)), y(n), {y(1): a}).simplify() == a**n

    assert rsolve(y(n) - a*y(n-2),y(n), \
            {y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \
            a**(n/2)*(-(-1)**n*b + a)

    f = (-16 * n**2 + 32 * n - 12) * y(n - 1) + (4 * n**2 - 12 * n + 9) * y(n)

    assert expand_func(rsolve(f, y(n), \
            {y(1): binomial(2*n + 1, 3)}).rewrite(gamma)).simplify() == \
        2**(2*n)*n*(2*n - 1)*(4*n**2 - 1)/12

    assert (rsolve(y(n) + a * (y(n + 1) + y(n - 1)) / 2, y(n)) -
            (C0 * ((sqrt(-a**2 + 1) - 1) / a)**n + C1 *
             ((-sqrt(-a**2 + 1) - 1) / a)**n)).simplify() == 0
def test_conditional_eq():
    E = Exponential('E', 1)
    assert P(Eq(E, 1), Eq(E, 1)) == 1
    assert P(Eq(E, 1), Eq(E, 2)) == 0
    assert P(E > 1, Eq(E, 2)) == 1
    assert P(E < 1, Eq(E, 2)) == 0
Exemple #12
0
def test_dice_bayes():
    X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6)

    BayesTest(X > 3, X + Y < 5)
    BayesTest(Eq(X - Y, Z), Z > Y)
    BayesTest(X > 3, X > 2)
Exemple #13
0
def test_tsolve():
    a, b = symbols('a,b')
    x, y, z = symbols('x,y,z')
    assert solve(exp(x)-3, x) == [log(3)]
    assert solve((a*x+b)*(exp(x)-3), x) == [-b/a, log(3)]
    assert solve(cos(x)-y, x) == [acos(y)]
    assert solve(2*cos(x)-y,x)== [acos(y/2)]
    raises(NotImplementedError, "solve(Eq(cos(x), sin(x)), x)")

    assert solve(exp(x) + exp(-x) - y, x, simplified=False) == [
        log((y/2 + sqrt(y**2 - 4)/2)**2)/2,
        log((y/2 - sqrt(y**2 - 4)/2)**2)/2]
    assert solve(exp(x)-3, x) == [log(3)]
    assert solve(Eq(exp(x), 3), x) == [log(3)]
    assert solve(log(x)-3, x) == [exp(3)]
    assert solve(sqrt(3*x)-4, x) == [Rational(16,3)]
    assert solve(3**(x+2), x) == [zoo]
    assert solve(3**(2-x), x) == [zoo]
    assert solve(4*3**(5*x+2)-7, x) == [(-2*log(3) - 2*log(2) + log(7))/(5*log(3))]
    assert solve(x+2**x, x) == [-LambertW(log(2))/log(2)]
    assert solve(3*x+5+2**(-5*x+3), x) in [
        [-((25*log(2) - 3*LambertW(-10240*2**(Rational(1, 3))*log(2)/3))/(15*log(2)))],
        [Rational(-5, 3) + LambertW(log(2**(-10240*2**(Rational(1, 3))/3)))/(5*log(2))],
        [-Rational(5,3) + LambertW(-10240*2**Rational(1,3)*log(2)/3)/(5*log(2))],
        [(-25*log(2) + 3*LambertW(-10240*2**(Rational(1, 3))*log(2)/3))/(15*log(2))],
        [-((25*log(2) - 3*LambertW(-10240*2**(Rational(1, 3))*log(2)/3)))/(15*log(2))],
        [-(25*log(2) - 3*LambertW(log(2**(-10240*2**Rational(1, 3)/3))))/(15*log(2))],
        [(25*log(2) - 3*LambertW(log(2**(-10240*2**Rational(1, 3)/3))))/(-15*log(2))]
        ]
    assert solve(5*x-1+3*exp(2-7*x), x) == \
        [Rational(1,5) + LambertW(-21*exp(Rational(3, 5))/5)/7]
    assert solve(2*x+5+log(3*x-2), x) == \
        [Rational(2,3) + LambertW(2*exp(-Rational(19, 3))/3)/2]
    assert solve(3*x+log(4*x), x) == [LambertW(Rational(3,4))/3]
    assert solve((2*x+8)*(8+exp(x)), x) == [-4, log(8) + pi*I]
    assert solve(2*exp(3*x+4)-3, x) in [
        [Rational(-4, 3) + log(2**Rational(2, 3)*3**Rational(1, 3)/2)],
        [-Rational(4, 3)+log(Rational(3, 2))/3],
        [Rational(-4, 3) - log(2)/3 + log(3)/3],
        ]
    assert solve(2*log(3*x+4)-3, x) == [(exp(Rational(3,2))-4)/3]
    assert solve(exp(x)+1, x) == [pi*I]
    assert solve(x**2 - 2**x, x) == [2]
    assert solve(x**3 - 3**x, x) == [-3*LambertW(-log(3)/3)/log(3)]

    A = -7*2**Rational(4, 5)*6**Rational(1, 5)*log(7)/10
    B = -7*3**Rational(1, 5)*log(7)/5

    result = solve(2*(3*x+4)**5 - 6*7**(3*x+9), x)

    assert len(result) == 1 and expand(result[0]) in [
        Rational(-4, 3) - 5/log(7)/3*LambertW(A),
        Rational(-4, 3) - 5/log(7)/3*LambertW(B),
    ]

    assert solve(z*cos(x)-y, x)      == [acos(y/z)]
    assert solve(z*cos(2*x)-y, x)    == [acos(y/z)/2]
    assert solve(z*cos(sin(x))-y, x) == [asin(acos(y/z))]

    assert solve(z*cos(x), x)        == [acos(0)]

    # issue #1409
    assert solve(y - b*x/(a+x), x) in [[-a*y/(y - b)], [a*y/(b - y)]]
    assert solve(y - b*exp(a/x), x) == [a/log(y/b)]
    # issue #1408
    assert solve(y-b/(1+a*x), x) in [[(b - y)/(a*y)], [-((y - b)/(a*y))]]
    # issue #1407
    assert solve(y-a*x**b , x) == [(y/a)**(1/b)]
    # issue #1406
    assert solve(z**x - y, x) == [log(y)/log(z)]
    # issue #1405
    assert solve(2**x - 10, x) == [log(10)/log(2)]
Exemple #14
0
from sympy.functions import *
from sympy.interactive import init_printing
from sympy.physics.units import Quantity
from sympy.physics.units import convert_to
from utils import *

init_printing()

hp_to_watts = 745.7

W0 = Quantity("W0")
W = Quantity("W")
m = Quantity("m")
v = Quantity("v")
g = Quantity("g")
theta = symbols("theta")

set_quantity(W0, un.power, 85 * hp_to_watts * un.watts)
set_quantity(W, un.power, 20 * hp_to_watts * un.watts)
set_quantity(m, un.mass, 1200 * un.kg)
set_quantity(v, un.velocity, 48 * un.km / un.hour)
set_quantity(g, un.acceleration, 9.81 * un.m / un.s**2)

eq = Eq(sin(theta), (W0 - W) / (m * g * v))
pretty_print(eq)

theta = solve(eq, theta)[1]

theta = convert_to(theta, un.watts).n()
pretty_print(convert_to(theta, un.degrees).n())
# Program 02g: A second order ODE.
from sympy import symbols, dsolve, Function, Eq, sin

t = symbols('t')
I = symbols('I', cls=Function)
sol = dsolve(Eq(I(t).diff(t, t) + 5 * I(t).diff(t) + 6 * I(t), 10 * sin(t)),
             I(t))

print(sol)
Exemple #16
0
def test_evalf_relational():
    assert Eq(x / 5, y / 10).evalf() == Eq(0.2 * x, 0.1 * y)
Exemple #17
0
def test_Intersection_as_relational():
    x = Symbol('x')
    assert (Intersection(Interval(0, 1), FiniteSet(2),
            evaluate=False).as_relational(x)
            == And(And(Le(0, x), Le(x, 1)), Eq(x, 2)))
Exemple #18
0
def test_Union_as_relational():
    x = Symbol('x')
    assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \
        Or(And(Le(0, x), Le(x, 1)), Eq(x, 2))
    assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \
        And(Lt(0, x), Le(x, 1))
Exemple #19
0
def test_Finite_as_relational():
    x = Symbol('x')
    y = Symbol('y')

    assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2))
    assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5))
Exemple #20
0
def test_solve_trig_abs():
    assert solveset(Eq(sin(Abs(x)), 1), x, domain=S.Reals) == \
        Union(ImageSet(Lambda(n, n*pi + (-1)**n*pi/2), S.Naturals0),
              ImageSet(Lambda(n, -n*pi - (-1)**n*pi/2), S.Naturals0))
def test_random_parameters_given():
    mu = Normal('mu', 2, 3)
    meas = Normal('T', mu, 1)
    assert given(meas, Eq(mu, 5)) == Normal('T', 5, 1)
Exemple #22
0
def test_equality_subs2():
    f = Function("f")
    x = abc.x
    eq = Eq(f(x)**2, 16)
    assert bool(eq.subs(f(x), 3)) == False
    assert bool(eq.subs(f(x), 4)) == True
def test_conjugate_priors():
    mu = Normal('mu', 2, 3)
    x = Normal('x', mu, 1)
    assert isinstance(simplify(density(mu, Eq(x, y), evaluate=False)(z)),
            Integral)
Exemple #24
0
 def __eq__(self, other):
     return Eq(self.symbol, _param_to_symbol(other))
Exemple #25
0
def test_tsolve():
    assert solve(exp(x) - 3, x) == [log(3)]
    assert set(solve((a * x + b) * (exp(x) - 3), x)) == set([-b / a, log(3)])
    assert solve(cos(x) - y, x) == [acos(y)]
    assert solve(2 * cos(x) - y, x) == [acos(y / 2)]
    assert solve(Eq(cos(x), sin(x)), x) == [-3 * pi / 4, pi / 4]

    assert set(solve(exp(x) + exp(-x) - y, x)) == set([
        log(y / 2 - sqrt(y**2 - 4) / 2),
        log(y / 2 + sqrt(y**2 - 4) / 2),
    ])
    assert solve(exp(x) - 3, x) == [log(3)]
    assert solve(Eq(exp(x), 3), x) == [log(3)]
    assert solve(log(x) - 3, x) == [exp(3)]
    assert solve(sqrt(3 * x) - 4, x) == [Rational(16, 3)]
    assert solve(3**(x + 2), x) == []
    assert solve(3**(2 - x), x) == []
    assert solve(x + 2**x, x) == [-LambertW(log(2)) / log(2)]
    assert solve(3 * x + 5 + 2**(-5 * x + 3), x) in [
        [
            -((25 * log(2) - 3 * LambertW(-10240 * 2**
                                          (Rational(1, 3)) * log(2) / 3)) /
              (15 * log(2)))
        ],
        [
            Rational(-5, 3) +
            LambertW(log(2**(-10240 * 2**(Rational(1, 3)) / 3))) / (5 * log(2))
        ],
        [
            -Rational(5, 3) +
            LambertW(-10240 * 2**Rational(1, 3) * log(2) / 3) / (5 * log(2))
        ],
        [(-25 * log(2) +
          3 * LambertW(-10240 * 2**(Rational(1, 3)) * log(2) / 3)) /
         (15 * log(2))],
        [
            -((25 * log(2) - 3 * LambertW(-10240 * 2**
                                          (Rational(1, 3)) * log(2) / 3))) /
            (15 * log(2))
        ],
        [
            -(25 * log(2) -
              3 * LambertW(log(2**(-10240 * 2**Rational(1, 3) / 3)))) /
            (15 * log(2))
        ],
        [(25 * log(2) - 3 * LambertW(log(2**(-10240 * 2**Rational(1, 3) / 3))))
         / (-15 * log(2))]
    ]
    assert solve(5*x-1+3*exp(2-7*x), x) == \
        [Rational(1,5) + LambertW(-21*exp(Rational(3, 5))/5)/7]
    assert solve(2*x+5+log(3*x-2), x) == \
        [Rational(2,3) + LambertW(2*exp(-Rational(19, 3))/3)/2]
    assert solve(3 * x + log(4 * x), x) == [LambertW(Rational(3, 4)) / 3]
    assert set(solve((2 * x + 8) * (8 + exp(x)),
                     x)) == set([S(-4), log(8) + pi * I])
    eq = 2 * exp(3 * x + 4) - 3
    ans = solve(eq, x)
    assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans)
    assert solve(2 * log(3 * x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4) / 3]
    assert solve(exp(x) + 1, x) == [pi * I]
    assert solve(x**2 - 2**x, x) == [2]
    assert solve(x**3 - 3**x, x) == [-3 * LambertW(-log(3) / 3) / log(3)]

    A = -7 * 2**Rational(4, 5) * 6**Rational(1, 5) * log(7) / 10
    B = -7 * 3**Rational(1, 5) * log(7) / 5

    result = solve(2 * (3 * x + 4)**5 - 6 * 7**(3 * x + 9), x)

    assert len(result) == 1 and expand(result[0]) in [
        Rational(-4, 3) - 5 / log(7) / 3 * LambertW(A),
        Rational(-4, 3) - 5 / log(7) / 3 * LambertW(B),
    ]

    assert solve(z * cos(x) - y, x) == [acos(y / z)]
    assert solve(z * cos(2 * x) - y, x) == [acos(y / z) / 2]
    assert solve(z * cos(sin(x)) - y, x) == [asin(acos(y / z))]

    assert solve(z * cos(x), x) == [acos(0)]

    # issue #1409
    assert solve(y - b * x / (a + x), x) in [[-a * y / (y - b)],
                                             [a * y / (b - y)]]
    assert solve(y - b * exp(a / x), x) == [a / log(y / b)]
    # issue #1408
    assert solve(y - b / (1 + a * x), x) in [[(b - y) / (a * y)],
                                             [-((y - b) / (a * y))]]
    # issue #1407
    assert solve(y - a * x**b, x) == [(y / a)**(1 / b)]
    # issue #1406
    assert solve(z**x - y, x) == [log(y) / log(z)]
    # issue #1405
    assert solve(2**x - 10, x) == [log(10) / log(2)]
Exemple #26
0
def test_given():
    X = Die('X', 6)
    density(X, X > 5) == {S(6): S(1)}
    where(X > 2, X > 5).as_boolean() == Eq(X.symbol, 6)
    sample(X, X > 5) == 6
Exemple #27
0
#!/usr/bin/python

from sympy import latex
from sympy import solve
from sympy import symbols

from sympy import Eq
from sympy import Rational

P, V, n, R, T = symbols('P V n R T')

igl = Eq(P * V, n * R * T)

values = {
    R : 8.3144621,
    T : 273,
    P : 101300,
    n : 1
}

answers = solve(igl.subs(values),V)
answer = answers[0]

print ""
print "The ideal gas law is ",latex(igl)
print ""
print "Where the gas constant R is {} in SI units".format(values[R])
print "Standard temperature is {} Kelvin, or 0 degrees Celsius".format(values[T])
print "Standard pressure is {} pascals, or 1 atm".format(values[P])
print ""
print "So, at standard temperature and pressure, one mole of an ideal gas"
def system_of_linear_equations_solver(sub):
    #NOTE: tests may fail due to sets being randomly ordered, but the answers are correct
    r"""System of Linear Equations Checker/Solver.

    Checks whether a given string is a system of linear equations in two variables,
    and if so, returns an explanation of how to solve it.

    Parameters
    ----------

    sub : str
        The submitted expression, as a math string, to be passed to SymPy.

    Returns
    -------

    explanation:
        False if unable to parse as linear system,
        A worked thorugh $\LaTeX$ explanation otherwise.

    Examples
    --------

    >>> system_of_linear_equations_solver("")
    False

    >>> system_of_linear_equations_solver("something abstract")
    False

    >>> system_of_linear_equations_solver("x+1")
    False

    >>> print(system_of_linear_equations_solver("x=1"))
    False

    >>> print(system_of_linear_equations_solver("a=1,b=0"))
    False

    >>> print(system_of_linear_equations_solver("a=b+1,0=a-b"))
    False

    >>> print(system_of_linear_equations_solver("x+y=0,2x-y=9,2x+y=3"))
    False

    >>> system_of_linear_equations_solver("x**2+y=1,xy=1")
    False

    >>> print(system_of_linear_equations_solver("a+2b = 1,a-b=3"))
    Let's solve the system of equations:
    \[
        \begin{align*}
            a + 2 b&=1\\
            a - b&=3
        \end{align*}
    \]
    First we multiply each equation by the coefficient of $b$ in the other equations.
    This way they will all have the same coefficient for $b$.
    \begin{align*}
        -1\left(a + 2 b\right)&=-1\left(1\right)\\
        - a - 2 b&=-1
    \end{align*}
    \begin{align*}
        2\left(a - b\right)&=2\left(3\right)\\
        2 a - 2 b&=6
    \end{align*}
    If we subtract the second equation from the first, we get:
    \begin{align*}
        - 3 a&=-7
    \end{align*}
    Since this is now an equation in one variable, we can solve it like we would
    any other linear equation.
    \begin{align*}
    \end{align*}
    Let's solve the equation:
    \[
        - 3 a = -7
    \]
    We have just one term on the left:
    The variable $a$ with coefficient $-3$.
    Divide both sides by $-3$:
    \begin{align*}
        \frac{ - 3 a }{ -3 } &=
        \frac{ -7 }{ -3 } \\
        a &= \frac{7}{3}
    \end{align*}
    The equation is in the form $a = \frac{7}{3}$;
    That is, the value of $a$ is $\frac{7}{3}$.\begin{align*}
    \end{align*}
    Plugging in $\frac{7}{3}$ for $a$ in the first equation, we can now
    solve for $b$ like we would any other linear equation.
    \begin{align*}
    \end{align*}
    Let's solve the equation:
    \[
        2 b + \frac{7}{3} = 1
    \]
    First, we subtract 7/3 from both sides:
    \begin{align*}
        (2 b + \frac{7}{3})-(7/3) &= 1-(7/3) \\
        2 b &= - \frac{4}{3}
    \end{align*}
    We have just one term on the left:
    The variable $b$ with coefficient $2$.
    Divide both sides by $2$:
    \begin{align*}
        \frac{ 2 b }{ 2 } &=
        \frac{ - \frac{4}{3} }{ 2 } \\
        b &= - \frac{2}{3}
    \end{align*}
    The equation is in the form $b = - \frac{2}{3}$;
    That is, the value of $b$ is $- \frac{2}{3}$.\begin{align*}
    \end{align*}
    Thus we have found the pair of values which satisfy the two linear equations:
    $b=- \frac{2}{3}$ and $a=\frac{7}{3}$.
    <BLANKLINE>

    >>> print(system_of_linear_equations_solver("3x+2/3y=5/2,5x-y=2"))
    Let's solve the system of equations:
    \[
        \begin{align*}
            3 x + \frac{2 y}{3}&=\frac{5}{2}\\
            5 x - y&=2
        \end{align*}
    \]
    First we multiply each equation by the coefficient of $y$ in the other equations.
    This way they will all have the same coefficient for $y$.
    \begin{align*}
        -1\left(3 x + \frac{2 y}{3}\right)&=-1\left(\frac{5}{2}\right)\\
        - 3 x - \frac{2 y}{3}&=- \frac{5}{2}
    \end{align*}
    \begin{align*}
        \frac{2}{3}\left(5 x - y\right)&=\frac{2}{3}\left(2\right)\\
        \frac{10 x}{3} - \frac{2 y}{3}&=\frac{4}{3}
    \end{align*}
    If we subtract the second equation from the first, we get:
    \begin{align*}
        - \frac{19 x}{3}&=- \frac{23}{6}
    \end{align*}
    Since this is now an equation in one variable, we can solve it like we would
    any other linear equation.
    \begin{align*}
    \end{align*}
    Let's solve the equation:
    \[
        - \frac{19 x}{3} = - \frac{23}{6}
    \]
    We have just one term on the left:
    The variable $x$ with coefficient $- \frac{19}{3}$.
    Divide both sides by $- \frac{19}{3}$:
    \begin{align*}
        \frac{ - \frac{19 x}{3} }{ - \frac{19}{3} } &=
        \frac{ - \frac{23}{6} }{ - \frac{19}{3} } \\
        x &= \frac{23}{38}
    \end{align*}
    The equation is in the form $x = \frac{23}{38}$;
    That is, the value of $x$ is $\frac{23}{38}$.\begin{align*}
    \end{align*}
    Plugging in $\frac{23}{38}$ for $x$ in the first equation, we can now
    solve for $y$ like we would any other linear equation.
    \begin{align*}
    \end{align*}
    Let's solve the equation:
    \[
        \frac{2 y}{3} + \frac{69}{38} = \frac{5}{2}
    \]
    First, we subtract 69/38 from both sides:
    \begin{align*}
        (\frac{2 y}{3} + \frac{69}{38})-(69/38) &= \frac{5}{2}-(69/38) \\
        \frac{2 y}{3} &= \frac{13}{19}
    \end{align*}
    We have just one term on the left:
    The variable $y$ with coefficient $\frac{2}{3}$.
    Divide both sides by $\frac{2}{3}$:
    \begin{align*}
        \frac{ \frac{2 y}{3} }{ \frac{2}{3} } &=
        \frac{ \frac{13}{19} }{ \frac{2}{3} } \\
        y &= \frac{39}{38}
    \end{align*}
    The equation is in the form $y = \frac{39}{38}$;
    That is, the value of $y$ is $\frac{39}{38}$.\begin{align*}
    \end{align*}
    Thus we have found the pair of values which satisfy the two linear equations:
    $y=\frac{39}{38}$ and $x=\frac{23}{38}$.
    <BLANKLINE>

    >>> print(system_of_linear_equations_solver("3a+2b=5,a+2b=3"))
    Let's solve the system of equations:
    \[
        \begin{align*}
            3 a + 2 b&=5\\
            a + 2 b&=3
        \end{align*}
    \]
    If we subtract the second equation from the first, we get:
    \begin{align*}
        4 a&=4
    \end{align*}
    Since this is now an equation in one variable, we can solve it like we would
    any other linear equation.
    \begin{align*}
    \end{align*}
    Let's solve the equation:
    \[
        4 a = 4
    \]
    We have just one term on the left:
    The variable $a$ with coefficient $4$.
    Divide both sides by $4$:
    \begin{align*}
        \frac{ 4 a }{ 4 } &=
        \frac{ 4 }{ 4 } \\
        a &= 1
    \end{align*}
    The equation is in the form $a = 1$;
    That is, the value of $a$ is $1$.\begin{align*}
    \end{align*}
    Plugging in $1$ for $a$ in the first equation, we can now
    solve for $b$ like we would any other linear equation.
    \begin{align*}
    \end{align*}
    Let's solve the equation:
    \[
        2 b + 3 = 5
    \]
    First, we subtract 3 from both sides:
    \begin{align*}
        (2 b + 3)-(3) &= 5-(3) \\
        2 b &= 2
    \end{align*}
    We have just one term on the left:
    The variable $b$ with coefficient $2$.
    Divide both sides by $2$:
    \begin{align*}
        \frac{ 2 b }{ 2 } &=
        \frac{ 2 }{ 2 } \\
        b &= 1
    \end{align*}
    The equation is in the form $b = 1$;
    That is, the value of $b$ is $1$.\begin{align*}
    \end{align*}
    Thus we have found the pair of values which satisfy the two linear equations:
    $b=1$ and $a=1$.
    <BLANKLINE>

    >>> print(system_of_linear_equations_solver("x+y=5,x+y=3"))
    Let's solve the system of equations:
    \[
        \begin{align*}
            x + y&=5\\
            x + y&=3
        \end{align*}
    \]
    If we subtract the second equation from the first, we get:
    \begin{align*}
        0&=2
    \end{align*}
    But these values aren't equal, so there are no solutions to this system of equations.
    <BLANKLINE>

    >>> print(system_of_linear_equations_solver("x+y=5,2x+2y=10"))
    Let's solve the system of equations:
    \[
        \begin{align*}
            x + y&=5\\
            2 x + 2 y&=10
        \end{align*}
    \]
    First we multiply each equation by the coefficient of $y$ in the other equations.
    This way they will all have the same coefficient for $y$.
    \begin{align*}
        2\left(x + y\right)&=2\left(5\right)\\
        2 x + 2 y&=10
    \end{align*}
    If we subtract the second equation from the first, we get:
    \begin{align*}
        0&=0
    \end{align*}
    In this case, both variables ended up cancelling out since the two
    equations were scalar multiples of each other. Thus there are an
    infinite number of solutions to this system of equations.
    <BLANKLINE>
    """

    #separate the equations at the comma
    eqns = sub.split(",")
    if len(eqns) != 2:
        return False
    # Check if SymPy can parse the expressions as equations
    try:
        expr = []
        for i in eqns:
            expr.append(
                parse_expr(i,
                           transformations=(*standard_transformations,
                                            implicit_multiplication,
                                            convert_equals_signs)))
    except:
        return False

    # Verify the structure of the equations

    # Check if the expressions are in 2 variables
    variables = set()
    for i in expr:
        variables.update(i.free_symbols)
        if len(i.free_symbols) != 2:
            return False
    if len(variables) != 2:
        return False
    x, y, = variables

    # Check if they are linear equations
    for i in expr:
        if not isinstance(i, Eq):
            return False
        if not i.rhs.is_constant():
            return False
        if not i.lhs.diff(x).is_constant():
            return False
        if not i.lhs.diff(y).is_constant():
            return False

    # Now that we know the structure of the equations,
    # we can turn them into a worked-through solution.

    lhs = []
    rhs = []
    coeff = []
    for i in expr:
        lhs.append(i.lhs)
        rhs.append(i.rhs)
        coeff.append((lhs[-1].coeff(x), lhs[-1].coeff(y)))

    explanation = dedent("""\
    Let's solve the system of equations:
    \\[
        \\begin{{align*}}
            {left1}&={right1}\\\\
            {left2}&={right2}
        \\end{{align*}}
    \\]
    """.format(left1=latex(lhs[0]),
               left2=latex(lhs[1]),
               right1=latex(rhs[0]),
               right2=latex(rhs[1])))

    new_coeff = [1]
    new_coeff.extend(new_coeff[-1] * i[0] for i in coeff)
    new_coeff = new_coeff[-1]
    new_lhs = [lhs[i] * new_coeff / coeff[i][0] for i in range(len(coeff))]
    new_rhs = [rhs[i] * new_coeff / coeff[i][0] for i in range(len(coeff))]

    if any(i[0] != coeff[0][0] for i in coeff):
        explanation += dedent("""\
        First we multiply each equation by the coefficient of ${variable}$ in the other equations.
        This way they will all have the same coefficient for ${variable}$.
        """.format(variable=latex(x)))

        if coeff[1][0] != 1:
            explanation += dedent("""\
            \\begin{{align*}}
                {coeff1}\\left({left1}\\right)&={coeff1}\\left({right1}\\right)\\\\
                {new_left1}&={new_right1}
            \\end{{align*}}
            """.format(variable=latex(x),
                       coeff1=latex(new_coeff / coeff[0][0]),
                       left1=latex(lhs[0]),
                       new_left1=latex(new_lhs[0]),
                       right1=latex(rhs[0]),
                       new_right1=latex(new_rhs[0])))

        if coeff[0][0] != 1:
            explanation += dedent("""\
            \\begin{{align*}}
                {coeff2}\\left({left2}\\right)&={coeff2}\\left({right2}\\right)\\\\
                {new_left2}&={new_right2}
            \\end{{align*}}
            """.format(variable=latex(x),
                       coeff2=latex(new_coeff / coeff[1][0]),
                       left2=latex(lhs[1]),
                       new_left2=latex(new_lhs[1]),
                       right2=latex(rhs[1]),
                       new_right2=latex(new_rhs[1])))

    combined_lhs = new_lhs[0] - new_lhs[1]
    combined_rhs = new_rhs[0] - new_rhs[1]

    explanation += dedent("""\
    If we subtract the second equation from the first, we get:
    \\begin{{align*}}
        {left}&={right}
    \\end{{align*}}
    """.format(left=latex(combined_lhs), right=latex(combined_rhs)))

    if combined_lhs.is_constant():
        if (combined_lhs - combined_rhs).is_zero:
            explanation += dedent("""\
            In this case, both variables ended up cancelling out since the two
            equations were scalar multiples of each other. Thus there are an
            infinite number of solutions to this system of equations.
            """)
        else:
            explanation += dedent("""\
            But these values aren't equal, so there are no solutions to this system of equations.
            """)
        return explanation

    y_explanation, y_value = linear_logic(Eq(combined_lhs, combined_rhs), y)
    x_explanation, x_value = zip(
        *[linear_logic(i.subs(y, y_value), x) for i in expr])

    explanation += dedent("""\
    Since this is now an equation in one variable, we can solve it like we would
    any other linear equation.
    \\begin{{align*}}
    \\end{{align*}}
    """.format())
    explanation += y_explanation
    explanation += dedent("""\
    \\begin{{align*}}
    \\end{{align*}}
    Plugging in ${value}$ for ${variable}$ in the first equation, we can now
    solve for ${other}$ like we would any other linear equation.
    \\begin{{align*}}
    \\end{{align*}}
    """.format(value=latex(y_value), variable=latex(y), other=latex(x)))
    explanation += x_explanation[0]
    explanation += dedent("""\
    \\begin{{align*}}
    \\end{{align*}}
    Thus we have found the pair of values which satisfy the two linear equations:
    ${var1}={val1}$ and ${var2}={val2}$.
    """.format(var1=latex(x),
               var2=latex(y),
               val1=latex(x_value[0]),
               val2=latex(y_value)))

    assert all(
        i == x_value[0] for i in x_value
    ), "Deduced value for {x} should be equal for all expressions".format(x=x)
    return explanation
Exemple #29
0
from sympy import symbols, Eq, Derivative, Integral, log, solve, exp, ccode

globals().update(symbs)  # see common.py: x, Y, Z, k_f, ...

eqs = []

# rate of x

rate_expr = k_f * (Y - x) * (Z - x)
rate_eq = Eq(Derivative(x, t), rate_expr)
eqs.append(rate_eq)

integrand = k_f / rate_expr
inte_eq_lhs = Integral(integrand.subs({x: chi}), (chi, 0, x))
inte_eq_rhs = Integral(k_f, (tau, 0, t))
inte_eq = Eq(inte_eq_lhs, inte_eq_rhs)
eqs.append(inte_eq)

expl_in_x_eq = inte_eq.doit(manual=True).simplify()
eqs.append(expl_in_x_eq)

expl_in_t_eq = Eq(x, solve(expl_in_x_eq, x)[0])

alt_expl_in_t = Y * (1 - exp(k_f * t * (Z - Y))) / (Y / Z - exp(k_f * t * (Z - Y)))
assert (alt_expl_in_t - expl_in_t_eq.rhs).simplify() == 0
alt_expl_in_t_eq = Eq(x, alt_expl_in_t)
eqs.append(alt_expl_in_t_eq)


def main():
    # GENERATES WITHOUT ARGUMENTS: irrev_binary_1.tex irrev_binary_2.tex irrev_binary_rate.tex irrev_binary_k_b.c irrev_binary_K_eq.c
Exemple #30
0
def test_distribution_over_equality():
    assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3))
    assert Sum(Eq(f(x), x**2), (x, 0, y)) == \
        Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
Exemple #31
0
    def set_free_surface(self, d, b, side, algo='robertsson'):
        """
        set free surface boundary condition to boundary d, at index b
        :param indices: list of indices, e.g. [t,x,y,z] for 3D
        :param d: direction of the boundary surface normal
        :param b: location of the boundary (index)
        :param algo: which algorithm to use to compute ghost cells
        algo == 'robertsson' [1]: setting all velocities at ghost cells to zero
        algo == 'levander' [2]: only valid for 4th spatial order. using 2nd order FD approximation for velocities
        side: lower boundary (0) or upper boundary (1)
        e.g. set_free_surface([t,x,y,z],1,2,0)
        set y-z plane at x=2 to be lower free surface
        ghost cells are calculated using reflection of stress fields
        store the code to populate ghost cells to self.bc
        [1] Robertsson, Johan OA. "A numerical free-surface condition for elastic/viscoelastic finite-difference modeling in the presence of topography." Geophysics 61.6 (1996): 1921-1934.
        [2] Levander, Alan R. "Fourth-order finite-difference P-SV seismograms." Geophysics 53.11 (1988): 1425-1436.
        """
        idx = list(self.indices)

        if d not in self.direction:
            if (not algo == 'levander') or (not self.direction[0] == self.direction[1]):
                # shear stress, e.g. Tyz no need to recalculate at x boundary (only depends on dV/dz and dW/dy)
                self.bc[d][side] = []
                return
            else:
                # normal stress, need to recalcuate Tyy, Tzz at x boundary
                expr = self.dt
                derivatives = get_all_objects(expr, DDerivative)
                for deriv in derivatives:
                    if deriv.var == idx[d]:
                        # replacing dx at x boundary with dy, dz terms
                        expr2 = self.sfields[d].dt
                        deriv_0 = deriv
                        deriv_sub = solve(expr2, deriv)[0]
                        break
                expr = expr.subs(deriv_0, deriv_sub)
                derivatives = get_all_objects(expr, DDerivative)
                # substitution dictionary
                dict1 = {}
                for deriv in derivatives:
                    dict1[deriv] = deriv.fd[4]
                expr = expr.subs(dict1)
                eq = Eq(self.d[0][1].fd[2], expr)
                eq = eq.subs(idx[d], b)
                t = idx[0]
                idx[0] = t+hf
                idx[d] = b
                # eq = eq.subs(t, t+hf)
                # idx[0] = t+1
                # idx[d] = b
                # solve for Txx(t+1/2)
                lhs = self[idx]
                rhs = solve(eq, lhs)[0]
                rhs = self.align(rhs)
                # change t+1/2 to t+1
                lhs = lhs.subs(t, t+hf)
                rhs = rhs.subs(t, t+hf)
                eq2 = Eq(lhs, rhs)
                self.bc[d][side] = [eq2]
                return

        # use anti-symmetry to ensure stress at boundary=0
        # this applies for all algorithms

        idx = list(self.indices)  # ghost cell
        idx2 = list(self.indices)  # cell inside domain

        if not self.staggered[d]:
            # if not staggered, assign T[d]=0, assign T[d-1]=-T[d+1]
            idx[d] = b
            idx2[d] = b
            eq1 = Eq(self[idx])
        else:
            # if staggered, assign T[d-1/2]=T[d+1/2], assign T[d-3/2]=T[d+3/2]
            idx[d] = b - (1-side)
            idx2[d] = idx[d] + (-1)**side
            eq1 = Eq(self[idx], -self[idx2])
        eq1 = eq1.subs(idx[0], idx[0]+1)
        self.bc[d][side] = [eq1]

        for depth in range(self.order[d]/2-1):
            # populate ghost cells
            idx[d] -= (-1)**side
            idx2[d] += (-1)**side
            eq = Eq(self[idx], -self[idx2])
            # change t to t+1
            eq = eq.subs(idx[0], idx[0]+1)
            self.bc[d][side].append(eq)
Exemple #32
0
def test_issue_10555():
    f = Function('f')
    assert solveset(f(x) - pi/2, x, S.Reals) == \
        ConditionSet(x, Eq(2*f(x) - pi, 0), S.Reals)
Exemple #33
0
def test_conditionset_equality():
    ''' Checking equality of different representations of ConditionSet'''
    assert solveset(Eq(tan(x), y), x) == ConditionSet(x, Eq(tan(x), y),
                                                      S.Complexes)
Exemple #34
0
def test_unrad():
    s = symbols('s', cls=Dummy)

    # checkers to deal with possibility of answer coming
    # back with a sign change (cf issue 2104)
    def check(rv, ans):
        rv, ans = list(rv), list(ans)
        rv[0] = rv[0].expand()
        ans[0] = ans[0].expand()
        return rv[0] in [ans[0], -ans[0]] and rv[1:] == ans[1:]

    def s_check(rv, ans):
        # get the dummy
        rv = list(rv)
        d = rv[0].atoms(Dummy)
        reps = zip(d, [s] * len(d))
        # replace s with this dummy
        rv = (rv[0].subs(reps).expand(), [
            (p[0].subs(reps), p[1].subs(reps)) for p in rv[1]
        ], [a.subs(reps) for a in rv[2]])
        ans = (ans[0].subs(reps).expand(), [
            (p[0].subs(reps), p[1].subs(reps)) for p in ans[1]
        ], [a.subs(reps) for a in ans[2]])
        return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \
               str(rv[1:]) == str(ans[1:])

    assert check(unrad(sqrt(x)), (x, [], []))
    assert check(unrad(sqrt(x) + 1), (x - 1, [], []))
    assert s_check(unrad(sqrt(x) + x**Rational(1, 3) + 2),
                   (2 + s**2 + s**3, [(s, x - s**6)], []))
    assert check(unrad(sqrt(x) * x**Rational(1, 3) + 2), (x**5 - 64, [], []))
    assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)),
                 (x**3 - (x + 1)**2, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2 * x)),
                 (-2 * sqrt(2) * x - 2 * x + 1, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + 2), (16 * x - 9, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)),
                 (-4 * x + 5 * x**2, [], []))
    assert check(unrad(a * sqrt(x) + b * sqrt(x) + c * sqrt(y) + d * sqrt(y)),
                 ((a * sqrt(x) + b * sqrt(x))**2 -
                  (c * sqrt(y) + d * sqrt(y))**2, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x)), (2 * x - 1, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) - 3),
                 (36 * x + (2 * x - 10)**2 - 36, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)),
                 (-5 * x**2 + 2 * x - 1, [], []))
    assert check(
        unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3),
        (-25 * x**4 - 376 * x**3 - 1256 * x**2 + 2272 * x - 784, [], []))
    assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2 * x)),
                 (-41 * x**4 - 40 * x**3 - 232 * x**2 + 160 * x - 16, [], []))
    assert check(unrad(sqrt(x) + sqrt(x + 1)), (S(1), [], []))

    eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x))
    assert check(unrad(eq), (16 * x**3 - 9 * x**2, [], []))
    assert solve(eq, check=False) == [0, S(9) / 16]
    assert solve(eq) == []
    # but this one really does have those solutions
    assert solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x))) == [0, S(9) / 16]
    '''real_root changes the value of the result if the solution is
    simplified; `a` in the text below is the root that is not 4/5:
    >>> eq
    sqrt(x) + sqrt(-x + 1) + sqrt(x + 1) - 6*sqrt(5)/5
    >>> eq.subs(x, a).n()
    -0.e-123 + 0.e-127*I
    >>> real_root(eq.subs(x, a)).n()
    -0.e-123 + 0.e-127*I
    >>> (eq.subs(x,simplify(a))).n()
    -0.e-126
    >>> real_root(eq.subs(x, simplify(a))).n()
    0.194825975605452 + 2.15093623885838*I

    >>> sqrt(x).subs(x, real_root(a)).n()
    0.809823827278194 - 0.e-25*I
    >>> sqrt(x).subs(x, (a)).n()
    0.809823827278194 - 0.e-25*I
    >>> sqrt(x).subs(x, simplify(a)).n()
    0.809823827278194 - 5.32999467690853e-25*I
    >>> sqrt(x).subs(x, real_root(simplify(a))).n()
    0.49864610868139 + 1.44572604257047*I
    '''
    eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6 * sqrt(5) / 5)
    ra = S('''-1484/375 - 4*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 +
    114*sqrt(12657)/78125)**(1/3) - 172564/(140625*(-1/2 +
    sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3))''')
    rb = S(4) / 5
    ans = solve(sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6 * sqrt(5) / 5)
    assert all(abs(eq.subs(x, i).n()) < 1e-10 for i in (ra, rb)) and \
        len(ans) == 2 and \
        sorted([i.n(chop=True) for i in ans]) == \
        sorted([i.n(chop=True) for i in (ra, rb)])

    ans = solve(sqrt(x) + sqrt(x + 1) - \
                 sqrt(1 - x) - sqrt(2 + x))
    assert len(ans) == 1 and NS(ans[0])[:4] == '0.73'
    # the fence optimization problem
    # http://code.google.com/p/sympy/issues/detail?id=1694#c159
    F = Symbol('F')
    eq = F - (2 * x + 2 * y + sqrt(x**2 + y**2))
    X = solve(eq, x, hint='minimal')[0]
    Y = solve((x * y).subs(x, X).diff(y), y, simplify=False, minimal=True)
    ans = 2 * F / 7 - sqrt(2) * F / 14
    assert any((a - ans).expand().is_zero for a in Y)

    raises(ValueError,
           lambda: unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3))
    raises(ValueError,
           lambda: unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2 * sqrt(y)))
    # same as last but consider only y
    assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2 * sqrt(y), y),
                 (4 * y - (sqrt(x) + (x + 1)**(S(1) / 3))**2, [], []))
    assert check(unrad(sqrt(x / (1 - x)) + (x + 1)**Rational(1, 3)),
                 (x**3 / (-x + 1)**3 - (x + 1)**2, [], [(-x + 1)**3]))
    # same as last but consider only y; no y-containing denominators now
    assert s_check(unrad(sqrt(x / (1 - x)) + 2 * sqrt(y), y),
                   (x / (-x + 1) - 4 * y, [], []))
    assert check(unrad(sqrt(x) * sqrt(1 - x) + 2, x),
                 (x * (-x + 1) - 4, [], []))

    # http://tutorial.math.lamar.edu/
    #        Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a
    assert solve(Eq(x, sqrt(x + 6))) == [3]
    assert solve(Eq(x + sqrt(x - 4), 4)) == [4]
    assert solve(Eq(1, x + sqrt(2 * x - 3))) == []
    assert solve(Eq(sqrt(5 * x + 6) - 2, x)) == [-1, 2]
    assert solve(Eq(sqrt(2 * x - 1) - sqrt(x - 4), 2)) == [5, 13]
    assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6]
    # http://www.purplemath.com/modules/solverad.htm
    assert solve((2 * x - 5)**Rational(1, 3) - 3) == [16]
    assert solve((x**3 - 3 * x**2)**Rational(1, 3) + 1 - x) == []
    assert solve(x + 1 - (x**4 + 4*x**3 - x)**Rational(1, 4)) == \
        [-S(1)/2, -S(1)/3]
    assert solve(sqrt(2 * x**2 - 7) - (3 - x)) == [-8, 2]
    assert solve(sqrt(2 * x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0]
    assert solve(sqrt(x + 4) + sqrt(2 * x - 1) - 3 * sqrt(x - 1)) == [5]
    assert solve(sqrt(x) * sqrt(x - 7) - 12) == [16]
    assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4]
    assert solve(sqrt(9 * x**2 + 4) - (3 * x + 2)) == [0]
    assert solve(sqrt(x) - 2 - 5) == [49]
    assert solve(sqrt(x - 3) - sqrt(x) - 3) == []
    assert solve(sqrt(x - 1) - x + 7) == [10]
    assert solve(sqrt(x - 2) - 5) == [27]
    assert solve(sqrt(17 * x - sqrt(x**2 - 5)) - 7) == [3]
    assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == []

    # don't posify the expession in unrad and use _mexpand
    z = sqrt(2 * x + 1) / sqrt(x) - sqrt(2 + 1 / x)
    p = posify(z)[0]
    assert solve(p) == []
    assert solve(z) == []
    assert solve(z + 6 * I) == [-S(1) / 11]
    assert solve(p + 6 * I) == []
Exemple #35
0
def plot_implicit(expr,
                  x_var=None,
                  y_var=None,
                  adaptive=True,
                  depth=0,
                  points=300,
                  line_color="blue",
                  show=True,
                  **kwargs):
    """A plot function to plot implicit equations / inequalities.

    Arguments
    =========

    - ``expr`` : The equation / inequality that is to be plotted.
    - ``x_var`` (optional) : symbol to plot on x-axis or tuple giving symbol
      and range as ``(symbol, xmin, xmax)``
    - ``y_var`` (optional) : symbol to plot on y-axis or tuple giving symbol
      and range as ``(symbol, ymin, ymax)``

    If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
    expression will be assigned in the order they are sorted.

    The following keyword arguments can also be used:

    - ``adaptive`` Boolean. The default value is set to True. It has to be
        set to False if you want to use a mesh grid.

    - ``depth`` integer. The depth of recursion for adaptive mesh grid.
        Default value is 0. Takes value in the range (0, 4).

    - ``points`` integer. The number of points if adaptive mesh grid is not
        used. Default value is 300.

    - ``show`` Boolean. Default value is True. If set to False, the plot will
        not be shown. See ``Plot`` for further information.

    - ``title`` string. The title for the plot.

    - ``xlabel`` string. The label for the x-axis

    - ``ylabel`` string. The label for the y-axis

    Aesthetics options:

    - ``line_color``: float or string. Specifies the color for the plot.
        See ``Plot`` to see how to set color for the plots.
        Default value is "Blue"

    plot_implicit, by default, uses interval arithmetic to plot functions. If
    the expression cannot be plotted using interval arithmetic, it defaults to
    a generating a contour using a mesh grid of fixed number of points. By
    setting adaptive to False, you can force plot_implicit to use the mesh
    grid. The mesh grid method can be effective when adaptive plotting using
    interval arithmetic, fails to plot with small line width.

    Examples
    ========

    Plot expressions:

    .. plot::
        :context: reset
        :format: doctest
        :include-source: True

        >>> from sympy import plot_implicit, cos, sin, symbols, Eq, And
        >>> x, y = symbols('x y')

    Without any ranges for the symbols in the expression:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))

    With the range for the symbols:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p2 = plot_implicit(
        ...     Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))

    With depth of recursion as argument:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p3 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)

    Using mesh grid and not using adaptive meshing:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p4 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
        ...     adaptive=False)

    Using mesh grid without using adaptive meshing with number of points
    specified:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p5 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
        ...     adaptive=False, points=400)

    Plotting regions:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p6 = plot_implicit(y > x**2)

    Plotting Using boolean conjunctions:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p7 = plot_implicit(And(y > x, y > -x))

    When plotting an expression with a single variable (y - 1, for example),
    specify the x or the y variable explicitly:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p8 = plot_implicit(y - 1, y_var=y)
        >>> p9 = plot_implicit(x - 1, x_var=x)
    """
    has_equality = False  # Represents whether the expression contains an Equality,

    #GreaterThan or LessThan

    def arg_expand(bool_expr):
        """
        Recursively expands the arguments of an Boolean Function
        """
        for arg in bool_expr.args:
            if isinstance(arg, BooleanFunction):
                arg_expand(arg)
            elif isinstance(arg, Relational):
                arg_list.append(arg)

    arg_list = []
    if isinstance(expr, BooleanFunction):
        arg_expand(expr)

        #Check whether there is an equality in the expression provided.
        if any(
                isinstance(e, (Equality, GreaterThan, LessThan))
                for e in arg_list):
            has_equality = True

    elif not isinstance(expr, Relational):
        expr = Eq(expr, 0)
        has_equality = True
    elif isinstance(expr, (Equality, GreaterThan, LessThan)):
        has_equality = True

    xyvar = [i for i in (x_var, y_var) if i is not None]
    free_symbols = expr.free_symbols
    range_symbols = Tuple(*flatten(xyvar)).free_symbols
    undeclared = free_symbols - range_symbols
    if len(free_symbols & range_symbols) > 2:
        raise NotImplementedError("Implicit plotting is not implemented for "
                                  "more than 2 variables")

    #Create default ranges if the range is not provided.
    default_range = Tuple(-5, 5)

    def _range_tuple(s):
        if isinstance(s, Symbol):
            return Tuple(s) + default_range
        if len(s) == 3:
            return Tuple(*s)
        raise ValueError('symbol or `(symbol, min, max)` expected but got %s' %
                         s)

    if len(xyvar) == 0:
        xyvar = list(_sort_gens(free_symbols))
    var_start_end_x = _range_tuple(xyvar[0])
    x = var_start_end_x[0]
    if len(xyvar) != 2:
        if x in undeclared or not undeclared:
            xyvar.append(Dummy('f(%s)' % x.name))
        else:
            xyvar.append(undeclared.pop())
    var_start_end_y = _range_tuple(xyvar[1])

    #Check whether the depth is greater than 4 or less than 0.
    if depth > 4:
        depth = 4
    elif depth < 0:
        depth = 0

    series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
                                     has_equality, adaptive, depth, points,
                                     line_color)

    #set the x and y limits
    kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
    kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
    # set the x and y labels
    kwargs.setdefault('xlabel', var_start_end_x[0].name)
    kwargs.setdefault('ylabel', var_start_end_y[0].name)
    p = Plot(series_argument, **kwargs)
    if show:
        p.show()
    return p
 def solve_constants(eq, ics, d_ics):
     udiff = Eq(d_ics[0][1], eq.rhs.diff(t))
     system = [eq.subs(ics), udiff.subs(t, 0)]
     consts = solve(system, [C1, C2])
     return eq.subs(consts)
Exemple #37
0
def test_dice():
    # TODO: Make iid method!
    X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6)
    a, b, t, p = symbols('a b t p')

    assert E(X) == 3 + S.Half
    assert variance(X) == Rational(35, 12)
    assert E(X + Y) == 7
    assert E(X + X) == 7
    assert E(a * X + b) == a * E(X) + b
    assert variance(X + Y) == variance(X) + variance(Y) == cmoment(X + Y, 2)
    assert variance(X + X) == 4 * variance(X) == cmoment(X + X, 2)
    assert cmoment(X, 0) == 1
    assert cmoment(4 * X, 3) == 64 * cmoment(X, 3)
    assert covariance(X, Y) is S.Zero
    assert covariance(X, X + Y) == variance(X)
    assert density(Eq(cos(X * S.Pi), 1))[True] == S.Half
    assert correlation(X, Y) == 0
    assert correlation(X, Y) == correlation(Y, X)
    assert smoment(X + Y, 3) == skewness(X + Y)
    assert smoment(X + Y, 4) == kurtosis(X + Y)
    assert smoment(X, 0) == 1
    assert P(X > 3) == S.Half
    assert P(2 * X > 6) == S.Half
    assert P(X > Y) == Rational(5, 12)
    assert P(Eq(X, Y)) == P(Eq(X, 1))

    assert E(X, X > 3) == 5 == moment(X, 1, 0, X > 3)
    assert E(X, Y > 3) == E(X) == moment(X, 1, 0, Y > 3)
    assert E(X + Y, Eq(X, Y)) == E(2 * X)
    assert moment(X, 0) == 1
    assert moment(5 * X, 2) == 25 * moment(X, 2)
    assert quantile(X)(p) == Piecewise((nan, (p > 1) | (p < 0)),\
        (S.One, p <= Rational(1, 6)), (S(2), p <= Rational(1, 3)), (S(3), p <= S.Half),\
        (S(4), p <= Rational(2, 3)), (S(5), p <= Rational(5, 6)), (S(6), p <= 1))

    assert P(X > 3, X > 3) is S.One
    assert P(X > Y, Eq(Y, 6)) is S.Zero
    assert P(Eq(X + Y, 12)) == Rational(1, 36)
    assert P(Eq(X + Y, 12), Eq(X, 6)) == Rational(1, 6)

    assert density(X + Y) == density(Y + Z) != density(X + X)
    d = density(2 * X + Y**Z)
    assert d[S(22)] == Rational(1, 108) and d[S(4100)] == Rational(
        1, 216) and S(3130) not in d

    assert pspace(X).domain.as_boolean() == Or(
        *[Eq(X.symbol, i) for i in [1, 2, 3, 4, 5, 6]])

    assert where(X > 3).set == FiniteSet(4, 5, 6)

    assert characteristic_function(X)(t) == exp(6 * I * t) / 6 + exp(
        5 * I * t) / 6 + exp(4 * I * t) / 6 + exp(3 * I * t) / 6 + exp(
            2 * I * t) / 6 + exp(I * t) / 6
    assert moment_generating_function(X)(
        t) == exp(6 * t) / 6 + exp(5 * t) / 6 + exp(4 * t) / 6 + exp(
            3 * t) / 6 + exp(2 * t) / 6 + exp(t) / 6
    assert median(X) == FiniteSet(3, 4)
    D = Die('D', 7)
    assert median(D) == FiniteSet(4)
    # Bayes test for die
    BayesTest(X > 3, X + Y < 5)
    BayesTest(Eq(X - Y, Z), Z > Y)
    BayesTest(X > 3, X > 2)

    # arg test for die
    raises(ValueError, lambda: Die('X', -1))  # issue 8105: negative sides.
    raises(ValueError, lambda: Die('X', 0))
    raises(ValueError, lambda: Die('X', 1.5))  # issue 8103: non integer sides.

    # symbolic test for die
    n, k = symbols('n, k', positive=True)
    D = Die('D', n)
    dens = density(D).dict
    assert dens == Density(DieDistribution(n))
    assert set(dens.subs(n, 4).doit().keys()) == {1, 2, 3, 4}
    assert set(dens.subs(n, 4).doit().values()) == {Rational(1, 4)}
    k = Dummy('k', integer=True)
    assert E(D).dummy_eq(Sum(Piecewise((k / n, k <= n), (0, True)), (k, 1, n)))
    assert variance(D).subs(n, 6).doit() == Rational(35, 12)

    ki = Dummy('ki')
    cumuf = cdf(D)(k)
    assert cumuf.dummy_eq(
        Sum(Piecewise((1 / n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, k)))
    assert cumuf.subs({n: 6, k: 2}).doit() == Rational(1, 3)

    t = Dummy('t')
    cf = characteristic_function(D)(t)
    assert cf.dummy_eq(
        Sum(Piecewise((exp(ki * I * t) / n, (ki >= 1) & (ki <= n)), (0, True)),
            (ki, 1, n)))
    assert cf.subs(
        n,
        3).doit() == exp(3 * I * t) / 3 + exp(2 * I * t) / 3 + exp(I * t) / 3
    mgf = moment_generating_function(D)(t)
    assert mgf.dummy_eq(
        Sum(Piecewise((exp(ki * t) / n, (ki >= 1) & (ki <= n)), (0, True)),
            (ki, 1, n)))
    assert mgf.subs(n,
                    3).doit() == exp(3 * t) / 3 + exp(2 * t) / 3 + exp(t) / 3
Exemple #38
0
    def set_free_surface(self, d, b, side, algo='robertsson'):
        """
        - set free surface boundary condition to boundary d, at index b
        :param d: direction of the boundary surface normal
        :param b: location of the boundary (index)
        :param side: lower boundary (0) or upper boundary (1)
        :param algo: which algorithm to use to compute ghost cells
        algo == 'robertsson' [1]: setting all velocities at ghost cells to zero
        algo == 'levander' [2]: only valid for 4th spatial order. using 2nd order FD approximation for velocities
        - e.g. set_free_surface([t,x,y,z],1,2,0)
        set y-z plane at x=2 to be lower free surface
        - ghost cells are calculated using reflection of stress fields
        - store the symbolic equations to populate ghost cells in self.bc
        [1] Robertsson, Johan OA. "A numerical free-surface condition for elastic/viscoelastic finite-difference modeling in the presence of topography." Geophysics 61.6 (1996): 1921-1934.
        [2] Levander, Alan R. "Fourth-order finite-difference P-SV seismograms." Geophysics 53.11 (1988): 1425-1436.
        """
        if algo == 'levander':
            # use this stress field to solve for ghost cell expression
            field = self.sfields[d]
            expr = field.dt
            idx = list(self.indices)
            # create substituion dictionary
            dict1 = {}
            derivatives = get_all_objects(expr, DDerivative)
            for deriv in derivatives:
                # using 2nd order approximation
                dict1[deriv] = deriv.fd[2]
            expr = expr.subs(dict1)
            if self.staggered[d]:
                # if staggered, solve ghost cell using T'[b]=0 (e.g. W at z surface, using Tzz)
                eq = Eq(expr)
                shift = hf
                t = b - hf  # real boundary location
            else:
                # if not staggered, solve ghost cell using T'[b-1/2]=T'[b+1/2] (e.g. U at z surface, using Txz)
                eq = Eq(expr.subs(idx[d], idx[d]-hf),
                        expr.subs(idx[d], idx[d]+hf))
                shift = 1
                t = b

            idx[d] -= ((-1)**side)*shift
            lhs = self[idx]
            rhs = solve(eq, lhs)[0]
            lhs = lhs.subs(self.indices[d], t)
            rhs = self.align(rhs.subs(self.indices[d], t))

            # change ti to t+1
            lhs = lhs.subs(idx[0], idx[0]+1)
            rhs = rhs.subs(idx[0], idx[0]+1)

            self.bc[d][side] = [Eq(lhs, rhs)]
        elif algo == 'robertsson':
            idx = list(self.indices)
            if self.staggered[d]:
                # e.g. W at z boundary
                idx[d] = b - (1-side)
            else:
                # e.g. U at z boundary
                idx[d] = b - (-1)**side
            eq = Eq(self[idx])
            eq = eq.subs(idx[0], idx[0]+1)
            self.bc[d][side] = [eq]
            # populate all ghost cells
            for depth in range(self.order[d]/2-1):
                idx[d] -= (-1)**side
                eq = Eq(self[idx])
                eq = eq.subs(idx[0], idx[0]+1)
                self.bc[d][side].append(eq)
        else:
            raise ValueError('Unknown boundary condition algorithm')
Exemple #39
0
def circular_random_walk():

    fig, axs = plt.subplots()
    plt.xlabel("Position - x")
    plt.ylabel("Position - y")

    Radius = 100
    step_addition_A = 0
    step_addition_B = 0

    #####
    ##Choosing initial points

    r_A = np.random.uniform(0, Radius)
    r_B = np.random.uniform(0, Radius)

    thet_A = np.random.uniform(0, 2 * np.pi)
    thet_B = np.random.uniform(0, 2 * np.pi)

    x_A = r_A * np.cos(thet_A)
    y_A = r_A * np.sin(thet_A)

    x_B = r_B * np.cos(thet_B)
    y_B = r_B * np.sin(thet_B)

    ####

    randomWalk_x_A = [x_A]
    randomWalk_y_A = [y_A]

    randomWalk_x_B = [x_B]
    randomWalk_y_B = [y_B]

    flag_A_ref = False
    flag_B_ref = False
    steps = 0

    counter = 0

    while True:
        angle_A = np.random.uniform(0, 2 * np.pi, size=1)
        angle_B = np.random.uniform(0, 2 * np.pi, size=1)

        distance_A = np.random.uniform(0, 1, size=1)
        distance_B = np.random.uniform(0, 1, size=1)

        x_coordinate_A = distance_A[0] * np.cos(angle_A[0])
        y_coordinate_A = distance_A[0] * np.sin(angle_A[0])

        x_coordinate_B = distance_B[0] * np.cos(angle_B[0])
        y_coordinate_B = distance_B[0] * np.sin(angle_B[0])

        new_x_A = randomWalk_x_A[-1] + x_coordinate_A
        new_y_A = randomWalk_y_A[-1] + y_coordinate_A

        new_x_B = randomWalk_x_B[-1] + x_coordinate_B
        new_y_B = randomWalk_y_B[-1] + y_coordinate_B

        distance_from_origin_A = ((new_x_A)**2 + (new_y_A)**2)**(0.5)
        distance_from_origin_B = ((new_x_B)**2 + (new_y_B)**2)**(0.5)

        while distance_from_origin_A >= (Radius):

            new_x_A = '%.3f' % (new_x_A)
            new_y_A = '%.3f' % (new_y_A)

            old_x_A = '%.3f' % (randomWalk_x_A[-1])
            old_y_A = '%.3f' % (randomWalk_y_A[-1])

            p1, p2 = Point(old_x_A, old_y_A), Point(new_x_A, new_y_A)

            if p1.equals(p2):
                randomWalk_x_A.append(old_x_A)
                randomWalk_y_A.append(old_y_A)

                flag_A_ref = True
                break

            line = Line(p1, p2)
            a, b, c = line.coefficients

            x, y = symbols('x,y')
            eq1 = Eq((x)**2 + (y)**2 - (Radius)**2, 0, evaluate=False)
            eq2 = Eq((a * x) + (b * y) + c, 0, evaluate=False)

            sol = solve([eq1, eq2], [x, y])

            #find the point on the circumference where our line will touch, call it circpoint

            sol1 = (sol[0][0], sol[0][1])
            sol2 = (sol[1][0], sol[1][1])

            d1 = ((p2[0] - sol1[0])**2 + (p2[1] - sol1[1])**2)**(0.5)
            d2 = ((p2[0] - sol2[0])**2 + (p2[1] - sol2[1])**2)**(0.5)

            if d1 <= d2:
                circ_point = sol[0]
            else:
                circ_point = sol[1]

            circ_point = Point(circ_point[0], circ_point[1])

            #we know the overflow amount, call that overflowed
            overflowed = p2.distance(circ_point)

            #get the vector from our curr_pos to circpoint, call it incident
            incident = np.array([circ_point[0] - p1[0], circ_point[1] - p1[1]])

            #circpoint to origin vector
            normal = np.array([circ_point[0], circ_point[1]])

            #-find the angle between incident and normal using dot product wali equation, call that theta

            if p1.equals(circ_point):
                randomWalk_x_A.append(old_x_A)
                randomWalk_y_A.append(old_y_A)

                flag_A_ref = True
                break

            dot = (circ_point[0] * incident[0]) + (circ_point[1] * incident[1])

            magnitude1 = math.sqrt(circ_point[0]**2 + circ_point[1]**2)
            magnitude2 = math.sqrt(incident[0]**2 + incident[1]**2)

            ang = dot / (magnitude1 * magnitude2)

            main_ang = math.acos(ang)

            Theta = main_ang

            if p2[0] < 0 and p2[1] > 0:  #second
                Theta = -Theta

            elif p2[0] > 0 and p2[1] > 0:  #first
                if incident[1] >= incident[0]:
                    Theta = -Theta

            elif p2[0] > 0 and p2[1] < 0:
                if incident[1] > -incident[0]:  #fourth
                    Theta = -Theta

            elif p2[0] < 0 and p2[1] < 0:
                if incident[1] <= incident[0]:
                    Theta = -Theta

            #-form a 2x2 rotation matrix, uska format dekh lo aram se mile ga
            rotation_matrix = np.array([[np.cos(Theta), -np.sin(Theta)],
                                        [np.sin(Theta),
                                         np.cos(Theta)]])

            #-multiply the rotation matrix by the normal vector to get another 2x1 vector, call it reflected
            reflected = np.dot(rotation_matrix, normal)

            reflected *= -1

            #-find the unit vector in the direction of reflected, call it ref_unit
            ref_unit = reflected / math.sqrt(reflected[0]**2 + reflected[1]**2)

            #-scalar multiply ref_unit with overflow
            ref_point = ref_unit * overflowed

            #-us vector ke components ko add to circpoint ke coordinates to get the final coordinates
            final = circ_point + ref_point

            #-add both circ point (optional but will look better) and final coord to the arrays
            randomWalk_x_A.append(circ_point[0])
            randomWalk_y_A.append(circ_point[1])

            distance_from_origin = math.sqrt((final[0])**2 + (final[1])**2)

            if distance_from_origin >= Radius:
                flag_A_ref = True
                break
            else:
                randomWalk_x_A.append(final[0])
                randomWalk_y_A.append(final[1])

            step_addition_A += 1
            flag_A_ref = True
            break

        while distance_from_origin_B >= (Radius):

            new_x_B = '%.3f' % (new_x_B)
            new_y_B = '%.3f' % (new_y_B)

            old_x_B = '%.3f' % (randomWalk_x_B[-1])
            old_y_B = '%.3f' % (randomWalk_y_B[-1])

            p1, p2 = Point(old_x_B, old_y_B), Point(new_x_B, new_y_B)

            if p1.equals(p2):
                randomWalk_x_B.append(old_x_B)
                randomWalk_y_B.append(old_y_B)

                flag_B_ref = True
                break

            line = Line(p1, p2)
            a, b, c = line.coefficients

            x, y = symbols('x,y')
            eq1 = Eq((x)**2 + (y)**2 - (Radius)**2, 0, evaluate=False)
            eq2 = Eq((a * x) + (b * y) + c, 0, evaluate=False)

            sol = solve([eq1, eq2], [x, y])

            #find the point on the circumference where our line will touch, call it circpoint

            sol1 = (sol[0][0], sol[0][1])
            sol2 = (sol[1][0], sol[1][1])

            d1 = ((p2[0] - sol1[0])**2 + (p2[1] - sol1[1])**2)**(0.5)
            d2 = ((p2[0] - sol2[0])**2 + (p2[1] - sol2[1])**2)**(0.5)

            if d1 <= d2:
                circ_point = sol[0]
            else:
                circ_point = sol[1]

            circ_point = Point(circ_point[0], circ_point[1])

            #we know the overflow amount, call that overflowed
            overflowed = p2.distance(circ_point)

            #get the vector from our curr_pos to circpoint, call it incident
            incident = np.array([circ_point[0] - p1[0], circ_point[1] - p1[1]])

            #circpoint to origin vector
            normal = np.array([circ_point[0], circ_point[1]])

            #-find the angle between incident and normal using dot product wali equation, call that theta

            if p1.equals(circ_point):
                randomWalk_x_B.append(old_x_B)
                randomWalk_y_B.append(old_y_B)

                flag_B_ref = True
                break

            dot = (circ_point[0] * incident[0]) + (circ_point[1] * incident[1])

            magnitude1 = math.sqrt(circ_point[0]**2 + circ_point[1]**2)
            magnitude2 = math.sqrt(incident[0]**2 + incident[1]**2)

            ang = dot / (magnitude1 * magnitude2)

            main_ang = math.acos(ang)

            Theta = main_ang

            if p2[0] < 0 and p2[1] > 0:  #second
                Theta = -Theta

            elif p2[0] > 0 and p2[1] > 0:  #first
                if incident[1] >= incident[0]:
                    Theta = -Theta

            elif p2[0] > 0 and p2[1] < 0:
                if incident[1] > -incident[0]:  #fourth
                    Theta = -Theta

            elif p2[0] < 0 and p2[1] < 0:
                if incident[1] <= incident[0]:
                    Theta = -Theta

            #-form a 2x2 rotation matrix, uska format dekh lo aram se mile ga
            rotation_matrix = np.array([[np.cos(Theta), -np.sin(Theta)],
                                        [np.sin(Theta),
                                         np.cos(Theta)]])

            #-multiply the rotation matrix by the normal vector to get another 2x1 vector, call it reflected
            reflected = np.dot(rotation_matrix, normal)

            reflected *= -1

            #-find the unit vector in the direction of reflected, call it ref_unit
            ref_unit = reflected / math.sqrt(reflected[0]**2 + reflected[1]**2)

            #-scalar multiply ref_unit with overflow
            ref_point = ref_unit * overflowed

            #-us vector ke components ko add to circpoint ke coordinates to get the final coordinates
            final = circ_point + ref_point

            #-add both circ point (optional but will look better) and final coord to the arrays
            randomWalk_x_B.append(circ_point[0])
            randomWalk_y_B.append(circ_point[1])

            distance_from_origin = ((final[0])**2 + (final[1])**2)**(0.5)

            if distance_from_origin >= Radius:
                flag_B_ref = True
                break
            else:
                randomWalk_x_B.append(final[0])
                randomWalk_y_B.append(final[1])

            step_addition_B += 1
            flag_B_ref = True
            break

        if flag_A_ref:
            pass
        else:
            randomWalk_x_A.append(new_x_A)
            randomWalk_y_A.append(new_y_A)

        if flag_B_ref:
            pass
        else:
            randomWalk_x_B.append(new_x_B)
            randomWalk_y_B.append(new_y_B)

        flag_A_ref = False
        flag_B_ref = False

        steps += 1

        curr_A = (randomWalk_x_A[-1], randomWalk_y_A[-1])
        curr_B = (randomWalk_x_B[-1], randomWalk_y_B[-1])

        dist_between_particles = ((curr_B[0] - curr_A[0])**2 +
                                  (curr_B[1] - curr_A[1])**2)**(0.5)

        counter += 1
        if counter % 1000 == 0:
            print(counter)

        if dist_between_particles <= 1:
            break

    #return steps

    size_A = steps + step_addition_A
    size_B = steps + step_addition_B

    ########################################################
    #UNCOMMENT FOR ANIMATION

    # xdata, ydata = [], []
    # ln, = plt.plot(xdata,ydata)

    # def init():
    #     #Radius = 5.64189584 when area of circle = 100 unit^2
    #     axs.set_xlim(-Radius,Radius)
    #     axs.set_ylim(-Radius,Radius)
    #     ln.set_data([], [])
    #     return ln,

    # def update(frame):
    #     xdata.append(randomWalk_x[int(frame)])
    #     ydata.append(randomWalk_y[int(frame)])
    #     ln.set_data(xdata, ydata)
    #     return ln,

    # ani = FuncAnimation(fig, update, frames=np.linspace(0, size, size+1, endpoint=True), interval = 20,
    #                 init_func=init, blit=True, repeat=False)

    #ANIMATION CODE
    #######################################################

    circle1 = plt.Circle((0, 0), Radius, color='r', alpha=0.2)
    plt.gcf().gca().add_artist(circle1)

    plt.plot(randomWalk_x_A, randomWalk_y_A)
    plt.plot(randomWalk_x_B, randomWalk_y_B)

    plt.show()
Exemple #40
0
def test_equality_subs2():
    f = Function('f')
    eq = Eq(f(x)**2, 16)
    assert bool(eq.subs(f(x), 3)) is False
    assert bool(eq.subs(f(x), 4)) is True
def test_diophantine():
    assert check_solutions((x - y) * (y - z) * (z - x))
    assert check_solutions((x - y) * (x**2 + y**2 - z**2))
    assert check_solutions((x - 3 * y + 7 * z) * (x**2 + y**2 - z**2))
    assert check_solutions(x**2 - 3 * y**2 - 1)
    assert check_solutions(y**2 + 7 * x * y)
    assert check_solutions(x**2 - 3 * x * y + y**2)
    assert check_solutions(z * (x**2 - y**2 - 15))
    assert check_solutions(x * (2 * y - 2 * z + 5))
    assert check_solutions((x**2 - 3 * y**2 - 1) * (x**2 - y**2 - 15))
    assert check_solutions((x**2 - 3 * y**2 - 1) * (y - 7 * z))
    assert check_solutions((x**2 + y**2 - z**2) * (x - 7 * y - 3 * z + 4 * w))
    # Following test case caused problems in parametric representation
    # But this can be solved by factoring out y.
    # No need to use methods for ternary quadratic equations.
    assert check_solutions(y**2 - 7 * x * y + 4 * y * z)
    assert check_solutions(x**2 - 2 * x + 1)

    assert diophantine(x - y) == diophantine(Eq(x, y))
    # 18196
    eq = x**4 + y**4 - 97
    assert diophantine(eq, permute=True) == diophantine(-eq, permute=True)
    assert diophantine(3 * x * pi - 2 * y * pi) == {(2 * t_0, 3 * t_0)}
    eq = x**2 + y**2 + z**2 - 14
    base_sol = {(1, 2, 3)}
    assert diophantine(eq) == base_sol
    complete_soln = set(signed_permutations(base_sol.pop()))
    assert diophantine(eq, permute=True) == complete_soln

    assert diophantine(x**2 + x * Rational(15, 14) - 3) == set()
    # test issue 11049
    eq = 92 * x**2 - 99 * y**2 - z**2
    coeff = eq.as_coefficients_dict()
    assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
           {(9, 7, 51)}
    assert diophantine(eq) == {
        (891 * p**2 + 9 * q**2, -693 * p**2 - 102 * p * q + 7 * q**2,
         5049 * p**2 - 1386 * p * q - 51 * q**2)
    }
    eq = 2 * x**2 + 2 * y**2 - z**2
    coeff = eq.as_coefficients_dict()
    assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
           {(1, 1, 2)}
    assert diophantine(eq) == {(2 * p**2 - q**2, -2 * p**2 + 4 * p * q - q**2,
                                4 * p**2 - 4 * p * q + 2 * q**2)}
    eq = 411 * x**2 + 57 * y**2 - 221 * z**2
    coeff = eq.as_coefficients_dict()
    assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
           {(2021, 2645, 3066)}
    assert diophantine(eq) == \
           {(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q -
             584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)}
    eq = 573 * x**2 + 267 * y**2 - 984 * z**2
    coeff = eq.as_coefficients_dict()
    assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
           {(49, 233, 127)}
    assert diophantine(eq) == \
           {(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2,
             11303*p**2 - 41474*p*q + 41656*q**2)}
    # this produces factors during reconstruction
    eq = x**2 + 3 * y**2 - 12 * z**2
    coeff = eq.as_coefficients_dict()
    assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
           {(0, 2, 1)}
    assert diophantine(eq) == \
           {(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)}
    # solvers have not been written for every type
    raises(NotImplementedError, lambda: diophantine(x * y**2 + 1))

    # rational expressions
    assert diophantine(1 / x) == set()
    assert diophantine(1 / x + 1 / y - S.Half) == {(6, 3), (-2, 1), (4, 4),
                                                   (1, -2), (3, 6)}
    assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \
           {(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)}

    #test issue 18186
    assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \
           {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
    assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \
           {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}

    # issue 18122
    assert check_solutions(x**2 - y)
    assert check_solutions(y**2 - x)
    assert diophantine((x**2 - y), t) == {(t, t**2)}
    assert diophantine((y**2 - x), t) == {(t**2, -t)}
Exemple #42
0
f = Poly("-x**3 + 3 * x**2 + 10 * x - 24")

vec_x = np.arange(-5, 5, 0.1)
vec_y = np.vectorize(f)(vec_x)
pprint(vec_y)

r = list(roots(f).keys())
print(r)

plt.scatter(r, len(r) * [0])
plot(vec_x, vec_y)

header("[1.1/2]")

x, y = symbols("x, y")
eq_1 = Eq(x**2 + 3 * y, 10)
eq_2 = Eq(4 * x - y**2, -2)
r = solve([eq_1, eq_2], (x, y))
print("solved")

header("[1.1/3]")

pprint(r)
print(f"len(r)={len(r)}")

header("[1.1/4]")
for sol in r:
    print(f"x, y = {[sym.evalf() for sym in sol]}")

header("[1.1/5]")
Exemple #43
0
def solve(eq, x):
    res = sympy.solve(eq, x)
    if len(res) == 1:
        return res[0]
    else:
        return res


half = sympy.Rational(1, 2)
third = sympy.Rational(1, 3)
Kf = sympy.IndexedBase('Kf', shape=(sympy.oo, ))
K_fac = Symbol(
    'Kf_1'
)  # currently sympy bugs just using Kf[1], so treat as separate symbol
K_fac_sub = 1 - 3 * K / k**2
K_sub = Eq(K, solve(K_fac_sub - K_fac, K))

H_t = diff(a, t) / a
dH = -a**2 / 6 * kappa * (rho + 3 * P)
Friedmann = Eq(H**2, a**2 * kappa * rho / 3 - K)
Friedmann_subs = [Friedmann, Eq(diff(H, t), dH), Eq(diff(a, t), a * H)]
Friedmann_Kfac_subs = subs(K_sub, Friedmann_subs)

delta_frame = Function('uprime')(t)


def LinearPerturbation(name,
                       species=None,
                       camb_var=None,
                       camb_sub=None,
                       frame_dependence=None,
Exemple #44
0
def test_equality_subs1():
    f = Function("f")
    x = abc.x
    eq = Eq(f(x)**2, x)
    res = Eq(Integer(16), x)
    assert eq.subs(f(x), 4) == res
Exemple #45
0
 def check(pdf, set):
     x = Dummy('x')
     val = Sum(pdf(x), (x, set._inf, set._sup)).doit()
     _value_check(Eq(val, 1) != S.false, "The pdf is incorrect on the given set.")
Exemple #46
0
)

globals().update(get_symbs()) # see common.py: x, Y, Z, k_f, ...

subs = {}
eqs = []

# rate of x
rate_expr = k_f*Y*(Z-x) - k_b*x
rate_eq = Eq(Derivative(x,t), rate_expr)
eqs.append(rate_eq)

integrand = 1/rate_expr
inte_eq_lhs = Integral(integrand.subs({x: chi}), (chi,0,x))
inte_eq_rhs = Integral(1, (tau,0,t))
inte_eq = Eq(inte_eq_lhs, inte_eq_rhs)
eqs.append(inte_eq)

expl_in_x_eq = inte_eq.doit().simplify()
eqs.append(expl_in_x_eq)

expl_in_t_eq = Eq(x, solve(expl_in_x_eq, x)[0])
eqs.append(expl_in_t_eq)

alt_expl_in_t = Z*k_f*Y/(k_f*Y+k_b)*(1-exp(-t*(k_f*Y+k_b)))
assert (expl_in_t_eq.rhs - alt_expl_in_t).simplify() == 0

alt_expl_in_t_eq = Eq(x, alt_expl_in_t)
eqs.append(alt_expl_in_t_eq)

Exemple #47
0
###################################
##       4. Adiabatic compression
###################################

p_i   = Symbol("p_i", positive=True)
V_i   = Symbol("V_i", positive=True)
tau_i = Symbol("tau_i", positive=True)
N_i   = Symbol("N_i", positive=True)
idealgaslaw_i = Eq( p_i*V_i, N_i*tau_i)

p_f   = Symbol("p_f", positive=True)
V_f   = Symbol("V_f", positive=True)
tau_f = Symbol("tau_f", positive=True)
idealgaslaw_f = Eq( p_f*V_f, N_i*tau_f)

adia_tV = Eq( tau_i*V_i**(gamma-1) , tau_f*V_f**(gamma-1) )

##############################
#         (a)
##############################

roomtemp_K = KCconv.subs(T_C,20).rhs # room temperature in Kelvin

Prob0104ans = adia_tV.subs(gamma,1.4).subs(V_f,1).subs(V_i,15).subs(tau_i, roomtemp_K) # answer to Problem 4 of Chapter 1

Prob0104ans = N( Prob0104ans.lhs) # 866.016969686253 K 
Prob0104ansC = solve( KCconv.subs( T_K, Prob0104ans), T_C )[0] # 592.866969686253 C 
solve( FCconv.subs( T_C, Prob0104ansC ), T_F)[0] # 1099.16054543526 F

##############################
#         (b)