Ejemplo n.º 1
0
def test_n_link_pendulum_on_cart_higher_order():
    l0, m0 = symbols("l0 m0")
    l1, m1 = symbols("l1 m1")
    m2 = symbols("m2")
    g = symbols("g")
    q0, q1, q2 = dynamicsymbols("q0 q1 q2")
    u0, u1, u2 = dynamicsymbols("u0 u1 u2")
    F, T1 = dynamicsymbols("F T1")

    kane1 = models.n_link_pendulum_on_cart(2)
    massmatrix1 = Matrix([[m0 + m1 + m2, -l0*m1*cos(q1) - l0*m2*cos(q1),
                           -l1*m2*cos(q2)],
                          [-l0*m1*cos(q1) - l0*m2*cos(q1), l0**2*m1 + l0**2*m2,
                           l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2))],
                          [-l1*m2*cos(q2),
                           l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2)),
                           l1**2*m2]])
    forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) - l0*m2*u1**2*sin(q1) -
                        l1*m2*u2**2*sin(q2) + F],
                       [g*l0*m1*sin(q1) + g*l0*m2*sin(q1) -
                        l0*l1*m2*(sin(q1)*cos(q2) - sin(q2)*cos(q1))*u2**2],
                       [g*l1*m2*sin(q2) - l0*l1*m2*(-sin(q1)*cos(q2) +
                                                    sin(q2)*cos(q1))*u1**2]])
    assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3)
    assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0])
Ejemplo n.º 2
0
def test_singular_value_decompositionD():
    A = Matrix([[1, 2], [2, 1]])
    U, S, V = A.singular_value_decomposition()
    assert U * S * V.T == A
    assert U.T * U == eye(U.cols)
    assert V.T * V == eye(V.cols)

    B = Matrix([[1, 2]])
    U, S, V = B.singular_value_decomposition()

    assert U * S * V.T == B
    assert U.T * U == eye(U.cols)
    assert V.T * V == eye(V.cols)

    C = Matrix([
        [1, 0, 0, 0, 2],
        [0, 0, 3, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 2, 0, 0, 0],
    ])

    U, S, V = C.singular_value_decomposition()

    assert U * S * V.T == C
    assert U.T * U == eye(U.cols)
    assert V.T * V == eye(V.cols)

    D = Matrix([[Rational(1, 3), sqrt(2)], [0, Rational(1, 4)]])
    U, S, V = D.singular_value_decomposition()
    assert simplify(U.T * U) == eye(U.cols)
    assert simplify(V.T * V) == eye(V.cols)
    assert simplify(U * S * V.T) == D
Ejemplo n.º 3
0
def test_form_2():
    symsystem2 = SymbolicSystem(coordinates,
                                comb_implicit_rhs,
                                speeds=speeds,
                                mass_matrix=comb_implicit_mat,
                                alg_con=alg_con_full,
                                output_eqns=out_eqns,
                                bodies=bodies,
                                loads=loads)

    assert symsystem2.coordinates == Matrix([x, y, lam])
    assert symsystem2.speeds == Matrix([u, v])
    assert symsystem2.states == Matrix([x, y, lam, u, v])

    assert symsystem2.alg_con == [4]

    inter = comb_implicit_rhs
    assert simplify(symsystem2.comb_implicit_rhs - inter) == zeros(5, 1)
    assert simplify(symsystem2.comb_implicit_mat -
                    comb_implicit_mat) == zeros(5)

    assert set(symsystem2.dynamic_symbols()) == {y, v, lam, u, x}
    assert type(symsystem2.dynamic_symbols()) == tuple
    assert set(symsystem2.constant_symbols()) == {l, g, m}
    assert type(symsystem2.constant_symbols()) == tuple

    inter = comb_explicit_rhs
    symsystem2.compute_explicit_form()
    assert simplify(symsystem2.comb_explicit_rhs - inter) == zeros(5, 1)

    assert symsystem2.output_eqns == out_eqns

    assert symsystem2.bodies == (Pa, )
    assert symsystem2.loads == ((P, g * m * N.x), )
Ejemplo n.º 4
0
def test_gosper_sum_AeqB_part3():
    f3a = 1 / n**4
    f3b = (6 * n + 3) / (4 * n**4 + 8 * n**3 + 8 * n**2 + 4 * n + 3)
    f3c = 2**n * (n**2 - 2 * n - 1) / (n**2 * (n + 1)**2)
    f3d = n**2 * 4**n / ((n + 1) * (n + 2))
    f3e = 2**n / (n + 1)
    f3f = 4 * (n - 1) * (n**2 - 2 * n - 1) / (n**2 * (n + 1)**2 * (n - 2)**2 *
                                              (n - 3)**2)
    f3g = (n**4 - 14 * n**2 - 24 * n - 9) * 2**n / (n**2 * (n + 1)**2 *
                                                    (n + 2)**2 * (n + 3)**2)

    # g3a -> no closed form
    g3b = m * (m + 2) / (2 * m**2 + 4 * m + 3)
    g3c = 2**m / m**2 - 2
    g3d = Rational(2, 3) + 4**(m + 1) * (m - 1) / (m + 2) / 3
    # g3e -> no closed form
    g3f = -(Rational(-1, 16) + 1 / ((m - 2)**2 *
                                    (m + 1)**2))  # the AeqB key is wrong
    g3g = Rational(-2, 9) + 2**(m + 1) / ((m + 1)**2 * (m + 3)**2)

    g = gosper_sum(f3a, (n, 1, m))
    assert g is None
    g = gosper_sum(f3b, (n, 1, m))
    assert g is not None and simplify(g - g3b) == 0
    g = gosper_sum(f3c, (n, 1, m - 1))
    assert g is not None and simplify(g - g3c) == 0
    g = gosper_sum(f3d, (n, 1, m))
    assert g is not None and simplify(g - g3d) == 0
    g = gosper_sum(f3e, (n, 0, m - 1))
    assert g is None
    g = gosper_sum(f3f, (n, 4, m))
    assert g is not None and simplify(g - g3f) == 0
    g = gosper_sum(f3g, (n, 1, m))
    assert g is not None and simplify(g - g3g) == 0
Ejemplo n.º 5
0
    def eval(cls, *_args):
        """."""
        
        if not _args:
            return

        if not( len(_args) == 2):
            raise ValueError('Expecting two arguments')

        u = _args[0]
        v = _args[1]


        if isinstance(u, (Add, Mul)):
            ls = u.atoms(Tuple)

            for i in ls:
                u = u.subs(i, Matrix(i))

            u = simplify(u)

        if isinstance(v, (Add, Mul)):
            ls = v.atoms(Tuple)
            for i in ls:
                v = v.subs(i, Matrix(i))
            v = simplify(v)

        return u[0]*v[0] + u[1]*v[1]
Ejemplo n.º 6
0
def test_log_product():
    from sympy.abc import n, m

    i, j = symbols('i,j', positive=True, integer=True)
    x, y = symbols('x,y', positive=True)
    z = symbols('z', real=True)
    w = symbols('w')

    expr = log(Product(x**i, (i, 1, n)))
    assert simplify(expr) == expr
    assert expr.expand() == Sum(i * log(x), (i, 1, n))
    expr = log(Product(x**i * y**j, (i, 1, n), (j, 1, m)))
    assert simplify(expr) == expr
    assert expr.expand() == Sum(i * log(x) + j * log(y), (i, 1, n), (j, 1, m))

    expr = log(Product(-2, (n, 0, 4)))
    assert simplify(expr) == expr
    assert expr.expand() == expr
    assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))

    expr = log(Product(exp(z * i), (i, 0, n)))
    assert expr.expand() == Sum(z * i, (i, 0, n))

    expr = log(Product(exp(w * i), (i, 0, n)))
    assert expr.expand() == expr
    assert expr.expand(force=True) == Sum(w * i, (i, 0, n))

    expr = log(Product(i**2 * abs(j), (i, 1, n), (j, 1, m)))
    assert expr.expand() == Sum(2 * log(i) + log(j), (i, 1, n), (j, 1, m))
Ejemplo n.º 7
0
def test_binomial_symbolic():
    n = 2
    p = symbols('p', positive=True)
    X = Binomial('X', n, p)
    t = Symbol('t')

    assert simplify(E(X)) == n * p == simplify(moment(X, 1))
    assert simplify(variance(X)) == n * p * (1 - p) == simplify(cmoment(X, 2))
    assert cancel(skewness(X) - (1 - 2 * p) / sqrt(n * p * (1 - p))) == 0
    assert cancel((kurtosis(X)) - (3 + (1 - 6 * p * (1 - p)) / (n * p *
                                                                (1 - p)))) == 0
    assert characteristic_function(X)(t) == p**2 * exp(
        2 * I * t) + 2 * p * (-p + 1) * exp(I * t) + (-p + 1)**2
    assert moment_generating_function(X)(
        t) == p**2 * exp(2 * t) + 2 * p * (-p + 1) * exp(t) + (-p + 1)**2

    # Test ability to change success/failure winnings
    H, T = symbols('H T')
    Y = Binomial('Y', n, p, succ=H, fail=T)
    assert simplify(E(Y) - (n * (H * p + T * (1 - p)))) == 0

    # test symbolic dimensions
    n = symbols('n')
    B = Binomial('B', n, p)
    raises(NotImplementedError, lambda: P(B > 2))
    assert density(B).dict == Density(BinomialDistribution(n, p, 1, 0))
    assert set(density(B).dict.subs(n, 4).doit().keys()) == \
    {S.Zero, S.One, S(2), S(3), S(4)}
    assert set(density(B).dict.subs(n, 4).doit().values()) == \
    {(1 - p)**4, 4*p*(1 - p)**3, 6*p**2*(1 - p)**2, 4*p**3*(1 - p), p**4}
    k = Dummy('k', integer=True)
    assert E(B > 2).dummy_eq(
        Sum(
            Piecewise((k * p**k * (1 - p)**(-k + n) * binomial(n, k), (k >= 0)
                       & (k <= n) & (k > 2)), (0, True)), (k, 0, n)))
Ejemplo n.º 8
0
def test_equation():
    p1 = Point(0, 0)
    p2 = Point(1, 1)
    l1 = Line(p1, p2)
    l3 = Line(Point(x1, x1), Point(x1, 1 + x1))

    assert simplify(l1.equation()) in (x - y, y - x)
    assert simplify(l3.equation()) in (x - x1, x1 - x)
    assert simplify(l1.equation()) in (x - y, y - x)
    assert simplify(l3.equation()) in (x - x1, x1 - x)

    assert Line(p1, Point(1, 0)).equation(x=x, y=y) == y
    assert Line(p1, Point(0, 1)).equation() == x
    assert Line(Point(2, 0), Point(2, 1)).equation() == x - 2
    assert Line(p2, Point(2, 1)).equation() == y - 1

    assert Line3D(Point(x1, x1, x1), Point(y1, y1,
                                           y1)).equation() == (-x + y, -x + z)
    assert Line3D(Point(1, 2, 3),
                  Point(2, 3, 4)).equation() == (-x + y - 1, -x + z - 2)
    assert Line3D(Point(1, 2, 3), Point(1, 3,
                                        4)).equation() == (x - 1, -y + z - 1)
    assert Line3D(Point(1, 2, 3), Point(2, 2,
                                        4)).equation() == (y - 2, -x + z - 2)
    assert Line3D(Point(1, 2, 3), Point(2, 3,
                                        3)).equation() == (-x + y - 1, z - 3)
    assert Line3D(Point(1, 2, 3), Point(1, 2, 4)).equation() == (x - 1, y - 2)
    assert Line3D(Point(1, 2, 3), Point(1, 3, 3)).equation() == (x - 1, z - 3)
    assert Line3D(Point(1, 2, 3), Point(2, 2, 3)).equation() == (y - 2, z - 3)
Ejemplo n.º 9
0
    def eval(cls, *_args):
        """."""

        if not _args:
            return

        if not (len(_args) == 2):
            raise ValueError('Expecting two arguments')

        u = _args[0]
        v = _args[1]

        if isinstance(u, (Matrix, ImmutableDenseMatrix)):
            if isinstance(v, (Matrix, ImmutableDenseMatrix)):
                return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]

            else:
                return Tuple(u[0, 0] * v[0] + u[0, 1] * v[1] + u[0, 2] * v[2],
                             u[1, 0] * v[0] + u[1, 1] * v[1] + u[1, 2] * v[2],
                             u[2, 0] * v[0] + u[2, 1] * v[1] + u[2, 2] * v[2])

        if isinstance(u, (Add, Mul)):
            ls = u.atoms(Tuple)
            for i in ls:
                u = u.subs(i, Matrix(i))
            u = simplify(u)

        if isinstance(v, (Add, Mul)):
            ls = v.atoms(Tuple)
            for i in ls:
                v = v.subs(i, Matrix(i))
            v = simplify(v)

        return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]
Ejemplo n.º 10
0
def test_dcm_diff_16824():
    # NOTE : This is a regression test for the bug introduced in PR 14758,
    # identified in 16824, and solved by PR 16828.

    # This is the solution to Problem 2.2 on page 264 in Kane & Lenvinson's
    # 1985 book.

    q1, q2, q3 = dynamicsymbols('q1:4')

    s1 = sin(q1)
    c1 = cos(q1)
    s2 = sin(q2)
    c2 = cos(q2)
    s3 = sin(q3)
    c3 = cos(q3)

    dcm = Matrix([[c2 * c3, s1 * s2 * c3 - s3 * c1, c1 * s2 * c3 + s3 * s1],
                  [c2 * s3, s1 * s2 * s3 + c3 * c1, c1 * s2 * s3 - c3 * s1],
                  [-s2, s1 * c2, c1 * c2]])

    A = ReferenceFrame('A')
    B = ReferenceFrame('B')
    B.orient(A, 'DCM', dcm)

    AwB = B.ang_vel_in(A)

    alpha2 = s3 * c2 * q1.diff() + c3 * q2.diff()
    beta2 = s1 * c2 * q3.diff() + c1 * q2.diff()

    assert simplify(AwB.dot(A.y) - alpha2) == 0
    assert simplify(AwB.dot(B.y) - beta2) == 0
Ejemplo n.º 11
0
def test_maximum():
    x, y = symbols('x y')
    assert maximum(sin(x), x) is S.One
    assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
    assert maximum(tan(x), x) is oo
    assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
    assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
    assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
        ) == sqrt(2)/4
    assert maximum((x+3)*(x-2), x) is oo
    assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
    assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
    assert simplify(maximum(-x**4-x**3+x**2+10, x)
        ) == 41*sqrt(41)/512 + Rational(5419, 512)
    assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
    assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
    assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
        ) is S.One
    assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
    assert maximum(y, x, S.Reals) == y
    assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10
    assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528
    assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528
    assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1

    raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
    raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
    raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
    raises(ValueError, lambda : maximum(sin(x), sin(x)))
    raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
    raises(ValueError, lambda : maximum(sin(x), S.One))
Ejemplo n.º 12
0
    def _check_orthogonality(equations):
        """
        Helper method for _connect_to_cartesian. It checks if
        set of transformation equations create orthogonal curvilinear
        coordinate system

        Parameters
        ==========

        equations : Lambda
            Lambda of transformation equations

        """

        x1, x2, x3 = symbols("x1, x2, x3", cls=Dummy)
        equations = equations(x1, x2, x3)
        v1 = Matrix([diff(equations[0], x1),
                     diff(equations[1], x1), diff(equations[2], x1)])

        v2 = Matrix([diff(equations[0], x2),
                     diff(equations[1], x2), diff(equations[2], x2)])

        v3 = Matrix([diff(equations[0], x3),
                     diff(equations[1], x3), diff(equations[2], x3)])

        if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)):
            return False
        else:
            if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 \
                and simplify(v3.dot(v1)) == 0:
                return True
            else:
                return False
Ejemplo n.º 13
0
def test_nonminimal_pendulum():
    q1, q2 = dynamicsymbols('q1:3')
    q1d, q2d = dynamicsymbols('q1:3', level=1)
    L, m, t = symbols('L, m, t')
    g = 9.8
    # Compose World Frame
    N = ReferenceFrame('N')
    pN = Point('N*')
    pN.set_vel(N, 0)
    # Create point P, the pendulum mass
    P = pN.locatenew('P1', q1 * N.x + q2 * N.y)
    P.set_vel(N, P.pos_from(pN).dt(N))
    pP = Particle('pP', P, m)
    # Constraint Equations
    f_c = Matrix([q1**2 + q2**2 - L**2])
    # Calculate the lagrangian, and form the equations of motion
    Lag = Lagrangian(N, pP)
    LM = LagrangesMethod(Lag, [q1, q2],
                         hol_coneqs=f_c,
                         forcelist=[(P, m * g * N.x)],
                         frame=N)
    LM.form_lagranges_equations()
    # Check solution
    lam1 = LM.lam_vec[0, 0]
    eom_sol = Matrix([[m * Derivative(q1, t, t) - 9.8 * m + 2 * lam1 * q1],
                      [m * Derivative(q2, t, t) + 2 * lam1 * q2]])
    assert LM.eom == eom_sol
    # Check multiplier solution
    lam_sol = Matrix([
        (19.6 * q1 + 2 * q1d**2 + 2 * q2d**2) / (4 * q1**2 / m + 4 * q2**2 / m)
    ])
    assert simplify(
        LM.solve_multipliers(sol_type='Matrix')) == simplify(lam_sol)
Ejemplo n.º 14
0
def test_series_AccumBounds():
    assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2)
    assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3)

    # not the exact bound
    assert limit(sin(k) - sin(k) * cos(k), k, oo) == AccumBounds(-2, 2)

    # test for issue #9934
    lo = (-3 + cos(1)) / 2
    hi = (1 + cos(1)) / 2
    t1 = Mul(AccumBounds(lo, hi), 1 / (-1 + cos(1)), evaluate=False)
    assert limit(
        simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k,
        oo) == t1

    t2 = Mul(AccumBounds(-1 + sin(1) / 2, sin(1) / 2 + 1), 1 / (1 - cos(1)))
    assert limit(
        simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k,
        oo) == t2

    assert limit(frac(x)**x, x, oo) == AccumBounds(0,
                                                   oo)  # wolfram gives (0, 1)
    assert limit(((sin(x) + 1) / 2)**x, x,
                 oo) == AccumBounds(0, oo)  # wolfram says 0

    # https://github.com/sympy/sympy/issues/12312
    e = 2**(-x) * (sin(x) + 1)**x
    assert limit(e, x, oo) == AccumBounds(0, oo)
Ejemplo n.º 15
0
 def _eval_simplify(self, ratio, measure):
     from sympy.simplify.simplify import expand_log, simplify
     if (len(self.args) == 2):
         return simplify(self.func(*self.args), ratio=ratio, measure=measure)
     expr = self.func(simplify(self.args[0], ratio=ratio, measure=measure))
     expr = expand_log(expr, deep=True)
     return min([expr, self], key=measure)
Ejemplo n.º 16
0
def test_expint():
    """ Test various exponential integrals. """
    from sympy.core.symbol import Symbol
    from sympy.functions.elementary.complexes import unpolarify
    from sympy.functions.elementary.hyperbolic import sinh
    from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si,
                                                         expint)
    assert simplify(
        unpolarify(
            integrate(exp(-z * x) / x**y, (x, 1, oo),
                      meijerg=True,
                      conds='none').rewrite(expint).expand(
                          func=True))) == expint(y, z)

    assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True,
                     conds='none').rewrite(expint).expand() == \
        expint(1, z)
    assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True,
                     conds='none').rewrite(expint).expand() == \
        expint(2, z).rewrite(Ei).rewrite(expint)
    assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,
                     conds='none').rewrite(expint).expand() == \
        expint(3, z).rewrite(Ei).rewrite(expint).expand()

    t = Symbol('t', positive=True)
    assert integrate(-cos(x) / x, (x, t, oo), meijerg=True).expand() == Ci(t)
    assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \
        Si(t) - pi/2
    assert integrate(sin(x) / x, (x, 0, z), meijerg=True) == Si(z)
    assert integrate(sinh(x) / x, (x, 0, z), meijerg=True) == Shi(z)
    assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \
        I*pi - expint(1, x)
    assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \
        == expint(1, x) - exp(-x)/x - I*pi

    u = Symbol('u', polar=True)
    assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
        == Ci(u)
    assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
        == Chi(u)

    assert integrate(
        expint(1, x), x,
        meijerg=True).rewrite(expint).expand() == x * expint(1, x) - exp(-x)
    assert integrate(expint(2, x), x, meijerg=True
            ).rewrite(expint).expand() == \
        -x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2
    assert simplify(unpolarify(integrate(expint(y, x), x,
                 meijerg=True).rewrite(expint).expand(func=True))) == \
        -expint(y + 1, x)

    assert integrate(Si(x), x, meijerg=True) == x * Si(x) + cos(x)
    assert integrate(Ci(u), u, meijerg=True).expand() == u * Ci(u) - sin(u)
    assert integrate(Shi(x), x, meijerg=True) == x * Shi(x) - cosh(x)
    assert integrate(Chi(u), u, meijerg=True).expand() == u * Chi(u) - sinh(u)

    assert integrate(Si(x) * exp(-x), (x, 0, oo), meijerg=True) == pi / 4
    assert integrate(expint(1, x) * sin(x), (x, 0, oo),
                     meijerg=True) == log(2) / 2
Ejemplo n.º 17
0
def test_coherent_state(n=10):
    # Maximum "n" which is tested:
    # test whether coherent state is the eigenstate of annihilation operator
    alpha = Symbol("alpha")
    for i in range(n + 1):
        assert simplify(sqrt(n + 1) *
                        coherent_state(n + 1, alpha)) == simplify(
                            alpha * coherent_state(n, alpha))
Ejemplo n.º 18
0
def test_log_product_simplify_to_sum():
    from sympy.abc import n, m
    i, j = symbols('i,j', positive=True, integer=True)
    x, y = symbols('x,y', positive=True)
    assert simplify(log(Product(x**i,
                                (i, 1, n)))) == Sum(i * log(x), (i, 1, n))
    assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
            Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
Ejemplo n.º 19
0
def test_simplification():
    """
    Test working of simplification methods.
    """
    set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]]
    set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]]
    assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x))
    assert Not(SOPform([x, y, z], set2)) == Not(Or(And(Not(x), Not(z)), And(x, z)))
    assert POSform([x, y, z], set1 + set2) is true
    assert SOPform([x, y, z], set1 + set2) is true
    assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true

    minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
        [1, 1, 1, 1]]
    dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
    assert (
        SOPform([w, x, y, z], minterms, dontcares) ==
        Or(And(Not(w), z), And(y, z)))
    assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)

    # test simplification
    ans = And(A, Or(B, C))
    assert simplify_logic(A & (B | C)) == ans
    assert simplify_logic((A & B) | (A & C)) == ans
    assert simplify_logic(Implies(A, B)) == Or(Not(A), B)
    assert simplify_logic(Equivalent(A, B)) == \
           Or(And(A, B), And(Not(A), Not(B)))
    assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C)
    assert simplify_logic(And(Equality(A, 2), A)) is S.false
    assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A)
    assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C)
    assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \
           == And(Equality(A, 3), Or(B, C))
    b = (~x & ~y & ~z) | ( ~x & ~y & z)
    e = And(A, b)
    assert simplify_logic(e) == A & ~x & ~y

    # check input
    ans = SOPform([x, y], [[1, 0]])
    assert SOPform([x, y], [[1, 0]]) == ans
    assert POSform([x, y], [[1, 0]]) == ans

    raises(ValueError, lambda: SOPform([x], [[1]], [[1]]))
    assert SOPform([x], [[1]], [[0]]) is true
    assert SOPform([x], [[0]], [[1]]) is true
    assert SOPform([x], [], []) is false

    raises(ValueError, lambda: POSform([x], [[1]], [[1]]))
    assert POSform([x], [[1]], [[0]]) is true
    assert POSform([x], [[0]], [[1]]) is true
    assert POSform([x], [], []) is false

    # check working of simplify
    assert simplify((A & B) | (A & C)) == And(A, Or(B, C))
    assert simplify(And(x, Not(x))) == False
    assert simplify(Or(x, Not(x))) == True
Ejemplo n.º 20
0
def test_yule_simon():
    from sympy.core.singleton import S
    rho = S(3)
    x = YuleSimon('x', rho)
    assert simplify(E(x)) == rho / (rho - 1)
    assert simplify(variance(x)) == rho**2 / ((rho - 1)**2 * (rho - 2))
    assert isinstance(E(x, evaluate=False), Expectation)
    # To test the cdf function
    assert cdf(x)(x) == Piecewise((-beta(floor(x), 4) * floor(x) + 1, x >= 1),
                                  (0, True))
Ejemplo n.º 21
0
    def _eval_simplify(self, **kwargs):
        from sympy.simplify.simplify import expand_log, simplify, inversecombine
        if len(self.args) == 2:  # it's unevaluated
            return simplify(self.func(*self.args), **kwargs)

        expr = self.func(simplify(self.args[0], **kwargs))
        if kwargs['inverse']:
            expr = inversecombine(expr)
        expr = expand_log(expr, deep=True)
        return min([expr, self], key=kwargs['measure'])
Ejemplo n.º 22
0
def test_issue_8866():
    assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
    assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10))

    y = Symbol('y', positive=True)
    l1 = log(exp(y), exp(10))
    b1 = log(exp(y), exp(5))
    l2 = log(exp(y), exp(10), evaluate=False)
    b2 = log(exp(y), exp(5), evaluate=False)
    assert simplify(log(l1, b1)) == simplify(log(l2, b2))
    assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
Ejemplo n.º 23
0
 def _eval_simplify(self, ratio, measure, rational, inverse):
     from sympy.simplify.simplify import expand_log, simplify, inversecombine
     if (len(self.args) == 2):
         return simplify(self.func(*self.args), ratio=ratio, measure=measure,
                         rational=rational, inverse=inverse)
     expr = self.func(simplify(self.args[0], ratio=ratio, measure=measure,
                      rational=rational, inverse=inverse))
     if inverse:
         expr = inversecombine(expr)
     expr = expand_log(expr, deep=True)
     return min([expr, self], key=measure)
Ejemplo n.º 24
0
def test_exptrigsimp():
    def valid(a, b):
        from sympy.core.random import verify_numerically as tn
        if not (tn(a, b) and a == b):
            return False
        return True

    assert exptrigsimp(exp(x) + exp(-x)) == 2 * cosh(x)
    assert exptrigsimp(exp(x) - exp(-x)) == 2 * sinh(x)
    assert exptrigsimp(
        (2 * exp(x) - 2 * exp(-x)) / (exp(x) + exp(-x))) == 2 * tanh(x)
    assert exptrigsimp((2 * exp(2 * x) - 2) / (exp(2 * x) + 1)) == 2 * tanh(x)
    e = [
        cos(x) + I * sin(x),
        cos(x) - I * sin(x),
        cosh(x) - sinh(x),
        cosh(x) + sinh(x)
    ]
    ok = [exp(I * x), exp(-I * x), exp(-x), exp(x)]
    assert all(valid(i, j) for i, j in zip([exptrigsimp(ei) for ei in e], ok))

    ue = [
        cos(x) + sin(x),
        cos(x) - sin(x),
        cosh(x) + I * sinh(x),
        cosh(x) - I * sinh(x)
    ]
    assert [exptrigsimp(ei) == ei for ei in ue]

    res = []
    ok = [
        y * tanh(1), 1 / (y * tanh(1)), I * y * tan(1), -I / (y * tan(1)),
        y * tanh(x), 1 / (y * tanh(x)), I * y * tan(x), -I / (y * tan(x)),
        y * tanh(1 + I), 1 / (y * tanh(1 + I))
    ]
    for a in (1, I, x, I * x, 1 + I):
        w = exp(a)
        eq = y * (w - 1 / w) / (w + 1 / w)
        res.append(simplify(eq))
        res.append(simplify(1 / eq))
    assert all(valid(i, j) for i, j in zip(res, ok))

    for a in range(1, 3):
        w = exp(a)
        e = w + 1 / w
        s = simplify(e)
        assert s == exptrigsimp(e)
        assert valid(s, 2 * cosh(a))
        e = w - 1 / w
        s = simplify(e)
        assert s == exptrigsimp(e)
        assert valid(s, 2 * sinh(a))
Ejemplo n.º 25
0
def test_density():
    x = Symbol('x')
    l = Symbol('l', positive=True)
    rate = Beta(l, 2, 3)
    X = Poisson(x, rate)
    assert isinstance(pspace(X), CompoundPSpace)
    assert density(X, Eq(rate, rate.symbol)) == PoissonDistribution(l)
    N1 = Normal('N1', 0, 1)
    N2 = Normal('N2', N1, 2)
    assert density(N2)(0).doit() == sqrt(10) / (10 * sqrt(pi))
    assert simplify(density(N2, Eq(N1, 1))(x)) == \
        sqrt(2)*exp(-(x - 1)**2/8)/(4*sqrt(pi))
    assert simplify(
        density(N2)(x)) == sqrt(10) * exp(-x**2 / 10) / (10 * sqrt(pi))
Ejemplo n.º 26
0
def test_dub_pen():

    # The system considered is the double pendulum. Like in the
    # test of the simple pendulum above, we begin by creating the generalized
    # coordinates and the simple generalized speeds and accelerations which
    # will be used later. Following this we create frames and points necessary
    # for the kinematics. The procedure isn't explicitly explained as this is
    # similar to the simple  pendulum. Also this is documented on the pydy.org
    # website.
    q1, q2 = dynamicsymbols('q1 q2')
    q1d, q2d = dynamicsymbols('q1 q2', 1)
    q1dd, q2dd = dynamicsymbols('q1 q2', 2)
    u1, u2 = dynamicsymbols('u1 u2')
    u1d, u2d = dynamicsymbols('u1 u2', 1)
    l, m, g = symbols('l m g')

    N = ReferenceFrame('N')
    A = N.orientnew('A', 'Axis', [q1, N.z])
    B = N.orientnew('B', 'Axis', [q2, N.z])

    A.set_ang_vel(N, q1d * A.z)
    B.set_ang_vel(N, q2d * A.z)

    O = Point('O')
    P = O.locatenew('P', l * A.x)
    R = P.locatenew('R', l * B.x)

    O.set_vel(N, 0)
    P.v2pt_theory(O, N, A)
    R.v2pt_theory(P, N, B)

    ParP = Particle('ParP', P, m)
    ParR = Particle('ParR', R, m)

    ParP.potential_energy = -m * g * l * cos(q1)
    ParR.potential_energy = -m * g * l * cos(q1) - m * g * l * cos(q2)
    L = Lagrangian(N, ParP, ParR)
    lm = LagrangesMethod(L, [q1, q2], bodies=[ParP, ParR])
    lm.form_lagranges_equations()

    assert simplify(l * m *
                    (2 * g * sin(q1) + l * sin(q1) * sin(q2) * q2dd +
                     l * sin(q1) * cos(q2) * q2d**2 - l * sin(q2) * cos(q1) *
                     q2d**2 + l * cos(q1) * cos(q2) * q2dd + 2 * l * q1dd) -
                    lm.eom[0]) == 0
    assert simplify(l * m *
                    (g * sin(q2) + l * sin(q1) * sin(q2) * q1dd - l * sin(q1) *
                     cos(q2) * q1d**2 + l * sin(q2) * cos(q1) * q1d**2 +
                     l * cos(q1) * cos(q2) * q1dd + l * q2dd) - lm.eom[1]) == 0
    assert lm.bodies == [ParP, ParR]
Ejemplo n.º 27
0
def test_n_link_pendulum_on_cart_inputs():
    l0, m0 = symbols("l0 m0")
    m1 = symbols("m1")
    g = symbols("g")
    q0, q1, F, T1 = dynamicsymbols("q0 q1 F T1")
    u0, u1 = dynamicsymbols("u0 u1")

    kane1 = models.n_link_pendulum_on_cart(1)
    massmatrix1 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
                          [-l0*m1*cos(q1), l0**2*m1]])
    forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]])
    assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(2)
    assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0])

    kane2 = models.n_link_pendulum_on_cart(1, False)
    massmatrix2 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
                          [-l0*m1*cos(q1), l0**2*m1]])
    forcing2 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1)]])
    assert simplify(massmatrix2 - kane2.mass_matrix) == zeros(2)
    assert simplify(forcing2 - kane2.forcing) == Matrix([0, 0])

    kane3 = models.n_link_pendulum_on_cart(1, False, True)
    massmatrix3 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
                          [-l0*m1*cos(q1), l0**2*m1]])
    forcing3 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1) + T1]])
    assert simplify(massmatrix3 - kane3.mass_matrix) == zeros(2)
    assert simplify(forcing3 - kane3.forcing) == Matrix([0, 0])

    kane4 = models.n_link_pendulum_on_cart(1, True, False)
    massmatrix4 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
                          [-l0*m1*cos(q1), l0**2*m1]])
    forcing4 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]])
    assert simplify(massmatrix4 - kane4.mass_matrix) == zeros(2)
    assert simplify(forcing4 - kane4.forcing) == Matrix([0, 0])
Ejemplo n.º 28
0
def test_multi_mass_spring_damper_inputs():

    c0, k0, m0 = symbols("c0 k0 m0")
    g = symbols("g")
    v0, x0, f0 = dynamicsymbols("v0 x0 f0")

    kane1 = models.multi_mass_spring_damper(1)
    massmatrix1 = Matrix([[m0]])
    forcing1 = Matrix([[-c0*v0 - k0*x0]])
    assert simplify(massmatrix1 - kane1.mass_matrix) == Matrix([0])
    assert simplify(forcing1 - kane1.forcing) == Matrix([0])

    kane2 = models.multi_mass_spring_damper(1, True)
    massmatrix2 = Matrix([[m0]])
    forcing2 = Matrix([[-c0*v0 + g*m0 - k0*x0]])
    assert simplify(massmatrix2 - kane2.mass_matrix) == Matrix([0])
    assert simplify(forcing2 - kane2.forcing) == Matrix([0])

    kane3 = models.multi_mass_spring_damper(1, True, True)
    massmatrix3 = Matrix([[m0]])
    forcing3 = Matrix([[-c0*v0 + g*m0 - k0*x0 + f0]])
    assert simplify(massmatrix3 - kane3.mass_matrix) == Matrix([0])
    assert simplify(forcing3 - kane3.forcing) == Matrix([0])

    kane4 = models.multi_mass_spring_damper(1, False, True)
    massmatrix4 = Matrix([[m0]])
    forcing4 = Matrix([[-c0*v0 - k0*x0 + f0]])
    assert simplify(massmatrix4 - kane4.mass_matrix) == Matrix([0])
    assert simplify(forcing4 - kane4.forcing) == Matrix([0])
Ejemplo n.º 29
0
def test_pinv_succeeds_with_rank_decomposition_method():
    # Test rank decomposition method of pseudoinverse succeeding
    As = [
        Matrix([[61, 89, 55, 20, 71, 0], [62, 96, 85, 85, 16, 0],
                [69, 56, 17, 4, 54, 0], [10, 54, 91, 41, 71, 0],
                [7, 30, 10, 48, 90, 0], [0, 0, 0, 0, 0, 0]])
    ]
    for A in As:
        A_pinv = A.pinv(method="RD")
        AAp = A * A_pinv
        ApA = A_pinv * A
        assert simplify(AAp * A) == A
        assert simplify(ApA * A_pinv) == A_pinv
        assert AAp.H == AAp
        assert ApA.H == ApA
Ejemplo n.º 30
0
def test_bessel():
    from sympy.functions.special.bessel import (besseli, besselj)
    assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo),
                     meijerg=True, conds='none')) == \
        2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b))
    assert simplify(
        integrate(besselj(a, z) * besselj(a, z) / z, (z, 0, oo),
                  meijerg=True,
                  conds='none')) == 1 / (2 * a)

    # TODO more orthogonality integrals

    assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S.Half)),
                              (x, 1, oo), meijerg=True, conds='none')
                    *2/((z/2)**y*sqrt(pi)*gamma(S.Half - y))) == \
        besselj(y, z)

    # Werner Rosenheinrich
    # SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS

    assert integrate(x * besselj(0, x), x, meijerg=True) == x * besselj(1, x)
    assert integrate(x * besseli(0, x), x, meijerg=True) == x * besseli(1, x)
    # TODO can do higher powers, but come out as high order ... should they be
    #      reduced to order 0, 1?
    assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x)
    assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \
        -(besselj(0, x)**2 + besselj(1, x)**2)/2
    # TODO more besseli when tables are extended or recursive mellin works
    assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \
        -2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \
        + 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x
    assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \
        -besselj(0, x)**2/2
    assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \
        x**2*besselj(1, x)**2/2
    assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \
        (x*besselj(0, x)**2 + x*besselj(1, x)**2 -
            besselj(0, x)*besselj(1, x))
    # TODO how does besselj(0, a*x)*besselj(0, b*x) work?
    # TODO how does besselj(0, x)**2*besselj(1, x)**2 work?
    # TODO sin(x)*besselj(0, x) etc come out a mess
    # TODO can x*log(x)*besselj(0, x) be done?
    # TODO how does besselj(1, x)*besselj(0, x+a) work?
    # TODO more indefinite integrals when struve functions etc are implemented

    # test a substitution
    assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \
        -besselj(0, x**2)/2