Example #1
0
def test_powdenest_polar():
    from sympy import powdenest
    x, y, z = symbols('x y z', polar=True)
    a, b, c = symbols('a b c')
    assert powdenest((x*y*z)**a) == x**a*y**a*z**a
    assert powdenest((x**a*y**b)**c) == x**(a*c)*y**(b*c)
    assert powdenest(((x**a)**b*y**c)**c) == x**(a*b*c)*y**(c**2)
Example #2
0
def test_issue_2750():
    I1, I2, I3, I4, I5, I6 = symbols('I1:7')
    dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4')

    e = (
        I1 - I2 - I3,
        I3 - I4 - I5,
        I4 + I5 - I6,
        -I1 + I2 + I6,
        -2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12,
        -I4 + dQ4,
        -I2 + dQ2,
        2*I3 + 2*I5 + 3*I6 - Q2,
        I4 - 2*I5 + 2*Q4 + dI4
    )

    ans = [{
           dQ4: I3 - I5,
    dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24,
    I4: I3 - I5,
    dQ2: I2,
    Q2: 2*I3 + 2*I5 + 3*I6,
    I1: I2 + I3,
    Q4: -I3/2 + 3*I5/2 - dI4/2}]
    assert solve(e, I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4, manual=True) == ans
    # the matrix solver (tested below) doesn't like this because it produces
    # a zero row in the matrix. Is this related to issue 1452?
    assert [ei.subs(
        ans[0]) for ei in e] == [0, 0, I3 - I6, -I3 + I6, 0, 0, 0, 0, 0]
Example #3
0
def test_log_symbolic():
    x, y = symbols('x,y')

    assert log(x, exp(1)) == log(x)
    assert log(exp(x)) != x

    assert log(x) == log(x)
    assert log(x, exp(1)) == log(x)
    assert log(x*y) != log(x) + log(y)

    assert log(x, 2) == log(x)/log(2)
    assert log(E, 2) == 1/log(2)


    p, q = symbols('p,q', positive=True)
    r = Symbol('r', real=True)

    assert log(p**2) != 2*log(p)
    assert log(p**2).expand() == 2*log(p)
    assert log(x**2).expand() != 2*log(x)
    assert log(p**q) != q*log(p)
    assert log(exp(p)) == p
    assert log(p*q) != log(p) + log(q)
    assert log(p*q).expand() == log(p) + log(q)

    assert log(-exp(p)) != p + I*pi
    assert log(-exp(x)).expand() != x + I*pi
    assert log(-exp(r)).expand() == r + I*pi

    assert log(x**y) != y*log(x)

    assert (log(x**-5)**-1).expand() != -1/log(x)/5
    assert (log(p**-5)**-1).expand() == -1/log(p)/5
    assert log(-x).func is log and log(-x).args[0] == -x
    assert log(-p).func is log and log(-p).args[0] == -p
Example #4
0
def test_subs_dict():
    a, b, c, d, e = symbols('a b c d e')
    z = symbols('z')

    assert (2*x + y + z).subs(dict(x=1, y=2)) == 4 + z

    l = [(sin(x), 2), (x, 1)]
    assert (sin(x)).subs(l) == \
           (sin(x)).subs(dict(l)) == 2
    assert sin(x).subs(reversed(l)) == sin(1)

    expr = sin(2*x) + sqrt(sin(2*x))*cos(2*x)*sin(exp(x)*x)
    reps = dict([
               (sin(2*x), c),
               (sqrt(sin(2*x)), a),
               (cos(2*x), b),
               (exp(x), e),
               (x, d),
    ])
    assert expr.subs(reps) == c + a*b*sin(d*e)

    l = [(x, 3), (y, x**2)]
    assert (x + y).subs(l) == 3 + x**2
    assert (x + y).subs(reversed(l)) == 12

    # If changes are made to convert lists into dictionaries and do
    # a dictionary-lookup replacement, these tests will help to catch
    # some logical errors that might occur
    l = [(y, z + 2), (1 + z, 5), (z, 2)]
    assert (y - 1 + 3*x).subs(l) == 5 + 3*x
    l = [(y, z + 2), (z, 3)]
    assert (y - 2).subs(l) == 3
Example #5
0
def test_exclude():
    R, C, Ri, Vout, V1, Vminus, Vplus, s = \
        symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s')
    Rf = symbols('Rf', positive=True)  # to eliminate Rf = 0 soln
    eqs = [C*V1*s + Vplus*(-2*C*s - 1/R),
           Vminus*(-1/Ri - 1/Rf) + Vout/Rf,
           C*Vplus*s + V1*(-C*s - 1/R) + Vout/R,
           -Vminus + Vplus]
    assert solve(eqs, exclude=s*C*R) == [
        {
            Rf: Ri*(C*R*s + 1)**2/(C*R*s),
            Vminus: Vplus,
            V1: Vplus*(2*C*R*s + 1)/(C*R*s),
            Vout: Vplus*(C**2*R**2*s**2 + 3*C*R*s + 1)/(C*R*s)},
        {
            Vplus: 0,
            Vminus: 0,
            V1: 0,
            Vout: 0},
    ]
    assert solve(eqs, exclude=[Vplus, s, C]) == [
        {
            Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)),
            Vminus: Vplus,
            Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus),
            R: Vplus/(C*s*(V1 - 2*Vplus))}]
Example #6
0
    def eq_sympy(input_dim, output_dim, ARD=False):
        """
        Latent force model covariance, exponentiated quadratic with multiple outputs. Derived from a diffusion equation with the initial spatial condition layed down by a Gaussian process with lengthscale given by shared_lengthscale.

        See IEEE Trans Pattern Anal Mach Intell. 2013 Nov;35(11):2693-705. doi: 10.1109/TPAMI.2013.86. Linear latent force models using Gaussian processes. Alvarez MA, Luengo D, Lawrence ND.

        :param input_dim: Dimensionality of the kernel
        :type input_dim: int
        :param output_dim: number of outputs in the covariance function.
        :type output_dim: int
        :param ARD: whether or not to user ARD (default False).
        :type ARD: bool

        """
        real_input_dim = input_dim
        if output_dim>1:
            real_input_dim -= 1
        X = sp.symbols('x_:' + str(real_input_dim))
        Z = sp.symbols('z_:' + str(real_input_dim))
        scale = sp.var('scale_i scale_j',positive=True)
        if ARD:
            lengthscales = [sp.var('lengthscale%i_i lengthscale%i_j' % i, positive=True) for i in range(real_input_dim)]
            shared_lengthscales = [sp.var('shared_lengthscale%i' % i, positive=True) for i in range(real_input_dim)]
            dist_string = ' + '.join(['(x_%i-z_%i)**2/(shared_lengthscale%i**2 + lengthscale%i_i**2 + lengthscale%i_j**2)' % (i, i, i) for i in range(real_input_dim)])
            dist = parse_expr(dist_string)
            f =  variance*sp.exp(-dist/2.)
        else:
            lengthscales = sp.var('lengthscale_i lengthscale_j',positive=True)
            shared_lengthscale = sp.var('shared_lengthscale',positive=True)
            dist_string = ' + '.join(['(x_%i-z_%i)**2' % (i, i) for i in range(real_input_dim)])
            dist = parse_expr(dist_string)
            f =  scale_i*scale_j*sp.exp(-dist/(2*(lengthscale_i**2 + lengthscale_j**2 + shared_lengthscale**2)))
        return kern(input_dim, [spkern(input_dim, f, output_dim=output_dim, name='eq_sympy')])
def test_issue_6966():
    i, k, m = symbols('i k m', integer=True)
    z_i, q_i = symbols('z_i q_i')
    a_k = Sum(-q_i*z_i/k,(i,1,m))
    b_k = a_k.diff(z_i)
    assert isinstance(b_k, Sum)
    assert b_k == Sum(-q_i/k,(i,1,m))
Example #8
0
def test_adjoint():
    a = Symbol('a', antihermitian=True)
    b = Symbol('b', hermitian=True)
    assert adjoint(a) == -a
    assert adjoint(I*a) == I*a
    assert adjoint(b) == b
    assert adjoint(I*b) == -I*b
    assert adjoint(a*b) == -b*a
    assert adjoint(I*a*b) == I*b*a

    x, y = symbols('x y')
    assert adjoint(adjoint(x)) == x
    assert adjoint(x + y) == adjoint(x) + adjoint(y)
    assert adjoint(x - y) == adjoint(x) - adjoint(y)
    assert adjoint(x * y) == adjoint(x) * adjoint(y)
    assert adjoint(x / y) == adjoint(x) / adjoint(y)
    assert adjoint(-x) == -adjoint(x)

    x, y = symbols('x y', commutative=False)
    assert adjoint(adjoint(x)) == x
    assert adjoint(x + y) == adjoint(x) + adjoint(y)
    assert adjoint(x - y) == adjoint(x) - adjoint(y)
    assert adjoint(x * y) == adjoint(y) * adjoint(x)
    assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x)
    assert adjoint(-x) == -adjoint(x)
Example #9
0
def test_is_constant():
    from sympy.solvers.solvers import checksol

    Sum(x, (x, 1, 10)).is_constant() == True
    Sum(x, (x, 1, n)).is_constant() == False
    Sum(x, (x, 1, n)).is_constant(y) == True
    Sum(x, (x, 1, n)).is_constant(n) == False
    Sum(x, (x, 1, n)).is_constant(x) == True
    eq = a * cos(x) ** 2 + a * sin(x) ** 2 - a
    eq.is_constant() == True
    assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
    assert x.is_constant() is False
    assert x.is_constant(y) is True

    assert checksol(x, x, Sum(x, (x, 1, n))) == False
    assert checksol(x, x, Sum(x, (x, 1, n))) == False
    f = Function("f")
    assert checksol(x, x, f(x)) == False

    p = symbols("p", positive=True)
    assert Pow(x, S(0), evaluate=False).is_constant() == True  # == 1
    assert Pow(S(0), x, evaluate=False).is_constant() == False  # == 0 or 1
    assert Pow(S(0), p, evaluate=False).is_constant() == True  # == 1
    assert (2 ** x).is_constant() == False
    assert Pow(S(2), S(3), evaluate=False).is_constant() == True

    z1, z2 = symbols("z1 z2", zero=True)
    assert (z1 + 2 * z2).is_constant() is True

    assert meter.is_constant() is True
    assert (3 * meter).is_constant() is True
    assert (x * meter).is_constant() is False
Example #10
0
def test_issue_11230():
    # a specific test that always failed
    a, b, f, k, l, i = symbols('a b f k l i')
    p = [a*b*f*k*l, a*i*k**2*l, f*i*k**2*l]
    R, C = cse(p)
    assert not any(i.is_Mul for a in C for i in a.args)

    # random tests for the issue
    from random import choice
    from sympy.core.function import expand_mul
    s = symbols('a:m')
    # 35 Mul tests, none of which should ever fail
    ex = [Mul(*[choice(s) for i in range(5)]) for i in range(7)]
    for p in subsets(ex, 3):
        p = list(p)
        R, C = cse(p)
        assert not any(i.is_Mul for a in C for i in a.args)
        for ri in reversed(R):
            for i in range(len(C)):
                C[i] = C[i].subs(*ri)
        assert p == C
    # 35 Add tests, none of which should ever fail
    ex = [Add(*[choice(s[:7]) for i in range(5)]) for i in range(7)]
    for p in subsets(ex, 3):
        p = list(p)
        was = R, C = cse(p)
        assert not any(i.is_Add for a in C for i in a.args)
        for ri in reversed(R):
            for i in range(len(C)):
                C[i] = C[i].subs(*ri)
        # use expand_mul to handle cases like this:
        # p = [a + 2*b + 2*e, 2*b + c + 2*e, b + 2*c + 2*g]
        # x0 = 2*(b + e) is identified giving a rebuilt p that
        # is now `[a + 2*(b + e), c + 2*(b + e), b + 2*c + 2*g]`
        assert p == [expand_mul(i) for i in C]
Example #11
0
def test_as_real_imag():
    n = pi**1000
    # the special code for working out the real
    # and complex parts of a power with Integer exponent
    # should not run if there is no imaginary part, hence
    # this should not hang
    assert n.as_real_imag() == (n, 0)

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

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

    assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
    i = symbols('i', imaginary=True)
    assert sqrt(i**2).as_real_imag() == (0, abs(i))
Example #12
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)
Example #13
0
def test_issue_1572_1364_1368():
    assert solve((sqrt(x**2 - 1) - 2)) in ([sqrt(5), -sqrt(5)],
                                           [-sqrt(5), sqrt(5)])
    assert solve((2**exp(y**2/x) + 2)/(x**2 + 15), y) == (
        [-sqrt(x)*sqrt(log((log(2) + I*pi)/log(2))),
          sqrt(x)*sqrt(log((log(2) + I*pi)/log(2)))]
          )

    C1, C2 = symbols('C1 C2')
    f = Function('f')
    assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))]
    a = symbols('a')
    E = S.Exp1
    assert solve(1 - log(a + 4*x**2), x) in (
                                        [-sqrt(-a + E)/2, sqrt(-a + E)/2],
                                        [sqrt(-a + E)/2, -sqrt(-a + E)/2]
                                        )
    assert solve(log(a**(-3) - x**2)/a, x) in (
                            [-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))],
                            [sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],)
    assert solve(1 - log(a + 4*x**2), x) in (
                                             [-sqrt(-a + E)/2, sqrt(-a + E)/2],
                                             [sqrt(-a + E)/2, -sqrt(-a + E)/2],)
    assert solve((a**2 + 1) * (sin(a*x) + cos(a*x)), x) == [-pi/(4*a), 3*pi/(4*a)]
    assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [2*atanh(S.Half)/a]
    assert solve(3-(sinh(a*x) + cosh(a*x)**2), x) == \
             [
             2*atanh(-1 + sqrt(2))/a,
             2*atanh(S(1)/2 + sqrt(5)/2)/a,
             2*atanh(-sqrt(2) - 1)/a,
             2*atanh(-sqrt(5)/2 + S(1)/2)/a
             ]
    assert solve(atan(x) - 1) == [tan(1)]
Example #14
0
def test_manualintegrate_orthogonal_poly():
    n = symbols('n')
    a, b = 7, S(5)/3
    polys = [jacobi(n, a, b, x), gegenbauer(n, a, x), chebyshevt(n, x),
        chebyshevu(n, x), legendre(n, x), hermite(n, x), laguerre(n, x),
        assoc_laguerre(n, a, x)]
    for p in polys:
        integral = manualintegrate(p, x)
        for deg in [-2, -1, 0, 1, 3, 5, 8]:
            # some accept negative "degree", some do not
            try:
                p_subbed = p.subs(n, deg)
            except ValueError:
                continue
            assert (integral.subs(n, deg).diff(x) - p_subbed).expand() == 0

        # can also integrate simple expressions with these polynomials
        q = x*p.subs(x, 2*x + 1)
        integral = manualintegrate(q, x)
        for deg in [2, 4, 7]:
            assert (integral.subs(n, deg).diff(x) - q.subs(n, deg)).expand() == 0

        # cannot integrate with respect to any other parameter
        t = symbols('t')
        for i in range(len(p.args) - 1):
            new_args = list(p.args)
            new_args[i] = t
            assert isinstance(manualintegrate(p.func(*new_args), t), Integral)
Example #15
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" )
Example #16
0
def Simple_manifold_with_scalar_function_derivative():
    Print_Function()
    coords = (x,y,z) = symbols('x y z')
    basis = (e1, e2, e3, grad) = MV.setup('e_1 e_2 e_3',metric='[1,1,1]',coords=coords)
    # Define surface
    mfvar = (u,v) = symbols('u v')
    X = u*e1+v*e2+(u**2+v**2)*e3
    print '\\f{X}{u,v} =',X
    MF = Manifold(X,mfvar)
    (eu,ev) = MF.Basis()
    # Define field on the surface.
    g = (v+1)*log(u)

    print '\\f{g}{u,v} =',g

    # Method 1: Using old Manifold routines.
    VectorDerivative = (MF.rbasis[0]/MF.E_sq)*diff(g,u) + (MF.rbasis[1]/MF.E_sq)*diff(g,v)
    print '\\eval{\\nabla g}{u=1,v=0} =', VectorDerivative.subs({u:1,v:0})

    # Method 2: Using new Manifold routines.
    dg = MF.Grad(g)
    print '\\eval{\\f{Grad}{g}}{u=1,v=0} =', dg.subs({u:1,v:0})
    dg = MF.grad*g
    print '\\eval{\\nabla g}{u=1,v=0} =', dg.subs({u:1,v:0})
    return
Example #17
0
def Test_Reciprocal_Frame():
    Print_Function()
    Format()
    coords = symbols('x y z')
    (ex,ey,ez,grad) = MV.setup('e_x e_y e_z',metric='[1,1,1]',coords=coords)

    mfvar = (u,v) = symbols('u v')

    eu = ex+ey
    ev = ex-ey

    (eu_r,ev_r) = ReciprocalFrame([eu,ev])

    oprint('\\mbox{Frame}',(eu,ev),'\\mbox{Reciprocal Frame}',(eu_r,ev_r))

    print r'%\bm{e}_{u}\cdot\bm{e}^{u} =',(eu|eu_r)
    print r'%\bm{e}_{u}\cdot\bm{e}^{v} =',eu|ev_r
    print r'%\bm{e}_{v}\cdot\bm{e}^{u} =',ev|eu_r
    print r'%\bm{e}_{v}\cdot\bm{e}^{v} =',ev|ev_r

    eu = ex+ey+ez
    ev = ex-ey

    (eu_r,ev_r) = ReciprocalFrame([eu,ev])

    oprint('\\mbox{Frame}',(eu,ev),'\\mbox{Reciprocal Frame}',(eu_r,ev_r))

    print r'%\bm{e}_{u}\cdot\bm{e}^{u} =',eu|eu_r
    print r'%\bm{e}_{u}\cdot\bm{e}^{v} =',eu|ev_r
    print r'%\bm{e}_{v}\cdot\bm{e}^{u} =',ev|eu_r
    print r'%\bm{e}_{v}\cdot\bm{e}^{v} =',ev|ev_r
    return
Example #18
0
def Simple_manifold_with_vector_function_derivative():
    Print_Function()
    coords = (x,y,z) = symbols('x y z')
    basis = (ex, ey, ez, grad) = \
            MV.setup('e_x e_y e_z',metric='[1,1,1]',coords=coords)
    # Define surface
    mfvar = (u,v) = symbols('u v')
    X = u*ex+v*ey+(u**2+v**2)*ez
    print '\\f{X}{u,v} =',X
    MF = Manifold(X,mfvar)
    (eu,ev) = MF.Basis()

    # Define field on the surface.
    g = (v+1)*log(u)

    print '\\mbox{Scalar Function: } g =',g
    dg = MF.grad*g
    dg.Fmt(3,'\\mbox{Scalar Function Derivative: } \\nabla g')
    print '\\eval{\\nabla g}{(1,0)} =',dg.subs({u:1,v:0})

    # Define vector field on the surface

    G = v**2*eu+u**2*ev
    print '\\mbox{Vector Function: } G =',G
    dG = MF.grad*G
    dG.Fmt(3,'\\mbox{Vector Function Derivative: } \\nabla G')
    print '\\eval{\\nabla G}{(1,0)} =',dG.subs({u:1,v:0})

    return
Example #19
0
def Distorted_manifold_with_scalar_function():
    Print_Function()
    coords = symbols('x y z')
    (ex,ey,ez,grad) = MV.setup('e_x e_y e_z',metric='[1,1,1]',coords=coords)
    mfvar = (u,v) = symbols('u v')
    X = 2*u*ex+2*v*ey+(u**3+v**3/2)*ez
    MF = Manifold(X,mfvar,I=MV.i)

    (eu,ev) = MF.Basis()

    g = (v+1)*log(u)
    dg = MF.Grad(g)
    print 'g =',g
    print 'dg =',dg
    print '\\eval{dg}{u=1,v=0} =',dg.subs({u:1,v:0})
    G = u*eu+v*ev
    dG = MF.Grad(G)
    print 'G =',G
    print 'P(G) =',MF.Proj(G)
    print 'dG =',dG
    print 'P(dG) =',MF.Proj(dG)
    PS = u*v*eu^ev
    print 'P(S) =',PS
    print 'dP(S) =',MF.Grad(PS)
    print 'P(dP(S)) =',MF.Proj(MF.Grad(PS))
    return
Example #20
0
def test_fraction():
    x, y, z = map(Symbol, 'xyz')
    A = Symbol('A', commutative=False)

    assert fraction(Rational(1, 2)) == (1, 2)

    assert fraction(x) == (x, 1)
    assert fraction(1/x) == (1, x)
    assert fraction(x/y) == (x, y)
    assert fraction(x/2) == (x, 2)

    assert fraction(x*y/z) == (x*y, z)
    assert fraction(x/(y*z)) == (x, y*z)

    assert fraction(1/y**2) == (1, y**2)
    assert fraction(x/y**2) == (x, y**2)

    assert fraction((x**2 + 1)/y) == (x**2 + 1, y)
    assert fraction(x*(y + 1)/y**7) == (x*(y + 1), y**7)

    assert fraction(exp(-x), exact=True) == (exp(-x), 1)
    assert fraction((1/(x + y))/2, exact=True) == (1, Mul(2,(x + y), evaluate=False))

    assert fraction(x*A/y) == (x*A, y)
    assert fraction(x*A**-1/y) == (x*A**-1, y)

    n = symbols('n', negative=True)
    assert fraction(exp(n)) == (1, exp(-n))
    assert fraction(exp(-n)) == (exp(-n), 1)

    p = symbols('p', positive=True)
    assert fraction(exp(-p)*log(p), exact=True) == (exp(-p)*log(p), 1)
Example #21
0
def test_mellin_transform_fail():
    skip("Risch takes forever.")

    from sympy import Max, Min
    MT = mellin_transform

    bpos = symbols('b', positive=True)
    bneg = symbols('b', negative=True)

    expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
    # TODO does not work with bneg, argument wrong. Needs changes to matching.
    assert MT(expr.subs(b, -bpos), x, s) == \
        ((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s)
         *gamma(1 - a - 2*s)/gamma(1 - s),
            (-re(a), -re(a)/2 + S(1)/2), True)

    expr = (sqrt(x + b**2) + b)**a
    assert MT(expr.subs(b, -bpos), x, s) == \
        (
            2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2*
                   s)*gamma(a + s)/gamma(-s + 1),
            (-re(a), -re(a)/2), True)

    # Test exponent 1:
    assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \
        (-bpos**(2*s + 1)*gamma(s)*gamma(-s - S(1)/2)/(2*sqrt(pi)),
            (-1, -S(1)/2), True)
Example #22
0
def test_take():
    X = numbered_symbols()

    assert take(X, 5) == list(symbols('x0:5'))
    assert take(X, 5) == list(symbols('x5:10'))

    assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
Example #23
0
def test_order_could_be_zero():
    x, y = symbols('x, y')
    n = symbols('n', integer=True, nonnegative=True)
    m = symbols('m', integer=True, positive=True)
    assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True))
    assert diff(y, (x, n + 1)) == S.Zero
    assert diff(y, (x, m)) == S.Zero
Example #24
0
def test_mul_noncommutative():
    x, y = symbols('x y')
    A, B = symbols('A B', commutative=False)
    u, v = symbols('u v', cls=Wild)
    w = Wild('w', commutative=False)

    assert (u*v).matches(x) in ({v: x, u: 1}, {u: x, v: 1})
    assert (u*v).matches(x*y) in ({v: y, u: x}, {u: y, v: x})
    assert (u*v).matches(A) is None
    assert (u*v).matches(A*B) is None
    assert (u*v).matches(x*A) is None
    assert (u*v).matches(x*y*A) is None
    assert (u*v).matches(x*A*B) is None
    assert (u*v).matches(x*y*A*B) is None

    assert (v*w).matches(x) is None
    assert (v*w).matches(x*y) is None
    assert (v*w).matches(A) == {w: A, v: 1}
    assert (v*w).matches(A*B) == {w: A*B, v: 1}
    assert (v*w).matches(x*A) == {w: A, v: x}
    assert (v*w).matches(x*y*A) == {w: A, v: x*y}
    assert (v*w).matches(x*A*B) == {w: A*B, v: x}
    assert (v*w).matches(x*y*A*B) == {w: A*B, v: x*y}

    assert (v*w).matches(-x) is None
    assert (v*w).matches(-x*y) is None
    assert (v*w).matches(-A) == {w: A, v: -1}
    assert (v*w).matches(-A*B) == {w: A*B, v: -1}
    assert (v*w).matches(-x*A) == {w: A, v: -x}
    assert (v*w).matches(-x*y*A) == {w: A, v: -x*y}
    assert (v*w).matches(-x*A*B) == {w: A*B, v: -x}
    assert (v*w).matches(-x*y*A*B) == {w: A*B, v: -x*y}
Example #25
0
def test_symarray():
    """Test creation of numpy arrays of sympy symbols."""

    import numpy as np
    import numpy.testing as npt
    
    syms = symbols('_0 _1 _2')
    s1 = symarray(3)
    s2 = symarray(3)
    npt.assert_array_equal (s1, np.array(syms, dtype=object))
    assert s1[0] is s2[0]
    
    a = symarray(3, 'a')
    b = symarray(3, 'b')
    assert not(a[0] is b[0])

    asyms = symbols('a_0 a_1 a_2')
    npt.assert_array_equal (a, np.array(asyms, dtype=object))

    # Multidimensional checks
    a2d = symarray((2,3), 'a')
    assert a2d.shape == (2,3)
    a00, a12 = symbols('a_0_0, a_1_2')
    assert a2d[0,0] is a00
    assert a2d[1,2] is a12

    a3d = symarray((2,3,2), 'a')
    assert a3d.shape == (2,3,2)
    a000, a120, a121 = symbols('a_0_0_0, a_1_2_0 a_1_2_1')
    assert a3d[0,0,0] is a000
    assert a3d[1,2,0] is a120
    assert a3d[1,2,1] is a121
Example #26
0
def test_pde_separate_mul():
    x, y, z, t = symbols("x,y,z,t")
    c = Symbol("C", real=True)
    Phi = Function("Phi")
    F, R, T, X, Y, Z, u = map(Function, "FRTXYZu")
    r, theta, z = symbols("r,theta,z")

    # Something simple :)
    eq = Eq(D(F(x, y, z), x) + D(F(x, y, z), y) + D(F(x, y, z), z))

    # Duplicate arguments in functions
    raises(ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), u(z, z)]))
    # Wrong number of arguments
    raises(ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), Y(y)]))
    # Wrong variables: [x, y] -> [x, z]
    raises(ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(t), Y(x, y)]))

    assert pde_separate_mul(eq, F(x, y, z), [Y(y), u(x, z)]) == [
        D(Y(y), y) / Y(y),
        -D(u(x, z), x) / u(x, z) - D(u(x, z), z) / u(x, z),
    ]
    assert pde_separate_mul(eq, F(x, y, z), [X(x), Y(y), Z(z)]) == [
        D(X(x), x) / X(x),
        -D(Z(z), z) / Z(z) - D(Y(y), y) / Y(y),
    ]

    # wave equation
    wave = Eq(D(u(x, t), t, t), c ** 2 * D(u(x, t), x, x))
    res = pde_separate_mul(wave, u(x, t), [X(x), T(t)])
    assert res == [D(X(x), x, x) / X(x), D(T(t), t, t) / (c ** 2 * T(t))]

    # Laplace equation in cylindrical coords
    eq = Eq(
        1 / r * D(Phi(r, theta, z), r)
        + D(Phi(r, theta, z), r, 2)
        + 1 / r ** 2 * D(Phi(r, theta, z), theta, 2)
        + D(Phi(r, theta, z), z, 2)
    )
    # Separate z
    res = pde_separate_mul(eq, Phi(r, theta, z), [Z(z), u(theta, r)])
    assert res == [
        D(Z(z), z, z) / Z(z),
        -D(u(theta, r), r, r) / u(theta, r)
        - D(u(theta, r), r) / (r * u(theta, r))
        - D(u(theta, r), theta, theta) / (r ** 2 * u(theta, r)),
    ]
    # Lets use the result to create a new equation...
    eq = Eq(res[1], c)
    # ...and separate theta...
    res = pde_separate_mul(eq, u(theta, r), [T(theta), R(r)])
    assert res == [
        D(T(theta), theta, theta) / T(theta),
        -r * D(R(r), r) / R(r) - r ** 2 * D(R(r), r, r) / R(r) - c * r ** 2,
    ]
    # ...or r...
    res = pde_separate_mul(eq, u(theta, r), [R(r), T(theta)])
    assert res == [
        r * D(R(r), r) / R(r) + r ** 2 * D(R(r), r, r) / R(r) + c * r ** 2,
        -D(T(theta), theta, theta) / T(theta),
    ]
Example #27
0
def test_as_numer_denom():
    assert oo.as_numer_denom() == (1, 0)
    assert (-oo).as_numer_denom() == (-1, 0)
    assert zoo.as_numer_denom() == (zoo, 1)
    assert (-zoo).as_numer_denom() == (zoo, 1)

    assert x.as_numer_denom() == (x, 1)
    assert (1/x).as_numer_denom() == (1, x)
    assert (x/y).as_numer_denom() == (x, y)
    assert (x/2).as_numer_denom() == (x, 2)
    assert (x*y/z).as_numer_denom() == (x*y, z)
    assert (x/(y*z)).as_numer_denom() == (x, y*z)
    assert Rational(1, 2).as_numer_denom() == (1, 2)
    assert (1/y**2).as_numer_denom() == (1, y**2)
    assert (x/y**2).as_numer_denom() == (x, y**2)
    assert ((x**2+1)/y).as_numer_denom() == (x**2+1, y)
    assert (x*(y+1)/y**7).as_numer_denom() == (x*(y+1), y**7)
    assert (x**-2).as_numer_denom() == (1, x**2)
    n = symbols('n', negative=True)
    assert (x**n).as_numer_denom() == (x**n, 1)
    assert sqrt(1/n).as_numer_denom() == (I, sqrt(-n))
    n = Symbol('0 or neg', nonpositive=True)
    assert ((x/n)**-S.Half).as_numer_denom() == (1, (x/n)**S.Half)

    A, B, C = symbols('A,B,C', commutative=False)

    assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1)
    assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x)
    assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1)
    assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x)
    assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1)
    assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x)
Example #28
0
def test_issue_9699():
    n, k = symbols('n k', real=True)
    x, y = symbols('x, y')
    assert combsimp((n + 1)*factorial(n)) == factorial(n + 1)
    assert combsimp((x + 1)*factorial(x)/gamma(y)) == gamma(x + 2)/gamma(y)
    assert combsimp(factorial(n)/n) == factorial(n - 1)
    assert combsimp(rf(x + n, k)*binomial(n, k)) == binomial(n, k)*gamma(k + n + x)/gamma(n + x)
Example #29
0
 def integra(self,A,l,momentum,mass):
     #returns regularized integral
     div=self.div_facets(alpha=A)
     #print(div)
     if len(div)==0:
         d=sympy.symbols("K"+str(A).replace(",","").replace(" ", "_").replace("]", "+e]"  ))
         return d
     result=0
     facet=div[-1]
     not_on_facet_index= where(self.lattice_points().dot(facet)>0)
     not_on_facet=self.lattice_points()[not_on_facet_index]
    # print(not_on_facet,len(not_on_facet))
    
     if facet.dot(A)==0:
        # print(facet[-1])
         e=(sympy.symbols("e")**(-1) )* (sympy.Rational(1,int(facet[-1])))
         
         
     else: e=facet.dot(A)**(-1)
     for x in not_on_facet:
         
         
         result= sympy.Add(result,(A[-1]+sympy.symbols("e"))*e*self.coef_of_cut(x[:-1],l,mass,momentum)*(int(facet.dot(x)))*(self.integra(A+x,l,momentum,mass)))
     
     return result
Example #30
0
 def gen_model(self):
     self.x = sympy.symbols(self.model['var'])
     self.p = sympy.symbols(self.model['par'])
     local_dict = {}
     for x in self.x: local_dict[x.name] = x
     for p in self.p: local_dict[p.name] = p
     self.ode = []
     for e in self.model['ode']:
         self.ode.append(sympy.parsing.sympy_parser.parse_expr(e, local_dict = local_dict))
     self.dim = len(self.ode)
     self.pv = []
     self.pc = []
     #cont = self.model['cont'].split(' ')
     cont = self.model['cont']
     self.npar = len(cont)
     for c in cont:
         for p in self.p:
             if p.name == c: 
                 self.pv.append(p)
                 break
     for p in self.p:
         if p.name not in cont: self.pc.append(p)
     self.pinit = {}
     self.xinit = {}
     for p in self.p:
         if p.name in self.model:
             self.pinit[p.name] = self.model[p.name]
         else:
             raise RuntimeError('Init value for parameter %s not set' % p.name)
     for x in self.x: self.xinit[x.name] = self.model.get(x.name, 0.0)
Example #31
0
def test_Function_subs():
    from sympy.abc import x, y
    f, g, h, i = symbols('f g h i', cls=Function)
    p = Piecewise((g(f(x, y)), x < -1), (g(x), x <= 1))
    assert p.subs(g, h) == Piecewise((h(f(x, y)), x < -1), (h(x), x <= 1))
    assert (f(y) + g(x)).subs({f: h, g: i}) == i(x) + h(y)
Example #32
0
def test_unit_propagate():
    A, B, C = symbols('A,B,C')
    assert unit_propagate([A | B], A) == []
    assert unit_propagate([A | B, ~A | C, ~C | B, A], A) == [C, ~C | B, A]
Example #33
0
def test_propKB_tolerant():
    """"tolerant to bad input"""
    kb = PropKB()
    A, B, C = symbols('A,B,C')
    assert kb.ask(B) is False
Example #34
0
def test_entails():
    A, B, C = symbols('A, B, C')
    assert entails(A, [A >> B, ~B]) is False
    assert entails(B, [Equivalent(A, B), A]) is True
    assert entails((A >> B) >> (~A >> ~B)) is False
    assert entails((A >> B) >> (~B >> ~A)) is True
Example #35
0
def test_literal():
    A, B = symbols('A,B')
    assert literal_symbol(True) is True
    assert literal_symbol(False) is False
    assert literal_symbol(A) is A
    assert literal_symbol(~A) is A
Example #36
0
def test_satisfiable():
    A, B, C = symbols('A,B,C')
    assert satisfiable(A & (A >> B) & ~B) is False
Example #37
0
def test_noncommutative_subs():
    x, y = symbols('x,y', commutative=False)
    assert (x * y * x).subs([(x, x * y), (y, x)],
                            simultaneous=True) == (x * y * x**2 * y)
from sympy import symbols, cos, sin, pi, simplify, sqrt, atan2
from sympy.matrices import Matrix

# Create joint variable symbols.
q1, q2, q3, q4, q5, q6, q7 = symbols('q1:8')
d1, d2, d3, d4, d5, d6, d7 = symbols('d1:8')
a0, a1, a2, a3, a4, a5, a6 = symbols('a0:7')
alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols('alpha0:7')

# Denavit-Hartenberg parameter values.
s = {
    alpha0: 0,
    a0: 0,
    d1: 0.75,
    alpha1: -pi / 2,
    a1: 0.35,
    d2: 0,
    q2: q2 - pi / 2,
    alpha2: 0,
    a2: 1.25,
    d3: 0,
    alpha3: -pi / 2,
    a3: -0.054,
    d4: 1.5,
    alpha4: pi / 2,
    a4: 0,
    d5: 0,
    alpha5: -pi / 2,
    a5: 0,
    d6: 0,
    alpha6: 0,
Example #39
0
    u(x=2\pi, y) &= u(x=0, y) \\
    g(x=2\pi, y) &= g(x=0, y)

We use a Tensorproductspace with Fourier expansions in the x-direction and a
composite Chebyshev or Legendre basis in the y-direction for ``u``, whereas a
regular Chebyshev or Legendre basis is used for ``g``. The equations are solved
coupled and implicit.

"""

import os
import numpy as np
from sympy import symbols, sin, cos
from shenfun import *

x, y, z = symbols("x,y,z", real=True)

#ue = (sin(2*x)*cos(3*y))*(1-x**2)
ue = (sin(4*x)*cos(5*y)*sin(4*z))*(1-z**2)
dux = ue.diff(x, 1)
duy = ue.diff(y, 1)
fe = ue.diff(x, 2) + ue.diff(y, 2) + ue.diff(z, 2)

N = (24, 24, 24)
K0 = FunctionSpace(N[0], 'Fourier', dtype='d')
K1 = FunctionSpace(N[1], 'Fourier', dtype='D')
SD = FunctionSpace(N[2], 'Legendre', bc=(0, 0))
ST = FunctionSpace(N[2], 'Legendre')

TD = TensorProductSpace(comm, (K0, K1, SD), axes=(2, 1, 0))
TT = TensorProductSpace(comm, (K0, K1, ST), axes=(2, 1, 0))
Example #40
0
def test_issue_5284():
    A, B = symbols('A B', commutative=False)
    assert (x * A).subs(x**2 * A, B) == x * A
    assert (A**2).subs(A**3, B) == A**2
    assert (A**6).subs(A**3, B) == B**2
Example #41
0
File: Ex9.12.py Project: zizai/pydy
Answer does not match text.
"""

from __future__ import division
from sympy import Dummy
from sympy import expand, symbols
from sympy.physics.mechanics import ReferenceFrame, Point
from sympy.physics.mechanics import dynamicsymbols
from util import msprint, partial_velocities
from util import generalized_active_forces, potential_energy


q1, q2, q3, q4, q5, q6 = q = dynamicsymbols('q1:7')
u1, u2, u3, u4, u5, u6 = u = dynamicsymbols('u1:7')
# L' is the natural length of the springs
a, k, L_prime = symbols('a k L\'', real=True, positive=True)

# reference frames
X = ReferenceFrame('X')
C = X.orientnew('C', 'body', [q4, q5, q6], 'xyz')

# define points
pO = Point('O') # point O is fixed in X
pC_star = pO.locatenew('C*', a*(q1*X.x + q2*X.y + q3*X.z))
# define points of the cube connected to springs
pC1 = pC_star.locatenew('C1', a*(C.x + C.y - C.z))
pC2 = pC_star.locatenew('C2', a*(C.y + C.z - C.x))
pC3 = pC_star.locatenew('C3', a*(C.z + C.x - C.y))
# define fixed spring points
pk1 = pO.locatenew('k1', L_prime * X.x + a*(X.x + X.y - X.z))
pk2 = pO.locatenew('k2', L_prime * X.y + a*(X.y + X.z - X.x))
from sympy import symbols, diff

x, y, t = symbols('x y t', real=True)
f = t*x - y
result = diff(f,t)
print(result)
# t

f2 = t + x - y
result2 = diff(f2,t)
print(result2)
# x
def SpinWeight_minus2_SphHarmonics(maximum_l=8,
                                   filename=os.path.join(
                                       "SpinWeight_minus2_SphHarmonics",
                                       "SpinWeight_minus2_SphHarmonics.h")):
    # Step 2: Defining the Goldberg function

    # Step 2.a: Declare SymPy symbols:
    th, ph = sp.symbols('th ph', real=True)
    m = sp.symbols('m', integer=True)

    # Step 2.b: Define the Goldberg formula for spin-weighted spherical harmonics
    #           (https://aip.scitation.org/doi/10.1063/1.1705135);
    #           referenced & described in Wikipedia Spin-weighted spherical harmonics article:
    #           https://en.wikipedia.org/w/index.php?title=Spin-weighted_spherical_harmonics&oldid=853425244
    def Y(s, l, m, th, ph, GenerateMathematicaCode=False):
        Sum = 0
        for r in range(l - s + 1):
            if GenerateMathematicaCode == True:
                # Mathematica needs expression to be in terms of cotangent, so that code validation below
                #    yields identity with existing Mathematica notebook on spin-weighted spherical harmonics.
                Sum += sp.binomial(l - s, r) * sp.binomial(
                    l + s, r + s - m) * (-1)**(l - r - s) * sp.exp(
                        sp.I * m * ph) * sp.cot(th / 2)**(2 * r + s - m)
            else:
                # SymPy C code generation cannot handle the cotangent function, so define cot(th/2) as 1/tan(th/2):
                Sum += sp.binomial(l - s, r) * sp.binomial(
                    l + s, r + s - m) * (-1)**(l - r - s) * sp.exp(
                        sp.I * m * ph) / sp.tan(th / 2)**(2 * r + s - m)

        return (-1)**m * sp.simplify(
            sp.sqrt(
                sp.factorial(l + m) * sp.factorial(l - m) * (2 * l + 1) /
                (4 * sp.pi * sp.factorial(l + s) * sp.factorial(l - s))) *
            sp.sin(th / 2)**(2 * l) * Sum)

    # Step 3: (DISABLED FOR NOW; PASSES TEST).
    #         Code Validation against Mathematica notebook:
    #         https://demonstrations.wolfram.com/versions/source.jsp?id=SpinWeightedSphericalHarmonics&version=0012

    # # For the l=0 case m=0, otherwise there is a divide-by-zero in the Y() function above.
    # print("FullSimplify[Y[-2, 0, 0, th, ph]-"+str(sp.mathematica_code(sp.simplify(Y(-2, 0, 0, th, ph,GenerateMathematicaCode=True))))+"] \n") # Agrees with Mathematica notebook for l = 0

    # # Check the other cases
    # for l in range(1,9): # Agrees with Mathematica notebook for  l = 1, 2, 4, 5, 6, 7, 8;
    #     print("FullSimplify[Y[-2, "+str(l)+", m, th, ph]-("+
    #           str(sp.mathematica_code(sp.simplify(Y(-2, l, m, th, ph, GenerateMathematicaCode=True)))).replace("binomial","Binomial").replace("factorial","Factorial")+")] \n")

    # Step 4: Generating C Code function for computing
    #         s=-2 spin-weighted spherical harmonics,
    #         using NRPy+'s outputC() function.

    outCparams = "preindent=3,outCfileaccess=a,outCverbose=False,includebraces=True"

    with open(filename, "w") as file:
        file.write("""
void SpinWeight_minus2_SphHarmonics(const int l, const int m, const REAL th, const REAL ph,
                                   REAL *reYlmswm2_l_m, REAL *imYlmswm2_l_m) {
if(l<0 || l>""" + str(maximum_l) + """ || m<-l || m>+l) {
    printf("ERROR: SpinWeight_minus2_SphHarmonics handles only l=[0,""" +
                   str(maximum_l) + """] and only m=[-l,+l] is defined.\\n");
    printf("       You chose l=%d and m=%d, which is out of these bounds.\\n",l,m);
    exit(1);
}\n""")

        file.write("switch(l) {\n")
        for l in range(maximum_l +
                       1):  # Output values up to and including l=8.
            file.write("    case " + str(l) + ":\n")
            file.write("        switch(m) {\n")
            for m in range(-l, l + 1):
                file.write("            case " + str(m) + ":\n")
                Y_m2_lm = Y(-2, l, m, th, ph)
                Cstring = outputC(
                    [sp.re(Y_m2_lm), sp.im(Y_m2_lm)],
                    ["*reYlmswm2_l_m", "*imYlmswm2_l_m"], "returnstring",
                    outCparams)
                file.write(Cstring)
                file.write("                  return;\n")
            file.write("        }  /* End switch(m) */\n")
        file.write("    } /* End switch(l) */\n")
        file.write("} /* End function SpinWeight_minus2_SphHarmonics() */\n")
def eval_function(f, x0):
    f = sympify_expr(f)
    x = symbols("x")

    return str(f.evalf(subs={x: x0}))
Example #45
0
def test_get_subNO():
    p, q, r = symbols('p,q,r')
    assert NO(F(p) * F(q) * F(r)).get_subNO(1) == NO(F(p) * F(r))
    assert NO(F(p) * F(q) * F(r)).get_subNO(0) == NO(F(q) * F(r))
    assert NO(F(p) * F(q) * F(r)).get_subNO(2) == NO(F(p) * F(q))
Example #46
0
 def test_to_equation(self):
     self.assertEqual(
         pybamm.Symbol("test").to_equation(), sympy.symbols("test"))
Example #47
0
def test_substitute_dummies_new_indices():
    i, j = symbols('i j', below_fermi=True, cls=Dummy)
    a, b = symbols('a b', above_fermi=True, cls=Dummy)
    p, q = symbols('p q', cls=Dummy)
    f = Function('f')
    assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0
Example #48
0
BE = A_e.series(p, 0, 4) - A.subs(theta, 1).series(p, 0, 4)
CN = A_e.series(p, 0, 4) - A.subs(theta, half).series(p, 0, 4)
FE
BE
CN

# Ratio of amplification factors
FE = 1 - (A.subs(theta, 0)/A_e).series(p, 0, 4)
BE = 1 - (A.subs(theta, 1)/A_e).series(p, 0, 4)
CN = 1 - (A.subs(theta, half)/A_e).series(p, 0, 4)
FE
BE
CN

print "Error in solution:"
n, a, dt, t, T = sym.symbols('n a dt t T')
u_e = sym.exp(-p*n)
u_n = A**n
error = u_e.series(p, 0, 4) - u_n.subs(theta, 0).series(p, 0, 4)
print error
FE = error
error = error.subs('n', 't/dt').subs(p, 'a*dt')
#error = error.extract_leading_order(dt)[0][0]  # as_leading_term is simpler
error = error.as_leading_term(dt)
print 'Global error at a point t:', error
# error = error.removeO()  # get rid of the O() term
error_L2 = sym.sqrt(sym.integrate(error**2, (t, 0, T)))
print 'L2 error:', sym.simplify(error_L2)
#error_error_L2 = error_L2.series(dt, 0, 3).as_leading_term(dt)  # series breaks down

Example #49
0
def test_substitute_dummies_without_dummies():
    i, j = symbols('i,j')
    assert substitute_dummies(att(i, j) + 2) == att(i, j) + 2
    assert substitute_dummies(att(i, j) + 1) == att(i, j) + 1
Example #50
0
def test_substitute_dummies_substitution_order():
    i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
    f = Function('f')
    from sympy.utilities.iterables import variations
    for permut in variations([i, j, k, l], 4):
        assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0
Example #51
0
def test_complex_apply():
    n, m = symbols("n,m")
    o = Bd(0) * B(0) * Bd(1) * B(0)
    e = apply_operators(o * BKet([n, m]))
    answer = sqrt(n) * sqrt(m + 1) * (-1 + n) * BKet([-1 + n, 1 + m])
    assert expand(e) == expand(answer)
Example #52
0
def test_substitute_dummies_SQ_operator():
    i, j = symbols('i j', cls=Dummy)
    assert substitute_dummies(
        att(i, j) * Fd(i) * F(j) - att(j, i) * Fd(j) * F(i)) == 0
Example #53
0
import numpy as np
from numpy import exp
from numpy import pi
from numpy import sqrt
from numpy import log
import numpy.testing as nut
import scipy.integrate as si
import mpmath as mp
import sympy as sp
import matplotlib.pylab as plt

# This file is only there to be able to see the source functions IXXP and IYYP once the propagation is over

x, xp, y, yp, dl = sp.symbols('x xp y yp dl')

#DEFINITION OF MATHEMATICAL OBJECTS
#Definition of the transformation matrices


def matrixFlightSymbolic(L):  # For a flight path of length
    return np.array([[1, -L, 0], [0, 1, 0], [0, 0, 1]])


def matrixMonoPlaneSymbolic(
        b, ThetaB):  # For a perfect flat crystal monochromator
    return np.array([[b, 0, 0], [0, 1 / b, (1 - 1 / b) * np.tan(ThetaB)],
                     [0, 0, 1]])


def matrixMonoBentSymbolic(
    b, Fc, ThetaB
Example #54
0
def test_number_operator():
    n = symbols("n")
    o = Bd(0) * B(0)
    e = apply_operators(o * BKet([n]))
    assert e == n * BKet([n])
xAxis = list(range(-128,129))
yAxis = list(range(-128,129))


# In[ ]:


#constants
maxSpeed = 100
#dic to store data
dic = {}
noPositive = 0

# In[24]:

Fc = sympy.symbols("Fc", real=True)
eq = sympy.Eq((Fc)**2, maxSpeed**2)
sol=sympy.solve(eq)
print(sol)

# In[77]:


Fa, Fb = sympy.symbols("Fa Fb", real=True)
Fx = 0
Fy = 128
eq1 = sympy.Eq((Fy-sqrt(3)*Fx)*Fb-(Fy+sqrt(3)*Fx)*Fa, 0)
eq2 = sympy.Eq(((sqrt(3)/2)*Fb+(sqrt(3)/2)*Fa)**2+(0.5*Fb-0.5*Fa)**2, 10000)
sol=sympy.solve([eq1, eq2])
if sol[0][Fa] >0 and sol[0][Fb]>0:
    print("yes")
Example #56
0
def test_basic_apply():
    n = symbols("n")
    e = B(0) * BKet([n])
    assert apply_operators(e) == sqrt(n) * BKet([n - 1])
    e = Bd(0) * BKet([n])
    assert apply_operators(e) == sqrt(n + 1) * BKet([n + 1])
def test_big_expr():
    f = Function('f')
    x = symbols('x')
    e1 = Dagger(
        AntiCommutator(
            Operator('A') + Operator('B'),
            Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3)) *
        TensorProduct(Jz**2,
                      Operator('A') + Operator('B'))) * (JzBra(1, 0) + JzBra(
                          1, 1)) * (JzKet(0, 0) + JzKet(1, -1))
    e2 = Commutator(Jz**2,
                    Operator('A') + Operator('B')) * AntiCommutator(
                        Dagger(Operator('C') * Operator('D')),
                        Operator('E').inv()**2) * Dagger(Commutator(Jz, J2))
    e3 = Wigner3j(1, 2, 3, 4, 5, 6) * TensorProduct(
        Commutator(
            Operator('A') + Dagger(Operator('B')),
            Operator('C') + Operator('D')), Jz - J2) * Dagger(
                OuterProduct(Dagger(JzBra(1, 1)), JzBra(
                    1, 0))) * TensorProduct(
                        JzKetCoupled(1, 1,
                                     (1, 1)) + JzKetCoupled(1, 0, (1, 1)),
                        JzKetCoupled(1, -1, (1, 1)))
    e4 = (ComplexSpace(1) * ComplexSpace(2) +
          FockSpace()**2) * (L2(Interval(0, oo)) + HilbertSpace())
    assert str(
        e1
    ) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)'
    ascii_str = \
"""\
                 /                                      3        \\                                 \n\
                 |/                                   +\\         |                                 \n\
    2  / +    +\\ <|                    /d            \\ |   +    +>                                 \n\
/J \\ x \\A  + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A  + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\
\\ z/             \\\\                    \\dx           / /         /                                 \
"""
    ucode_str = \
u("""\
                 ⎧                                      3        ⎫                                 \n\
                 ⎪⎛                                   †⎞         ⎪                                 \n\
    2  ⎛ †    †⎞ ⎨⎜                    ⎛d            ⎞ ⎟   †    †⎬                                 \n\
⎛J ⎞ ⨂ ⎝A  + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A  + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\
⎝ z⎠             ⎩⎝                    ⎝dx           ⎠ ⎠         ⎭                                 \
""")
    assert pretty(e1) == ascii_str
    assert upretty(e1) == ucode_str
    assert latex(e1) == \
        r'{J_z^{2}}\otimes \left({A^{\dagger} + B^{\dagger}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)^{\dagger}\right)^{3},A^{\dagger} + B^{\dagger}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)'
    sT(
        e1,
        "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))"
    )
    assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]'
    ascii_str = \
"""\
[    2      ] / -2  +  +\\ [ 2   ]\n\
[/J \\ ,A + B]*<E  ,D *C >*[J ,J ]\n\
[\\ z/       ] \\         / [    z]\
"""
    ucode_str = \
u("""\
⎡    2      ⎤ ⎧ -2  †  †⎫ ⎡ 2   ⎤\n\
⎢⎛J ⎞ ,A + B⎥⋅⎨E  ,D ⋅C ⎬⋅⎢J ,J ⎥\n\
⎣⎝ z⎠       ⎦ ⎩         ⎭ ⎣    z⎦\
""")
    assert pretty(e2) == ascii_str
    assert upretty(e2) == ucode_str
    assert latex(e2) == \
        r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dagger} C^{\dagger}\right\} \left[J^2,J_z\right]'
    sT(
        e2,
        "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))"
    )
    assert str(e3) == \
        "Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>"
    ascii_str = \
"""\
          [ +          ]  /   2     \\                                                                 \n\
/1  3  5\\*[B  + A,C + D]x |- J  + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\
|       |                 \\        z/                                                                 \n\
\\2  4  6/                                                                                             \
"""
    ucode_str = \
u("""\
          ⎡ †          ⎤  ⎛   2     ⎞                                                                 \n\
⎛1  3  5⎞⋅⎣B  + A,C + D⎦⨂ ⎜- J  + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\
⎜       ⎟                 ⎝        z⎠                                                                 \n\
⎝2  4  6⎠                                                                                             \
""")
    assert pretty(e3) == ascii_str
    assert upretty(e3) == ucode_str
    assert latex(e3) == \
        r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dagger} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}'
    sT(
        e3,
        "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))"
    )
    assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)'
    ascii_str = \
"""\
// 1    2\\    x2\\   / 2    \\\n\
\\\\C  x C / + F  / x \\L  + H/\
"""
    ucode_str = \
u("""\
⎛⎛ 1    2⎞    ⨂2⎞   ⎛ 2    ⎞\n\
⎝⎝C  ⨂ C ⎠ ⊕ F  ⎠ ⨂ ⎝L  ⊕ H⎠\
""")
    assert pretty(e4) == ascii_str
    assert upretty(e4) == ucode_str
    assert latex(e4) == \
        r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)'
    sT(
        e4,
        "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, false, true)),HilbertSpace())))"
    )
Example #58
0
#instalar matplotlib y seaborn
import sympy as syp
from sympy.plotting import plot
import seaborn as sns
sns.set()
sns.set_style("whitegrid", {'grid.linestyle': '--'})
x = syp.symbols('x')
p1 = syp.plot((x+7)*(x-5) , show=False)
p2 = syp.plot((x-5)**3, show=False)
#p2.xlim=-40,40
p1.append(p2[0])
p1.xlim=-40,40
p1.ylim=-40,40
p1.title='Hola'
#p1.autoscale=True
#p1.show()
p1.save('/home/yan/graph.svg')
def test_state():
    x = symbols('x')
    bra = Bra()
    ket = Ket()
    bra_tall = Bra(x / 2)
    ket_tall = Ket(x / 2)
    tbra = TimeDepBra()
    tket = TimeDepKet()
    assert str(bra) == '<psi|'
    assert pretty(bra) == '<psi|'
    assert upretty(bra) == u'⟨ψ❘'
    assert latex(bra) == r'{\left\langle \psi\right|}'
    sT(bra, "Bra(Symbol('psi'))")
    assert str(ket) == '|psi>'
    assert pretty(ket) == '|psi>'
    assert upretty(ket) == u'❘ψ⟩'
    assert latex(ket) == r'{\left|\psi\right\rangle }'
    sT(ket, "Ket(Symbol('psi'))")
    assert str(bra_tall) == '<x/2|'
    ascii_str = \
"""\
 / |\n\
/ x|\n\
\\ -|\n\
 \\2|\
"""
    ucode_str = \
u("""\
 ╱ │\n\
╱ x│\n\
╲ ─│\n\
 ╲2│\
""")
    assert pretty(bra_tall) == ascii_str
    assert upretty(bra_tall) == ucode_str
    assert latex(bra_tall) == r'{\left\langle \frac{x}{2}\right|}'
    sT(bra_tall, "Bra(Mul(Rational(1, 2), Symbol('x')))")
    assert str(ket_tall) == '|x/2>'
    ascii_str = \
"""\
| \\ \n\
|x \\\n\
|- /\n\
|2/ \
"""
    ucode_str = \
u("""\
│ ╲ \n\
│x ╲\n\
│─ ╱\n\
│2╱ \
""")
    assert pretty(ket_tall) == ascii_str
    assert upretty(ket_tall) == ucode_str
    assert latex(ket_tall) == r'{\left|\frac{x}{2}\right\rangle }'
    sT(ket_tall, "Ket(Mul(Rational(1, 2), Symbol('x')))")
    assert str(tbra) == '<psi;t|'
    assert pretty(tbra) == u'<psi;t|'
    assert upretty(tbra) == u'⟨ψ;t❘'
    assert latex(tbra) == r'{\left\langle \psi;t\right|}'
    sT(tbra, "TimeDepBra(Symbol('psi'),Symbol('t'))")
    assert str(tket) == '|psi;t>'
    assert pretty(tket) == '|psi;t>'
    assert upretty(tket) == u'❘ψ;t⟩'
    assert latex(tket) == r'{\left|\psi;t\right\rangle }'
    sT(tket, "TimeDepKet(Symbol('psi'),Symbol('t'))")
Example #60
0
import importlib
from sympy import symbols, sin
import numpy as np
from shenfun import inner, div, grad, TestFunction, TrialFunction, Basis, \
    Array, Function
try:
    import matplotlib.pyplot as plt
except ImportError:
    plt = None

# Collect basis from either Chebyshev or Legendre submodules
family = sys.argv[-1].lower() if len(sys.argv) == 2 else 'chebyshev'
shen = importlib.import_module('.'.join(('shenfun', family)))

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

# Size of discretization
N = 32

SD = Basis(N, family=family, bc='Neumann')
X = SD.mesh()
u = TrialFunction(SD)
v = TestFunction(SD)

# Get f on quad points
fj = Array(SD, buffer=fe)

# Compute right hand side of Poisson equation