Exemplo n.º 1
1
def test_pend():
    q, u = dynamicsymbols('q u')
    qd, ud = dynamicsymbols('q u', 1)
    m, l, g = symbols('m l g')
    N = ReferenceFrame('N')
    P = Point('P')
    P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y)
    kd = [qd - u]

    FL = [(P, m * g * N.x)]
    pa = Particle()
    pa.mass = m
    pa.point = P
    BL = [pa]

    KM = Kane(N)
    KM.coords([q])
    KM.speeds([u])
    KM.kindiffeq(kd)
    KM.kanes_equations(FL, BL)
    MM = KM.mass_matrix
    forcing = KM.forcing
    rhs = MM.inv() * forcing
    rhs.simplify()
    assert expand(rhs[0]) == expand(-g / l * sin(q))
Exemplo n.º 2
0
def test_integrate_poly_accurately():
    y = Symbol('y')
    assert integrate(x*sin(y), x) == x**2*sin(y)/2

    # when passed to risch_norman, this will be a CPU hog, so this really
    # checks, that integrated function is recognized as polynomial
    assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001
Exemplo n.º 3
0
def test_sincos_rewrite():
    x = Symbol("x")
    y = Symbol("y")
    assert sin(pi/2-x) == cos(x)
    assert sin(pi-x) == sin(x)
    assert cos(pi/2-x) == sin(x)
    assert cos(pi-x) == -cos(x)
Exemplo n.º 4
0
def test_tan_rewrite():
    x = Symbol('x')
    neg_exp, pos_exp = exp(-x*I), exp(x*I)
    assert tan(x).rewrite(exp) == I*(neg_exp-pos_exp)/(neg_exp+pos_exp)
    assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x)
    assert tan(x).rewrite(cos) == -cos(x + S.Pi/2)/cos(x)
    assert tan(x).rewrite(cot) == 1/cot(x)
Exemplo n.º 5
0
def test_integrate_linearterm_pow():
    # check integrate((a*x+b)^c, x)  --  issue 3499
    y = Symbol('y', positive=True)
    # TODO: Remove conds='none' below, let the assumption take care of it.
    assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1)
    assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \
        exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y))
Exemplo n.º 6
0
def test_cot_rewrite():
    x = Symbol('x')
    neg_exp, pos_exp = exp(-x*I), exp(x*I)
    assert cot(x).rewrite(exp) == I*(pos_exp+neg_exp)/(pos_exp-neg_exp)
    assert cot(x).rewrite(sin) == 2*sin(2*x)/sin(x)**2
    assert cot(x).rewrite(cos) == -cos(x)/cos(x + S.Pi/2)
    assert cot(x).rewrite(tan) == 1/tan(x)
Exemplo n.º 7
0
def test_cross_different_frames3():
    assert cross(A[1], C[1]) == sin(q3)*C[2]
    assert cross(A[1], C[2]) == -sin(q3)*C[1] + cos(q3)*C[3]
    assert cross(A[1], C[3]) == -cos(q3)*C[2]
    assert cross(C[1], A[1]) == -sin(q3)*C[2]
    assert cross(C[2], A[1]) == sin(q3)*C[1] - cos(q3)*C[3]
    assert cross(C[3], A[1]) == cos(q3)*C[2]
Exemplo n.º 8
0
def test_cross_method():
    N = NewtonianReferenceFrame('N')
    q, qd = N.declare_coords('q', 3)
    q1, q2, q3 = q
    A = N.rotate('A', 1, q1)
    B = N.rotate('B', 2, q2)
    C = N.rotate('C', 3, q3)
    assert cross(N[1], N[1]) == Vector(0) == 0
    assert cross(N[1], N[2]) == N[3]
    assert N[1].cross(N[3]) == Vector({N[2]: -1})

    assert N[2].cross(N[1]) == Vector({N[3]: -1})
    assert N[2].cross(N[2]) == Vector(0)
    assert N[2].cross(N[3]) == N[1]

    assert N[3].cross(N[1]) == N[2]
    assert N[3].cross(N[2]) == Vector({N[1]: -1})
    assert N[3].cross(N[3]) == Vector(0)

    assert N[1].cross(A[1]) == Vector(0)
    assert N[1].cross(A[2]) == A[3]
    assert N[1].cross(A[3]) == Vector(-A[2])

    assert N[2].cross(A[1]) == Vector(-N[3])
    assert N[2].cross(A[2]) == Vector(sin(q1)*N[1])
    assert N[2].cross(A[3]) == Vector(cos(q1)*N[1])

    assert N[1].cross(B[1]) == Vector(sin(q2)*N[2])
    assert N[1].cross(B[2]) == N[3]
    assert N[1].cross(B[3]) == Vector(-cos(q2)*N[2])
Exemplo n.º 9
0
def plotgrid_and_save(name):
    tmp_file = TmpFileManager.tmp_file

    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    p1 = plot(x)
    p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False)
    p3 = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500, show=False)
    p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False)
    # symmetric grid
    p = PlotGrid(2, 2, p1, p2, p3, p4)
    p.save(tmp_file('%s_grid1' % name))
    p._backend.close()

    # grid size greater than the number of subplots
    p = PlotGrid(3, 4, p1, p2, p3, p4)
    p.save(tmp_file('%s_grid2' % name))
    p._backend.close()

    p5 = plot(cos(x),(x, -pi, pi), show=False)
    p5[0].line_color = lambda a: a
    p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False)
    p7 = plot_contour((x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False)
    # unsymmetric grid (subplots in one line)
    p = PlotGrid(1, 3, p5, p6, p7)
    p.save(tmp_file('%s_grid3' % name))
    p._backend.close()
Exemplo n.º 10
0
def test_image_interval():
    from sympy.core.numbers import Rational
    x = Symbol('x', real=True)
    a = Symbol('a', real=True)
    assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2)
    assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \
        Interval(-4, 2, True, False)
    assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
        Interval(0, 4, False, True)
    assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4)
    assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
        Interval(0, 4, False, True)
    assert imageset(x, x**2, Interval(-2, 1, True, True)) == \
        Interval(0, 4, False, True)
    assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1)
    assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \
        Interval(-35, 0)  # Multiple Maxima
    assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \
        + Interval(2, oo)  # Single Infinite discontinuity
    assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \
        Interval(Rational(3, 2), oo, False)  # Multiple Infinite discontinuities

    # Test for Python lambda
    assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2)

    assert imageset(Lambda(x, a*x), Interval(0, 1)) == \
            ImageSet(Lambda(x, a*x), Interval(0, 1))

    assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \
            ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1))
Exemplo n.º 11
0
def test_equals():
    assert (-3 - sqrt(5) + (-sqrt(10) / 2 - sqrt(2) / 2) ** 2).equals(0)
    assert (x ** 2 - 1).equals((x + 1) * (x - 1))
    assert (cos(x) ** 2 + sin(x) ** 2).equals(1)
    assert (a * cos(x) ** 2 + a * sin(x) ** 2).equals(a)
    r = sqrt(2)
    assert (-1 / (r + r * x) + 1 / r / (1 + x)).equals(0)
    assert factorial(x + 1).equals((x + 1) * factorial(x))
    assert sqrt(3).equals(2 * sqrt(3)) is False
    assert (sqrt(5) * sqrt(3)).equals(sqrt(3)) is False
    assert (sqrt(5) + sqrt(3)).equals(0) is False
    assert (sqrt(5) + pi).equals(0) is False
    assert meter.equals(0) is False
    assert (3 * meter ** 2).equals(0) is False

    # from integrate(x*sqrt(1+2*x), x);
    # diff is zero, but differentiation does not show it
    i = 2 * sqrt(2) * x ** (S(5) / 2) * (1 + 1 / (2 * x)) ** (S(5) / 2) / 5 + 2 * sqrt(2) * x ** (S(3) / 2) * (
        1 + 1 / (2 * x)
    ) ** (S(5) / 2) / (-6 - 3 / x)
    ans = sqrt(2 * x + 1) * (6 * x ** 2 + x - 1) / 15
    diff = i - ans
    assert diff.equals(0) is not False  # should be True, but now it's None
    # XXX TODO add a force=True option to equals to posify both
    # self and other before beginning comparisions
    p = Symbol("p", positive=True)
    assert diff.subs(x, p).equals(0) is True
Exemplo n.º 12
0
def test_has_basics():
    f = Function("f")
    g = Function("g")
    p = Wild("p")

    assert sin(x).has(x)
    assert sin(x).has(sin)
    assert not sin(x).has(y)
    assert not sin(x).has(cos)
    assert f(x).has(x)
    assert f(x).has(f)
    assert not f(x).has(y)
    assert not f(x).has(g)

    assert f(x).diff(x).has(x)
    assert f(x).diff(x).has(f)
    assert f(x).diff(x).has(Derivative)
    assert not f(x).diff(x).has(y)
    assert not f(x).diff(x).has(g)
    assert not f(x).diff(x).has(sin)

    assert (x ** 2).has(Symbol)
    assert not (x ** 2).has(Wild)
    assert (2 * p).has(Wild)

    assert not x.has()
Exemplo n.º 13
0
def test_as_real_imag():
    n = pi**1000
    # the special code for working out the real
    # and complex parts of a power with Integer exponent
    # should not run if there is no imaginary part, hence
    # this should not hang
    assert n.as_real_imag() == (n, 0)

    # issue 6261
    x = Symbol('x')
    assert sqrt(x).as_real_imag() == \
        ((re(x)**2 + im(x)**2)**(S(1)/4)*cos(atan2(im(x), re(x))/2),
     (re(x)**2 + im(x)**2)**(S(1)/4)*sin(atan2(im(x), re(x))/2))

    # issue 3853
    a, b = symbols('a,b', real=True)
    assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
           (
               (a**2 + b**2)**Rational(
                   1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2),
               (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)

    assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
    i = symbols('i', imaginary=True)
    assert sqrt(i**2).as_real_imag() == (0, abs(i))
Exemplo n.º 14
0
def test_as_ordered_terms():
    f, g = symbols("f,g", cls=Function)

    assert x.as_ordered_terms() == [x]
    assert (sin(x) ** 2 * cos(x) + sin(x) * cos(x) ** 2 + 1).as_ordered_terms() == [
        sin(x) ** 2 * cos(x),
        sin(x) * cos(x) ** 2,
        1,
    ]

    args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
    expr = Add(*args)

    assert expr.as_ordered_terms() == args

    assert (1 + 4 * sqrt(3) * pi * x).as_ordered_terms() == [4 * pi * x * sqrt(3), 1]

    assert (2 + 3 * I).as_ordered_terms() == [2, 3 * I]
    assert (-2 + 3 * I).as_ordered_terms() == [-2, 3 * I]
    assert (2 - 3 * I).as_ordered_terms() == [2, -3 * I]
    assert (-2 - 3 * I).as_ordered_terms() == [-2, -3 * I]

    assert (4 + 3 * I).as_ordered_terms() == [4, 3 * I]
    assert (-4 + 3 * I).as_ordered_terms() == [-4, 3 * I]
    assert (4 - 3 * I).as_ordered_terms() == [4, -3 * I]
    assert (-4 - 3 * I).as_ordered_terms() == [-4, -3 * I]

    f = x ** 2 * y ** 2 + x * y ** 4 + y + 2

    assert f.as_ordered_terms(order="lex") == [x ** 2 * y ** 2, x * y ** 4, y, 2]
    assert f.as_ordered_terms(order="grlex") == [x * y ** 4, x ** 2 * y ** 2, y, 2]
    assert f.as_ordered_terms(order="rev-lex") == [2, y, x * y ** 4, x ** 2 * y ** 2]
    assert f.as_ordered_terms(order="rev-grlex") == [2, y, x ** 2 * y ** 2, x * y ** 4]
Exemplo n.º 15
0
def test_evalf_bugs():
    assert NS(sin(1)+exp(-10**10),10) == NS(sin(1),10)
    assert NS(exp(10**10)+sin(1),10) == NS(exp(10**10),10)
    assert NS('log(1+1/10**50)',20) == '1.0000000000000000000e-50'
    assert NS('log(10**100,10)',10) == '100.0000000'
    assert NS('log(2)',10) == '0.6931471806'
    assert NS('(sin(x)-x)/x**3', 15, subs={x:'1/10**50'}) == '-0.166666666666667'
    assert NS(sin(1)+Rational(1,10**100)*I,15) == '0.841470984807897 + 1.00000000000000e-100*I'
    assert x.evalf() == x
    assert NS((1+I)**2*I, 6) == '-2.00000'
    d={n: (-1)**Rational(6,7), y: (-1)**Rational(4,7), x: (-1)**Rational(2,7)}
    assert NS((x*(1+y*(1 + n))).subs(d).evalf(),6) == '0.346011 + 0.433884*I'
    assert NS(((-I-sqrt(2)*I)**2).evalf()) == '-5.82842712474619'
    assert NS((1+I)**2*I,15) == '-2.00000000000000'
    #1659 (1/2):
    assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71'
    #1659 (2/2): With the bug present, this still only fails if the
    # terms are in the order given here. This is not generally the case,
    # because the order depends on the hashes of the terms.
    assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n,
              subs={n:.01}) == '19.8100000000000'
    assert NS(((x - 1)*((1 - x))**1000).n()) == '(-x + 1.00000000000000)**1000*(x - 1.00000000000000)'
    assert NS((-x).n()) == '-x'
    assert NS((-2*x).n()) == '-2.00000000000000*x'
    assert NS((-2*x*y).n()) == '-2.00000000000000*x*y'
Exemplo n.º 16
0
def test_dmp_clear_denoms():
    assert dmp_clear_denoms([[]], 1, QQ, ZZ) == (ZZ(1), [[]])

    assert dmp_clear_denoms([[QQ(1)]], 1, QQ, ZZ) == (ZZ(1), [[QQ(1)]])
    assert dmp_clear_denoms([[QQ(7)]], 1, QQ, ZZ) == (ZZ(1), [[QQ(7)]])

    assert dmp_clear_denoms([[QQ(7, 3)]], 1, QQ) == (ZZ(3), [[QQ(7)]])
    assert dmp_clear_denoms([[QQ(7, 3)]], 1, QQ, ZZ) == (ZZ(3), [[QQ(7)]])

    assert dmp_clear_denoms(
        [[QQ(3)], [QQ(1)], []], 1, QQ, ZZ) == (ZZ(1), [[QQ(3)], [QQ(1)], []])
    assert dmp_clear_denoms([[QQ(
        1)], [QQ(1, 2)], []], 1, QQ, ZZ) == (ZZ(2), [[QQ(2)], [QQ(1)], []])

    assert dmp_clear_denoms([QQ(3), QQ(
        1), QQ(0)], 0, QQ, ZZ, convert=True) == (ZZ(1), [ZZ(3), ZZ(1), ZZ(0)])
    assert dmp_clear_denoms([QQ(1), QQ(1, 2), QQ(
        0)], 0, QQ, ZZ, convert=True) == (ZZ(2), [ZZ(2), ZZ(1), ZZ(0)])

    assert dmp_clear_denoms([[QQ(3)], [QQ(
        1)], []], 1, QQ, ZZ, convert=True) == (ZZ(1), [[QQ(3)], [QQ(1)], []])
    assert dmp_clear_denoms([[QQ(1)], [QQ(1, 2)], []], 1, QQ, ZZ,
                            convert=True) == (ZZ(2), [[QQ(2)], [QQ(1)], []])

    assert dmp_clear_denoms(
        [[EX(S(3)/2)], [EX(S(9)/4)]], 1, EX) == (EX(4), [[EX(6)], [EX(9)]])
    assert dmp_clear_denoms([[EX(7)]], 1, EX) == (EX(1), [[EX(7)]])
    assert dmp_clear_denoms([[EX(sin(x)/x), EX(0)]], 1, EX) == (EX(x), [[EX(sin(x)), EX(0)]])
Exemplo n.º 17
0
def test_si():
    assert Si(I*x) == I*Shi(x)
    assert Shi(I*x) == I*Si(x)
    assert Si(-I*x) == -I*Shi(x)
    assert Shi(-I*x) == -I*Si(x)
    assert Si(-x) == -Si(x)
    assert Shi(-x) == -Shi(x)
    assert Si(exp_polar(2*pi*I)*x) == Si(x)
    assert Si(exp_polar(-2*pi*I)*x) == Si(x)
    assert Shi(exp_polar(2*pi*I)*x) == Shi(x)
    assert Shi(exp_polar(-2*pi*I)*x) == Shi(x)

    assert mytd(Si(x), sin(x)/x, x)
    assert mytd(Shi(x), sinh(x)/x, x)

    assert mytn(Si(x), Si(x).rewrite(Ei),
                -I*(-Ei(x*exp_polar(-I*pi/2))/2 \
                        + Ei(x*exp_polar(I*pi/2))/2 - I*pi) + pi/2, x)
    assert mytn(Si(x), Si(x).rewrite(expint),
                -I*(-expint(1, x*exp_polar(-I*pi/2))/2 + \
                    expint(1, x*exp_polar(I*pi/2))/2) + pi/2, x)
    assert mytn(Shi(x), Shi(x).rewrite(Ei),
                Ei(x)/2 - Ei(x*exp_polar(I*pi))/2 + I*pi/2, x)
    assert mytn(Shi(x), Shi(x).rewrite(expint),
                expint(1, x)/2 - expint(1, x*exp_polar(I*pi))/2 - I*pi/2, x)

    assert tn_arg(Si)
    assert tn_arg(Shi)

    from sympy import O
    assert Si(x).nseries(x, n=8) == x - x**3/18 + x**5/600 - x**7/35280 + O(x**9)
    assert Shi(x).nseries(x, n=8) == x + x**3/18 + x**5/600 + x**7/35280 + O(x**9)
    assert Si(sin(x)).nseries(x, n=5) == x - 2*x**3/9 + 17*x**5/450 + O(x**6)
    assert Si(x).nseries(x, 1, n=3) == \
           Si(1) + x*sin(1) + x**2/2*cos(1) - x**2/2*sin(1) + O(x**3)
Exemplo n.º 18
0
def test_issue_6920():
    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)]
    # wrap in f to show that the change happens wherever ei occurs
    f = Function('f')
    assert [simplify(f(ei)).args[0] for ei in e] == ok
Exemplo n.º 19
0
def test_Matrix_printing():
    x, y, z = symbols('x,y,z')
    # Test returning a Matrix
    mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
    A = MatrixSymbol('A', 3, 1)
    assert fcode(mat, A) == (
        "      A(1, 1) = x*y\n"
        "      if (y > 0) then\n"
        "         A(2, 1) = x + 2\n"
        "      else\n"
        "         A(2, 1) = y\n"
        "      end if\n"
        "      A(3, 1) = sin(z)")
    # Test using MatrixElements in expressions
    expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
    assert fcode(expr, standard=95) == (
        "      merge(2*A(3, 1), A(3, 1), x > 0) + sin(A(2, 1)) + A(1, 1)")
    # Test using MatrixElements in a Matrix
    q = MatrixSymbol('q', 5, 1)
    M = MatrixSymbol('M', 3, 3)
    m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
        [q[1,0] + q[2,0], q[3, 0], 5],
        [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
    assert fcode(m, M) == (
        "      M(1, 1) = sin(q(2, 1))\n"
        "      M(2, 1) = q(2, 1) + q(3, 1)\n"
        "      M(3, 1) = 2*q(5, 1)/q(2, 1)\n"
        "      M(1, 2) = 0\n"
        "      M(2, 2) = q(4, 1)\n"
        "      M(3, 2) = sqrt(q(1, 1)) + 4\n"
        "      M(1, 3) = cos(q(3, 1))\n"
        "      M(2, 3) = 5\n"
        "      M(3, 3) = 0")
Exemplo n.º 20
0
def test_case():
    ob = FCodePrinter()
    x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y')
    assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \
                        '      exp(x_) + sin(x*y) + cos(X__*Y_)'
    assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \
                        '      2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)'
    assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \
                        '      exp(x_) + sin(x*y) + cos(X*Y)'
    assert fcode(x - cos(X), name_mangling=False) == '      x - cos(X)'
    assert ob.doprint(X*sin(x) + x_, assign_to='me') == '      me = X*sin(x_) + x__'
    assert ob.doprint(X*sin(x), assign_to='mu') == '      mu = X*sin(x_)'
    assert ob.doprint(x_, assign_to='ad') == '      ad = x__'
    n, m = symbols('n,m', integer=True)
    A = IndexedBase('A')
    x = IndexedBase('x')
    y = IndexedBase('y')
    i = Idx('i', m)
    I = Idx('I', n)
    assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == (
                                            "do i = 1, m\n"
                                            "   y(i) = 0\n"
                                            "end do\n"
                                            "do i = 1, m\n"
                                            "   do I_ = 1, n\n"
                                            "      y(i) = A(i, I_)*x(I_) + y(i)\n"
                                            "   end do\n"
                                            "end do" )
def test_special_is_rational():
    i = Symbol('i', integer=True)
    r = Symbol('r', rational=True)
    x = Symbol('x')
    assert sqrt(3).is_rational is False
    assert (3 + sqrt(3)).is_rational is False
    assert (3*sqrt(3)).is_rational is False
    assert exp(3).is_rational is False
    assert exp(i).is_rational is False
    assert exp(r).is_rational is False
    assert exp(x).is_rational is None
    assert exp(log(3), evaluate=False).is_rational is True
    assert log(exp(3), evaluate=False).is_rational is True
    assert log(3).is_rational is False
    assert log(i).is_rational is False
    assert log(r).is_rational is False
    assert log(x).is_rational is None
    assert (sqrt(3) + sqrt(5)).is_rational is None
    assert (sqrt(3) + S.Pi).is_rational is None
    assert (x**i).is_rational is None
    assert (i**i).is_rational is True
    assert (r**i).is_rational is True
    assert (r**r).is_rational is None
    assert (r**x).is_rational is None
    assert sin(1).is_rational is False
    assert sin(i).is_rational is False
    assert sin(r).is_rational is False
    assert sin(x).is_rational is None
    assert asin(r).is_rational is False
    assert sin(asin(3), evaluate=False).is_rational is True
Exemplo n.º 22
0
def test_expr_sorting():
    f, g = symbols('f,g', cls=Function)

    exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n, sin(x**2), cos(x), cos(x**2), tan(x)]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [[3], [1, 2]]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [[1, 2], [2, 3]]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [[1, 2], [1, 2, 3]]
    assert sorted(exprs, key=default_sort_key) == exprs

    exprs = [{x: -y}, {x: y}]
    assert sorted(exprs, key=default_sort_key) == exprs
Exemplo n.º 23
0
def trig_rule(integral):
    integrand, symbol = integral
    if isinstance(integrand, sympy.sin) or isinstance(integrand, sympy.cos):
        arg = integrand.args[0]

        if not isinstance(arg, sympy.Symbol):
            return  # perhaps a substitution can deal with it

        if isinstance(integrand, sympy.sin):
            func = "sin"
        else:
            func = "cos"

        return TrigRule(func, arg, integrand, symbol)

    if integrand == sympy.sec(symbol) ** 2:
        return TrigRule("sec**2", symbol, integrand, symbol)
    elif integrand == sympy.csc(symbol) ** 2:
        return TrigRule("csc**2", symbol, integrand, symbol)

    if isinstance(integrand, sympy.tan):
        rewritten = sympy.sin(*integrand.args) / sympy.cos(*integrand.args)
    elif isinstance(integrand, sympy.cot):
        rewritten = sympy.cos(*integrand.args) / sympy.sin(*integrand.args)
    elif isinstance(integrand, sympy.sec):
        arg = integrand.args[0]
        rewritten = (sympy.sec(arg) ** 2 + sympy.tan(arg) * sympy.sec(arg)) / (sympy.sec(arg) + sympy.tan(arg))
    elif isinstance(integrand, sympy.csc):
        arg = integrand.args[0]
        rewritten = (sympy.csc(arg) ** 2 + sympy.cot(arg) * sympy.csc(arg)) / (sympy.csc(arg) + sympy.cot(arg))
    else:
        return

    return RewriteRule(rewritten, integral_steps(rewritten, symbol), integrand, symbol)
Exemplo n.º 24
0
def test_solve_sqrt_3():
    R = Symbol("R")
    eq = sqrt(2) * R * sqrt(1 / (R + 1)) + (R + 1) * (sqrt(2) * sqrt(1 / (R + 1)) - 1)
    sol = solveset_complex(eq, R)

    assert sol == FiniteSet(
        *[
            S(5) / 3 + 4 * sqrt(10) * cos(atan(3 * sqrt(111) / 251) / 3) / 3,
            -sqrt(10) * cos(atan(3 * sqrt(111) / 251) / 3) / 3
            + 40 * re(1 / ((-S(1) / 2 - sqrt(3) * I / 2) * (S(251) / 27 + sqrt(111) * I / 9) ** (S(1) / 3))) / 9
            + sqrt(30) * sin(atan(3 * sqrt(111) / 251) / 3) / 3
            + S(5) / 3
            + I
            * (
                -sqrt(30) * cos(atan(3 * sqrt(111) / 251) / 3) / 3
                - sqrt(10) * sin(atan(3 * sqrt(111) / 251) / 3) / 3
                + 40 * im(1 / ((-S(1) / 2 - sqrt(3) * I / 2) * (S(251) / 27 + sqrt(111) * I / 9) ** (S(1) / 3))) / 9
            ),
        ]
    )

    # the number of real roots will depend on the value of m: for m=1 there are 4
    # and for m=-1 there are none.
    eq = -sqrt((m - q) ** 2 + (-m / (2 * q) + S(1) / 2) ** 2) + sqrt(
        (-m ** 2 / 2 - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) / 4 - S(1) / 4) ** 2
        + (m ** 2 / 2 - m - sqrt(4 * m ** 4 - 4 * m ** 2 + 8 * m + 1) / 4 - S(1) / 4) ** 2
    )
    raises(NotImplementedError, lambda: solveset_real(eq, q))
Exemplo n.º 25
0
def test_ode_solutions():
    # only a few examples here, the rest will be tested in the actual dsolve tests
    assert constant_renumber(constantsimp(C1*exp(2*x)+exp(x)*(C2+C3), x, 3), 'C', 1, 3) == \
        constant_renumber(C1*exp(x)+C2*exp(2*x), 'C', 1, 2)
    assert constant_renumber(constantsimp(Eq(f(x),I*C1*sinh(x/3) + C2*cosh(x/3)), x, 2),
        'C', 1, 2) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3)), 'C', 1, 2)
    assert constant_renumber(constantsimp(Eq(f(x),acos((-C1)/cos(x))), x, 1), 'C', 1, 1) == \
        Eq(f(x),acos(C1/cos(x)))
    assert constant_renumber(constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), x, 1),
        'C', 1, 1) ==  Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0)
    assert constant_renumber(constantsimp(Eq(log(x*sqrt(2)*sqrt(1/x)*sqrt(f(x))\
        /C1) + x**2/(2*f(x)**2), 0), x, 1), 'C', 1, 1) == \
        Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
    assert constant_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) - \
        cos(f(x)/x)*exp(-f(x)/x)/2, 0), x, 1), 'C', 1, 1) == \
        Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*exp(-f(x)/x)/2, 0)
    u2 = Symbol('u2')
    _a = Symbol('_a')
    assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2), \
        (u2, _a, x/f(x))) + log(f(x)/C1), 0), x, 1), 'C', 1, 1) == \
        Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) + \
        log(C1*f(x)), 0)
    assert [constant_renumber(constantsimp(i, x, 1), 'C', 1, 1) for i in
        [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x +
        x**2))]] == [Eq(f(x), sqrt(C1*x + x**2)),
        Eq(f(x), -sqrt(C1*x + x**2))]
Exemplo n.º 26
0
def test_ode_solutions():
    # only a few examples here, the rest will be tested in the actual dsolve tests
    assert ode_renumber(constantsimp(C1*exp(2*x)+exp(x)*(C2+C3), x, 3), 'C', 1, 3) == \
        ode_renumber(C1*exp(x)+C2*exp(2*x), 'C', 1, 2)
    assert ode_renumber(constantsimp(Eq(f(x),I*C1*sinh(x/3) + C2*cosh(x/3)), x, 2),
        'C', 1, 2) == ode_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3)), 'C', 1, 2)
    assert ode_renumber(constantsimp(Eq(f(x),acos((-C1)/cos(x))), x, 1), 'C', 1, 1) == \
        Eq(f(x),acos(C1/cos(x)))
    assert ode_renumber(constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), x, 1),
        'C', 1, 1) ==  Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0)
    assert ode_renumber(constantsimp(Eq(log(x*2**Rational(1,2)*(1/x)**Rational(1,2)*f(x)\
        **Rational(1,2)/C1) + x**2/(2*f(x)**2), 0), x, 1), 'C', 1, 1) == \
        Eq(log(C1*x*(1/x)**Rational(1,2)*f(x)**Rational(1,2)) + x**2/(2*f(x)**2), 0)
    assert ode_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) - \
        cos(f(x)/x)*exp(-f(x)/x)/2, 0), x, 1), 'C', 1, 1) == \
        Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*exp(-f(x)/x)/2, 0)
    u2 = Symbol('u2')
    _a = Symbol('_a')
    assert ode_renumber(constantsimp(Eq(-Integral(-1/((1 - u2**2)**Rational(1,2)*u2), \
        (u2, _a, x/f(x))) + log(f(x)/C1), 0), x, 1), 'C', 1, 1) == \
        Eq(-Integral(-1/(u2*(1 - u2**2)**Rational(1,2)), (u2, _a, x/f(x))) + \
        log(C1*f(x)), 0)
    assert map(lambda i: ode_renumber(constantsimp(i, x, 1), 'C', 1, 1),
        [Eq(f(x), (-C1*x + x**2)**Rational(1,2)), Eq(f(x), -(-C1*x +
        x**2)**Rational(1,2))]) == [Eq(f(x), (C1*x + x**2)**Rational(1,2)),
        Eq(f(x), -(C1*x + x**2)**Rational(1,2))]
Exemplo n.º 27
0
def func2b(x, y, out, alpha, beta):
    from numpy import sin, cos
    out *= beta
    out += alpha*np.array(
            [[    x*cos(y),    x*cos(y)**2, x*cos(y)**2*sin(y) ],
             [ x**2*cos(y), x**2*sin(y)**2,     x**2*sin(y)**3 ],
             [ x**3*cos(y), x**3*cos(y)**2,     x**3*sin(y)**3 ]])
Exemplo n.º 28
0
def test_transform():
    a = Integral(x**2 + 1, (x, -1, 2))
    fx = x
    fy = 3*y + 1
    assert a.doit() == a.transform(fx, fy).doit()
    assert a.transform(fx, fy).transform(fy, fx) == a
    fx = 3*x + 1
    fy = y
    assert a.transform(fx, fy).transform(fy, fx) == a
    a = Integral(sin(1/x), (x, 0, 1))
    assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo))
    assert a.transform(x, 1/y).transform(y, 1/x) == a
    a = Integral(exp(-x**2), (x, -oo, oo))
    assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo))
    # < 3 arg limit handled properly
    assert Integral(x, x).transform(x, a*y).doit() == \
        Integral(y*a**2, y).doit()
    _3 = S(3)
    assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \
        Integral(-1/x**3, (x, -oo, -1/_3)).doit()
    assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \
        Integral(y**(-3), (y, 1/_3, oo))
    # issue 8400
    i = Integral(x + y, (x, 1, 2), (y, 1, 2))
    assert i.transform(x, (x + 2*y, x)).doit() == \
        i.transform(x, (x + 2*z, x)).doit() == 3
Exemplo n.º 29
0
def test_expand_integral():
    assert Integral(cos(x**2)*(sin(x**2) + 1), (x, 0, 1)).expand() == \
        Integral(cos(x**2)*sin(x**2), (x, 0, 1)) + \
        Integral(cos(x**2), (x, 0, 1))
    assert Integral(cos(x**2)*(sin(x**2) + 1), x).expand() == \
        Integral(cos(x**2)*sin(x**2), x) + \
        Integral(cos(x**2), x)
Exemplo n.º 30
0
def test_manualintegrate_derivative():
    assert manualintegrate(pi * Derivative(x**2 + 2*x + 3), x) == \
        pi * ((x**2 + 2*x + 3))
    assert manualintegrate(Derivative(x**2 + 2*x + 3, y), x) == \
        Integral(Derivative(x**2 + 2*x + 3, y))
    assert manualintegrate(Derivative(sin(x), x, x, x, y), x) == \
        Derivative(sin(x), x, x, y)
Exemplo n.º 31
0
"""
import sys
import os
from sympy import symbols, cos, sin
import numpy as np
from shenfun import inner, div, grad, TestFunction, TrialFunction, Array, \
    Function, TensorProductSpace, FunctionSpace, comm
from shenfun.la import SolverGeneric2ND

# Collect basis and solver from either Chebyshev or Legendre submodules
family = sys.argv[-1].lower() if len(sys.argv) == 2 else 'chebyshev'

# Use sympy to compute a rhs, given an analytical solution
x, y, z = symbols("x,y,z")
ue = (sin(2 * np.pi * z) * sin(4 * np.pi * y) *
      cos(4 * x)) * (1 - y**2) * (1 - z**2)
fe = ue.diff(x, 4) + ue.diff(y, 4) + ue.diff(z, 4) + 2 * ue.diff(
    x, 2, y, 2) + 2 * ue.diff(x, 2, z, 2) + 2 * ue.diff(y, 2, z, 2)

# Size of discretization
N = (36, 36, 36)

K0 = FunctionSpace(N[0], 'Fourier', dtype='d')
S0 = FunctionSpace(N[1], family=family, bc=(0, 0, 0, 0))
S1 = FunctionSpace(N[2], family=family, bc=(0, 0, 0, 0))

T = TensorProductSpace(comm, (K0, S0, S1), axes=(1, 0, 2), slab=True)
u = TrialFunction(T)
v = TestFunction(T)
Exemplo n.º 32
0
def test_laplace_transform():
    from sympy import fresnels, fresnelc
    LT = laplace_transform
    a, b, c, = symbols('a b c', positive=True)
    t = symbols('t')
    w = Symbol("w")
    f = Function("f")

    # Test unevaluated form
    assert laplace_transform(f(t), t, w) == LaplaceTransform(f(t), t, w)
    assert inverse_laplace_transform(f(w), w, t,
                                     plane=0) == InverseLaplaceTransform(
                                         f(w), w, t, 0)

    # test a bug
    spos = symbols('s', positive=True)
    assert LT(exp(t), t, spos)[:2] == (1 / (spos - 1), True)

    # basic tests from wikipedia

    assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \
        ((s + c)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True)
    assert LT(t**a, t, s) == (s**(-a - 1) * gamma(a + 1), 0, True)
    assert LT(Heaviside(t), t, s) == (1 / s, 0, True)
    assert LT(Heaviside(t - a), t, s) == (exp(-a * s) / s, 0, True)
    assert LT(1 - exp(-a * t), t, s) == (a / (s * (a + s)), 0, True)

    assert LT((exp(2*t) - 1)*exp(-b - t)*Heaviside(t)/2, t, s, noconds=True) \
        == exp(-b)/(s**2 - 1)

    assert LT(exp(t), t, s)[:2] == (1 / (s - 1), 1)
    assert LT(exp(2 * t), t, s)[:2] == (1 / (s - 2), 2)
    assert LT(exp(a * t), t, s)[:2] == (1 / (s - a), a)

    assert LT(log(t / a), t,
              s) == ((log(a * s) + EulerGamma) / s / -1, 0, True)

    assert LT(erf(t), t, s) == ((erfc(s / 2)) * exp(s**2 / 4) / s, 0, True)

    assert LT(sin(a * t), t, s) == (a / (a**2 + s**2), 0, True)
    assert LT(cos(a * t), t, s) == (s / (a**2 + s**2), 0, True)
    # TODO would be nice to have these come out better
    assert LT(exp(-a * t) * sin(b * t), t,
              s) == (b / (b**2 + (a + s)**2), -a, True)
    assert LT(exp(-a*t)*cos(b*t), t, s) == \
        ((a + s)/(b**2 + (a + s)**2), -a, True)

    assert LT(besselj(0, t), t, s) == (1 / sqrt(1 + s**2), 0, True)
    assert LT(besselj(1, t), t, s) == (1 - 1 / sqrt(1 + 1 / s**2), 0, True)
    # TODO general order works, but is a *mess*
    # TODO besseli also works, but is an even greater mess

    # test a bug in conditions processing
    # TODO the auxiliary condition should be recognised/simplified
    assert LT(exp(t) * cos(t), t, s)[:-1] in [
        ((s - 1) / (s**2 - 2 * s + 2), -oo),
        ((s - 1) / ((s - 1)**2 + 1), -oo),
    ]

    # Fresnel functions
    assert laplace_transform(fresnels(t), t, s) == \
        ((-sin(s**2/(2*pi))*fresnels(s/pi) + sin(s**2/(2*pi))/2 -
            cos(s**2/(2*pi))*fresnelc(s/pi) + cos(s**2/(2*pi))/2)/s, 0, True)
    assert laplace_transform(
        fresnelc(t), t,
        s) == ((sin(s**2 / (2 * pi)) * fresnelc(s / pi) / s -
                cos(s**2 / (2 * pi)) * fresnels(s / pi) / s +
                sqrt(2) * cos(s**2 / (2 * pi) + pi / 4) / (2 * s), 0, True))

    assert LT(Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]]), t, s) ==\
        Matrix([
            [(1/(s - 1), 1, True), ((s + 1)**(-2), 0, True)],
            [((s + 1)**(-2), 0, True), (1/(s - 1), 1, True)]
        ])
Exemplo n.º 33
0
 def sinc(x):
     return sin(pi * x) / (pi * x)
Exemplo n.º 34
0
def test_inverse_mellin_transform():
    from sympy import (sin, simplify, Max, Min, expand, powsimp, exp_polar,
                       cos, cot)
    IMT = inverse_mellin_transform

    assert IMT(gamma(s), s, x, (0, oo)) == exp(-x)
    assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1 / x)
    assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \
        (x**2 + 1)*Heaviside(1 - x)/(4*x)

    # test passing "None"
    assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
    assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)

    # test expansion of sums
    assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1) * exp(-x) / x

    # test factorisation of polys
    r = symbols('r', real=True)
    assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo)
              ).subs(x, r).rewrite(sin).simplify() \
        == sin(r)*Heaviside(1 - exp(-r))

    # test multiplicative substitution
    _a, _b = symbols('a b', positive=True)
    assert IMT(_b**(-s / _a) * factorial(s / _a) / s, s, x,
               (0, oo)) == exp(-_b * x**_a)
    assert IMT(factorial(_a / _b + s / _b) / (_a + s), s, x,
               (-_a, oo)) == x**_a * exp(-x**_b)

    def simp_pows(expr):
        return simplify(powsimp(expand_mul(expr, deep=False),
                                force=True)).replace(exp_polar, exp)

    # Now test the inverses of all direct transforms tested above

    # Section 8.4.2
    nu = symbols('nu', real=True, finite=True)
    assert IMT(-1 / (nu + s), s, x, (-oo, None)) == x**nu * Heaviside(x - 1)
    assert IMT(1 / (nu + s), s, x, (None, oo)) == x**nu * Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \
        == (1 - x)**(beta - 1)*Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
                         s, x, (-oo, None))) \
        == (x - 1)**(beta - 1)*Heaviside(x - 1)
    assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \
        == (1/(x + 1))**rho
    assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c)
                         *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi,
                         s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \
        == (x**c - d**c)/(x - d)

    assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s)
                        *gamma(-c/2 - s)/gamma(1 - c - s),
                        s, x, (0, -re(c)/2))) == \
        (1 + sqrt(x + 1))**c
    assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s)
                        /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \
        b**(a - 1)*(sqrt(1 + x/b**2) + 1)**(a - 1)*(b**2*sqrt(1 + x/b**2) +
        b**2 + x)/(b**2 + x)
    assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s)
                        / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \
        b**c*(sqrt(1 + x/b**2) + 1)**c

    # Section 8.4.5
    assert IMT(24 / s**5, s, x, (0, oo)) == log(x)**4 * Heaviside(1 - x)
    assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \
        log(x)**3*Heaviside(x - 1)
    assert IMT(pi / (s * sin(pi * s)), s, x, (-1, 0)) == log(x + 1)
    assert IMT(pi / (s * sin(pi * s / 2)), s, x, (-2, 0)) == log(x**2 + 1)
    assert IMT(pi / (s * sin(2 * pi * s)), s, x,
               (-S(1) / 2, 0)) == log(sqrt(x) + 1)
    assert IMT(pi / (s * sin(pi * s)), s, x, (0, 1)) == log(1 + 1 / x)

    # TODO
    def mysimp(expr):
        from sympy import expand, logcombine, powsimp
        return expand(powsimp(logcombine(expr, force=True),
                              force=True,
                              deep=True),
                      force=True).replace(exp_polar, exp)

    assert mysimp(mysimp(IMT(pi / (s * tan(pi * s)), s, x, (-1, 0)))) in [
        log(1 - x) * Heaviside(1 - x) + log(x - 1) * Heaviside(x - 1),
        log(x) * Heaviside(x - 1) + log(1 - 1 / x) * Heaviside(x - 1) +
        log(-x + 1) * Heaviside(-x + 1)
    ]
    # test passing cot
    assert mysimp(IMT(pi * cot(pi * s) / s, s, x, (0, 1))) in [
        log(1 / x - 1) * Heaviside(1 - x) + log(1 - 1 / x) * Heaviside(x - 1),
        -log(x) * Heaviside(-x + 1) + log(1 - 1 / x) * Heaviside(x - 1) +
        log(-x + 1) * Heaviside(-x + 1),
    ]

    # 8.4.14
    assert IMT(-gamma(s + S(1)/2)/(sqrt(pi)*s), s, x, (-S(1)/2, 0)) == \
        erf(sqrt(x))

    # 8.4.19
    assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, S(3)/4))) \
        == besselj(a, 2*sqrt(x))
    assert simplify(IMT(2**a*gamma(S(1)/2 - 2*s)*gamma(s + (a + 1)/2)
                      / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-(re(a) + 1)/2, S(1)/4))) == \
        sin(sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S(1)/2 - 2*s)
                      / (gamma(S(1)/2 - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-re(a)/2, S(1)/4))) == \
        cos(sqrt(x))*besselj(a, sqrt(x))
    # TODO this comes out as an amazing mess, but simplifies nicely
    assert simplify(IMT(gamma(a + s)*gamma(S(1)/2 - s)
                      / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
                      s, x, (-re(a), S(1)/2))) == \
        besselj(a, sqrt(x))**2
    assert simplify(IMT(gamma(s)*gamma(S(1)/2 - s)
                      / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)),
                      s, x, (0, S(1)/2))) == \
        besselj(-a, sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
                      / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
                         *gamma(a/2 + b/2 - s + 1)),
                      s, x, (-(re(a) + re(b))/2, S(1)/2))) == \
        besselj(a, sqrt(x))*besselj(b, sqrt(x))

    # Section 8.4.20
    # TODO this can be further simplified!
    assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) *
                    gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) /
                    (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
                    s, x,
                    (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S(1)/2))) == \
                    besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) -
                    besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b)
    # TODO more

    # for coverage

    assert IMT(pi / cos(pi * s), s, x, (0, S(1) / 2)) == sqrt(x) / (x + 1)
Exemplo n.º 35
0
def test_mellin_transform_bessel():
    from sympy import Max
    MT = mellin_transform

    # 8.4.19
    assert MT(besselj(a, 2*sqrt(x)), x, s) == \
        (gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, S(3)/4), True)
    assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (2**a*gamma(-2*s + S(1)/2)*gamma(a/2 + s + S(1)/2)/(
        gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), (
        -re(a)/2 - S(1)/2, S(1)/4), True)
    assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (2**a*gamma(a/2 + s)*gamma(-2*s + S(1)/2)/(
        gamma(-a/2 - s + S(1)/2)*gamma(a - 2*s + 1)), (
        -re(a)/2, S(1)/4), True)
    assert MT(besselj(a, sqrt(x))**2, x, s) == \
        (gamma(a + s)*gamma(S(1)/2 - s)
         / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
            (-re(a), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \
        (gamma(s)*gamma(S(1)/2 - s)
         / (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)),
            (0, S(1)/2), True)
    # NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as
    #       I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large)
    assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (gamma(1 - s)*gamma(a + s - S(1)/2)
         / (sqrt(pi)*gamma(S(3)/2 - s)*gamma(a - s + S(1)/2)),
            (S(1)/2 - re(a), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \
        (4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s)
         / (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2)
            *gamma( 1 - s + (a + b)/2)),
            (-(re(a) + re(b))/2, S(1)/2), True)
    assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \
        ((Max(re(a), -re(a)), S(1)/2), True)

    # Section 8.4.20
    assert MT(bessely(a, 2*sqrt(x)), x, s) == \
        (-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi,
            (Max(-re(a)/2, re(a)/2), S(3)/4), True)
    assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-4**s*sin(pi*(a/2 - s))*gamma(S(1)/2 - 2*s)
         * gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s)
         / (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)),
            (Max(-(re(a) + 1)/2, (re(a) - 1)/2), S(1)/4), True)
    assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S(1)/2 - 2*s)
         / (sqrt(pi)*gamma(S(1)/2 - s - a/2)*gamma(S(1)/2 - s + a/2)),
            (Max(-re(a)/2, re(a)/2), S(1)/4), True)
    assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S(1)/2 - s)
         / (pi**S('3/2')*gamma(1 + a - s)),
            (Max(-re(a), 0), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \
        (-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s)
         * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s)
         / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
            (Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S(1)/2), True)
    # NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x))
    # are a mess (no matter what way you look at it ...)
    assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \
             ((Max(-re(a), 0, re(a)), S(1)/2), True)

    # Section 8.4.22
    # TODO we can't do any of these (delicate cancellation)

    # Section 8.4.23
    assert MT(besselk(a, 2*sqrt(x)), x, s) == \
        (gamma(
         s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True)
    assert MT(
        besselj(a, 2 * sqrt(2 * sqrt(x))) * besselk(a, 2 * sqrt(2 * sqrt(x))),
        x, s) == (4**(-s) * gamma(2 * s) * gamma(a / 2 + s) /
                  (2 * gamma(a / 2 - s + 1)), (Max(0, -re(a) / 2), oo), True)
    # TODO bessely(a, x)*besselk(a, x) is a mess
    assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
        (gamma(s)*gamma(
        a + s)*gamma(-s + S(1)/2)/(2*sqrt(pi)*gamma(a - s + 1)),
        (Max(-re(a), 0), S(1)/2), True)
    assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
        (2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \
        gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \
        gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \
        re(a)/2 - re(b)/2), S(1)/2), True)

    # TODO products of besselk are a mess

    mt = MT(exp(-x / 2) * besselk(a, x / 2), x, s)
    mt0 = combsimp((trigsimp(combsimp(mt[0].expand(func=True)))))
    assert mt0 == 2 * pi**(S(3) / 2) * cos(pi * s) * gamma(-s + S(1) / 2) / (
        (cos(2 * pi * a) - cos(2 * pi * s)) * gamma(-a - s + 1) *
        gamma(a - s + 1))
    assert mt[1:] == ((Max(-re(a), re(a)), oo), True)
Exemplo n.º 36
0
####################################################

## Translational Transformations #################################

g_transb = sym.Matrix([[1, 0, 0, x], [0, 1, 0, h], [0, 0, 1, 0], [0, 0, 0, 1]])

g_transp2 = sym.Matrix([[1, 0, 0, l / 2], [0, 1, 0, 0], [0, 0, 1, 0],
                        [0, 0, 0, 1]])

g_transx = sym.Matrix([[1, 0, 0, 0], [0, 1, 0, -h], [0, 0, 1, 0], [0, 0, 0,
                                                                   1]])

## Rotational Transformations ####################################

g_rotp1 = sym.Matrix([[sym.cos(th1), -sym.sin(th1), 0, 0],
                      [sym.sin(th1), sym.cos(th1), 0, 0], [0, 0, 1, 0],
                      [0, 0, 0, 1]])

g_rotp2 = sym.Matrix([[sym.cos(th2), -sym.sin(th2), 0, 0],
                      [sym.sin(th2), sym.cos(th2), 0, 0], [0, 0, 1, 0],
                      [0, 0, 0, 1]])

## System Transformations - all bodies relative to the base frame ##########################

g_bp1 = g_rotp1

g_bp2 = g_bp1 * g_transp2 * g_rotp2

g_bx = g_transx
Exemplo n.º 37
0
 def _represent_XOp(self, basis, **options):
     x = Symbol('x')
     n = Symbol('n')
     subs_info = options.get('subs', {})
     return sqrt(2 / L) * sin(n * pi * x / L).subs(subs_info)
Exemplo n.º 38
0
def test_order_symbols():
    e = x * y * sin(x) * Integral(x, (x, 1, 2))
    assert O(e) == O(x**2 * y, x, y)
    assert O(e, x) == O(x**2)
Exemplo n.º 39
0
from nlsymb import np, sym, matmult, tensor
import nlsymb.tensor as tn

from sympy import Symbol as S, sin, cos

from Cdynamics import WriteDynamics, WriteLinearizations

if __name__ == "__main__":
    # x, u
    x = np.array([S('x1'), S('x2'), S('x3'), S('x4')])  # theta, theta', x, x'
    u = np.array([S('u1')])  # x''

    # constants
    g = S('m_g')
    h = S('h')

    # dynamics
    f = np.array([x[1], (g * sin(x[0]) + cos(x[0]) * u[0]) / h, x[3], u[0]])

    # linearizations
    A = tn.diff(f, x)
    B = tn.diff(f, u)

    # write to file
    WriteDynamics(f, x, u)
    WriteLinearizations(A, B, x, u)
Exemplo n.º 40
0
def cylinder_stream_function(U=1, R=1):
    r = sympy.sqrt(x ** 2 + y ** 2)
    theta = sympy.atan2(y, x)
    return U * (r - R ** 2 / r) * sympy.sin(theta)
Exemplo n.º 41
0
def test_roots():
    assert roots(1, x) == {}
    assert roots(x, x) == {S.Zero: 1}
    assert roots(x**9, x) == {S.Zero: 9}
    assert roots(((x - 2) * (x + 3) * (x - 4)).expand(), x) == {
        -S(3): 1,
        S(2): 1,
        S(4): 1
    }

    assert roots(2 * x + 1, x) == {-S.Half: 1}
    assert roots((2 * x + 1)**2, x) == {-S.Half: 2}
    assert roots((2 * x + 1)**5, x) == {-S.Half: 5}
    assert roots((2 * x + 1)**10, x) == {-S.Half: 10}

    assert roots(x**4 - 1, x) == {I: 1, S.One: 1, -S.One: 1, -I: 1}
    assert roots((x**4 - 1)**2, x) == {I: 2, S.One: 2, -S.One: 2, -I: 2}

    assert roots(((2 * x - 3)**2).expand(), x) == {Rational(3, 2): 2}
    assert roots(((2 * x + 3)**2).expand(), x) == {-Rational(3, 2): 2}

    assert roots(((2 * x - 3)**3).expand(), x) == {Rational(3, 2): 3}
    assert roots(((2 * x + 3)**3).expand(), x) == {-Rational(3, 2): 3}

    assert roots(((2 * x - 3)**5).expand(), x) == {Rational(3, 2): 5}
    assert roots(((2 * x + 3)**5).expand(), x) == {-Rational(3, 2): 5}

    assert roots(((a * x - b)**5).expand(), x) == {b / a: 5}
    assert roots(((a * x + b)**5).expand(), x) == {-b / a: 5}

    assert roots(x**4 - 2 * x**2 + 1, x) == {S.One: 2, -S.One: 2}

    assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \
        {S.One: 2, -1 - sqrt(2): 1, S.Zero: 2, -1 + sqrt(2): 1}

    assert roots(x**8 - 1, x) == {
        sqrt(2) / 2 + I * sqrt(2) / 2: 1,
        sqrt(2) / 2 - I * sqrt(2) / 2: 1,
        -sqrt(2) / 2 + I * sqrt(2) / 2: 1,
        -sqrt(2) / 2 - I * sqrt(2) / 2: 1,
        S.One: 1,
        -S.One: 1,
        I: 1,
        -I: 1
    }

    f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \
        224*x**7 - 384*x**8 - 64*x**9

    assert roots(f) == {
        S(0): 2,
        -S(2): 2,
        S(2): 1,
        -S(7) / 2: 1,
        -S(3) / 2: 1,
        -S(1) / 2: 1,
        S(3) / 2: 1
    }

    assert roots((a + b + c) * x - (a + b + c + d), x) == {
        (a + b + c + d) / (a + b + c): 1
    }

    assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {}
    assert roots(((x - 2) * (x + 3) * (x - 4)).expand(), x, cubics=False) == {
        -S(3): 1,
        S(2): 1,
        S(4): 1
    }
    assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \
        {-S(3): 1, S(2): 1, S(4): 1, S(5): 1}
    assert roots(x**3 + 2 * x**2 + 4 * x + 8, x) == {
        -S(2): 1,
        -2 * I: 1,
        2 * I: 1
    }
    assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \
        {-2*I: 1, 2*I: 1, -S(2): 1}
    assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x ) == \
        {S(1): 1, S(0): 1, -S(2): 1, -2*I: 1, 2*I: 1}

    r1_2, r1_3, r1_9, r4_9, r19_27 = [
        Rational(*r) for r in ((1, 2), (1, 3), (1, 9), (4, 9), (19, 27))
    ]

    U = -r1_2 - r1_2 * I * 3**r1_2
    V = -r1_2 + r1_2 * I * 3**r1_2
    W = (r19_27 + r1_9 * 33**r1_2)**r1_3

    assert roots(x**3 + x**2 - x + 1, x, cubics=True) == {
        -r1_3 - U * W - r4_9 * (U * W)**(-1): 1,
        -r1_3 - V * W - r4_9 * (V * W)**(-1): 1,
        -r1_3 - W - r4_9 * (W)**(-1): 1,
    }

    f = (x**2 + 2 * x + 3).subs(x, 2 * x**2 + 3 * x).subs(x, 5 * x - 4)

    r13_20, r1_20 = [Rational(*r) for r in ((13, 20), (1, 20))]

    s2 = sqrt(2)
    assert roots(f, x) == {
        r13_20 + r1_20 * sqrt(1 - 8 * I * s2): 1,
        r13_20 - r1_20 * sqrt(1 - 8 * I * s2): 1,
        r13_20 + r1_20 * sqrt(1 + 8 * I * s2): 1,
        r13_20 - r1_20 * sqrt(1 + 8 * I * s2): 1,
    }

    f = x**4 + x**3 + x**2 + x + 1

    r1_4, r1_8, r5_8 = [Rational(*r) for r in ((1, 4), (1, 8), (5, 8))]

    assert roots(f, x) == {
        -r1_4 + r1_4 * 5**r1_2 + I * (r5_8 + r1_8 * 5**r1_2)**r1_2: 1,
        -r1_4 + r1_4 * 5**r1_2 - I * (r5_8 + r1_8 * 5**r1_2)**r1_2: 1,
        -r1_4 - r1_4 * 5**r1_2 + I * (r5_8 - r1_8 * 5**r1_2)**r1_2: 1,
        -r1_4 - r1_4 * 5**r1_2 - I * (r5_8 - r1_8 * 5**r1_2)**r1_2: 1,
    }

    f = z**3 + (-2 - y) * z**2 + (1 + 2 * y - 2 * x**2) * z - y + 2 * x**2

    assert roots(f, z) == {
        S.One: 1,
        S.Half + S.Half * y + S.Half * sqrt(1 - 2 * y + y**2 + 8 * x**2): 1,
        S.Half + S.Half * y - S.Half * sqrt(1 - 2 * y + y**2 + 8 * x**2): 1,
    }

    assert roots(a * b * c * x**3 + 2 * x**2 + 4 * x + 8, x,
                 cubics=False) == {}
    assert roots(a * b * c * x**3 + 2 * x**2 + 4 * x + 8, x, cubics=True) != {}

    assert roots(x**4 - 1, x, filter='Z') == {S.One: 1, -S.One: 1}
    assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1}

    assert roots((x - 1) * (x + 1), x) == {S.One: 1, -S.One: 1}
    assert roots((x - 1) * (x + 1), x, predicate=lambda r: r.is_positive) == {
        S.One: 1
    }

    assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-S.One, S.One]
    assert roots(x**4 - 1, x, filter='I', multiple=True) == [-I, I]

    assert roots(x**3, x, multiple=True) == [S.Zero, S.Zero, S.Zero]
    assert roots(1234, x, multiple=True) == []

    f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1

    assert roots(f) == {
        -I * sin(pi / 7) + cos(pi / 7): 1,
        -I * sin(2 * pi / 7) - cos(2 * pi / 7): 1,
        -I * sin(3 * pi / 7) + cos(3 * pi / 7): 1,
        I * sin(pi / 7) + cos(pi / 7): 1,
        I * sin(2 * pi / 7) - cos(2 * pi / 7): 1,
        I * sin(3 * pi / 7) + cos(3 * pi / 7): 1,
    }

    g = ((x**2 + 1) * f**2).expand()

    assert roots(g) == {
        -I * sin(pi / 7) + cos(pi / 7): 2,
        -I * sin(2 * pi / 7) - cos(2 * pi / 7): 2,
        -I * sin(3 * pi / 7) + cos(3 * pi / 7): 2,
        I * sin(pi / 7) + cos(pi / 7): 2,
        I * sin(2 * pi / 7) - cos(2 * pi / 7): 2,
        I * sin(3 * pi / 7) + cos(3 * pi / 7): 2,
        -I: 1,
        I: 1,
    }

    r = roots(x**3 + 40 * x + 64)
    real_root = [rx for rx in r if rx.is_real][0]
    cr = 4 + 2 * sqrt(1074) / 9
    assert real_root == -2 * cr**(S(1) / 3) + 20 / (3 * cr**(S(1) / 3))

    eq = Poly((7 + 5 * sqrt(2)) * x**3 + (-6 - 4 * sqrt(2)) * x**2 +
              (-sqrt(2) - 1) * x + 2,
              x,
              domain='EX')
    assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2 * sqrt(2): 1, -sqrt(2) + 1: 1}

    eq = Poly(41 * x**5 + 29 * sqrt(2) * x**5 - 153 * x**4 -
              108 * sqrt(2) * x**4 + 175 * x**3 + 125 * sqrt(2) * x**3 -
              45 * x**2 - 30 * sqrt(2) * x**2 - 26 * sqrt(2) * x - 26 * x + 24,
              x,
              domain='EX')
    assert roots(eq) == {
        -sqrt(2) + 1: 1,
        -2 + 2 * sqrt(2): 1,
        -1 + sqrt(2): 1,
        -4 + 4 * sqrt(2): 1,
        -3 + 3 * sqrt(2): 1
    }

    eq = Poly(x**3 - 2 * x**2 + 6 * sqrt(2) * x**2 - 8 * sqrt(2) * x + 23 * x -
              14 + 14 * sqrt(2),
              x,
              domain='EX')
    assert roots(eq) == {
        -2 * sqrt(2) + 2: 1,
        -2 * sqrt(2) + 1: 1,
        -2 * sqrt(2) - 1: 1
    }

    assert roots(Poly((x + sqrt(2))**3 - 7, x, domain='EX')) == \
        {-sqrt(2) - 7**(S(1)/3)/2 - sqrt(3)*7**(S(1)/3)*I/2: 1,
         -sqrt(2) - 7**(S(1)/3)/2 + sqrt(3)*7**(S(1)/3)*I/2: 1,
         -sqrt(2) + 7**(S(1)/3): 1}
Exemplo n.º 42
0
def test_contains_4():
    assert Order(sin(1 / x**2)).contains(Order(cos(1 / x**2))) is None
    assert Order(cos(1 / x**2)).contains(Order(sin(1 / x**2))) is None
Exemplo n.º 43
0
def test_cosh():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert cosh(nan) == nan
    assert cosh(zoo) == nan

    assert cosh(oo) == oo
    assert cosh(-oo) == oo

    assert cosh(0) == 1

    assert cosh(1) == cosh(1)
    assert cosh(-1) == cosh(1)

    assert cosh(x) == cosh(x)
    assert cosh(-x) == cosh(x)

    assert cosh(pi*I) == cos(pi)
    assert cosh(-pi*I) == cos(pi)

    assert cosh(2**1024 * E) == cosh(2**1024 * E)
    assert cosh(-2**1024 * E) == cosh(2**1024 * E)

    assert cosh(pi*I/2) == 0
    assert cosh(-pi*I/2) == 0
    assert cosh((-3*10**73 + 1)*pi*I/2) == 0
    assert cosh((7*10**103 + 1)*pi*I/2) == 0

    assert cosh(pi*I) == -1
    assert cosh(-pi*I) == -1
    assert cosh(5*pi*I) == -1
    assert cosh(8*pi*I) == 1

    assert cosh(pi*I/3) == S.Half
    assert cosh(-2*pi*I/3) == -S.Half

    assert cosh(pi*I/4) == S.Half*sqrt(2)
    assert cosh(-pi*I/4) == S.Half*sqrt(2)
    assert cosh(11*pi*I/4) == -S.Half*sqrt(2)
    assert cosh(-3*pi*I/4) == -S.Half*sqrt(2)

    assert cosh(pi*I/6) == S.Half*sqrt(3)
    assert cosh(-pi*I/6) == S.Half*sqrt(3)
    assert cosh(7*pi*I/6) == -S.Half*sqrt(3)
    assert cosh(-5*pi*I/6) == -S.Half*sqrt(3)

    assert cosh(pi*I/105) == cos(pi/105)
    assert cosh(-pi*I/105) == cos(pi/105)

    assert cosh(2 + 3*I) == cosh(2 + 3*I)

    assert cosh(x*I) == cos(x)

    assert cosh(k*pi*I) == cos(k*pi)
    assert cosh(17*k*pi*I) == cos(17*k*pi)

    assert cosh(k*pi) == cosh(k*pi)

    assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)),
                sin(im(x))*sinh(re(x)))
    x = Symbol('x', extended_real=True)
    assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)

    x = Symbol('x', real=True)
    assert cosh(I*x).is_finite is True
Exemplo n.º 44
0
def test_Vector_diffs():
    q1, q2, q3, q4 = dynamicsymbols("q1 q2 q3 q4")
    q1d, q2d, q3d, q4d = dynamicsymbols("q1 q2 q3 q4", 1)
    q1dd, q2dd, q3dd, q4dd = dynamicsymbols("q1 q2 q3 q4", 2)
    N = ReferenceFrame("N")
    A = N.orientnew("A", "Axis", [q3, N.z])
    B = A.orientnew("B", "Axis", [q2, A.x])
    v1 = q2 * A.x + q3 * N.y
    v2 = q3 * B.x + v1
    v3 = v1.dt(B)
    v4 = v2.dt(B)
    v5 = q1 * A.x + q2 * A.y + q3 * A.z

    assert v1.dt(N) == q2d * A.x + q2 * q3d * A.y + q3d * N.y
    assert v1.dt(A) == q2d * A.x + q3 * q3d * N.x + q3d * N.y
    assert v1.dt(B) == (q2d * A.x + q3 * q3d * N.x + q3d * N.y -
                        q3 * cos(q3) * q2d * N.z)
    assert v2.dt(N) == (q2d * A.x + (q2 + q3) * q3d * A.y + q3d * B.x +
                        q3d * N.y)
    assert v2.dt(A) == q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y
    assert v2.dt(B) == (q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y -
                        q3 * cos(q3) * q2d * N.z)
    assert v3.dt(N) == (q2dd * A.x + q2d * q3d * A.y +
                        (q3d**2 + q3 * q3dd) * N.x + q3dd * N.y +
                        (q3 * sin(q3) * q2d * q3d - cos(q3) * q2d * q3d -
                         q3 * cos(q3) * q2dd) * N.z)
    assert v3.dt(A) == (q2dd * A.x + (2 * q3d**2 + q3 * q3dd) * N.x +
                        (q3dd - q3 * q3d**2) * N.y +
                        (q3 * sin(q3) * q2d * q3d - cos(q3) * q2d * q3d -
                         q3 * cos(q3) * q2dd) * N.z)
    assert v3.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y +
                        (2 * q3d**2 + q3 * q3dd) * N.x +
                        (q3dd - q3 * q3d**2) * N.y +
                        (2 * q3 * sin(q3) * q2d * q3d -
                         2 * cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
    assert v4.dt(N) == (q2dd * A.x + q3d * (q2d + q3d) * A.y + q3dd * B.x +
                        (q3d**2 + q3 * q3dd) * N.x + q3dd * N.y +
                        (q3 * sin(q3) * q2d * q3d - cos(q3) * q2d * q3d -
                         q3 * cos(q3) * q2dd) * N.z)
    assert v4.dt(A) == (q2dd * A.x + q3dd * B.x +
                        (2 * q3d**2 + q3 * q3dd) * N.x +
                        (q3dd - q3 * q3d**2) * N.y +
                        (q3 * sin(q3) * q2d * q3d - cos(q3) * q2d * q3d -
                         q3 * cos(q3) * q2dd) * N.z)
    assert v4.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y + q3dd * B.x +
                        (2 * q3d**2 + q3 * q3dd) * N.x +
                        (q3dd - q3 * q3d**2) * N.y +
                        (2 * q3 * sin(q3) * q2d * q3d -
                         2 * cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
    assert v5.dt(
        B) == q1d * A.x + (q3 * q2d + q2d) * A.y + (-q2 * q2d + q3d) * A.z
    assert v5.dt(A) == q1d * A.x + q2d * A.y + q3d * A.z
    assert v5.dt(
        N) == (-q2 * q3d + q1d) * A.x + (q1 * q3d + q2d) * A.y + q3d * A.z
    assert v3.diff(q1d, N) == 0
    assert v3.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
    assert v3.diff(q3d, N) == q3 * N.x + N.y
    assert v3.diff(q1d, A) == 0
    assert v3.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
    assert v3.diff(q3d, A) == q3 * N.x + N.y
    assert v3.diff(q1d, B) == 0
    assert v3.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
    assert v3.diff(q3d, B) == q3 * N.x + N.y
    assert v4.diff(q1d, N) == 0
    assert v4.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
    assert v4.diff(q3d, N) == B.x + q3 * N.x + N.y
    assert v4.diff(q1d, A) == 0
    assert v4.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
    assert v4.diff(q3d, A) == B.x + q3 * N.x + N.y
    assert v4.diff(q1d, B) == 0
    assert v4.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
    assert v4.diff(q3d, B) == B.x + q3 * N.x + N.y
Exemplo n.º 45
0
def test_coth():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert coth(nan) == nan
    assert coth(zoo) == nan

    assert coth(oo) == 1
    assert coth(-oo) == -1

    assert coth(0) == coth(0)
    assert coth(0) == zoo
    assert coth(1) == coth(1)
    assert coth(-1) == -coth(1)

    assert coth(x) == coth(x)
    assert coth(-x) == -coth(x)

    assert coth(pi*I) == -I*cot(pi)
    assert coth(-pi*I) == cot(pi)*I

    assert coth(2**1024 * E) == coth(2**1024 * E)
    assert coth(-2**1024 * E) == -coth(2**1024 * E)

    assert coth(pi*I) == -I*cot(pi)
    assert coth(-pi*I) == I*cot(pi)
    assert coth(2*pi*I) == -I*cot(2*pi)
    assert coth(-2*pi*I) == I*cot(2*pi)
    assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi)
    assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi)

    assert coth(pi*I/2) == 0
    assert coth(-pi*I/2) == 0
    assert coth(5*pi*I/2) == 0
    assert coth(7*pi*I/2) == 0

    assert coth(pi*I/3) == -I/sqrt(3)
    assert coth(-2*pi*I/3) == -I/sqrt(3)

    assert coth(pi*I/4) == -I
    assert coth(-pi*I/4) == I
    assert coth(17*pi*I/4) == -I
    assert coth(-3*pi*I/4) == -I

    assert coth(pi*I/6) == -sqrt(3)*I
    assert coth(-pi*I/6) == sqrt(3)*I
    assert coth(7*pi*I/6) == -sqrt(3)*I
    assert coth(-5*pi*I/6) == -sqrt(3)*I

    assert coth(pi*I/105) == -cot(pi/105)*I
    assert coth(-pi*I/105) == cot(pi/105)*I

    assert coth(2 + 3*I) == coth(2 + 3*I)

    assert coth(x*I) == -cot(x)*I

    assert coth(k*pi*I) == -cot(k*pi)*I
    assert coth(17*k*pi*I) == -cot(17*k*pi)*I

    assert coth(k*pi*I) == -cot(k*pi)*I

    assert coth(log(tan(2))) == coth(log(-tan(2)))
    assert coth(1 + I*pi/2) == tanh(1)

    assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2
                                + sinh(re(x))**2),
                                -sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2))
    x = Symbol('x', extended_real=True)
    assert coth(x).as_real_imag(deep=False) == (coth(x), 0)
Exemplo n.º 46
0
def test_im():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert im(nan) == nan

    assert im(oo * I) == oo
    assert im(-oo * I) == -oo

    assert im(0) == 0

    assert im(1) == 0
    assert im(-1) == 0

    assert im(E * I) == E
    assert im(-E * I) == -E

    assert unchanged(im, x)
    assert im(x * I) == re(x)
    assert im(r * I) == r
    assert im(r) == 0
    assert im(i * I) == 0
    assert im(i) == -I * i

    assert im(x + y) == im(x + y)
    assert im(x + r) == im(x)
    assert im(x + r * I) == im(x) + r

    assert im(im(x) * I) == im(x)

    assert im(2 + I) == 1
    assert im(x + I) == im(x) + 1

    assert im(x + y * I) == im(x) + re(y)
    assert im(x + r * I) == im(x) + r

    assert im(log(2 * I)) == pi / 2

    assert im((2 + I)**2).expand(complex=True) == 4

    assert im(conjugate(x)) == -im(x)
    assert conjugate(im(x)) == im(x)

    assert im(x).as_real_imag() == (im(x), 0)

    assert im(i * r * x).diff(r) == im(i * x)
    assert im(i * r * x).diff(i) == -I * re(r * x)

    assert im(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * sin(atan2(b, a) / 2)
    assert im(a * (2 + b * I)) == a * b

    assert im((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2

    assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
    assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False

    assert im(S.ComplexInfinity) == S.NaN

    n, m, l = symbols('n m l')
    A = MatrixSymbol('A', n, m)

    assert im(A) == (S(1) / (2 * I)) * (A - conjugate(A))

    A = Matrix([[1 + 4 * I, 2], [0, -3 * I]])
    assert im(A) == Matrix([[4, 0], [0, -3]])

    A = ImmutableMatrix([[1 + 3 * I, 3 - 2 * I], [0, 2 * I]])
    assert im(A) == ImmutableMatrix([[3, -2], [0, 2]])

    X = ImmutableSparseMatrix([[i * I + i for i in range(5)]
                               for i in range(5)])
    Y = SparseMatrix([[i for i in range(5)] for i in range(5)])
    assert im(X).as_immutable() == Y

    X = FunctionMatrix(3, 3, Lambda((n, m), n + m * I))
    assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
Exemplo n.º 47
0
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9):
    """Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.

    Solve the equation

    .. math::

    Ry(2*theta1).Rz(2*xi).Ry(2*theta2) = Rz(2*phi).Ry(2*theta).Rz(2*lambda)

    for theta, phi, and lambda. This is equivalent to solving the system
    given in the comment for test_solution. Use eps for comparisons with zero.

    Return a solution theta, phi, and lambda.
    """
    solutions = []  # list of potential solutions
    # Four cases to avoid singularities
    if abs(sympy.cos(xi)) < eps / 10:
        solutions.append((theta2 - theta1, xi, 0.0))
    elif abs(sympy.sin(theta1 + theta2)) < eps / 10:
        phi_minus_lambda = [
            sympy.pi / 2, 3 * sympy.pi / 2, sympy.pi / 2, 3 * sympy.pi / 2
        ]
        stheta_1 = sympy.asin(sympy.sin(xi) * sympy.sin(-theta1 + theta2))
        stheta_2 = sympy.asin(-sympy.sin(xi) * sympy.sin(-theta1 + theta2))
        stheta_3 = sympy.pi - stheta_1
        stheta_4 = sympy.pi - stheta_2
        stheta = [stheta_1, stheta_2, stheta_3, stheta_4]
        phi_plus_lambda = list(
            map(
                lambda x: sympy.acos(
                    sympy.cos(theta1 + theta2) * sympy.cos(xi) / sympy.cos(x)),
                stheta))
        sphi = [(term[0] + term[1]) / 2
                for term in zip(phi_plus_lambda, phi_minus_lambda)]
        slam = [(term[0] - term[1]) / 2
                for term in zip(phi_plus_lambda, phi_minus_lambda)]
        solutions = list(zip(stheta, sphi, slam))
    elif abs(sympy.cos(theta1 + theta2)) < eps / 10:
        phi_plus_lambda = [
            sympy.pi / 2, 3 * sympy.pi / 2, sympy.pi / 2, 3 * sympy.pi / 2
        ]
        stheta_1 = sympy.acos(sympy.sin(xi) * sympy.cos(theta1 - theta2))
        stheta_2 = sympy.acos(-sympy.sin(xi) * sympy.cos(theta1 - theta2))
        stheta_3 = -stheta_1
        stheta_4 = -stheta_2
        stheta = [stheta_1, stheta_2, stheta_3, stheta_4]
        phi_minus_lambda = list(
            map(
                lambda x: sympy.acos(
                    sympy.sin(theta1 + theta2) * sympy.cos(xi) / sympy.sin(x)),
                stheta))
        sphi = [(term[0] + term[1]) / 2
                for term in zip(phi_plus_lambda, phi_minus_lambda)]
        slam = [(term[0] - term[1]) / 2
                for term in zip(phi_plus_lambda, phi_minus_lambda)]
        solutions = list(zip(stheta, sphi, slam))
    else:
        phi_plus_lambda = sympy.atan(
            sympy.sin(xi) * sympy.cos(theta1 - theta2) /
            (sympy.cos(xi) * sympy.cos(theta1 + theta2)))
        phi_minus_lambda = sympy.atan(
            sympy.sin(xi) * sympy.sin(-theta1 + theta2) /
            (sympy.cos(xi) * sympy.sin(theta1 + theta2)))
        sphi = (phi_plus_lambda + phi_minus_lambda) / 2
        slam = (phi_plus_lambda - phi_minus_lambda) / 2
        solutions.append((sympy.acos(
            sympy.cos(xi) * sympy.cos(theta1 + theta2) /
            sympy.cos(sphi + slam)), sphi, slam))
        solutions.append((sympy.acos(
            sympy.cos(xi) * sympy.cos(theta1 + theta2) /
            sympy.cos(sphi + slam + sympy.pi)), sphi + sympy.pi / 2,
                          slam + sympy.pi / 2))
        solutions.append((sympy.acos(
            sympy.cos(xi) * sympy.cos(theta1 + theta2) /
            sympy.cos(sphi + slam)), sphi + sympy.pi / 2, slam - sympy.pi / 2))
        solutions.append((sympy.acos(
            sympy.cos(xi) * sympy.cos(theta1 + theta2) /
            sympy.cos(sphi + slam + sympy.pi)), sphi + sympy.pi, slam))
    # Select the first solution with the required accuracy
    deltas = list(
        map(lambda x: test_trig_solution(x[0], x[1], x[2], xi, theta1, theta2),
            solutions))
    for delta_sol in zip(deltas, solutions):
        if delta_sol[0] < eps:
            return delta_sol[1]
    logger.debug("xi=%s", xi)
    logger.debug("theta1=%s", theta1)
    logger.debug("theta2=%s", theta2)
    logger.debug("solutions=%s", pprint.pformat(solutions))
    logger.debug("deltas=%s", pprint.pformat(deltas))
    assert False, "Error! No solution found. This should not happen."
Exemplo n.º 48
0
def test_complex():
    a, b = symbols('a,b', real=True)
    z = a + b*I
    for func in [sinh, cosh, tanh, coth, sech, csch]:
        assert func(z).conjugate() == func(a - b*I)
    for deep in [True, False]:
        assert sinh(z).expand(
            complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b)
        assert cosh(z).expand(
            complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b)
        assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
            a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2)
        assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
            a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2)
        assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\
            *cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\
            *cosh(a)**2 + cos(b)**2 * sinh(a)**2)
        assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\
            *sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\
            *sinh(a)**2 + cos(b)**2 * cosh(a)**2)
Exemplo n.º 49
0
    def __init__(self, R=2, Bt=1.0, eps=0.1, dr=0.02, q=lambda x: 2 + x**2):
        """
        R    - Major radius [m]

        Bt   - Toroidal field [T]

        eps  - Inverse aspect ratio

        dr   - Width of the radial region [m]

        q(x) - A function which returns the safety factor
               as a function of x in range [0,1]


        Coordinates:
        x - Radial, [0,1]
        y - Poloidal, [0,2pi]. Origin is at inboard midplane.


        """
        # X has a range [0,1], and y [0,2pi]
        #x, y = symbols("x y")

        self.x = x
        self.y = y

        self.R = R

        self.dr = dr

        # Minor radius
        self.r = R * eps

        # Get safety factor
        self.q = q(x)

        # Toroidal angle of a field-line as function
        # of poloidal angle y
        self.zShift = self.q * (y + eps * sin(y))

        # Field-line pitch
        self.nu = self.q * (1 + eps * cos(y))  #diff(self.zShift, y)

        # Coordinates of grid points
        self.Rxy = R - self.r * cos(y)
        self.Zxy = self.r * sin(y)

        # Poloidal arc length
        self.hthe = self.r + 0. * x

        # Toroidal magnetic field
        self.Btxy = Bt * R / self.Rxy

        # Poloidal magnetic field
        self.Bpxy = self.Btxy * self.hthe / (self.nu * self.Rxy)

        # Total magnetic field
        self.Bxy = sqrt(self.Btxy**2 + self.Bpxy**2)

        # Approximate poloidal field for radial width calculation
        Bp0 = Bt * self.r / (q(0.5) * R)
        print("Bp0 = %e" % Bp0)

        # dx = Bp * R * dr  -- width of the box in psi space
        self.psiwidth = Bp0 * R * dr
        print("psi width = %e" % self.psiwidth)

        # Integrated shear
        self.sinty = diff(self.zShift, x) / self.psiwidth

        # Extra expressions to add to grid file
        self._extra = {}
Exemplo n.º 50
0
simple_substitution_cases = [
    (a * b, {
        'a': c
    }, b * c),
    (a * b, {
        'a': b,
        'b': a
    }, a * b),
    (a * b, {
        'a': 1,
        'b': 2
    }, 2),
]

elem_func_substitution_cases = [
    (a * b + sin(c), {
        'a': b,
        'c': sympy.pi / 2
    }, b**2 + 1),
]

sum_substitution_cases = [
    (a * b + Sum(c * k, (k, 0, n)), {
        'a': b,
        'b': 2,
        'k': 1,
        'n': 2
    }, b * 2 + c * (1 + 2)),
]

indexed_substitution_cases = [(a_[i] * b, {
def test_floor():

    assert floor(nan) == nan

    assert floor(oo) == oo
    assert floor(-oo) == -oo
    assert floor(zoo) == zoo

    assert floor(0) == 0

    assert floor(1) == 1
    assert floor(-1) == -1

    assert floor(E) == 2
    assert floor(-E) == -3

    assert floor(2 * E) == 5
    assert floor(-2 * E) == -6

    assert floor(pi) == 3
    assert floor(-pi) == -4

    assert floor(Rational(1, 2)) == 0
    assert floor(-Rational(1, 2)) == -1

    assert floor(Rational(7, 3)) == 2
    assert floor(-Rational(7, 3)) == -3

    assert floor(Float(17.0)) == 17
    assert floor(-Float(17.0)) == -17

    assert floor(Float(7.69)) == 7
    assert floor(-Float(7.69)) == -8

    assert floor(I) == I
    assert floor(-I) == -I
    e = floor(i)
    assert e.func is floor and e.args[0] == i

    assert floor(oo * I) == oo * I
    assert floor(-oo * I) == -oo * I
    assert floor(exp(I * pi / 4) * oo) == exp(I * pi / 4) * oo

    assert floor(2 * I) == 2 * I
    assert floor(-2 * I) == -2 * I

    assert floor(I / 2) == 0
    assert floor(-I / 2) == -I

    assert floor(E + 17) == 19
    assert floor(pi + 2) == 5

    assert floor(E + pi) == floor(E + pi)
    assert floor(I + pi) == floor(I + pi)

    assert floor(floor(pi)) == 3
    assert floor(floor(y)) == floor(y)
    assert floor(floor(x)) == floor(floor(x))

    assert floor(x) == floor(x)
    assert floor(2 * x) == floor(2 * x)
    assert floor(k * x) == floor(k * x)

    assert floor(k) == k
    assert floor(2 * k) == 2 * k
    assert floor(k * n) == k * n

    assert floor(k / 2) == floor(k / 2)

    assert floor(x + y) == floor(x + y)

    assert floor(x + 3) == floor(x + 3)
    assert floor(x + k) == floor(x + k)

    assert floor(y + 3) == floor(y) + 3
    assert floor(y + k) == floor(y) + k

    assert floor(3 + I * y + pi) == 6 + floor(y) * I

    assert floor(k + n) == k + n

    assert floor(x * I) == floor(x * I)
    assert floor(k * I) == k * I

    assert floor(Rational(23, 10) - E * I) == 2 - 3 * I

    assert floor(sin(1)) == 0
    assert floor(sin(-1)) == -1

    assert floor(exp(2)) == 7

    assert floor(log(8) / log(2)) != 2
    assert int(floor(log(8) / log(2)).evalf(chop=True)) == 3

    assert floor(factorial(50)/exp(1)) == \
        11188719610782480504630258070757734324011354208865721592720336800

    assert (floor(y) <= y) == True
    assert (floor(y) > y) == False
    assert (floor(x) <= x).is_Relational  # x could be non-real
    assert (floor(x) > x).is_Relational
    assert (floor(x) <= y).is_Relational  # arg is not same as rhs
    assert (floor(x) > y).is_Relational

    assert floor(y).rewrite(frac) == y - frac(y)
    assert floor(y).rewrite(ceiling) == -ceiling(-y)
    assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi)
    assert floor(y).rewrite(frac).subs(y, E) == floor(E)
    assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E)
    assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi)

    assert Eq(floor(y), y - frac(y))
    assert Eq(floor(y), -ceiling(-y))
Exemplo n.º 52
0
    def __init__(self,
                 Rmaj=6.0,
                 rmin=2.0,
                 dr=0.1,
                 kappa=1.0,
                 delta=0.0,
                 b=0.0,
                 ss=0.0,
                 Bt0=1.0,
                 Bp0=0.2):
        """
        Rmaj  - Major radius [m]
        rmin  - Minor radius [m]
        dr    - Radial width of region [m]

        kappa - Ellipticity, 1 for a circle
        delta - Triangularity, 0 for circle
        b     - Indentation ("bean" shape), 0 for circle

        ss    - Shafranov shift [m]

        Bt0   - Toroidal magnetic field on axis [T]. Varies as 1/R
        Bp0   - Poloidal field at outboard midplane [T]

        Outputs
        -------

        Assigns member variables

        x, y    - Symbols for x and y coordinates

        R (x,y)
        Z (x,y)

        """

        # X has a range [0,1], and y [0,2pi]
        x, y = symbols("x y")

        # Minor radius as function of x
        rminx = rmin + (x - 0.5) * dr

        # Analytical expression for R and Z coordinates as function of x and y
        Rxy = Rmaj - b + (rminx + b * cos(y)) * cos(
            y + delta * sin(y)) + ss * (0.5 - x) * (dr / rmin)
        Zxy = kappa * rminx * sin(y)

        # Toroidal magnetic field
        Btxy = Bt0 * Rmaj / Rxy

        # Poloidal field. dx constant, so set poloidal field
        # at outboard midplane (y = 0)
        # NOTE: Approximate calculation

        # Distance between flux surface relative to outboard midplane.
        expansion = (1 - (old_div(ss, rmin)) * cos(y)) / (1 - (ss / rmin))

        Bpxy = Bp0 * ((Rmaj + rmin) / Rxy) / expansion

        # Calculate hthe
        hthe = sqrt(diff(Rxy, y)**2 + diff(Zxy, y)**2)
        try:
            hthe = trigsimp(hthe)
        except ValueError:
            pass

        # Field-line pitch
        nu = Btxy * hthe / (Bpxy * Rxy)

        # Shift angle
        # NOTE: Since x has a range [0,1] this could be done better
        # than ignoring convergence conditions
        self.zShift = integrate(nu, y, conds='none')

        # Safety factor
        self.shiftAngle = self.zShift.subs(y, 2 * pi) - self.zShift.subs(y, 0)

        # Integrated shear
        self.I = diff(self.zShift, x)

        self.x = x
        self.y = y

        self.R = Rxy
        self.Z = Zxy

        self.Bt = Btxy
        self.Bp = Bpxy
        self.B = sqrt(Btxy**2 + Bpxy**2)

        self.hthe = hthe
Exemplo n.º 53
0
def test_solve_ics():
    # Basic tests that things work from dsolve.
    assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \
        Eq(f(x), sqrt(2 * x + 2))
    assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x))
    assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0):
                                                  1}) == Eq(f(x), exp(x))
    assert dsolve(f(x).diff(x, x) + f(x),
                  f(x),
                  ics={
                      f(0): 1,
                      f(x).diff(x).subs(x, 0): 1
                  }) == Eq(f(x),
                           sin(x) + cos(x))
    assert dsolve([f(x).diff(x) - f(x) + g(x),
                   g(x).diff(x) - g(x) - f(x)], [f(x), g(x)],
                  ics={
                      f(0): 1,
                      g(0): 0
                  }) == [Eq(f(x),
                            exp(x) * cos(x)),
                         Eq(g(x),
                            exp(x) * sin(x))]

    # Test cases where dsolve returns two solutions.
    eq = (x**2 * f(x)**2 - x).diff(x)
    assert dsolve(eq, f(x), ics={f(1): 0}) == [
                                     Eq(f(x), -sqrt(x - 1) / x),
                                     Eq(f(x),
                                        sqrt(x - 1) / x)
                                 ]
    assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [
                                     Eq(f(x), -sqrt(x - S.Half) / x),
                                     Eq(f(x),
                                        sqrt(x - S.Half) / x)
                                 ]

    eq = cos(f(x)) - (x * sin(f(x)) - f(x)**2) * f(x).diff(x)
    assert dsolve(eq, f(x), ics={f(0): 1}, hint='1st_exact',
                  simplify=False) == Eq(x * cos(f(x)) + f(x)**3 / 3,
                                        Rational(1, 3))
    assert dsolve(eq, f(x), ics={f(0): 1}, hint='1st_exact',
                  simplify=True) == Eq(x * cos(f(x)) + f(x)**3 / 3,
                                       Rational(1, 3))

    assert solve_ics([Eq(f(x), C1 * exp(x))], [f(x)], [C1], {f(0): 1}) == {
                                                                 C1: 1
                                                             }
    assert solve_ics([Eq(f(x),
                         C1 * sin(x) + C2 * cos(x))], [f(x)], [C1, C2], {
                             f(0): 1,
                             f(pi / 2): 1
                         }) == {
                             C1: 1,
                             C2: 1
                         }

    assert solve_ics([Eq(f(x),
                         C1 * sin(x) + C2 * cos(x))], [f(x)], [C1, C2], {
                             f(0): 1,
                             f(x).diff(x).subs(x, 0): 1
                         }) == {
                             C1: 1,
                             C2: 1
                         }

    assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \
        {C2: 1}

    # Some more complicated tests Refer to PR #16098

    assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \
        {Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)}
    assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \
        {Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)}

    K, r, f0 = symbols('K r f0')
    sol = Eq(
        f(x),
        K * f0 * exp(r * x) / ((-K + f0) * (f0 * exp(r * x) / (-K + f0) - 1)))
    assert (dsolve(Eq(f(x).diff(x),
                      r * f(x) * (1 - f(x) / K)),
                   f(x),
                   ics={f(0): f0})) == sol

    #Order dependent issues Refer to PR #16098
    assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \
        {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}
    assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \
        {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)}

    # XXX: Ought to be ValueError
    raises(
        ValueError,
        lambda: solve_ics([Eq(f(x),
                              C1 * sin(x) + C2 * cos(x))], [f(x)], [C1, C2], {
                                  f(0): 1,
                                  f(pi): 1
                              }))

    # Degenerate case. f'(0) is identically 0.
    raises(
        ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)],
                                      [C1], {f(x).diff(x).subs(x, 0): 0}))

    EI, q, L = symbols('EI q L')

    # eq = Eq(EI*diff(f(x), x, 4), q)
    sols = [
        Eq(f(x), C1 + C2 * x + C3 * x**2 + C4 * x**3 + q * x**4 / (24 * EI))
    ]
    funcs = [f(x)]
    constants = [C1, C2, C3, C4]
    # Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)),
    # and Subs
    ics1 = {
        f(0): 0,
        f(x).diff(x).subs(x, 0): 0,
        f(L).diff(L, 2): 0,
        f(L).diff(L, 3): 0
    }
    ics2 = {
        f(0): 0,
        f(x).diff(x).subs(x, 0): 0,
        Subs(f(x).diff(x, 2), x, L): 0,
        Subs(f(x).diff(x, 3), x, L): 0
    }

    solved_constants1 = solve_ics(sols, funcs, constants, ics1)
    solved_constants2 = solve_ics(sols, funcs, constants, ics2)
    assert solved_constants1 == solved_constants2 == {
        C1: 0,
        C2: 0,
        C3: L**2 * q / (4 * EI),
        C4: -L * q / (6 * EI)
    }
def test_ceiling():

    assert ceiling(nan) == nan

    assert ceiling(oo) == oo
    assert ceiling(-oo) == -oo
    assert ceiling(zoo) == zoo

    assert ceiling(0) == 0

    assert ceiling(1) == 1
    assert ceiling(-1) == -1

    assert ceiling(E) == 3
    assert ceiling(-E) == -2

    assert ceiling(2 * E) == 6
    assert ceiling(-2 * E) == -5

    assert ceiling(pi) == 4
    assert ceiling(-pi) == -3

    assert ceiling(Rational(1, 2)) == 1
    assert ceiling(-Rational(1, 2)) == 0

    assert ceiling(Rational(7, 3)) == 3
    assert ceiling(-Rational(7, 3)) == -2

    assert ceiling(Float(17.0)) == 17
    assert ceiling(-Float(17.0)) == -17

    assert ceiling(Float(7.69)) == 8
    assert ceiling(-Float(7.69)) == -7

    assert ceiling(I) == I
    assert ceiling(-I) == -I
    e = ceiling(i)
    assert e.func is ceiling and e.args[0] == i

    assert ceiling(oo * I) == oo * I
    assert ceiling(-oo * I) == -oo * I
    assert ceiling(exp(I * pi / 4) * oo) == exp(I * pi / 4) * oo

    assert ceiling(2 * I) == 2 * I
    assert ceiling(-2 * I) == -2 * I

    assert ceiling(I / 2) == I
    assert ceiling(-I / 2) == 0

    assert ceiling(E + 17) == 20
    assert ceiling(pi + 2) == 6

    assert ceiling(E + pi) == ceiling(E + pi)
    assert ceiling(I + pi) == ceiling(I + pi)

    assert ceiling(ceiling(pi)) == 4
    assert ceiling(ceiling(y)) == ceiling(y)
    assert ceiling(ceiling(x)) == ceiling(ceiling(x))

    assert ceiling(x) == ceiling(x)
    assert ceiling(2 * x) == ceiling(2 * x)
    assert ceiling(k * x) == ceiling(k * x)

    assert ceiling(k) == k
    assert ceiling(2 * k) == 2 * k
    assert ceiling(k * n) == k * n

    assert ceiling(k / 2) == ceiling(k / 2)

    assert ceiling(x + y) == ceiling(x + y)

    assert ceiling(x + 3) == ceiling(x + 3)
    assert ceiling(x + k) == ceiling(x + k)

    assert ceiling(y + 3) == ceiling(y) + 3
    assert ceiling(y + k) == ceiling(y) + k

    assert ceiling(3 + pi + y * I) == 7 + ceiling(y) * I

    assert ceiling(k + n) == k + n

    assert ceiling(x * I) == ceiling(x * I)
    assert ceiling(k * I) == k * I

    assert ceiling(Rational(23, 10) - E * I) == 3 - 2 * I

    assert ceiling(sin(1)) == 1
    assert ceiling(sin(-1)) == 0

    assert ceiling(exp(2)) == 8

    assert ceiling(-log(8) / log(2)) != -2
    assert int(ceiling(-log(8) / log(2)).evalf(chop=True)) == -3

    assert ceiling(factorial(50)/exp(1)) == \
        11188719610782480504630258070757734324011354208865721592720336801

    assert (ceiling(y) >= y) == True
    assert (ceiling(y) < y) == False
    assert (ceiling(x) >= x).is_Relational  # x could be non-real
    assert (ceiling(x) < x).is_Relational
    assert (ceiling(x) >= y).is_Relational  # arg is not same as rhs
    assert (ceiling(x) < y).is_Relational

    assert ceiling(y).rewrite(floor) == -floor(-y)
    assert ceiling(y).rewrite(frac) == y + frac(-y)
    assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi)
    assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E)
    assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi)
    assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E)

    assert Eq(ceiling(y), y + frac(-y))
    assert Eq(ceiling(y), -floor(-y))
import selectphi from selecting_phi
#jointlimits
#theta_1_u=
#theta_1_l=
#theta_2_u=
#theta_2_l=
#theta_3_u=
#theta_3_l=
#theta_4_u=
#theta_4_l=
#theta_5_u=
#theta_5_l=
#theta_6_u=
#theta_6_l=
alpha,beta,gamma,p_x,p_y,p_z,l_bs,l_se,l_we,l_wt,theta_1,theta_2,theta_3,theta_4,theta_5,theta_6,u_x,u_y,u_z,theta_11,theta_22,theta_33,theta_44,alpha_1,beta_2,phi=dynamicsymbols('alpha,beta,gamma,p_x,p_y,p_z,l_bs,l_se,l_we,l_wt,theta_1,theta_2,theta_3,theta_4,theta_5,theta_6,u_x,u_y,u_z,theta_11,theta_22,theta_33,theta_44,alpha_1,beta_2,phi')
rot_end=sp.Matrix([[sp.cos(beta), -sp.sin(beta)*sp.cos(gamma), sp.sin(beta)*sp.sin(gamma)],
                 [sp.sin(beta)*sp.cos(alpha), (sp.cos(alpha)*sp.cos(beta)*sp.cos(gamma)-sp.sin(alpha)*sp.sin(gamma)), (-sp.cos(alpha)*sp.cos(beta)*sp.sin(gamma)-sp.sin(alpha)*sp.cos(gamma))],
                 [sp.sin(alpha)*sp.sin(beta), (sp.cos(alpha)*sp.sin(gamma)+ sp.cos(beta)*sp.cos(gamma)*sin(alpha)), (sp.cos(alpha)*sp.cos(gamma)-sp.cos(beta)*sp.sin(alpha)*sin(gamma))]])
#Euler angle XZX for orientation#
#print(rot_end[0,2])
pos_end=sp.Matrix([[p_x],[p_y],[p_z]])
#print(pos_end.shape)
w=np.zeros((3,1))
l_wt=sp.Matrix([[0],[0],[l_wt]])

w=pos_end-(rot_end*(l_wt))
w_x=w[0,0]
w_y=w[1,0]
w_z=w[2,0]
L_bs=sp.Matrix([[0],[0],[l_bs]])
#wrist position
Exemplo n.º 56
0
def test_undetermined_coefficients_match():
    assert _undetermined_coefficients_match(g(x), x) == {'test': False}
    assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \
        {'test': True, 'trialset':
            {cos(2*x + sqrt(5)), sin(2*x + sqrt(5))}}
    assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \
        {'test': False}
    s = {cos(x), x * cos(x), x**2 * cos(x), x**2 * sin(x), x * sin(x), sin(x)}
    assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
        {'test': True, 'trialset': s}
    assert _undetermined_coefficients_match(
        sin(x) * x**2 + sin(x) * x + sin(x), x) == {
            'test': True,
            'trialset': s
        }
    assert _undetermined_coefficients_match(
        exp(2 * x) * sin(x) * (x**2 + x + 1), x) == {
            'test': True,
            'trialset': {
                exp(2 * x) * sin(x), x**2 * exp(2 * x) * sin(x),
                cos(x) * exp(2 * x), x**2 * cos(x) * exp(2 * x),
                x * cos(x) * exp(2 * x), x * exp(2 * x) * sin(x)
            }
        }
    assert _undetermined_coefficients_match(1 / sin(x), x) == {'test': False}
    assert _undetermined_coefficients_match(log(x), x) == {'test': False}
    assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \
        {'test': True, 'trialset': {2**x, x*2**x, x**2*2**x}}
    assert _undetermined_coefficients_match(x**y, x) == {'test': False}
    assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \
        {'test': True, 'trialset': {exp(1 + 3*x)}}
    assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
        {'test': True, 'trialset': {x*cos(x), x*sin(x), x**2*cos(x),
        x**2*sin(x), cos(x), sin(x)}}
    assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \
        {'test': False}
    assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \
        {'test': False}
    assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \
        {'test': False}
    assert _undetermined_coefficients_match(
        x**2 * sin(x) * exp(x) + x * sin(x) + x, x) == {
            'test': True,
            'trialset': {
                x**2 * cos(x) * exp(x), x,
                cos(x), S.One,
                exp(x) * sin(x),
                sin(x), x * exp(x) * sin(x), x * cos(x), x * cos(x) * exp(x),
                x * sin(x),
                cos(x) * exp(x), x**2 * exp(x) * sin(x)
            }
        }
    assert _undetermined_coefficients_match(4 * x * sin(x - 2), x) == {
        'trialset': {x * cos(x - 2), x * sin(x - 2),
                     cos(x - 2),
                     sin(x - 2)},
        'test': True,
    }
    assert _undetermined_coefficients_match(2**x*x, x) == \
        {'test': True, 'trialset': {2**x, x*2**x}}
    assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \
        {'test': True, 'trialset': {2**x*exp(2*x)}}
    assert _undetermined_coefficients_match(exp(-x)/x, x) == \
        {'test': False}
    # Below are from Ordinary Differential Equations,
    #                Tenenbaum and Pollard, pg. 231
    assert _undetermined_coefficients_match(S(4), x) == \
        {'test': True, 'trialset': {S.One}}
    assert _undetermined_coefficients_match(12*exp(x), x) == \
        {'test': True, 'trialset': {exp(x)}}
    assert _undetermined_coefficients_match(exp(I*x), x) == \
        {'test': True, 'trialset': {exp(I*x)}}
    assert _undetermined_coefficients_match(sin(x), x) == \
        {'test': True, 'trialset': {cos(x), sin(x)}}
    assert _undetermined_coefficients_match(cos(x), x) == \
        {'test': True, 'trialset': {cos(x), sin(x)}}
    assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \
        {'test': True, 'trialset': {S.One, cos(x), sin(x), exp(x)}}
    assert _undetermined_coefficients_match(x**2, x) == \
        {'test': True, 'trialset': {S.One, x, x**2}}
    assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \
        {'test': True, 'trialset': {x*exp(x), exp(x), exp(-x)}}
    assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \
        {'test': True, 'trialset': {exp(2*x)*sin(x), cos(x)*exp(2*x)}}
    assert _undetermined_coefficients_match(x - sin(x), x) == \
        {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}}
    assert _undetermined_coefficients_match(x**2 + 2*x, x) == \
        {'test': True, 'trialset': {S.One, x, x**2}}
    assert _undetermined_coefficients_match(4*x*sin(x), x) == \
        {'test': True, 'trialset': {x*cos(x), x*sin(x), cos(x), sin(x)}}
    assert _undetermined_coefficients_match(x*sin(2*x), x) == \
        {'test': True, 'trialset':
            {x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)}}
    assert _undetermined_coefficients_match(x**2*exp(-x), x) == \
        {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}}
    assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \
        {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}}
    assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \
        {'test': True, 'trialset': {S.One, x, x**2, exp(-2*x)}}
    assert _undetermined_coefficients_match(x*exp(-x), x) == \
        {'test': True, 'trialset': {x*exp(-x), exp(-x)}}
    assert _undetermined_coefficients_match(x + exp(2*x), x) == \
        {'test': True, 'trialset': {S.One, x, exp(2*x)}}
    assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \
        {'test': True, 'trialset': {cos(x), sin(x), exp(-x)}}
    assert _undetermined_coefficients_match(exp(x), x) == \
        {'test': True, 'trialset': {exp(x)}}
    # converted from sin(x)**2
    assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \
        {'test': True, 'trialset': {S.One, cos(2*x), sin(2*x)}}
    # converted from exp(2*x)*sin(x)**2
    assert _undetermined_coefficients_match(
        exp(2 * x) * (S.Half + cos(2 * x) / 2), x) == {
            'test': True,
            'trialset':
            {exp(2 * x) * sin(2 * x),
             cos(2 * x) * exp(2 * x),
             exp(2 * x)}
        }
    assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \
        {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}}
    # converted from sin(2*x)*sin(x)
    assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \
        {'test': True, 'trialset': {cos(x), cos(3*x), sin(x), sin(3*x)}}
    assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False}
    assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False}
Exemplo n.º 57
0
           ['exxL', 'ettL', 'gxtL', 'kxxL', 'kttL', 'kxtL']]
for i, filename in enumerate(filenames):
    outname = outputs[i]
    with open(filename) as f:
        lines = [line.strip() for line in f.readlines()]
    string = ''.join(lines)
    string = string.replace('Pi','pi')
    string = string.replace('Sin','sin')
    string = string.replace('Cos','cos')
    string = string.replace('\\','')
    tmp = eval(string)
    matrix = Matrix(np.atleast_2d(tmp))

    var('sini1x, cosi1x, sini2x, cosi2x, sinj2t, cosj2t')
    subs = {
            sin(pi*i1*x/L):sini1x,
            cos(pi*i1*x/L):cosi1x,
            sin(pi*i2*x/L):sini2x,
            cos(pi*i2*x/L):cosi2x,
            sin(j2*t):sinj2t,
            cos(j2*t):cosj2t,
            }

    filename = outname

    with open(filename, 'w') as out:
        out.write('subs\n\n')
        for k, value in subs.items():
            out.write('{0} = {1}\n'.format(k, value))
        out.write('\nexpressions\n\n')
        for (row,col),value in np.ndenumerate(matrix):
Exemplo n.º 58
0
def test_dsolve_options():
    eq = x * f(x).diff(x) + f(x)
    a = dsolve(eq, hint='all')
    b = dsolve(eq, hint='all', simplify=False)
    c = dsolve(eq, hint='all_Integral')
    keys = [
        '1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best',
        '1st_homogeneous_coeff_subs_dep_div_indep',
        '1st_homogeneous_coeff_subs_dep_div_indep_Integral',
        '1st_homogeneous_coeff_subs_indep_div_dep',
        '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear',
        '1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral',
        'almost_linear', 'almost_linear_Integral', 'best', 'best_hint',
        'default', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'order',
        'separable', 'separable_Integral'
    ]
    Integral_keys = [
        '1st_exact_Integral',
        '1st_homogeneous_coeff_subs_dep_div_indep_Integral',
        '1st_homogeneous_coeff_subs_indep_div_dep_Integral',
        '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral',
        'best', 'best_hint', 'default', 'nth_linear_euler_eq_homogeneous',
        'order', 'separable_Integral'
    ]
    assert sorted(a.keys()) == keys
    assert a['order'] == ode_order(eq, f(x))
    assert a['best'] == Eq(f(x), C1 / x)
    assert dsolve(eq, hint='best') == Eq(f(x), C1 / x)
    assert a['default'] == 'separable'
    assert a['best_hint'] == 'separable'
    assert not a['1st_exact'].has(Integral)
    assert not a['separable'].has(Integral)
    assert not a['1st_homogeneous_coeff_best'].has(Integral)
    assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
    assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
    assert not a['1st_linear'].has(Integral)
    assert a['1st_linear_Integral'].has(Integral)
    assert a['1st_exact_Integral'].has(Integral)
    assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
    assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
    assert a['separable_Integral'].has(Integral)
    assert sorted(b.keys()) == keys
    assert b['order'] == ode_order(eq, f(x))
    assert b['best'] == Eq(f(x), C1 / x)
    assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1 / x)
    assert b['default'] == 'separable'
    assert b['best_hint'] == '1st_linear'
    assert a['separable'] != b['separable']
    assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \
        b['1st_homogeneous_coeff_subs_dep_div_indep']
    assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \
        b['1st_homogeneous_coeff_subs_indep_div_dep']
    assert not b['1st_exact'].has(Integral)
    assert not b['separable'].has(Integral)
    assert not b['1st_homogeneous_coeff_best'].has(Integral)
    assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral)
    assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral)
    assert not b['1st_linear'].has(Integral)
    assert b['1st_linear_Integral'].has(Integral)
    assert b['1st_exact_Integral'].has(Integral)
    assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral)
    assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral)
    assert b['separable_Integral'].has(Integral)
    assert sorted(c.keys()) == Integral_keys
    raises(ValueError, lambda: dsolve(eq, hint='notarealhint'))
    raises(ValueError, lambda: dsolve(eq, hint='Liouville'))
    assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \
        dsolve(f(x).diff(x) - 1/f(x)**2, hint='best')
    assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x),
                  hint="1st_linear_Integral") == \
        Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)*
                exp(Integral(1, x)), x))*exp(-Integral(1, x)))
Exemplo n.º 59
0
def kinematic_equations(speeds, coords, rot_type, rot_order=''):
    """Gives equations relating the qdot's to u's for a rotation type.

    Supply rotation type and order as in orient. Speeds are assumed to be
    body-fixed; if we are defining the orientation of B in A using by rot_type,
    the angular velocity of B in A is assumed to be in the form: speed[0]*B.x +
    speed[1]*B.y + speed[2]*B.z

    Parameters
    ==========

    speeds : list of length 3
        The body fixed angular velocity measure numbers.
    coords : list of length 3 or 4
        The coordinates used to define the orientation of the two frames.
    rot_type : str
        The type of rotation used to create the equations. Body, Space, or
        Quaternion only
    rot_order : str
        If applicable, the order of a series of rotations.

    Examples
    ========

    >>> from sympy.physics.mechanics import dynamicsymbols
    >>> from sympy.physics.mechanics import kinematic_equations, mprint
    >>> u1, u2, u3 = dynamicsymbols('u1 u2 u3')
    >>> q1, q2, q3 = dynamicsymbols('q1 q2 q3')
    >>> mprint(kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', '313'),
    ...     order=None)
    [-(u1*sin(q3) + u2*cos(q3))/sin(q2) + q1', -u1*cos(q3) + u2*sin(q3) + q2', (u1*sin(q3) + u2*cos(q3))*cos(q2)/sin(q2) - u3 + q3']

    """

    # Code below is checking and sanitizing input
    approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131',
                       '212', '232', '313', '323', '1', '2', '3', '')
    rot_order = str(rot_order).upper()  # Now we need to make sure XYZ = 123
    rot_type = rot_type.upper()
    rot_order = [i.replace('X', '1') for i in rot_order]
    rot_order = [i.replace('Y', '2') for i in rot_order]
    rot_order = [i.replace('Z', '3') for i in rot_order]
    rot_order = ''.join(rot_order)

    if not isinstance(speeds, (list, tuple)):
        raise TypeError('Need to supply speeds in a list')
    if len(speeds) != 3:
        raise TypeError('Need to supply 3 body-fixed speeds')
    if not isinstance(coords, (list, tuple)):
        raise TypeError('Need to supply coordinates in a list')
    if rot_type.lower() in ['body', 'space']:
        if rot_order not in approved_orders:
            raise ValueError('Not an acceptable rotation order')
        if len(coords) != 3:
            raise ValueError('Need 3 coordinates for body or space')
        # Actual hard-coded kinematic differential equations
        q1, q2, q3 = coords
        q1d, q2d, q3d = [diff(i, dynamicsymbols._t) for i in coords]
        w1, w2, w3 = speeds
        s1, s2, s3 = [sin(q1), sin(q2), sin(q3)]
        c1, c2, c3 = [cos(q1), cos(q2), cos(q3)]
        if rot_type.lower() == 'body':
            if rot_order == '123':
                return [
                    q1d - (w1 * c3 - w2 * s3) / c2, q2d - w1 * s3 - w2 * c3,
                    q3d - (-w1 * c3 + w2 * s3) * s2 / c2 - w3
                ]
            if rot_order == '231':
                return [
                    q1d - (w2 * c3 - w3 * s3) / c2, q2d - w2 * s3 - w3 * c3,
                    q3d - w1 - (-w2 * c3 + w3 * s3) * s2 / c2
                ]
            if rot_order == '312':
                return [
                    q1d - (-w1 * s3 + w3 * c3) / c2, q2d - w1 * c3 - w3 * s3,
                    q3d - (w1 * s3 - w3 * c3) * s2 / c2 - w2
                ]
            if rot_order == '132':
                return [
                    q1d - (w1 * c3 + w3 * s3) / c2, q2d + w1 * s3 - w3 * c3,
                    q3d - (w1 * c3 + w3 * s3) * s2 / c2 - w2
                ]
            if rot_order == '213':
                return [
                    q1d - (w1 * s3 + w2 * c3) / c2, q2d - w1 * c3 + w2 * s3,
                    q3d - (w1 * s3 + w2 * c3) * s2 / c2 - w3
                ]
            if rot_order == '321':
                return [
                    q1d - (w2 * s3 + w3 * c3) / c2, q2d - w2 * c3 + w3 * s3,
                    q3d - w1 - (w2 * s3 + w3 * c3) * s2 / c2
                ]
            if rot_order == '121':
                return [
                    q1d - (w2 * s3 + w3 * c3) / s2, q2d - w2 * c3 + w3 * s3,
                    q3d - w1 + (w2 * s3 + w3 * c3) * c2 / s2
                ]
            if rot_order == '131':
                return [
                    q1d - (-w2 * c3 + w3 * s3) / s2, q2d - w2 * s3 - w3 * c3,
                    q3d - w1 - (w2 * c3 - w3 * s3) * c2 / s2
                ]
            if rot_order == '212':
                return [
                    q1d - (w1 * s3 - w3 * c3) / s2, q2d - w1 * c3 - w3 * s3,
                    q3d - (-w1 * s3 + w3 * c3) * c2 / s2 - w2
                ]
            if rot_order == '232':
                return [
                    q1d - (w1 * c3 + w3 * s3) / s2, q2d + w1 * s3 - w3 * c3,
                    q3d + (w1 * c3 + w3 * s3) * c2 / s2 - w2
                ]
            if rot_order == '313':
                return [
                    q1d - (w1 * s3 + w2 * c3) / s2, q2d - w1 * c3 + w2 * s3,
                    q3d + (w1 * s3 + w2 * c3) * c2 / s2 - w3
                ]
            if rot_order == '323':
                return [
                    q1d - (-w1 * c3 + w2 * s3) / s2, q2d - w1 * s3 - w2 * c3,
                    q3d - (w1 * c3 - w2 * s3) * c2 / s2 - w3
                ]
        if rot_type.lower() == 'space':
            if rot_order == '123':
                return [
                    q1d - w1 - (w2 * s1 + w3 * c1) * s2 / c2,
                    q2d - w2 * c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / c2
                ]
            if rot_order == '231':
                return [
                    q1d - (w1 * c1 + w3 * s1) * s2 / c2 - w2,
                    q2d + w1 * s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / c2
                ]
            if rot_order == '312':
                return [
                    q1d - (w1 * s1 + w2 * c1) * s2 / c2 - w3,
                    q2d - w1 * c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / c2
                ]
            if rot_order == '132':
                return [
                    q1d - w1 - (-w2 * c1 + w3 * s1) * s2 / c2,
                    q2d - w2 * s1 - w3 * c1, q3d - (w2 * c1 - w3 * s1) / c2
                ]
            if rot_order == '213':
                return [
                    q1d - (w1 * s1 - w3 * c1) * s2 / c2 - w2,
                    q2d - w1 * c1 - w3 * s1, q3d - (-w1 * s1 + w3 * c1) / c2
                ]
            if rot_order == '321':
                return [
                    q1d - (-w1 * c1 + w2 * s1) * s2 / c2 - w3,
                    q2d - w1 * s1 - w2 * c1, q3d - (w1 * c1 - w2 * s1) / c2
                ]
            if rot_order == '121':
                return [
                    q1d - w1 + (w2 * s1 + w3 * c1) * c2 / s2,
                    q2d - w2 * c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / s2
                ]
            if rot_order == '131':
                return [
                    q1d - w1 - (w2 * c1 - w3 * s1) * c2 / s2,
                    q2d - w2 * s1 - w3 * c1, q3d - (-w2 * c1 + w3 * s1) / s2
                ]
            if rot_order == '212':
                return [
                    q1d - (-w1 * s1 + w3 * c1) * c2 / s2 - w2,
                    q2d - w1 * c1 - w3 * s1, q3d - (w1 * s1 - w3 * c1) / s2
                ]
            if rot_order == '232':
                return [
                    q1d + (w1 * c1 + w3 * s1) * c2 / s2 - w2,
                    q2d + w1 * s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / s2
                ]
            if rot_order == '313':
                return [
                    q1d + (w1 * s1 + w2 * c1) * c2 / s2 - w3,
                    q2d - w1 * c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / s2
                ]
            if rot_order == '323':
                return [
                    q1d - (w1 * c1 - w2 * s1) * c2 / s2 - w3,
                    q2d - w1 * s1 - w2 * c1, q3d - (-w1 * c1 + w2 * s1) / s2
                ]
    elif rot_type.lower() == 'quaternion':
        if rot_order != '':
            raise ValueError('Cannot have rotation order for quaternion')
        if len(coords) != 4:
            raise ValueError('Need 4 coordinates for quaternion')
        # Actual hard-coded kinematic differential equations
        e0, e1, e2, e3 = coords
        w = Matrix(speeds + [0])
        E = Matrix([[e0, -e3, e2, e1], [e3, e0, -e1, e2], [-e2, e1, e0, e3],
                    [-e1, -e2, -e3, e0]])
        edots = Matrix([diff(i, dynamicsymbols._t) for i in [e1, e2, e3, e0]])
        return list(edots.T - 0.5 * w.T * E.T)
    else:
        raise ValueError('Not an approved rotation type for this function')
Exemplo n.º 60
0
def test_shifted_sum():
    from sympy import simplify
    assert simplify(hyperexpand(z**4*hyper([2], [3, S('3/2')], -z**2))) \
        == z*sin(2*z) + (-z**2 + S.Half)*cos(2*z) - S.Half