Beispiel #1
1
def test_dyadic():
    d1 = A.x | A.x
    d2 = A.y | A.y
    d3 = A.x | A.y
    assert d1 * 0 == 0
    assert d1 != 0
    assert d1 * 2 == 2 * A.x | A.x
    assert d1 / 2. == 0.5 * d1
    assert d1 & (0 * d1) == 0
    assert d1 & d2 == 0
    assert d1 & A.x == A.x
    assert d1 ^ A.x == 0
    assert d1 ^ A.y == A.x | A.z
    assert d1 ^ A.z == - A.x | A.y
    assert d2 ^ A.x == - A.y | A.z
    assert A.x ^ d1 == 0
    assert A.y ^ d1 == - A.z | A.x
    assert A.z ^ d1 == A.y | A.x
    assert A.x & d1 == A.x
    assert A.y & d1 == 0
    assert A.y & d2 == A.y
    assert d1 & d3 == A.x | A.y
    assert d3 & d1 == 0
    assert d1.dt(A) == 0
    q = dynamicsymbols('q')
    qd = dynamicsymbols('q', 1)
    B = A.orientnew('B', 'Axis', [q, A.z])
    assert d1.express(B) == d1.express(B, B)
    assert d1.express(B) == ((cos(q)**2) * (B.x | B.x) + (-sin(q) * cos(q)) *
            (B.x | B.y) + (-sin(q) * cos(q)) * (B.y | B.x) + (sin(q)**2) *
            (B.y | B.y))
    assert d1.express(B, A) == (cos(q)) * (B.x | A.x) + (-sin(q)) * (B.y | A.x)
    assert d1.express(A, B) == (cos(q)) * (A.x | B.x) + (-sin(q)) * (A.x | B.y)
    assert d1.dt(B) == (-qd) * (A.y | A.x) + (-qd) * (A.x | A.y)
Beispiel #2
0
def rotZ_symbolic(angle='ψ'):
    t = _sy.symbols(angle, real=True)
    r = _sy.Matrix(((_sy.cos(t), -_sy.sin(t), 0), 
                    (_sy.sin(t),  _sy.cos(t), 0),
                    (     0,          0,      1),
                    ))
    return r
Beispiel #3
0
def test_arithmetic_sums():
    assert summation(1, (n, a, b)) == b - a + 1
    assert Sum(S.NaN, (n, a, b)) is S.NaN
    assert Sum(x, (n, a, a)).doit() == x
    assert Sum(x, (x, a, a)).doit() == a
    assert Sum(x, (n, 1, a)).doit() == a*x
    lo, hi = 1, 2
    s1 = Sum(n, (n, lo, hi))
    s2 = Sum(n, (n, hi, lo))
    assert s1 != s2
    assert s1.doit() == s2.doit() == 3
    lo, hi = x, x + 1
    s1 = Sum(n, (n, lo, hi))
    s2 = Sum(n, (n, hi, lo))
    assert s1 != s2
    assert s1.doit() == s2.doit() == 2*x + 1
    assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \
        y**2 + 2
    assert summation(1, (n, 1, 10)) == 10
    assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000
    assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \
        2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2
    assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1)
    assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2)
    assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum)
Beispiel #4
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)
Beispiel #5
0
def test_nfloat():
    from sympy.core.basic import _aresame
    from sympy.polys.rootoftools import rootof

    x = Symbol("x")
    eq = x**(S(4)/3) + 4*x**(S(1)/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3))
    assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
    eq = x**(S(4)/3) + 4*x**(x/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3))
    big = 12345678901234567890
    # specify precision to match value used in nfloat
    Float_big = Float(big, 15)
    assert _aresame(nfloat(big), Float_big)
    assert _aresame(nfloat(big*x), Float_big*x)
    assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
    assert nfloat({x: sqrt(2)}) == {x: nfloat(sqrt(2))}
    assert nfloat({sqrt(2): x}) == {sqrt(2): x}
    assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))

    # issue 6342
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139)))

    # issue 6632
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11

    # issue 7122
    eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0)
    assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'
Beispiel #6
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)
Beispiel #7
0
def eval_trigsubstitution(theta, func, rewritten, substep, restriction, integrand, symbol):
    func = func.subs(sympy.sec(theta), 1/sympy.cos(theta))

    trig_function = list(func.find(TrigonometricFunction))
    assert len(trig_function) == 1
    trig_function = trig_function[0]
    relation = sympy.solve(symbol - func, trig_function)
    assert len(relation) == 1
    numer, denom = sympy.fraction(relation[0])

    if isinstance(trig_function, sympy.sin):
        opposite = numer
        hypotenuse = denom
        adjacent = sympy.sqrt(denom**2 - numer**2)
        inverse = sympy.asin(relation[0])
    elif isinstance(trig_function, sympy.cos):
        adjacent = numer
        hypotenuse = denom
        opposite = sympy.sqrt(denom**2 - numer**2)
        inverse = sympy.acos(relation[0])
    elif isinstance(trig_function, sympy.tan):
        opposite = numer
        adjacent = denom
        hypotenuse = sympy.sqrt(denom**2 + numer**2)
        inverse = sympy.atan(relation[0])

    substitution = [
        (sympy.sin(theta), opposite/hypotenuse),
        (sympy.cos(theta), adjacent/hypotenuse),
        (sympy.tan(theta), opposite/adjacent),
        (theta, inverse)
    ]
    return sympy.Piecewise(
        (_manualintegrate(substep).subs(substitution).trigsimp(), restriction)
    )
Beispiel #8
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)
Beispiel #9
0
def test_Vector_class():
    t = symbols('t')
    u1 = Function('u1')(t)
    v1 = Vector(0)
    v2 = Vector(q1*u1*A[1] + q2*t*sin(t)*A[2])
    v3 = Vector({B[1]: q1*sin(q2), B[2]: t*u1*q1*sin(q2)})
    # Basic functionality tests
    assert v1.parse_terms(A[1]) == {A[1]: 1}
    assert v1.parse_terms(0) == {}
    assert v1.parse_terms(S(0)) == {}
    assert v1.parse_terms(q1*sin(t)*A[1] + A[2]*cos(q2)*u1) == {A[1]: \
            q1*sin(t), A[2]: cos(q2)*u1}
    test = sin(q1)*sin(q1)*q2*A[3]  + q1*A[2] + S(0) + cos(q3)*A[2]
    assert v1.parse_terms(test) == {A[3]: sin(q1)*sin(q1)*q2, \
            A[2]:cos(q3) + q1}
    # Equality tests
    v4 = v2 + v3
    assert v4 == v2 + v3
    v3 = Vector({B[1]: q1*sin(q2), B[2]: t*u1*q1*sin(q2)})
    v5 = Vector({B[1]: q1*sin(q2), B[2]: t*u1*q1*sin(q2)})
    assert v3 == v5
    # Another way to generate the same vector
    v5 = Vector(q1*sin(q2)*B[1] + t*u1*q1*sin(q2)*B[2])
    assert v3 == v5
    assert v5.dict == {B[1]: q1*sin(q2), B[2]: t*u1*q1*sin(q2)}
Beispiel #10
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])
Beispiel #11
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))
Beispiel #12
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]
Beispiel #13
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
Beispiel #14
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()
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))
Beispiel #16
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]
Beispiel #17
0
def test_logcombine_1():
    x, y = symbols("x,y")
    a = Symbol("a")
    z, w = symbols("z,w", positive=True)
    b = Symbol("b", real=True)
    assert logcombine(log(x) + 2*log(y)) == log(x) + 2*log(y)
    assert logcombine(log(x) + 2*log(y), force=True) == log(x*y**2)
    assert logcombine(a*log(w) + log(z)) == a*log(w) + log(z)
    assert logcombine(b*log(z) + b*log(x)) == log(z**b) + b*log(x)
    assert logcombine(b*log(z) - log(w)) == log(z**b/w)
    assert logcombine(log(x)*log(z)) == log(x)*log(z)
    assert logcombine(log(w)*log(x)) == log(w)*log(x)
    assert logcombine(cos(-2*log(z) + b*log(w))) in [cos(log(w**b/z**2)),
                                                   cos(log(z**2/w**b))]
    assert logcombine(log(log(x) - log(y)) - log(z), force=True) == \
        log(log(x/y)/z)
    assert logcombine((2 + I)*log(x), force=True) == (2 + I)*log(x)
    assert logcombine((x**2 + log(x) - log(y))/(x*y), force=True) == \
        (x**2 + log(x/y))/(x*y)
    # the following could also give log(z*x**log(y**2)), what we
    # are testing is that a canonical result is obtained
    assert logcombine(log(x)*2*log(y) + log(z), force=True) == \
        log(z*y**log(x**2))
    assert logcombine((x*y + sqrt(x**4 + y**4) + log(x) - log(y))/(pi*x**Rational(2, 3)*
            sqrt(y)**3), force=True) == (
            x*y + sqrt(x**4 + y**4) + log(x/y))/(pi*x**(S(2)/3)*y**(S(3)/2))
    assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \
        acos(-log(x/y))*gamma(-log(x/y))

    assert logcombine(2*log(z)*log(w)*log(x) + log(z) + log(w)) == \
        log(z**log(w**2))*log(x) + log(w*z)
    assert logcombine(3*log(w) + 3*log(z)) == log(w**3*z**3)
    assert logcombine(x*(y + 1) + log(2) + log(3)) == x*(y + 1) + log(6)
    assert logcombine((x + y)*log(w) + (-x - y)*log(3)) == (x + y)*log(w/3)
Beispiel #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
Beispiel #19
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" )
Beispiel #20
0
def error_of_methods():
	"""
	Complie test with returning error
	"""
	import math
	import numpy as np
	import sympy
	from sympy import cos
	from sympy import sin
	from sympy.utilities.lambdify import lambdify
	
	w,x, L ,t= sympy.symbols("w x L t")
	pi = math.pi	

	u = lambda x,t : cos(w*t)*cos(pi*x/L)
	q = lambda x : 1 + ( x -L/2.0)**4

	def source_term(u,q):
		return sympy.simplify(u(x,t).diff(t, t) - (u(x,t).diff(x)*q(x)).diff(x) )

	w=1
	L = 2
	T=10
	Nx=40

	f =  sympy.lambdify((x,t), source_term(u,q)  ,'numpy')
	q = sympy.lambdify(x,q(x) ,'numpy')
	I = sympy.lambdify(x, u(x,t).subs(t,0),'numpy')
	u = sympy.lambdify((x,t), u(x,t),'numpy')

	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=sum_approximation)[1]
	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=centered_difference)[1]
	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=centered_difference)[1]
	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=shifted_domain)[1]
Beispiel #21
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)
Beispiel #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
Beispiel #23
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))
Beispiel #24
0
def test_issue_8368():
    assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \
        Piecewise(
            (   pi*Piecewise(
                    (   -s/(pi*(-s**2 + 1)),
                        Abs(s**2) < 1),
                    (   1/(pi*s*(1 - 1/s**2)),
                        Abs(s**(-2)) < 1),
                    (   meijerg(
                            ((S(1)/2,), (0, 0)),
                            ((0, S(1)/2), (0,)),
                            polar_lift(s)**2),
                        True)
                ),
                And(
                    Abs(periodic_argument(polar_lift(s)**2, oo)) < pi,
                    cos(Abs(periodic_argument(polar_lift(s)**2, oo))/2)*sqrt(Abs(s**2)) - 1 > 0,
                    Ne(s**2, 1))
            ),
            (
                Integral(exp(-s*x)*cosh(x), (x, 0, oo)),
                True))
    assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \
        Piecewise(
            (   -1/(s + 1)/2 - 1/(-s + 1)/2,
                And(
                    Ne(1/s, 1),
                    Abs(periodic_argument(s, oo)) < pi/2,
                    Abs(periodic_argument(s, oo)) <= pi/2,
                    cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1 > 0)),
            (   Integral(exp(-s*x)*sinh(x), (x, 0, oo)),
                True))
Beispiel #25
0
def test_matrices():
    M = Matrix(2, 2, lambda i, j: (i + j + 1)*sin((i + j + 1)*x))

    assert integrate(M, x) == Matrix([
        [-cos(x), -cos(2*x)],
        [-cos(2*x), -cos(3*x)],
    ])
Beispiel #26
0
def test_tan_rewrite():
    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)
    assert tan(sinh(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n()
    assert tan(cosh(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n()
    assert tan(tanh(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n()
    assert tan(coth(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n()
    assert tan(sin(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n()
    assert tan(cos(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n()
    assert tan(tan(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n()
    assert tan(cot(x)).rewrite(
        exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n()
    assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I)
    assert 0 == (cos(pi/15)*tan(pi/15) - sin(pi/15)).rewrite(pow)
    assert tan(pi/19).rewrite(pow) == tan(pi/19)
    assert tan(8*pi/19).rewrite(sqrt) == tan(8*pi/19)
Beispiel #27
0
    def arbitrary_point(self, t=None):
        """ Returns an arbitrary point on the Plane; varying `t` from 0 to 2*pi
        will move the point in a circle of radius 1 about p1 of the Plane.

        Examples
        ========

        >>> from sympy.geometry.plane import Plane
        >>> from sympy.abc import t
        >>> p = Plane((0, 0, 0), (0, 0, 1), (0, 1, 0))
        >>> p.arbitrary_point(t)
        Point3D(0, cos(t), sin(t))
        >>> _.distance(p.p1).simplify()
        1

        Returns
        =======

        Point3D

        """
        from sympy import cos, sin
        t = t or Dummy('t')
        x, y, z = self.normal_vector
        a, b, c = self.p1.args
        if x == y == 0:
            return Point3D(a + cos(t), b + sin(t), c)
        elif x == z == 0:
            return Point3D(a + cos(t), b, c + sin(t))
        elif y == z == 0:
            return Point3D(a, b + cos(t), c + sin(t))
        m = Dummy()
        p = self.projection(Point3D(self.p1.x + cos(t), self.p1.y + sin(t), 0)*m)
        return p.xreplace({m: solve(p.distance(self.p1) - 1, m)[0]})
Beispiel #28
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))]
Beispiel #29
0
def test_derivative_by_array():
    from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z

    bexpr = x*y**2*exp(z)*log(t)
    sexpr = sin(bexpr)
    cexpr = cos(bexpr)

    a = Array([sexpr])

    assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
    assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
    assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])

    assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
    assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
    assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
    assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
                                                                         [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])

    assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
    assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
    assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])

    assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
    assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
    assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
    assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
                                                                         [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
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))]
Beispiel #31
0
def test_nonpolymonial_relations():
    assert Eq(cos(x), 0).simplify() == Eq(cos(x), 0)
Beispiel #32
0
def test_nfloat():
    from sympy.core.basic import _aresame
    from sympy.polys.rootoftools import rootof

    x = Symbol("x")
    eq = x**Rational(4, 3) + 4*x**(S.One/3)/3
    assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(S.One/3))
    assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
    eq = x**Rational(4, 3) + 4*x**(x/3)/3
    assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(x/3))
    big = 12345678901234567890
    # specify precision to match value used in nfloat
    Float_big = Float(big, 15)
    assert _aresame(nfloat(big), Float_big)
    assert _aresame(nfloat(big*x), Float_big*x)
    assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
    assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))

    # issue 6342
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139)))

    # issue 6632
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11

    # issue 7122
    eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0)
    assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'

    # issue 10933
    for ti in (dict, Dict):
        d = ti({S.Half: S.Half})
        n = nfloat(d)
        assert isinstance(n, ti)
        assert _aresame(list(n.items()).pop(), (S.Half, Float(.5)))
    for ti in (dict, Dict):
        d = ti({S.Half: S.Half})
        n = nfloat(d, dkeys=True)
        assert isinstance(n, ti)
        assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5)))
    d = [S.Half]
    n = nfloat(d)
    assert type(n) is list
    assert _aresame(n[0], Float(.5))
    assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5))
    assert _aresame(nfloat(S(True)), S(True))
    assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5))
    assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false
    # pass along kwargs
    assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}]

    # Issue 17706
    A = MutableMatrix([[1, 2], [3, 4]])
    B = MutableMatrix(
        [[Float('1.0', precision=53), Float('2.0', precision=53)],
        [Float('3.0', precision=53), Float('4.0', precision=53)]])
    assert _aresame(nfloat(A), B)
    A = ImmutableMatrix([[1, 2], [3, 4]])
    B = ImmutableMatrix(
        [[Float('1.0', precision=53), Float('2.0', precision=53)],
        [Float('3.0', precision=53), Float('4.0', precision=53)]])
    assert _aresame(nfloat(A), B)
def test_orienters():
    A = CoordSys3D('A')
    axis_orienter = AxisOrienter(a, A.k)
    body_orienter = BodyOrienter(a, b, c, '123')
    space_orienter = SpaceOrienter(a, b, c, '123')
    q_orienter = QuaternionOrienter(q1, q2, q3, q4)
    assert axis_orienter.rotation_matrix(A) == Matrix([
        [ cos(a), sin(a), 0],
        [-sin(a), cos(a), 0],
        [      0,      0, 1]])
    assert body_orienter.rotation_matrix() == Matrix([
        [ cos(b)*cos(c),  sin(a)*sin(b)*cos(c) + sin(c)*cos(a),
          sin(a)*sin(c) - sin(b)*cos(a)*cos(c)],
        [-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c),
         sin(a)*cos(c) + sin(b)*sin(c)*cos(a)],
        [        sin(b),                        -sin(a)*cos(b),
                 cos(a)*cos(b)]])
    assert space_orienter.rotation_matrix() == Matrix([
        [cos(b)*cos(c), sin(c)*cos(b),       -sin(b)],
        [sin(a)*sin(b)*cos(c) - sin(c)*cos(a),
         sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)],
        [sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) +
         sin(b)*sin(c)*cos(a), cos(a)*cos(b)]])
    assert q_orienter.rotation_matrix() == Matrix([
        [q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3,
         -2*q1*q3 + 2*q2*q4],
        [-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2,
         2*q1*q2 + 2*q3*q4],
        [2*q1*q3 + 2*q2*q4,
         -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]])
def test_transformation_equations():

    x, y, z = symbols('x y z')
    # Str
    a = CoordSys3D('a', transformation='spherical',
                   variable_names=["r", "theta", "phi"])
    r, theta, phi = a.base_scalars()

    assert r == a.r
    assert theta == a.theta
    assert phi == a.phi

    raises(AttributeError, lambda: a.x)
    raises(AttributeError, lambda: a.y)
    raises(AttributeError, lambda: a.z)

    assert a.transformation_to_parent() == (
        r*sin(theta)*cos(phi),
        r*sin(theta)*sin(phi),
        r*cos(theta)
    )
    assert a.lame_coefficients() == (1, r, r*sin(theta))
    assert a.transformation_from_parent_function()(x, y, z) == (
        sqrt(x ** 2 + y ** 2 + z ** 2),
        acos((z) / sqrt(x**2 + y**2 + z**2)),
        atan2(y, x)
    )
    a = CoordSys3D('a', transformation='cylindrical',
                   variable_names=["r", "theta", "z"])
    r, theta, z = a.base_scalars()
    assert a.transformation_to_parent() == (
        r*cos(theta),
        r*sin(theta),
        z
    )
    assert a.lame_coefficients() == (1, a.r, 1)
    assert a.transformation_from_parent_function()(x, y, z) == (sqrt(x**2 + y**2),
                            atan2(y, x), z)

    a = CoordSys3D('a', 'cartesian')
    assert a.transformation_to_parent() == (a.x, a.y, a.z)
    assert a.lame_coefficients() == (1, 1, 1)
    assert a.transformation_from_parent_function()(x, y, z) == (x, y, z)

    # Variables and expressions

    # Cartesian with equation tuple:
    x, y, z = symbols('x y z')
    a = CoordSys3D('a', ((x, y, z), (x, y, z)))
    a._calculate_inv_trans_equations()
    assert a.transformation_to_parent() == (a.x1, a.x2, a.x3)
    assert a.lame_coefficients() == (1, 1, 1)
    assert a.transformation_from_parent_function()(x, y, z) == (x, y, z)
    r, theta, z = symbols("r theta z")

    # Cylindrical with equation tuple:
    a = CoordSys3D('a', [(r, theta, z), (r*cos(theta), r*sin(theta), z)],
                   variable_names=["r", "theta", "z"])
    r, theta, z = a.base_scalars()
    assert a.transformation_to_parent() == (
        r*cos(theta), r*sin(theta), z
    )
    assert a.lame_coefficients() == (
        sqrt(sin(theta)**2 + cos(theta)**2),
        sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2),
        1
    )  # ==> this should simplify to (1, r, 1), tests are too slow with `simplify`.

    # Definitions with `lambda`:

    # Cartesian with `lambda`
    a = CoordSys3D('a', lambda x, y, z: (x, y, z))
    assert a.transformation_to_parent() == (a.x1, a.x2, a.x3)
    assert a.lame_coefficients() == (1, 1, 1)
    a._calculate_inv_trans_equations()
    assert a.transformation_from_parent_function()(x, y, z) == (x, y, z)

    # Spherical with `lambda`
    a = CoordSys3D('a', lambda r, theta, phi: (r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta)),
                   variable_names=["r", "theta", "phi"])
    r, theta, phi = a.base_scalars()
    assert a.transformation_to_parent() == (
        r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)
    )
    assert a.lame_coefficients() == (
        sqrt(sin(phi)**2*sin(theta)**2 + sin(theta)**2*cos(phi)**2 + cos(theta)**2),
        sqrt(r**2*sin(phi)**2*cos(theta)**2 + r**2*sin(theta)**2 + r**2*cos(phi)**2*cos(theta)**2),
        sqrt(r**2*sin(phi)**2*sin(theta)**2 + r**2*sin(theta)**2*cos(phi)**2)
    )  # ==> this should simplify to (1, r, sin(theta)*r), `simplify` is too slow.

    # Cylindrical with `lambda`
    a = CoordSys3D('a', lambda r, theta, z:
        (r*cos(theta), r*sin(theta), z),
        variable_names=["r", "theta", "z"]
    )
    r, theta, z = a.base_scalars()
    assert a.transformation_to_parent() == (r*cos(theta), r*sin(theta), z)
    assert a.lame_coefficients() == (
        sqrt(sin(theta)**2 + cos(theta)**2),
        sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2),
        1
    )  # ==> this should simplify to (1, a.x, 1)

    raises(TypeError, lambda: CoordSys3D('a', transformation={
        x: x*sin(y)*cos(z), y:x*sin(y)*sin(z), z:  x*cos(y)}))
def test_vector_with_orientation():
    """
    Tests the effects of orientation of coordinate systems on
    basic vector operations.
    """
    N = CoordSys3D('N')
    A = N.orient_new_axis('A', q1, N.k)
    B = A.orient_new_axis('B', q2, A.i)
    C = B.orient_new_axis('C', q3, B.j)

    # Test to_matrix
    v1 = a*N.i + b*N.j + c*N.k
    assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)],
                                      [-a*sin(q1) + b*cos(q1)],
                                      [                     c]])

    # Test dot
    assert N.i.dot(A.i) == cos(q1)
    assert N.i.dot(A.j) == -sin(q1)
    assert N.i.dot(A.k) == 0
    assert N.j.dot(A.i) == sin(q1)
    assert N.j.dot(A.j) == cos(q1)
    assert N.j.dot(A.k) == 0
    assert N.k.dot(A.i) == 0
    assert N.k.dot(A.j) == 0
    assert N.k.dot(A.k) == 1

    assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \
           (A.i + A.j).dot(N.i)

    assert A.i.dot(C.i) == cos(q3)
    assert A.i.dot(C.j) == 0
    assert A.i.dot(C.k) == sin(q3)
    assert A.j.dot(C.i) == sin(q2)*sin(q3)
    assert A.j.dot(C.j) == cos(q2)
    assert A.j.dot(C.k) == -sin(q2)*cos(q3)
    assert A.k.dot(C.i) == -cos(q2)*sin(q3)
    assert A.k.dot(C.j) == sin(q2)
    assert A.k.dot(C.k) == cos(q2)*cos(q3)

    # Test cross
    assert N.i.cross(A.i) == sin(q1)*A.k
    assert N.i.cross(A.j) == cos(q1)*A.k
    assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j
    assert N.j.cross(A.i) == -cos(q1)*A.k
    assert N.j.cross(A.j) == sin(q1)*A.k
    assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j
    assert N.k.cross(A.i) == A.j
    assert N.k.cross(A.j) == -A.i
    assert N.k.cross(A.k) == Vector.zero

    assert N.i.cross(A.i) == sin(q1)*A.k
    assert N.i.cross(A.j) == cos(q1)*A.k
    assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k
    assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k

    assert A.i.cross(C.i) == sin(q3)*C.j
    assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k
    assert A.i.cross(C.k) == -cos(q3)*C.j
    assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \
           (-sin(q2)*sin(q3))*A.k
    assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k
    assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j
def test_rotation_matrix():
    N = CoordSys3D('N')
    A = N.orient_new_axis('A', q1, N.k)
    B = A.orient_new_axis('B', q2, A.i)
    C = B.orient_new_axis('C', q3, B.j)
    D = N.orient_new_axis('D', q4, N.j)
    E = N.orient_new_space('E', q1, q2, q3, '123')
    F = N.orient_new_quaternion('F', q1, q2, q3, q4)
    G = N.orient_new_body('G', q1, q2, q3, '123')
    assert N.rotation_matrix(C) == Matrix([
        [- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) *
        cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], \
        [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), \
         cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * \
         cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]])
    test_mat = D.rotation_matrix(C) - Matrix(
        [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) +
        sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) *
            cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \
          (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \
         [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * \
          cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], \
         [sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \
                                                   sin(q1) * sin(q2) * \
                                                   sin(q4)), sin(q2) *
                cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \
          sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \
                                         sin(q1) * sin(q2) * sin(q4))]])
    assert test_mat.expand() == zeros(3, 3)
    assert E.rotation_matrix(N) == Matrix(
        [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)],
        [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \
         sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \
         [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \
          sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]])
    assert F.rotation_matrix(N) == Matrix([[
        q1**2 + q2**2 - q3**2 - q4**2,
        2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4],[ -2*q1*q4 + 2*q2*q3,
            q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4],
                                           [2*q1*q3 + 2*q2*q4,
                                            -2*q1*q2 + 2*q3*q4,
                                q1**2 - q2**2 - q3**2 + q4**2]])
    assert G.rotation_matrix(N) == Matrix([[
        cos(q2)*cos(q3),  sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1),
        sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [
            -sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3),
            sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],[
                sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]])
Beispiel #37
0
    'R3', 'R3_origin', 'relations_3d', 'R3_r', 'R3_c', 'R3_s'
]

###############################################################################
# R2
###############################################################################
R2 = Manifold('R^2', 2)  # type: Any

R2_origin = Patch('origin', R2)  # type: Any

x, y = symbols('x y', real=True)
r, theta = symbols('rho theta', nonnegative=True)

relations_2d = {
    ('rectangular', 'polar'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])),
    ('polar', 'rectangular'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)])),
}

R2_r = CoordSystem('rectangular', R2_origin, [x, y], relations_2d)  # type: Any
R2_p = CoordSystem('polar', R2_origin, [r, theta], relations_2d)  # type: Any

# support deprecated feature
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    x, y, r, theta = symbols('x y r theta', cls=Dummy)
    R2_r.connect_to(R2_p, [x, y],
                        [sqrt(x**2 + y**2), atan2(y, x)],
                    inverse=False, fill_in_gaps=False)
    R2_p.connect_to(R2_r, [r, theta],
                        [r*cos(theta), r*sin(theta)],
                    inverse=False, fill_in_gaps=False)
Beispiel #38
0
def test_Subs():
    assert Subs(1, (), ()) is S.One
    # check null subs influence on hashing
    assert Subs(x, y, z) != Subs(x, y, 1)
    # neutral subs works
    assert Subs(x, x, 1).subs(x, y).has(y)
    # self mapping var/point
    assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x)
    assert Subs(x, x, 0).has(x)  # it's a structural answer
    assert not Subs(x, x, 0).free_symbols
    assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1))
    assert Subs(x, (x,), (0,)) == Subs(x, x, 0)
    assert Subs(x, x, 0) == Subs(y, y, 0)
    assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0)
    assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0)
    assert Subs(f(x), x, 0).doit() == f(0)
    assert Subs(f(x**2), x**2, 0).doit() == f(0)
    assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \
        Subs(f(x, y, z), (x, y, z), (0, 0, 1))
    assert Subs(x, y, 2).subs(x, y).doit() == 2
    assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \
        Subs(f(x, y) + z, (x, y, z), (0, 1, 0))
    assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1)
    assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1)
    raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1)))
    raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1)))

    assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2
    assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1)

    assert Subs(f(x), x, 0) == Subs(f(y), y, 0)
    assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0))
    assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1))
    assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1))

    assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
    assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
    assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2)
    assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y

    assert Subs(f(x), x, 0).free_symbols == set([])
    assert Subs(f(x, y), x, z).free_symbols == {y, z}

    assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0)
    assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0)
    assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \
        2*Subs(Derivative(f(x, 2), x), x, 0)
    assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0)

    e = Subs(y**2*f(x), x, y)
    assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y)

    assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0)
    e1 = Subs(z*f(x), x, 1)
    e2 = Subs(z*f(y), y, 1)
    assert e1 + e2 == 2*e1
    assert e1.__hash__() == e2.__hash__()
    assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ]
    assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x))
    assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x),
        x, x + y)
    assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \
        Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \
        z + Rational('1/2').n(2)*f(0)

    assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0)
    assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0)
    assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
        ).doit() == 2*exp(x)
    assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
        ).doit(deep=False) == 2*Derivative(exp(x), x)
    assert Derivative(f(x, g(x)), x).doit() == Derivative(
        f(x, g(x)), g(x))*Derivative(g(x), x) + Subs(Derivative(
        f(y, g(x)), y), y, x)
theta1 = sym.Function('theta1')(t)
theta2 = sym.Function('theta2')(t)
phi = sym.Function('phi')(theta1, theta2)


theta1_dot = theta1.diff(t)
theta1_dot_dot = theta1.diff(t, t)

theta2_dot = theta2.diff(t)
theta2_dot_dot = theta2.diff(t,t)

# First, write out the position of the two masses 
# We will differentiate these to get the mass's velocities
x1 = R1 * sym.sin(theta1)

y1 = -1 * (R1 * sym.cos(theta1) )


x2 = x1 + (R2 * sym.sin(theta1 + theta2) )

y2 =  (y1 - R2 * sym.cos(theta1 + theta2) )

x1_dt = x1.diff(t)
y1_dt = y1.diff(t)

x2_dt = x2.diff(t)
y2_dt = y2.diff(t)

phi = ( sym.sqrt( ( (x2**2) + (y2**2)) ) - np.sqrt(2) )

Beispiel #40
0
def test_derivative_numerically():
    from random import random
    z0 = random() + I*random()
    assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15
Beispiel #41
0
def test_collect_2():
    """Collect with respect to a sum"""
    a, b, x = symbols('a,b,x')
    assert collect(a * (cos(x) + sin(x)) + b * (cos(x) + sin(x)),
                   sin(x) + cos(x)) == (a + b) * (cos(x) + sin(x))
Beispiel #42
0
def test_issue_7027():
    for wrt in (cos(x), re(x), Derivative(cos(x), x)):
        raises(ValueError, lambda: diff(f(x), wrt))
Beispiel #43
0
def test_expr_to_holonomic():
    x = symbols('x')
    R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
    p = expr_to_holonomic((sin(x) / x)**2)
    q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \
        [1, 0, Rational(-2, 3)])
    assert p == q
    p = expr_to_holonomic(1 / (1 + x**2)**2)
    q = HolonomicFunction(4 * x + (x**2 + 1) * Dx, x, 0, [1])
    assert p == q
    p = expr_to_holonomic(exp(x) * sin(x) + x * log(1 + x))
    q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \
        - 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \
        (-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \
        7*x**2/2 + x + Rational(5, 2))*Dx**4, x, 0, [0, 1, 4, -1])
    assert p == q
    p = expr_to_holonomic(x * exp(x) + cos(x) + 1)
    q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \
        0, [2, 1, 1, 3])
    assert p == q
    assert (x * exp(x) + cos(x) + 1).series(n=10) == p.series(n=10)
    p = expr_to_holonomic(log(1 + x)**2 + 1)
    q = HolonomicFunction(
        Dx + (3 * x + 3) * Dx**2 + (x**2 + 2 * x + 1) * Dx**3, x, 0, [1, 0, 2])
    assert p == q
    p = expr_to_holonomic(erf(x)**2 + x)
    q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \
        (x**2+ Rational(1, 4))*Dx**4, x, 0, [0, 1, 8/pi, 0])
    assert p == q
    p = expr_to_holonomic(cosh(x) * x)
    q = HolonomicFunction((-x**2 + 2) - 2 * x * Dx + x**2 * Dx**2, x, 0,
                          [0, 1])
    assert p == q
    p = expr_to_holonomic(besselj(2, x))
    q = HolonomicFunction((x**2 - 4) + x * Dx + x**2 * Dx**2, x, 0, [0, 0])
    assert p == q
    p = expr_to_holonomic(besselj(0, x) + exp(x))
    q = HolonomicFunction((-x**2 - x/2 + S.Half) + (x**2 - x/2 - Rational(3, 2))*Dx + (-x**2 + x/2 + 1)*Dx**2 +\
        (x**2 + x/2)*Dx**3, x, 0, [2, 1, S.Half])
    assert p == q
    p = expr_to_holonomic(sin(x)**2 / x)
    q = HolonomicFunction(4 + 4 * x * Dx + 3 * Dx**2 + x * Dx**3, x, 0,
                          [0, 1, 0])
    assert p == q
    p = expr_to_holonomic(sin(x)**2 / x, x0=2)
    q = HolonomicFunction((4) + (4 * x) * Dx + (3) * Dx**2 + (x) * Dx**3, x, 2,
                          [
                              sin(2)**2 / 2,
                              sin(2) * cos(2) - sin(2)**2 / 4,
                              -3 * sin(2)**2 / 4 + cos(2)**2 - sin(2) * cos(2)
                          ])
    assert p == q
    p = expr_to_holonomic(log(x) / 2 - Ci(2 * x) / 2 + Ci(2) / 2)
    q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \
        [-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0])
    assert p == q
    p = p.to_expr()
    q = log(x) / 2 - Ci(2 * x) / 2 + Ci(2) / 2
    assert p == q
    p = expr_to_holonomic(x**S.Half, x0=1)
    q = HolonomicFunction(x * Dx - S.Half, x, 1, [1])
    assert p == q
    p = expr_to_holonomic(sqrt(1 + x**2))
    q = HolonomicFunction((-x) + (x**2 + 1) * Dx, x, 0, [1])
    assert p == q
    assert (expr_to_holonomic(sqrt(x) + sqrt(2*x)).to_expr()-\
        (sqrt(x) + sqrt(2*x))).simplify() == 0
    assert expr_to_holonomic(3 * x +
                             2 * sqrt(x)).to_expr() == 3 * x + 2 * sqrt(x)
    p = expr_to_holonomic((x**4 + x**3 + 5 * x**2 + 3 * x + 2) / x**2,
                          lenics=3)
    q = HolonomicFunction((-2*x**4 - x**3 + 3*x + 4) + (x**5 + x**4 + 5*x**3 + 3*x**2 + \
        2*x)*Dx, x, 0, {-2: [2, 3, 5]})
    assert p == q
    p = expr_to_holonomic(1 / (x - 1)**2, lenics=3, x0=1)
    q = HolonomicFunction((2) + (x - 1) * Dx, x, 1, {-2: [1, 0, 0]})
    assert p == q
    a = symbols("a")
    p = expr_to_holonomic(sqrt(a * x), x=x)
    assert p.to_expr() == sqrt(a) * sqrt(x)
Beispiel #44
0
import sympy
from sympy import sin, cos

theta = sympy.Symbol('theta', real=True, nonnegative=True)
# 二つの円の半径
r1 = 5
r2 = 10
# 点A
A_x = -2
A_y = 0

# 三角形の面積
area = ((r2 * cos(2 * theta) - A_x) * (r1 * sin(theta) - A_y) -
        (r1 * cos(theta) - A_x) * (r2 * sin(2 * theta) - A_y)) / 2
diff_area = sympy.diff(area, theta)

eq = sympy.solve(diff_area, theta)

area_max = 0  # 三角形の面積の最大値
for i in eq:
    if (area_max < abs(area.subs(theta, i))):
        area_max = area.subs(theta, i)
print('S max is {}'.format(area_max.evalf()))
Beispiel #45
0
def test_periodicity():
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z', real=True)

    assert periodicity(sin(2*x), x) == pi
    assert periodicity((-2)*tan(4*x), x) == pi/4
    assert periodicity(sin(x)**2, x) == 2*pi
    assert periodicity(3**tan(3*x), x) == pi/3
    assert periodicity(tan(x)*cos(x), x) == 2*pi
    assert periodicity(sin(x)**(tan(x)), x) == 2*pi
    assert periodicity(tan(x)*sec(x), x) == 2*pi
    assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
    assert periodicity(tan(x) + cot(x), x) == pi
    assert periodicity(sin(x) - cos(2*x), x) == 2*pi
    assert periodicity(sin(x) - 1, x) == 2*pi
    assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
    assert periodicity(exp(sin(x)), x) == 2*pi
    assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
    assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
    assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
    assert periodicity(tan(sin(2*x)), x) == pi
    assert periodicity(2*tan(x)**2, x) == pi
    assert periodicity(sin(x%4), x) == 4
    assert periodicity(sin(x)%4, x) == 2*pi
    assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
    assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
    assert periodicity((x**2+1) % x, x) is None
    assert periodicity(sin(re(x)), x) == 2*pi
    assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
    assert periodicity(tan(x), y) is S.Zero
    assert periodicity(sin(x) + I*cos(x), x) == 2*pi
    assert periodicity(x - sin(2*y), y) == pi

    assert periodicity(exp(x), x) is None
    assert periodicity(exp(I*x), x) == 2*pi
    assert periodicity(exp(I*z), z) == 2*pi
    assert periodicity(exp(z), z) is None
    assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi
    assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi
    assert periodicity(exp(sin(z)), z) == 2*pi
    assert periodicity(exp(2*I*z), z) == pi
    assert periodicity(exp(z + I*sin(z)), z) is None
    assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi
    assert periodicity(log(x), x) is None
    assert periodicity(exp(x)**sin(x), x) is None
    assert periodicity(sin(x)**y, y) is None

    assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
    assert all(periodicity(Abs(f(x)), x) == pi for f in (
        cos, sin, sec, csc, tan, cot))
    assert periodicity(Abs(sin(tan(x))), x) == pi
    assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
    assert periodicity(sin(x) > S.Half, x) == 2*pi

    assert periodicity(x > 2, x) is None
    assert periodicity(x**3 - x**2 + 1, x) is None
    assert periodicity(Abs(x), x) is None
    assert periodicity(Abs(x**2 - 1), x) is None

    assert periodicity((x**2 + 4)%2, x) is None
    assert periodicity((E**x)%3, x) is None

    assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
Beispiel #46
0
def test_radsimp():
    r2 = sqrt(2)
    r3 = sqrt(3)
    r5 = sqrt(5)
    r7 = sqrt(7)
    assert fraction(radsimp(1 / r2)) == (sqrt(2), 2)
    assert radsimp(1/(1 + r2)) == \
        -1 + sqrt(2)
    assert radsimp(1/(r2 + r3)) == \
        -sqrt(2) + sqrt(3)
    assert fraction(radsimp(1/(1 + r2 + r3))) == \
        (-sqrt(6) + sqrt(2) + 2, 4)
    assert fraction(radsimp(1/(r2 + r3 + r5))) == \
        (-sqrt(30) + 2*sqrt(3) + 3*sqrt(2), 12)
    assert fraction(radsimp(
        1 /
        (1 + r2 + r3 + r5))) == ((-34 * sqrt(10) - 26 * sqrt(15) -
                                  55 * sqrt(3) - 61 * sqrt(2) + 14 * sqrt(30) +
                                  93 + 46 * sqrt(6) + 53 * sqrt(5), 71))
    assert fraction(radsimp(
        1 / (r2 + r3 + r5 + r7))) == ((-50 * sqrt(42) - 133 * sqrt(5) -
                                       34 * sqrt(70) - 145 * sqrt(3) +
                                       22 * sqrt(105) + 185 * sqrt(2) +
                                       62 * sqrt(30) + 135 * sqrt(7), 215))
    z = radsimp(1 / (1 + r2 / 3 + r3 / 5 + r5 + r7))
    assert len((3616791619821680643598 * z).args) == 16
    assert radsimp(1 / z) == 1 / z
    assert radsimp(1 / z,
                   max_terms=20).expand() == 1 + r2 / 3 + r3 / 5 + r5 + r7
    assert radsimp(1/(r2*3)) == \
        sqrt(2)/6
    assert radsimp(1 / (r2 * a + r3 + r5 + r7)) == (
        (8 * sqrt(2) * a**7 - 8 * sqrt(7) * a**6 - 8 * sqrt(5) * a**6 -
         8 * sqrt(3) * a**6 - 180 * sqrt(2) * a**5 + 8 * sqrt(30) * a**5 +
         8 * sqrt(42) * a**5 + 8 * sqrt(70) * a**5 - 24 * sqrt(105) * a**4 +
         84 * sqrt(3) * a**4 + 100 * sqrt(5) * a**4 + 116 * sqrt(7) * a**4 -
         72 * sqrt(70) * a**3 - 40 * sqrt(42) * a**3 - 8 * sqrt(30) * a**3 +
         782 * sqrt(2) * a**3 - 462 * sqrt(3) * a**2 - 302 * sqrt(7) * a**2 -
         254 * sqrt(5) * a**2 + 120 * sqrt(105) * a**2 - 795 * sqrt(2) * a -
         62 * sqrt(30) * a + 82 * sqrt(42) * a + 98 * sqrt(70) * a -
         118 * sqrt(105) + 59 * sqrt(7) + 295 * sqrt(5) + 531 * sqrt(3)) /
        (16 * a**8 - 480 * a**6 + 3128 * a**4 - 6360 * a**2 + 3481))
    assert radsimp(1 / (r2 * a + r2 * b + r3 + r7)) == (
        (sqrt(2) * a *
         (a + b)**2 - 5 * sqrt(2) * a + sqrt(42) * a + sqrt(2) * b *
         (a + b)**2 - 5 * sqrt(2) * b + sqrt(42) * b - sqrt(7) *
         (a + b)**2 - sqrt(3) * (a + b)**2 - 2 * sqrt(3) + 2 * sqrt(7)) /
        (2 * a**4 + 8 * a**3 * b + 12 * a**2 * b**2 - 20 * a**2 +
         8 * a * b**3 - 40 * a * b + 2 * b**4 - 20 * b**2 + 8))
    assert radsimp(1/(r2*a + r2*b + r2*c + r2*d)) == \
        sqrt(2)/(2*a + 2*b + 2*c + 2*d)
    assert radsimp(1 / (1 + r2 * a + r2 * b + r2 * c + r2 * d)) == (
        (sqrt(2) * a + sqrt(2) * b + sqrt(2) * c + sqrt(2) * d - 1) /
        (2 * a**2 + 4 * a * b + 4 * a * c + 4 * a * d + 2 * b**2 + 4 * b * c +
         4 * b * d + 2 * c**2 + 4 * c * d + 2 * d**2 - 1))
    assert radsimp((y**2 - x)/(y - sqrt(x))) == \
        sqrt(x) + y
    assert radsimp(-(y**2 - x)/(y - sqrt(x))) == \
        -(sqrt(x) + y)
    assert radsimp(1/(1 - I + a*I)) == \
        (-I*a + 1 + I)/(a**2 - 2*a + 2)
    assert radsimp(1/((-x + y)*(x - sqrt(y)))) == \
        (-x - sqrt(y))/((x - y)*(x**2 - y))
    e = (3 + 3 * sqrt(2)) * x * (3 * x - 3 * sqrt(y))
    assert radsimp(e) == x * (3 + 3 * sqrt(2)) * (3 * x - 3 * sqrt(y))
    assert radsimp(1 / e) == (
        (-9 * x + 9 * sqrt(2) * x - 9 * sqrt(y) + 9 * sqrt(2) * sqrt(y)) /
        (9 * x * (9 * x**2 - 9 * y)))
    assert radsimp(1 + 1/(1 + sqrt(3))) == \
        Mul(S.Half, -1 + sqrt(3), evaluate=False) + 1
    A = symbols("A", commutative=False)
    assert radsimp(x**2 + sqrt(2)*x**2 - sqrt(2)*x*A) == \
        x**2 + sqrt(2)*x**2 - sqrt(2)*x*A
    assert radsimp(1 / sqrt(5 + 2 * sqrt(6))) == -sqrt(2) + sqrt(3)
    assert radsimp(1 / sqrt(5 + 2 * sqrt(6))**3) == -(-sqrt(3) + sqrt(2))**3

    # issue 6532
    assert fraction(radsimp(1 / sqrt(x))) == (sqrt(x), x)
    assert fraction(radsimp(1 / sqrt(2 * x + 3))) == (sqrt(2 * x + 3),
                                                      2 * x + 3)
    assert fraction(radsimp(1 / sqrt(2 * (x + 3)))) == (sqrt(2 * x + 6),
                                                        2 * x + 6)

    # issue 5994
    e = S('-(2 + 2*sqrt(2) + 4*2**(1/4))/'
          '(1 + 2**(3/4) + 3*2**(1/4) + 3*sqrt(2))')
    assert radsimp(e).expand(
    ) == -2 * 2**Rational(3, 4) - 2 * 2**Rational(1, 4) + 2 + 2 * sqrt(2)

    # issue 5986 (modifications to radimp didn't initially recognize this so
    # the test is included here)
    assert radsimp(1 / (-sqrt(5) / 2 - S.Half +
                        (-sqrt(5) / 2 - S.Half)**2)) == 1

    # from issue 5934
    eq = ((-240 * sqrt(2) * sqrt(sqrt(5) + 5) * sqrt(8 * sqrt(5) + 40) -
           360 * sqrt(2) * sqrt(-8 * sqrt(5) + 40) * sqrt(-sqrt(5) + 5) -
           120 * sqrt(10) * sqrt(-8 * sqrt(5) + 40) * sqrt(-sqrt(5) + 5) +
           120 * sqrt(2) * sqrt(-sqrt(5) + 5) * sqrt(8 * sqrt(5) + 40) +
           120 * sqrt(2) * sqrt(-8 * sqrt(5) + 40) * sqrt(sqrt(5) + 5) +
           120 * sqrt(10) * sqrt(-sqrt(5) + 5) * sqrt(8 * sqrt(5) + 40) +
           120 * sqrt(10) * sqrt(-8 * sqrt(5) + 40) * sqrt(sqrt(5) + 5)) /
          (-36000 - 7200 * sqrt(5) + (12 * sqrt(10) * sqrt(sqrt(5) + 5) +
                                      24 * sqrt(10) * sqrt(-sqrt(5) + 5))**2))
    assert radsimp(eq) is S.NaN  # it's 0/0

    # work with normal form
    e = 1 / sqrt(sqrt(7) / 7 + 2 * sqrt(2) + 3 * sqrt(3) + 5 * sqrt(5)) + 3
    assert radsimp(e) == (
        -sqrt(sqrt(7) + 14 * sqrt(2) + 21 * sqrt(3) + 35 * sqrt(5)) *
        (-11654899 * sqrt(35) - 1577436 * sqrt(210) - 1278438 * sqrt(15) -
         1346996 * sqrt(10) + 1635060 * sqrt(6) + 5709765 +
         7539830 * sqrt(14) + 8291415 * sqrt(21)) / 1300423175 + 3)

    # obey power rules
    base = sqrt(3) - sqrt(2)
    assert radsimp(1 / base**3) == (sqrt(3) + sqrt(2))**3
    assert radsimp(1 / (-base)**3) == -(sqrt(2) + sqrt(3))**3
    assert radsimp(1 / (-base)**x) == (-base)**(-x)
    assert radsimp(1 / base**x) == (sqrt(2) + sqrt(3))**x
    assert radsimp(root(1 / (-1 - sqrt(2)),
                        -x)) == (-1)**(-1 / x) * (1 + sqrt(2))**(1 / x)

    # recurse
    e = cos(1 / (1 + sqrt(2)))
    assert radsimp(e) == cos(-sqrt(2) + 1)
    assert radsimp(e / 2) == cos(-sqrt(2) + 1) / 2
    assert radsimp(1 / e) == 1 / cos(-sqrt(2) + 1)
    assert radsimp(2 / e) == 2 / cos(-sqrt(2) + 1)
    assert fraction(radsimp(e / sqrt(x))) == (sqrt(x) * cos(-sqrt(2) + 1), x)

    # test that symbolic denominators are not processed
    r = 1 + sqrt(2)
    assert radsimp(x / r, symbolic=False) == -x * (-sqrt(2) + 1)
    assert radsimp(x / (y + r), symbolic=False) == x / (y + 1 + sqrt(2))
    assert radsimp(x/(y + r)/r, symbolic=False) == \
        -x*(-sqrt(2) + 1)/(y + 1 + sqrt(2))

    # issue 7408
    eq = sqrt(x) / sqrt(y)
    assert radsimp(eq) == umul(sqrt(x), sqrt(y), 1 / y)
    assert radsimp(eq, symbolic=False) == eq

    # issue 7498
    assert radsimp(sqrt(x) / sqrt(y)**3) == umul(sqrt(x), sqrt(y**3), 1 / y**3)

    # for coverage
    eq = sqrt(x) / y**2
    assert radsimp(eq) == eq
def test_minpoly_compose():
    # issue 6868
    eq = S('''
        -1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
        sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
        sqrt(15)*I/28800000)**(1/3)))''')
    mp = minimal_polynomial(eq + 3, x)
    assert mp == 8000 * x**2 - 48000 * x + 71999

    # issue 5888
    assert minimal_polynomial(exp(I * pi / 8), x) == x**8 + 1

    mp = minimal_polynomial(sin(pi / 7) + sqrt(2), x)
    assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
        770912*x**4 - 268432*x**2 + 28561
    mp = minimal_polynomial(cos(pi / 7) + sqrt(2), x)
    assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
            232*x - 239
    mp = minimal_polynomial(exp(I * pi / 7) + sqrt(2), x)
    assert mp == x**12 - 2 * x**11 - 9 * x**10 + 16 * x**9 + 43 * x**8 - 70 * x**7 - 97 * x**6 + 126 * x**5 + 211 * x**4 - 212 * x**3 - 37 * x**2 + 142 * x + 127

    mp = minimal_polynomial(sin(pi / 7) + sqrt(2), x)
    assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
        770912*x**4 - 268432*x**2 + 28561
    mp = minimal_polynomial(cos(pi / 7) + sqrt(2), x)
    assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
            232*x - 239
    mp = minimal_polynomial(exp(I * pi / 7) + sqrt(2), x)
    assert mp == x**12 - 2 * x**11 - 9 * x**10 + 16 * x**9 + 43 * x**8 - 70 * x**7 - 97 * x**6 + 126 * x**5 + 211 * x**4 - 212 * x**3 - 37 * x**2 + 142 * x + 127

    mp = minimal_polynomial(exp(2 * I * pi / 7), x)
    assert mp == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
    mp = minimal_polynomial(exp(2 * I * pi / 15), x)
    assert mp == x**8 - x**7 + x**5 - x**4 + x**3 - x + 1
    mp = minimal_polynomial(cos(2 * pi / 7), x)
    assert mp == 8 * x**3 + 4 * x**2 - 4 * x - 1
    mp = minimal_polynomial(sin(2 * pi / 7), x)
    ex = (5 * cos(2 * pi / 7) - 7) / (9 * cos(pi / 7) - 5 * cos(3 * pi / 7))
    mp = minimal_polynomial(ex, x)
    assert mp == x**3 + 2 * x**2 - x - 1
    assert minimal_polynomial(-1 / (2 * cos(pi / 7)),
                              x) == x**3 + 2 * x**2 - x - 1
    assert minimal_polynomial(sin(2*pi/15), x) == \
            256*x**8 - 448*x**6 + 224*x**4 - 32*x**2 + 1
    assert minimal_polynomial(sin(5 * pi / 14),
                              x) == 8 * x**3 - 4 * x**2 - 4 * x + 1
    assert minimal_polynomial(cos(
        pi / 15), x) == 16 * x**4 + 8 * x**3 - 16 * x**2 - 8 * x + 1

    ex = RootOf(x**3 + x * 4 + 1, 0)
    mp = minimal_polynomial(ex, x)
    assert mp == x**3 + 4 * x + 1
    mp = minimal_polynomial(ex + 1, x)
    assert mp == x**3 - 3 * x**2 + 7 * x - 4
    assert minimal_polynomial(exp(I * pi / 3), x) == x**2 - x + 1
    assert minimal_polynomial(exp(I * pi / 4), x) == x**4 + 1
    assert minimal_polynomial(exp(I * pi / 6), x) == x**4 - x**2 + 1
    assert minimal_polynomial(exp(I * pi / 9), x) == x**6 - x**3 + 1
    assert minimal_polynomial(exp(I * pi / 10),
                              x) == x**8 - x**6 + x**4 - x**2 + 1
    assert minimal_polynomial(sin(pi / 9),
                              x) == 64 * x**6 - 96 * x**4 + 36 * x**2 - 3
    assert minimal_polynomial(sin(pi/11), x) == 1024*x**10 - 2816*x**8 + \
            2816*x**6 - 1232*x**4 + 220*x**2 - 11

    ex = 2**Rational(1, 3) * exp(Rational(2, 3) * I * pi)
    assert minimal_polynomial(ex, x) == x**3 - 2

    raises(NotAlgebraic, lambda: minimal_polynomial(cos(pi * sqrt(2)), x))
    raises(NotAlgebraic, lambda: minimal_polynomial(sin(pi * sqrt(2)), x))
    raises(NotAlgebraic, lambda: minimal_polynomial(exp(I * pi * sqrt(2)), x))

    # issue 5934
    ex = 1 / (-36000 - 7200 * sqrt(5) +
              (12 * sqrt(10) * sqrt(sqrt(5) + 5) +
               24 * sqrt(10) * sqrt(-sqrt(5) + 5))**2) + 1
    raises(ZeroDivisionError, lambda: minimal_polynomial(ex, x))

    ex = sqrt(1 + 2**Rational(1, 3)) + sqrt(1 + 2**Rational(1, 4)) + sqrt(2)
    mp = minimal_polynomial(ex, x)
    assert degree(mp) == 48 and mp.subs({x: 0}) == -16630256576
Beispiel #48
0
def _solve_A(A, **kwargs):
    r"""
    Centrifugal corrected equivalent moment
    =======================================

    Convert beam loading into a single equivalent bending moment. Note that
    this is dependent on the location in the cross section. Due to the
    way we measure the strain on the blade and how we did the calibration
    of those sensors.

    .. math::

        \epsilon = \frac{M_{x_{equiv}}y}{EI_{xx}} = \frac{M_x y}{EI_{xx}}
        + \frac{M_y x}{EI_{yy}} + \frac{F_z}{EA}

        M_{x_{equiv}} = M_x + \frac{I_{xx}}{I_{yy}} M_y \frac{x}{y}
        + \frac{I_{xx}}{Ay} F_z

    Parameters
    ----------

    st_arr : np.ndarray(19)
        Only one line of the st_arr is allowed and it should correspond
        to the correct radial position of the strain gauge.

    load : list(6)
        list containing the load time series of following components
        .. math:: load = F_x, F_y, F_z, M_x, M_y, M_z
        and where each component is an ndarray(m)

    """

    d = kwargs.get('d', 40.)
    L = kwargs.get('L', 150.)
    acc_check = kwargs.get('acc_check', 0.0000001)
    solve_acc = kwargs.get('solve_acc', 20)

    # set the accuracy target of the solver
    sympy.mpmath.mp.dps = solve_acc
    psi = sympy.Symbol('psi')
    f1 = L - (L * sympy.tan(psi)) + (d / (2. * sympy.cos(psi))) - A
    # initial guess: solve system for delta_x = 0
    psi0 = math.atan(1 - (A / L))
    # solve the equation numerically with sympy
    psi_sol = sympy.nsolve(f1, psi, psi0)

    # verify if the solution is valid
    delta_x = d / (2. * math.cos(psi_sol))
    x = L * math.tan(psi_sol)
    Asym = sympy.Symbol('Asym')
    f_check = x - L + Asym - delta_x

    # verify that f_check == 0
    if not sympy.solvers.checksol(f_check, Asym, A):
        # in the event that it does not pass the checksol, see how close
        # the are manually. Seems they are rather close
        check_A = L + delta_x - x
        error = abs(A - check_A) / A
        if error > acc_check:
            msg = 'sympy\'s solution does not passes checksol()'
            msg += '\n A_check=%.12f <=> A=%.12f' % (check_A, A)
            raise ValueError, msg
        else:
            msg = 'sympy.solvers.checksol() failed, manual check is ok. '
            msg += 'A=%.2f, rel error=%2.3e' % (A, error)
            logging.warning(msg)

    return psi_sol * 180. / math.pi, psi0 * 180. / math.pi
Beispiel #49
0
def test_ltes():

    import numpy
    numpy.seterr(all='raise',
                 divide='raise',
                 over=None,
                 under=None,
                 invalid=None)

    def check_lte(method_residual, lte, exact_symb, base_dt, implicit):

        exact, residual, dys, J = utils.symb2functions(exact_symb)
        dddy = dys[3]
        Fddy = lambda t, y: J(t, y) * dys[2](t, y)

        newton_tol = 1e-10

        # tmax varies with dt so that we can vary dt over orders of
        # magnitude.
        tmax = 50 * dt

        # Run ode solver
        if implicit:
            ts, ys = ode._odeint(
                residual, [0.0], [sp.array([exact(0.0)], ndmin=1)],
                dt,
                tmax,
                method_residual,
                target_error=None,
                time_adaptor=ode.create_random_time_adaptor(base_dt),
                initialisation_actions=par(ode.higher_order_start, 3),
                newton_tol=newton_tol)

        else:
            ts, ys = ode.odeint_explicit(
                dys[1],
                exact(0.0),
                base_dt,
                tmax,
                method_residual,
                time_adaptor=ode.create_random_time_adaptor(base_dt))

        dts = utils.ts2dts(ts)

        # Check it's accurate-ish
        exact_ys = map(exact, ts)
        errors = map(op.sub, exact_ys, ys)
        utils.assert_list_almost_zero(errors, 1e-3)

        # Calculate ltes by two methods. Note that we need to drop a few
        # values because exact calculation (may) need a few dts. Could be
        # dodgy: exact dddys might not correspond to dddy in experiment if
        # done over long time and we've wandered away from the solution.
        exact_dddys = map(dddy, ts, ys)
        exact_Fddys = map(Fddy, ts, ys)
        exact_ltes = map(lte, dts[2:], dts[1:-1], dts[:-2], exact_dddys[3:],
                         exact_Fddys[3:])
        error_diff_ltes = map(op.sub, errors[1:], errors[:-1])[2:]

        # Print for debugging when something goes wrong
        print exact_ltes
        print error_diff_ltes

        # Probably the best test is that they give the same order of
        # magnitude and the same sign... Can't test much more than that
        # because we have no idea what the constant in front of the dt**4
        # term is. Effective zero (noise level) is either dt**4 or newton
        # tol, whichever is larger.
        z = 50 * max(dt**4, newton_tol)
        map(par(utils.assert_same_sign, fp_zero=z), exact_ltes,
            error_diff_ltes)
        map(par(utils.assert_same_order_of_magnitude, fp_zero=z), exact_ltes,
            error_diff_ltes)

        # For checking imr in more detail on J!=0 cases
        # if method_residual is ode.imr_residual:
        #     if J(1,2) != 0:
        #         assert False

    t = sympy.symbols('t')
    functions = [
        2 * t**2, t**3 + 3 * t**4,
        sympy.exp(t), 3 * sympy.exp(-t),
        sympy.sin(t),
        sympy.sin(t)**2 + sympy.cos(t)**2
    ]

    methods = [
        (ode.imr_residual, True,
         lambda dtn, _, _1, dddyn, Fddy: imr_lte(dtn, dddyn, Fddy)),
        (ode.bdf2_residual, True,
         lambda dtn, dtnm1, _, dddyn, _1: bdf2_lte(dtn, dtnm1, dddyn)),
        (ode.bdf3_residual, True,
         lambda dtn, dtnm1, dtnm2, dddyn, _: bdf3_lte(dtn, dtnm1, dtnm2, dddyn)
         ),
        ('ab2', False,
         lambda dtn, dtnm1, _, dddyn, _1: ab2_lte(dtn, dtnm1, dddyn)),

        # ('ebdf2', False,
        # lambda dtn, dtnm1, _, dddyn, _1: ebdf2_lte(dtn, dtnm1, dddyn)
        # ),

        # ('ebdf3', False,
        # lambda *_: ebdf3_lte()
        # ),
    ]

    # Seems to work from 1e-2 down until newton method stops converging due
    # to FD'ed Jacobian. Just do a middling value so that we can wobble the
    # step size around lots without problems.
    dts = [1e-3]

    for exact_symb in functions:
        for method_residual, implicit, lte in methods:
            for dt in dts:
                yield check_lte, method_residual, lte, exact_symb, dt, implicit
Beispiel #50
0
import pytest
import sympy as sp
import numpy as np
from shenfun import FunctionSpace, Function, project, TensorProductSpace, \
    comm, Array

x, y = sp.symbols('x,y', real=True)
f = sp.sin(sp.cos(x))
h = sp.sin(sp.cos(x)) * sp.atan2(y, x)
N = 16


def test_backward():
    T = FunctionSpace(N, 'C')
    L = FunctionSpace(N, 'L')

    uT = Function(T, buffer=f)
    uL = Function(L, buffer=f)

    uLT = uL.backward(kind=T)
    uT2 = project(uLT, T)
    assert np.linalg.norm(uT2 - uT) < 1e-8

    uTL = uT.backward(kind=L)
    uL2 = project(uTL, L)
    assert np.linalg.norm(uL2 - uL) < 1e-8

    T2 = FunctionSpace(N, 'C', bc=(f.subs(x, -1), f.subs(x, 1)))
    L = FunctionSpace(N, 'L')

    uT = Function(T2, buffer=f)
Beispiel #51
0
def test_Sum():
    assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))"
    assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \
        "Sum(x*y**2, (x, -2, 2), (y, -5, 5))"
import numpy as np
import sympy as smp
import matplotlib.pyplot as plt

x = smp.Symbol('x', real=True)  # ТОЛЬКО ВЕЩЕСТВЕННЫЕ

# F_expr = (0.4 - x)**2 + smp.tan(3*x)

F_expr = smp.tan(x) - smp.cos(x) + 0.1

# F_expr = x**8 + 1
H_expr = F_expr * smp.Abs(x)

print(F_expr)
print(H_expr)


def subs_x(value, expr):
    # print(smp.simplify(expr))

    return expr.subs(x, value)


def subs_to_np_expr(value, expr):
    # print(smp.simplify(expr))

    expr = expr.subs(x, value)
    expr_vector = smp.lambdify(x, expr, 'numpy')

    return expr_vector(value)
import matplotlib.pyplot as plt
from control import TransferFunction as Tf
### Note: This Question took a while to run for me, please be patient ###

import sympy as sm
from sympy import inverse_laplace_transform as ilt

# Code from Question 1 starting off then laplace is applied

# Define all involved symbolic variables
M, m, ell, g, x1, x2, x3, x4, F = \
    sm.symbols('M, m, ell, g, x1, x2, x3, x4, F', real=True, positive=True)

# Define phi
phi = 4 * m * ell * x4**2 * sm.sin(x3) + 4 * F - 3 * m * g * sm.sin(
    x3) * sm.cos(x3)
phi /= 4 * (M + m) - 3 * m * sm.cos(x3)**2

# define psi
psi = (-3) * (4 * m * ell * x4**2 * sm.sin(x3) * sm.cos(x3) + F * sm.cos(x3) -
              (M + m) * g * sm.sin(x3))
psi /= (4 * (M + m) - 3 * m * sm.cos(x3)**2) * ell

# differentiation of phi
dphi_F = phi.diff(F)
dphi_x3 = phi.diff(x3)
dphi_x4 = phi.diff(x4)

# differentiation of psi
dpsi_F = psi.diff(F)
dpsi_x3 = psi.diff(x3)
Beispiel #54
0
def test_differentiation():
    from sympy.functions.special.tensor_functions import KroneckerDelta
    i, j, k, l = symbols('i j k l', cls=Idx)
    a = symbols('a')
    m, n = symbols("m, n", integer=True, finite=True)
    assert m.is_real
    h, L = symbols('h L', cls=IndexedBase)
    hi, hj = h[i], h[j]

    expr = hi
    assert expr.diff(hj) == KroneckerDelta(i, j)
    assert expr.diff(hi) == KroneckerDelta(i, i)

    expr = S(2) * hi
    assert expr.diff(hj) == S(2) * KroneckerDelta(i, j)
    assert expr.diff(hi) == S(2) * KroneckerDelta(i, i)
    assert expr.diff(a) == S.Zero

    assert Sum(expr, (i, -oo, oo)).diff(hj) == Sum(2 * KroneckerDelta(i, j),
                                                   (i, -oo, oo))
    assert Sum(expr.diff(hj), (i, -oo, oo)) == Sum(2 * KroneckerDelta(i, j),
                                                   (i, -oo, oo))
    assert Sum(expr, (i, -oo, oo)).diff(hj).doit() == 2

    assert Sum(expr.diff(hi), (i, -oo, oo)).doit() == Sum(2,
                                                          (i, -oo, oo)).doit()
    assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == oo

    expr = a * hj * hj / S(2)
    assert expr.diff(hi) == a * h[j] * KroneckerDelta(i, j)
    assert expr.diff(a) == hj * hj / S(2)
    assert expr.diff(a, 2) == S.Zero

    assert Sum(expr,
               (i, -oo, oo)).diff(hi) == Sum(a * KroneckerDelta(i, j) * h[j],
                                             (i, -oo, oo))
    assert Sum(expr.diff(hi),
               (i, -oo, oo)) == Sum(a * KroneckerDelta(i, j) * h[j],
                                    (i, -oo, oo))
    assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == a * h[j]

    assert Sum(expr,
               (j, -oo, oo)).diff(hi) == Sum(a * KroneckerDelta(i, j) * h[j],
                                             (j, -oo, oo))
    assert Sum(expr.diff(hi),
               (j, -oo, oo)) == Sum(a * KroneckerDelta(i, j) * h[j],
                                    (j, -oo, oo))
    assert Sum(expr, (j, -oo, oo)).diff(hi).doit() == a * h[i]

    expr = a * sin(hj * hj)
    assert expr.diff(hi) == 2 * a * cos(hj * hj) * hj * KroneckerDelta(i, j)
    assert expr.diff(hj) == 2 * a * cos(hj * hj) * hj

    expr = a * L[i, j] * h[j]
    assert expr.diff(hi) == a * L[i, j] * KroneckerDelta(i, j)
    assert expr.diff(hj) == a * L[i, j]
    assert expr.diff(L[i, j]) == a * h[j]
    assert expr.diff(
        L[k, l]) == a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j]
    assert expr.diff(L[i, l]) == a * KroneckerDelta(j, l) * h[j]

    assert Sum(expr, (j, -oo, oo)).diff(L[k, l]) == Sum(
        a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j], (j, -oo, oo))
    assert Sum(expr, (j, -oo, oo)).diff(
        L[k, l]).doit() == a * KroneckerDelta(i, k) * h[l]

    assert h[m].diff(h[m]) == 1
    assert h[m].diff(h[n]) == KroneckerDelta(m, n)
    assert Sum(a * h[m],
               (m, -oo, oo)).diff(h[n]) == Sum(a * KroneckerDelta(m, n),
                                               (m, -oo, oo))
    assert Sum(a * h[m], (m, -oo, oo)).diff(h[n]).doit() == a
    assert Sum(a * h[m],
               (n, -oo, oo)).diff(h[n]) == Sum(a * KroneckerDelta(m, n),
                                               (n, -oo, oo))
    assert Sum(a * h[m], (m, -oo, oo)).diff(h[m]).doit() == oo * a
Beispiel #55
0
def test_issue_10304():
    d = cos(1)**2 + sin(1)**2 - 1
    assert d.is_comparable is False  # if this fails, find a new d
    e = 1 + d * I
    assert simplify(Eq(e, 0)) is S.false
Beispiel #56
0
        # Constants
        v, u_max = symbols('v, u_max')
        xb, yb = symbols('xb, yb')
        Dt, sigv, sigw, sigr = symbols('Dt, sigv, sigw, sigr')

        # Primary States
        x, y, theta = symbols('x, y, theta')

        # Control
        w = symbols('w')

        # Secondary States

        # Primary State Rates
        x_dot = v * cos(theta)
        y_dot = v * sin(theta)
        theta_dot = u_max * sin(w)

        writeList = [x_dot, y_dot, theta_dot]

        # Covariance Calculations

        p11, p12, p13,\
            p22, p23, \
            p33 \
            = symbols('p11 p12 p13\
                       p22 p23 \
                       p33'                           )

        P = Matrix([[p11, p12, p13], [p12, p22, p23], [p13, p13, p33]])
Beispiel #57
0
def test_norm_2d_1():

    domain = Domain('Omega', dim=2)
    x,y = domain.coordinates

    V = ScalarFunctionSpace('V', domain)
    F = element_of(V, name='F')

    # ...
    expr = x*y
    l2_norm_u = Norm(expr, domain, kind='l2')
    h1_norm_u = Norm(expr, domain, kind='h1')

    print('> l2 norm = ', TerminalExpr(l2_norm_u))
    print('> h1 norm = ', TerminalExpr(h1_norm_u))
    print('')
    # ...

    # ...
    expr = sin(pi*x)*sin(pi*y)
    l2_norm_u = Norm(expr, domain, kind='l2')
    h1_norm_u = Norm(expr, domain, kind='h1')

    print('> l2 norm = ', TerminalExpr(l2_norm_u))
    print('> h1 norm = ', TerminalExpr(h1_norm_u))
    print('')
    # ...

    # ...
    expr = F-x*y
    l2_norm_u = Norm(expr, domain, kind='l2')
    h1_norm_u = Norm(expr, domain, kind='h1')

    print('> l2 norm = ', TerminalExpr(l2_norm_u))
    print('> h1 norm = ', TerminalExpr(h1_norm_u))
    print('')
    # ...

    # ...
    expr = F-sin(pi*x)*sin(pi*y)
    l2_norm_u = Norm(expr, domain, kind='l2')
    h1_norm_u = Norm(expr, domain, kind='h1')

    print('> l2 norm = ', TerminalExpr(l2_norm_u))
    print('> h1 norm = ', TerminalExpr(h1_norm_u))
    print('')
    # ...

    # ...
    expr = F-sin(0.5*pi*(1.-x))*sin(pi*y)
    l2_norm_u = Norm(expr, domain, kind='l2')
    h1_norm_u = Norm(expr, domain, kind='h1')

    print('> l2 norm = ', TerminalExpr(l2_norm_u))
    print('> h1 norm = ', TerminalExpr(h1_norm_u))
    print('')
    # ...

    # ...
    expr = F-cos(0.5*pi*x)*sin(pi*y)
    l2_norm_u = Norm(expr, domain, kind='l2')
    h1_norm_u = Norm(expr, domain, kind='h1')

    print('> l2 norm = ', TerminalExpr(l2_norm_u))
    print('> h1 norm = ', TerminalExpr(h1_norm_u))
    print('')
Beispiel #58
0
class WBCellSymb4Param(bu.SymbExpr):

    a, b, c = sp.symbols('a, b, c', positive=True)
    u_2, u_3 = sp.symbols('u_2, u_3', positive=True)
    gamma = sp.symbols('gamma', positive=True)

    U0_a = sp.Matrix([a, b, 0])
    W0_a = sp.Matrix([c, 0, 0])
    UW0_a = W0_a - U0_a
    L2_U_0 = (U0_a.T * U0_a)[0]
    L2_UW_0 = (UW0_a.T * UW0_a)[0]

    U1_a = sp.Matrix([a, u_2, u_3])
    W1_a = sp.Matrix([c * sp.sin(gamma), 0, c * sp.cos(gamma)])
    UW1_a = U1_a - W1_a
    L2_U_1 = (U1_a.T * U1_a)[0]
    L2_UW_1 = (UW1_a.T * UW1_a)[0]

    u2_sol = sp.solve(L2_U_1 - L2_U_0, u_2)[0]
    u3_sol = sp.solve((L2_UW_1 - L2_UW_0).subs(u_2, u2_sol), u_3)[0]
    u_3_ = u3_sol
    u_2_ = u2_sol.subs(u_3, u3_sol)

    U_pp_a = U1_a.subs({u_2: u_2_, u_3: u_3_})
    U_mm_a = sp.Matrix([-U_pp_a[0], -U_pp_a[1], U_pp_a[2]])
    U_mp_a = sp.Matrix([-U_pp_a[0], U_pp_a[1], U_pp_a[2]])
    U_pm_a = sp.Matrix([U_pp_a[0], -U_pp_a[1], U_pp_a[2]])
    W_p_a = W1_a.subs({u_2: u_2_, u_3: u_3_})
    W_m_a = sp.Matrix([-W_p_a[0], W_p_a[1], W_p_a[2]])

    V_UW = U_pp_a - W_p_a
    L_UW = sp.sqrt(V_UW[1] ** 2 + V_UW[2] ** 2)
    theta_sol = sp.simplify(2 * sp.asin(V_UW[2] / L_UW))

    theta = sp.Symbol(r'theta')
    q_theta = Quaternion.from_axis_angle([1, 0, 0], theta)

    d_1, d_2, d_3 = sp.symbols('d_1, d_2, d_3')
    D_a = sp.Matrix([d_1, d_2, d_3])
    UD_pp_a = U_pp_a + D_a
    WD_p_a = W_p_a + D_a
    d_subs = sp.solve(UD_pp_a - W_m_a, [d_1, d_2, d_3])

    # center of rotation
    UD_pp_a_ = UD_pp_a.subs(d_subs)
    # rotated point
    WD_p_a_ = WD_p_a.subs(d_subs)
    # pull back
    WD_p_a_pb = WD_p_a_ - UD_pp_a_
    # rotate using quaternion
    WD_p_a_rot = q_theta.rotate_point(WD_p_a_pb.T, q_theta)
    # push forward
    WD_p_a_pf = sp.Matrix(WD_p_a_rot) + UD_pp_a_
    # rotated compatibility point
    WD_p_a_theta = WD_p_a_pf.subs(theta, -theta_sol)

    # rotate the center of the neighbour cell
    DD_a_pb = D_a.subs(d_subs) - UD_pp_a_
    DD_a_rot = q_theta.rotate_point(DD_a_pb.T, q_theta)
    DD_a_pf = sp.simplify(sp.Matrix(DD_a_rot) + UD_pp_a_)
    DD_a_theta = DD_a_pf.subs(theta, -theta_sol)

    H = W_p_a[2]

    rho = (U_mm_a[2] - DD_a_theta[2]) / (U_mm_a[1] - DD_a_theta[1]) * U_mm_a[1]
    R_0 = U_mm_a[2] - rho
    delta_phi = sp.asin(DD_a_theta[1] / R_0)
    delta_x = a + W_p_a[0]

    # theta = sp.symbols('theta')
    # x_1, x_2, x_3 = sp.symbols('x_1, x_2, x_3')
    #
    # q_theta = Quaternion.from_axis_angle([1, 0, 0], theta)
    # X_rot = q_theta.rotate_point((x_1, x_2, x_3), q_theta)
    # X_theta_a = sp.simplify(sp.Matrix(X_rot))

    symb_model_params = ['gamma', 'a', 'b', 'c', ]
    symb_expressions = [
        ('u_2_', ()),
        ('u_3_', ()),
        ('R_0', ()),
        ('delta_phi', ()),
        ('delta_x', ()),
        ('H', ()),
        ('theta_sol', ())
    ]
Beispiel #59
0
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt

from SimpleIterationMethod import simple_iteration_root_searcher
from DichotomyRootSearcher import dichotomy_root_searcher

if __name__ == '__main__':

    # Task 2

    # Input:

    x = sp.Symbol('x')
    func = (x) * sp.cos(x) - 0.56
    bounds = [-2, 2]
    error = 10**(-6)

    # Solution:

    # отрезки на которых один корень найдем графически

    y = sp.lambdify(x, func, 'numpy')

    t_list = np.linspace(bounds[0], bounds[1], 120, endpoint=True)
    y_list = [y(x) for x in t_list]

    plt.plot(t_list, y_list, 'b')
    plt.plot([-2, 2], [0, 0], 'r')
    plt.show()
Beispiel #60
0
def test_simplify_relational():
    assert simplify(x * (y + 1) - x * y - x + 1 < x) == (x > 1)
    assert simplify(x * (y + 1) - x * y - x - 1 < x) == (x > -1)
    assert simplify(x < x * (y + 1) - x * y - x + 1) == (x < 1)
    q, r = symbols("q r")
    assert (((-q + r) - (q - r)) <= 0).simplify() == (q >= r)
    root2 = sqrt(2)
    equation = ((root2 * (-q + r) - root2 * (q - r)) <= 0).simplify()
    assert equation == (q >= r)
    r = S.One < x
    # canonical operations are not the same as simplification,
    # so if there is no simplification, canonicalization will
    # be done unless the measure forbids it
    assert simplify(r) == r.canonical
    assert simplify(r, ratio=0) != r.canonical
    # this is not a random test; in _eval_simplify
    # this will simplify to S.false and that is the
    # reason for the 'if r.is_Relational' in Relational's
    # _eval_simplify routine
    assert simplify(-(2**(pi * Rational(3, 2)) + 6**pi)**(1 / pi) + 2 *
                    (2**(pi / 2) + 3**pi)**(1 / pi) < 0) is S.false
    # canonical at least
    assert Eq(y, x).simplify() == Eq(x, y)
    assert Eq(x - 1, 0).simplify() == Eq(x, 1)
    assert Eq(x - 1, x).simplify() == S.false
    assert Eq(2 * x - 1, x).simplify() == Eq(x, 1)
    assert Eq(2 * x, 4).simplify() == Eq(x, 2)
    z = cos(1)**2 + sin(1)**2 - 1  # z.is_zero is None
    assert Eq(z * x, 0).simplify() == S.true

    assert Ne(y, x).simplify() == Ne(x, y)
    assert Ne(x - 1, 0).simplify() == Ne(x, 1)
    assert Ne(x - 1, x).simplify() == S.true
    assert Ne(2 * x - 1, x).simplify() == Ne(x, 1)
    assert Ne(2 * x, 4).simplify() == Ne(x, 2)
    assert Ne(z * x, 0).simplify() == S.false

    # No real-valued assumptions
    assert Ge(y, x).simplify() == Le(x, y)
    assert Ge(x - 1, 0).simplify() == Ge(x, 1)
    assert Ge(x - 1, x).simplify() == S.false
    assert Ge(2 * x - 1, x).simplify() == Ge(x, 1)
    assert Ge(2 * x, 4).simplify() == Ge(x, 2)
    assert Ge(z * x, 0).simplify() == S.true
    assert Ge(x, -2).simplify() == Ge(x, -2)
    assert Ge(-x, -2).simplify() == Le(x, 2)
    assert Ge(x, 2).simplify() == Ge(x, 2)
    assert Ge(-x, 2).simplify() == Le(x, -2)

    assert Le(y, x).simplify() == Ge(x, y)
    assert Le(x - 1, 0).simplify() == Le(x, 1)
    assert Le(x - 1, x).simplify() == S.true
    assert Le(2 * x - 1, x).simplify() == Le(x, 1)
    assert Le(2 * x, 4).simplify() == Le(x, 2)
    assert Le(z * x, 0).simplify() == S.true
    assert Le(x, -2).simplify() == Le(x, -2)
    assert Le(-x, -2).simplify() == Ge(x, 2)
    assert Le(x, 2).simplify() == Le(x, 2)
    assert Le(-x, 2).simplify() == Ge(x, -2)

    assert Gt(y, x).simplify() == Lt(x, y)
    assert Gt(x - 1, 0).simplify() == Gt(x, 1)
    assert Gt(x - 1, x).simplify() == S.false
    assert Gt(2 * x - 1, x).simplify() == Gt(x, 1)
    assert Gt(2 * x, 4).simplify() == Gt(x, 2)
    assert Gt(z * x, 0).simplify() == S.false
    assert Gt(x, -2).simplify() == Gt(x, -2)
    assert Gt(-x, -2).simplify() == Lt(x, 2)
    assert Gt(x, 2).simplify() == Gt(x, 2)
    assert Gt(-x, 2).simplify() == Lt(x, -2)

    assert Lt(y, x).simplify() == Gt(x, y)
    assert Lt(x - 1, 0).simplify() == Lt(x, 1)
    assert Lt(x - 1, x).simplify() == S.true
    assert Lt(2 * x - 1, x).simplify() == Lt(x, 1)
    assert Lt(2 * x, 4).simplify() == Lt(x, 2)
    assert Lt(z * x, 0).simplify() == S.false
    assert Lt(x, -2).simplify() == Lt(x, -2)
    assert Lt(-x, -2).simplify() == Gt(x, 2)
    assert Lt(x, 2).simplify() == Lt(x, 2)
    assert Lt(-x, 2).simplify() == Gt(x, -2)