示例#1
1
def test_n_link_pendulum_on_cart_higher_order():
    l0, m0 = symbols("l0 m0")
    l1, m1 = symbols("l1 m1")
    m2 = symbols("m2")
    g = symbols("g")
    q0, q1, q2 = dynamicsymbols("q0 q1 q2")
    u0, u1, u2 = dynamicsymbols("u0 u1 u2")
    F, T1 = dynamicsymbols("F T1")

    kane1 = models.n_link_pendulum_on_cart(2)
    massmatrix1 = Matrix([[m0 + m1 + m2, -l0*m1*cos(q1) - l0*m2*cos(q1),
                           -l1*m2*cos(q2)],
                          [-l0*m1*cos(q1) - l0*m2*cos(q1), l0**2*m1 + l0**2*m2,
                           l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2))],
                          [-l1*m2*cos(q2),
                           l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2)),
                           l1**2*m2]])
    forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) - l0*m2*u1**2*sin(q1) -
                        l1*m2*u2**2*sin(q2) + F],
                       [g*l0*m1*sin(q1) + g*l0*m2*sin(q1) -
                        l0*l1*m2*(sin(q1)*cos(q2) - sin(q2)*cos(q1))*u2**2],
                       [g*l1*m2*sin(q2) - l0*l1*m2*(-sin(q1)*cos(q2) +
                                                    sin(q2)*cos(q1))*u1**2]])
    assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3)
    assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0])
示例#2
0
def test_commutation():
    c = commutator(B(0), Bd(0))
    e = simplify(apply_operators(c*Ket([n])))
    assert e == Ket([n])
    c = commutator(B(0), B(1))
    e = simplify(apply_operators(c*Ket([n,m])))
    assert e == 0
示例#3
0
def calc(g):
    nm = 1
    for i, ae in enumerate(g.en):
        nm = nm * simplify(g.bn[i]) ** ae
    for i, ae in enumerate(g.ed):
        nm = nm / simplify(g.bd[i]) ** ae
    return [sstr(simplify(nm))]
示例#4
0
    def _check_orthogonality(equations):
        """
        Helper method for _connect_to_cartesian. It checks if
        set of transformation equations create orthogonal curvilinear
        coordinate system

        Parameters
        ==========

        equations : Lambda
            Lambda of transformation equations

        """

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

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

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

        if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)):
            return False
        else:
            if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 \
                and simplify(v3.dot(v1)) == 0:
                return True
            else:
                return False
示例#5
0
def test_factorial_simplify():
    # There are more tests in test_factorials.py. These are just to
    # ensure that simplify() calls factorial_simplify correctly
    from sympy.specfun.factorials import factorial
    x = Symbol('x')
    assert simplify(factorial(x)/x) == factorial(x - 1)
    assert simplify(factorial(factorial(x))) == factorial(factorial(x))
示例#6
0
def test_combsimp_gamma():
    from sympy.abc import x, y
    assert combsimp(gamma(x)) == gamma(x)
    assert combsimp(gamma(x+1)/x) == gamma(x)
    assert combsimp(gamma(x)/(x-1)) == gamma(x-1)
    assert combsimp(x*gamma(x)) == gamma(x + 1)
    assert combsimp((x+1)*gamma(x+1)) == gamma(x + 2)
    assert combsimp(gamma(x+y)*(x+y)) == gamma(x + y + 1)
    assert combsimp(x/gamma(x+1)) == 1/gamma(x)
    assert combsimp((x+1)**2/gamma(x+2)) == (x + 1)/gamma(x + 1)
    assert combsimp(x*gamma(x) + gamma(x+3)/(x+2)) == gamma(x+1) + gamma(x+2)

    assert combsimp(gamma(2*x)*x) == gamma(2*x + 1)/2
    assert combsimp(gamma(2*x)/(x - S(1)/2)) == 2*gamma(2*x - 1)

    assert combsimp(gamma(x)*gamma(1-x)) == pi/sin(pi*x)
    assert combsimp(gamma(x)*gamma(-x)) == -pi/(x*sin(pi*x))
    assert combsimp(1/gamma(x+3)/gamma(1-x)) == sin(pi*x)/(pi*x*(x+1)*(x+2))

    assert simplify(combsimp(gamma(x)*gamma(x+S(1)/2)*gamma(y)/gamma(x+y))) \
           == 2**(-2*x + 1)*sqrt(pi)*gamma(2*x)*gamma(y)/gamma(x + y)
    assert combsimp(1/gamma(x)/gamma(x-S(1)/3)/gamma(x+S(1)/3)) == \
           3**(3*x + S(1)/2)/(18*pi*gamma(3*x - 1))
    assert simplify(gamma(S(1)/2 + x/2)*gamma(1 + x/2)/gamma(1+x)/sqrt(pi)*2**x) \
           == 1
    assert combsimp(gamma(S(-1)/4)*gamma(S(-3)/4)) == 16*sqrt(2)*pi/3

    assert simplify(combsimp(gamma(2*x)/gamma(x))) == \
           2**(2*x - 1)*gamma(x + S(1)/2)/sqrt(pi)
示例#7
0
def test_atan2():
    assert atan2(0, 0) == S.NaN
    assert atan2(0, 1) == 0
    assert atan2(1, 1) == pi/4
    assert atan2(1, 0) == pi/2
    assert atan2(1, -1) == 3*pi/4
    assert atan2(0, -1) == pi
    assert atan2(-1, -1) == -3*pi/4
    assert atan2(-1, 0) == -pi/2
    assert atan2(-1, 1) == -pi/4

    u = Symbol("u", positive=True)
    assert atan2(0, u) == 0
    u = Symbol("u", negative=True)
    assert atan2(0, u) == pi

    assert atan2(y, oo) ==  0
    assert atan2(y, -oo)==  2*pi*Heaviside(re(y)) - pi

    assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
    assert atan2(y, x).rewrite(atan) == 2*atan(y/(x + sqrt(x**2 + y**2)))

    assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
    assert diff(atan2(y, x), y) == x/(x**2 + y**2)

    assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
    assert simplify(diff(atan2(y, x).rewrite(log), y)) ==  x/(x**2 + y**2)

    assert isinstance(atan2(2, 3*I).n(), atan2)
示例#8
0
def calculate(str_expr, return_float=False):
    """
    Evaluate a string STR_EXPR.
    if STR_EXPR is a mathematical expression, simplify it with sympy.simplify
    Otherwise, search WolframAlpha for answers
    """
    try:
        result = simplify(str_expr)
        return result
    except Exception:
        # use Wolfram Alpha
        
        payload = {'input': str_expr, 'appid': 'UAGAWR-3X6Y8W777Q'}
        r = requests.get('http://api.wolframalpha.com/v2/query', params=payload)

        soup = BeautifulSoup(r.content,"lxml")
        if soup.queryresult['success'] == 'true':
            pods = soup.queryresult.findAll('pod')
            assert len(pods) >= 2
            num_string =  pods[1].plaintext.string.split()[0]
            if return_float:
                return float(simplify(num_string.replace(u"\u00D7", '*')))
            else:
                return num_string
        else:
            return "I don't know the answer"
示例#9
0
def test_symbolic_twoport():
    circuit.default_toolkit = symbolic
    cir = SubCircuit()

    k = symbolic.kboltzmann
    var('R1 R0 C1 w T', real=True, positive=True)
    s = 1j*w

    cir['R0'] = R(1, gnd, r=R0)
    cir['R1'] = R(1, 2, r=R1)
#    cir['C1'] = C(2, gnd, c=C1)

    ## Add an AC source to verify that the source will not affect results
#    cir['IS'] = IS(1, gnd, iac=1) 

    ## Run symbolic 2-port analysis
    twoport_ana = TwoPortAnalysis(cir, Node('1'), gnd, Node('2'), gnd,
                                  noise = True, toolkit=symbolic,
                                  noise_outquantity = 'v')
    result = twoport_ana.solve(freqs=s, complexfreq=True)
    
    ABCD = Matrix(result['twoport'].A)
    ABCD.simplify()

    assert_array_equal(ABCD, np.array([[1 + 0*R1*C1*s, R1],
                                    [(1 + 0*R0*C1*s + 0*R1*C1*s) / R0,  (R0 + R1)/R0]]))

    assert_array_equal(simplify(result['Sin'] - (4*k*T/R0 + 4*R1*k*T/R0**2)), 0)
    assert_array_equal(simplify(result['Svn']), 4*k*T*R1)
示例#10
0
def get_solid_harmonics(shell, xyz):
    x, y, z = xyz
    theta = Symbol("theta", real=True)
    phi = Symbol("phi", real=True)
    r = Symbol("r", real=True)
    result = []
    for m in range(shell+1):
        if m > 0:
            part_plus = (Ylm(shell,m,theta,phi)*r**shell).expand()
            part_plus = part_plus.subs(exp(I*phi),(x+I*y)/sin(theta)/r)
            part_min = (Ylm(shell,-m,theta,phi)*r**shell).expand()
            part_min = part_min.subs(exp(-I*phi),(x-I*y)/sin(theta)/r)
            sym = simplify(((-1)**m*part_plus+part_min)/sqrt(2))
            sym = sym.subs(r*cos(theta),z)
            sym = sym.subs(r**2,x**2+y**2+z**2)
            sym = sym.subs(cos(theta)**2,1-sin(theta)**2)
            sym = simplify(sym)
            asym = simplify(((-1)**m*part_plus-part_min)/I/sqrt(2))
            asym = asym.subs(r*cos(theta),z)
            asym = asym.subs(r**2,x**2+y**2+z**2)
            asym = asym.subs(cos(theta)**2,1-sin(theta)**2)
            asym = simplify(asym)
            result.append(sym)
            result.append(asym)
        else:
            part = (Ylm(shell,0,theta,phi)*r**shell).expand()
            part = part.subs(r*cos(theta),z)
            part = part.subs(r**2,x**2+y**2+z**2)
            part = simplify(part)
            result.append(part)
    return result
def check_sign_algebraically(expr, param_names, species_id, initial_values):

    import sympy
    from sympy import Symbol

    # create variables for each param and species
    for parameter_name in param_names:
        exec("%s = Symbol('%s', positive=True)" % (parameter_name, parameter_name))

    # create variables for time and avogadro's constant: N_A
    exec("t = Symbol('t', positive=True)")
    exec("N_A = Symbol('N_A', positive=True)")

    exec("query_var = %s" % species_id)

    converted_rate_law = convert_rate_law(expr, output_type="sympy")
    if converted_rate_law == "piecewise":
        return "?"

    exec("rate = %s" % converted_rate_law)
    if sympy.simplify(rate.diff(query_var)).is_positive:
        return "monotonic_increasing"
    elif sympy.simplify(rate.diff(query_var)).is_negative:
        return "monotonic_decreasing"
    else:
        return "?"
示例#12
0
def test_gosper_sum_AeqB_part2():
    f2a = n**2*a**n
    f2b = (n - r/2)*binomial(r, n)
    f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x))

    g2a = -a*(a + 1)/(a - 1)**3 + a**(
        m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3
    g2b = (m - r)*binomial(r, m)/2
    ff = factorial(1 - x)*factorial(1 + x)
    g2c = 1/ff*(
        1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x))

    g = gosper_sum(f2a, (n, 0, m))
    assert g is not None and simplify(g - g2a) == 0
    g = gosper_sum(f2b, (n, 0, m))
    assert g is not None and simplify(g - g2b) == 0
    g = gosper_sum(f2c, (n, 1, m))
    assert g is not None and simplify(g - g2c) == 0

    # delete these lines and unXFAIL the nan test below when it passes
    f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b))
    g2d = 1/(factorial(a - 1)*factorial(
        b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m))
    assert simplify(
        sum(f2d.subs(n, i) for i in range(3)) - g2d.subs(m, 2)) == 0
示例#13
0
def test_gosper_sum_AeqB_part3():
    f3a = 1/n**4
    f3b = (6*n + 3)/(4*n**4 + 8*n**3 + 8*n**2 + 4*n + 3)
    f3c = 2**n*(n**2 - 2*n - 1)/(n**2*(n + 1)**2)
    f3d = n**2*4**n/((n + 1)*(n + 2))
    f3e = 2**n/(n + 1)
    f3f = 4*(n - 1)*(n**2 - 2*n - 1)/(n**2*(n + 1)**2*(n - 2)**2*(n - 3)**2)
    f3g = (n**4 - 14*n**2 - 24*n - 9)*2**n/(n**2*(n + 1)**2*(n + 2)**2*
           (n + 3)**2)

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

    g = gosper_sum(f3a, (n, 1, m))
    assert g is None
    g = gosper_sum(f3b, (n, 1, m))
    assert g is not None and simplify(g - g3b) == 0
    g = gosper_sum(f3c, (n, 1, m - 1))
    assert g is not None and simplify(g - g3c) == 0
    g = gosper_sum(f3d, (n, 1, m))
    assert g is not None and simplify(g - g3d) == 0
    g = gosper_sum(f3e, (n, 0, m - 1))
    assert g is None
    g = gosper_sum(f3f, (n, 4, m))
    assert g is not None and simplify(g - g3f) == 0
    g = gosper_sum(f3g, (n, 1, m))
    assert g is not None and simplify(g - g3g) == 0
示例#14
0
文件: test_line.py 项目: Lenqth/sympy
def test_equation():
    p1 = Point(0, 0)
    p2 = Point(1, 1)
    l1 = Line(p1, p2)
    l3 = Line(Point(x1, x1), Point(x1, 1 + x1))

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

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

    assert Line3D(Point(x1, x1, x1), Point(y1, y1, y1)
        ).equation() == (-x + y, -x + z)
    assert Line3D(Point(1, 2, 3), Point(2, 3, 4)
        ).equation() == (-x + y - 1, -x + z - 2)
    assert Line3D(Point(1, 2, 3), Point(1, 3, 4)
        ).equation() == (x - 1, -y + z - 1)
    assert Line3D(Point(1, 2, 3), Point(2, 2, 4)
        ).equation() == (y - 2, -x + z - 2)
    assert Line3D(Point(1, 2, 3), Point(2, 3, 3)
        ).equation() == (-x + y - 1, z - 3)
    assert Line3D(Point(1, 2, 3), Point(1, 2, 4)
        ).equation() == (x - 1, y - 2)
    assert Line3D(Point(1, 2, 3), Point(1, 3, 3)
        ).equation() == (x - 1, z - 3)
    assert Line3D(Point(1, 2, 3), Point(2, 2, 3)
        ).equation() == (y - 2, z - 3)
示例#15
0
def test_weibull():
    a, b = symbols('a b', positive=True)
    X = Weibull('x', a, b)

    assert simplify(E(X)) == simplify(a * gamma(1 + 1/b))
    assert simplify(variance(X)) == simplify(a**2 * gamma(1 + 2/b) - E(X)**2)
    assert simplify(skewness(X)) == (2*gamma(1 + 1/b)**3 - 3*gamma(1 + 1/b)*gamma(1 + 2/b) + gamma(1 + 3/b))/(-gamma(1 + 1/b)**2 + gamma(1 + 2/b))**(S(3)/2)
示例#16
0
def test_commutation():
    n, m = symbols("n,m", above_fermi=True)
    c = Commutator(B(0), Bd(0))
    assert c == 1
    c = Commutator(Bd(0), B(0))
    assert c == -1
    c = Commutator(B(n), Bd(0))
    assert c == KroneckerDelta(n, 0)
    c = Commutator(B(0), Bd(0))
    e = simplify(apply_operators(c*BKet([n])))
    assert e == BKet([n])
    c = Commutator(B(0), B(1))
    e = simplify(apply_operators(c*BKet([n, m])))
    assert e == 0

    c = Commutator(F(m), Fd(m))
    assert c == +1 - 2*NO(Fd(m)*F(m))
    c = Commutator(Fd(m), F(m))
    assert c == -1 + 2*NO(Fd(m)*F(m))

    C = Commutator
    X, Y, Z = symbols('X,Y,Z', commutative=False)
    assert C(C(X, Y), Z) != 0
    assert C(C(X, Z), Y) != 0
    assert C(Y, C(X, Z)) != 0

    i, j, k, l = symbols('i,j,k,l', below_fermi=True)
    a, b, c, d = symbols('a,b,c,d', above_fermi=True)
    p, q, r, s = symbols('p,q,r,s')
    D = KroneckerDelta

    assert C(Fd(a), F(i)) == -2*NO(F(i)*Fd(a))
    assert C(Fd(j), NO(Fd(a)*F(i))).doit(wicks=True) == -D(j, i)*Fd(a)
    assert C(Fd(a)*F(i), Fd(b)*F(j)).doit(wicks=True) == 0
示例#17
0
def interpolation(f, psi, points):
    """
    Given a function f(x), return the approximation to
    f(x) in the space V, spanned by psi, that interpolates
    f at the given points. Must have len(points) = len(psi)
    """
    N = len(psi) - 1
    A = sym.zeros((N+1, N+1))
    b = sym.zeros((N+1, 1))
    # Wrap psi and f in Python functions rather than expressions
    # so that we can evaluate psi at points[i] (alternative to subs?)
    x = sym.Symbol('x')
    psi = [sym.lambdify([x], psi[i]) for i in range(N+1)]
    f = sym.lambdify([x], f)
    print '...evaluating matrix...'
    for i in range(N+1):
        for j in range(N+1):
            print '(%d,%d)' % (i, j)
            A[i,j] = psi[j](points[i])
        b[i,0] = f(points[i])
    print
    print 'A:\n', A, '\nb:\n', b
    c = A.LUsolve(b)
    # c is a sympy Matrix object, turn to list
    c = [sym.simplify(c[i,0]) for i in range(c.shape[0])]
    print 'coeff:', c
    u = 0
    for i in range(len(psi)):
        u += c[i]*psi[i](x)
    # Alternative:
    # u = sum(c[i,0]*psi[i] for i in range(len(psi)))
    print 'approximation:', sym.simplify(u)
    return u, c
示例#18
0
def test_simplify_other():
    assert simplify(sin(x)**2 + cos(x)**2) == 1
    assert simplify(gamma(x + 1)/gamma(x)) == x
    assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x
    assert simplify(Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(1, x)
    nc = symbols('nc', commutative=False)
    assert simplify(x + x*nc) == x*(1 + nc)
示例#19
0
def check_param(x, y, a, t):
    """
    Check if there is a number modulo a such that x and y are both
    integers. If exist, then find a parametric representation for x and y.
    """
    k, m, n = symbols("k, m, n", Integer=True)
    p = Wild("p", exclude=[k])
    q = Wild("q", exclude=[k])
    ok = False

    for i in range(a):

        z_x = simplify(Subs(x, t, a*k + i).doit()).match(p*k + q)
        z_y = simplify(Subs(y, t, a*k + i).doit()).match(p*k + q)

        if (isinstance(z_x[p], Integer) and isinstance(z_x[q], Integer) and
            isinstance(z_y[p], Integer) and isinstance(z_y[q], Integer)):
            ok = True
            break

    if ok == True:

        x_param = x.match(p*t + q)
        y_param = y.match(p*t + q)
        eq = S(m -x_param[q])/x_param[p] - S(n - y_param[q])/y_param[p]

        lcm_denom, junk = Poly(eq).clear_denoms()
        eq = eq * lcm_denom

        return diop_solve(eq, t)[m], diop_solve(eq, t)[n]
    else:
        return (None, None)
示例#20
0
    def _check_orthogonality(self):
        """
        Helper method for _connect_to_cartesian. It checks if
        set of transformation equations create orthogonal curvilinear
        coordinate system

        Parameters
        ==========

        equations : tuple
            Tuple of transformation equations

        """

        eq = self._transformation_equations()

        v1 = Matrix([diff(eq[0], self.x), diff(eq[1], self.x), diff(eq[2], self.x)])
        v2 = Matrix([diff(eq[0], self.y), diff(eq[1], self.y), diff(eq[2], self.y)])
        v3 = Matrix([diff(eq[0], self.z), diff(eq[1], self.z), diff(eq[2], self.z)])

        if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)):
            return False
        else:
            if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 and simplify(v3.dot(v1)) == 0:
                return True
            else:
                return False
示例#21
0
def test_M23():
    x = symbols('x', complex=True)

    assert solve(x - 1/sqrt(1 + x**2)) == [
        simplify(-I*sqrt((sqrt(5) + 1)/2)),
        simplify(   sqrt((sqrt(5) - 1)/2)),
    ]
示例#22
0
    def __pow__(self, e, z=None):
        """
        Perform multinomial expansion and return terms of order less than
        `self.order`.
        """
        data = {}
        exps,coeffs = zip(*(self.d.items()))
        m = len(exps)

        print "EXPONENT:",e

        multinoms = sympy.multinomial.multinomial_coefficients_iterator(m,int(e))
        for k,mcoeff in multinoms:
            exp = sum( expi*ki for expi,ki in zip(exps,k) )
            
            if exp < self.order:
                try:
                    coeff = sympy.simplify(
                        mcoeff * sympy.prod(ci**ki for ci,ki in zip(coeffs,k))
                        ) 
                    coeff = sympy.simplify(coeff + data[exp])                
                except KeyError:
                    data[exp] = coeff
            
        return PuiseuxSeries(data, self.alpha, self.order, self.var)
示例#23
0
def reciprocal_frame_test():
    Print_Function()

    metric = "1 # #," + "# 1 #," + "# # 1,"

    (e1, e2, e3) = MV.setup("e1 e2 e3", metric)

    print("g_{ij} =\n", MV.metric)

    E = e1 ^ e2 ^ e3
    Esq = (E * E).scalar()
    print("E =", E)
    print("E**2 =", Esq)
    Esq_inv = 1 / Esq

    E1 = (e2 ^ e3) * E
    E2 = (-1) * (e1 ^ e3) * E
    E3 = (e1 ^ e2) * E

    print("E1 = (e2^e3)*E =", E1)
    print("E2 =-(e1^e3)*E =", E2)
    print("E3 = (e1^e2)*E =", E3)

    w = E1 | e2
    w = w.expand()
    print("E1|e2 =", w)

    w = E1 | e3
    w = w.expand()
    print("E1|e3 =", w)

    w = E2 | e1
    w = w.expand()
    print("E2|e1 =", w)

    w = E2 | e3
    w = w.expand()
    print("E2|e3 =", w)

    w = E3 | e1
    w = w.expand()
    print("E3|e1 =", w)

    w = E3 | e2
    w = w.expand()
    print("E3|e2 =", w)

    w = E1 | e1
    w = (w.expand()).scalar()
    Esq = expand(Esq)
    print("(E1|e1)/E**2 =", simplify(w / Esq))

    w = E2 | e2
    w = (w.expand()).scalar()
    print("(E2|e2)/E**2 =", simplify(w / Esq))

    w = E3 | e3
    w = (w.expand()).scalar()
    print("(E3|e3)/E**2 =", simplify(w / Esq))
    return
示例#24
0
def test_medium():
    m1 = Medium('m1')
    assert m1.intrinsic_impedance == sqrt(u0/e0)
    assert m1.speed == 1/sqrt(e0*u0)
    assert m1.refractive_index == c*sqrt(e0*u0)
    assert m1.permittivity == e0
    assert m1.permeability == u0
    m2 = Medium('m2', epsilon, mu)
    assert m2.intrinsic_impedance == sqrt(mu/epsilon)
    assert m2.speed == 1/sqrt(epsilon*mu)
    assert m2.refractive_index == c*sqrt(epsilon*mu)
    assert m2.permittivity == epsilon
    assert m2.permeability == mu
    # Increasing electric permittivity and magnetic permeability
    # by small amount from its value in vacuum.
    m3 = Medium('m3', 9.0*10**(-12)*s**4*A**2/(m**3*kg), 1.45*10**(-6)*kg*m/(A**2*s**2))
    assert m3.refractive_index > m1.refractive_index
    assert m3 > m1
    # Decreasing electric permittivity and magnetic permeability
    # by small amount from its value in vacuum.
    m4 = Medium('m4', 7.0*10**(-12)*s**4*A**2/(m**3*kg), 1.15*10**(-6)*kg*m/(A**2*s**2))
    assert m4.refractive_index < m1.refractive_index
    assert m4 < m1
    m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
    assert simplify(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) == 0
    assert abs(m5.speed - 225407863.157895*m/s) < 1e-6*m/s
    assert simplify(m5.refractive_index - 1.33000000000000) == 0
    assert simplify(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) == 0
    assert simplify(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) == 0
    def get_S(self, theta=0., strain_type="Engineering"):
        """
        Calculates the compliance matrix for the ply oriented at angle theta
        in the specified strain units
        Parameters
        ----------
        theta : 'Int' or 'Float'
            Angle in degrees of ply orientation.
        strain_type : 'String'
            Specifies 'Engineering' or 'Tensorial' strain.
        """

        if strain_type.lower().startswith('e'):
            strain_multiplier = 1
        else:
            strain_multiplier = 2

        compliance = sp.Matrix([[1 / self.E11, -self.v21 / self.E22, 0],
                               [-self.v12 / self.E11, 1 / self.E22, 0],
                               [0, 0, 1 / (strain_multiplier * self.G12)]])

        if theta == 0.:
            return compliance
        else:
            T = T_Matrix(theta)
            if strain_type.lower().startswith('e'):
                R = R_Matrix()
                TI = sp.simplify(R * T.inv() * R.inv())
            else:
                TI = T.inv()
            return sp.simplify(sp.N(TI * compliance * T, chop=1e-10))
示例#26
0
def test_nullor_vva():
    """Test nullor element by building a V-V amplifier"""
    pycircuit.circuit.circuit.default_toolkit = symbolic

    c = SubCircuit()

    Vin = Symbol('Vin')
    R1 =Symbol('R1')
    R2 = Symbol('R2')
    
    nin = c.add_node('in')
    n1 = c.add_node('n1')
    nout = c.add_node('out')
     
    c['vin'] = VS(nin, gnd, vac=Vin)
    c['R1'] = R(n1, gnd, r=R1)
    c['R2'] = R(nout, n1, r=R2)
    c['nullor'] = Nullor(n1, nin, gnd, nout)
    
    result = AC(c, toolkit=symbolic).solve(Symbol('s'))
    
    vout = result.v(nout)

    assert simplify(vout - Vin * (R1 + R2) / R1) == 0, \
        'Did not get the expected result, %s != 0'% \
        str(simplify(vout - Vin * (R1 + R2) / R1))
示例#27
0
def test_SVCVS_laplace_d3_n1():
    """Test VCCS with a laplace defined transfer function with second order
    numerator and third order denominator
    """

    pycircuit.circuit.circuit.default_toolkit = symbolic
    cir = SubCircuit()

    n1,n2 = cir.add_nodes('1','2')

    b0,a0,a1,a2,a3,Gdc = [sympy.Symbol(symname, real=True) for
                                symname in 'b0,a0,a1,a2,a3,Gdc'
                                .split(',')]

    s = sympy.Symbol('s', complex=True)

    cir['VS']   = VS( n1, gnd, vac=1)
    cir['VCVS'] = SVCVS( n1, gnd, n2, gnd,
                        denominator = [a0, a1, a2, a3],
                        numerator   = [b0, 0, 0])

    res = AC(cir, toolkit=symbolic).solve(s, complexfreq=True)

    assert_equal(sympy.simplify(res.v(n2,gnd)),
                 sympy.simplify((b0*s*s)/(a0*s*s*s+a1*s*s+a2*s+a3)))
示例#28
0
def hamiltonian(Lagrangian, t = Symbol('t'), delta = False):
    """
    Returns the Hamiltonian of the Lagrangian.

    Examples
    ========

    >>> from sympy import *
    >>> t, k = symbols('t k')
    >>> x = symbols('x', cls=Function)
    >>> hamiltonian(diff(x(t),t)**2/2 - k*x(t)**2/2)
    k*x**2/2 + v_x**2/2
    """
    Lagrangian = simplify(Lagrangian)
    var_list = [list(x.atoms(Function))[0] for x in Lagrangian.atoms(Derivative)]
    nvar = len(var_list)
    # New variables.
    str_list = [ str(variable).replace("("+str(t)+")","") for variable in var_list ]
    v_subs = {diff(var_list[i],t): Symbol('v_' + str_list[i]) for i in range(nvar)}
    x_subs = {var_list[i]: Symbol(str_list[i]) for i in range(nvar)}
    # Hamiltonian calculus.
    dxdLv = 0
    for variable in var_list:
        dxdLv += diff(variable,t)*diff(Lagrangian, diff(variable,t))
    result = simplify((dxdLv - Lagrangian).subs(v_subs).subs(x_subs))
    if delta:
        v0_subs = {Symbol('v_' + str_list[i]): Symbol('v_' + str_list[i] + "0") for i in range(nvar)}
        x0_subs = {Symbol(str_list[i]): Symbol(str_list[i] + "0") for i in range(nvar)}
        return result - result.subs(v0_subs).subs(x0_subs)
    else:
        return result
    def calculate_eigenvalues(self):
        r"""Calculate the two eigenvalues :math:`\lambda_i(x)` of the potential :math:`V(x)`.
        We can do this by symbolic calculations. The multiplicities are taken into account.
        Note: This function is idempotent and the eigenvalues are memoized for later reuse.
        """
        if self._eigenvalues_s is not None:
            return

        # Symbolic formula for the eigenvalues of a general 2x2 matrix
        T = self._potential_s.trace()
        D = self._potential_s.det()

        l1 = (T + sympy.sqrt(T**2 - 4*D)) * sympy.Rational(1,2)
        l2 = (T - sympy.sqrt(T**2 - 4*D)) * sympy.Rational(1,2)

        # Symbolic simplification may fail
        if self._try_simplify:
            try:
                l1 = sympy.simplify(l1)
                l2 = sympy.simplify(l2)
            except:
                pass

        # The symbolic expressions for the eigenvalues
        self._eigenvalues_s = (l1, l2)

        # The numerical functions for the eigenvalues
        self._eigenvalues_n = tuple([ sympy.lambdify(self._variables, item, "numpy") for item in self._eigenvalues_s ])
示例#30
0
def test_form_2():
    symsystem2 = SymbolicSystem(coordinates, comb_implicit_rhs, speeds=speeds,
                                mass_matrix=comb_implicit_mat,
                                alg_con=alg_con_full, output_eqns=out_eqns,
                                bodies=bodies, loads=loads)

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

    assert symsystem2.alg_con == [4]

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

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

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


    assert symsystem2.output_eqns == out_eqns

    assert symsystem2.bodies == (Pa,)
    assert symsystem2.loads == ((P, g * m * N.x),)
示例#31
0
def test_simplify_rational():
    expr = 2**x * 2.**y
    assert simplify(expr, rational=True) == 2**(x + y)
    assert simplify(expr, rational=None) == 2.0**(x + y)
    assert simplify(expr, rational=False) == expr
示例#32
0
def test_simplify_float_vs_integer():
    # Test for issue 4473:
    # https://github.com/sympy/sympy/issues/4473
    assert simplify(x**2.0 - x**2) == 0
    assert simplify(x**2 - x**2.0) == 0
示例#33
0
def test_issue_4194():
    # simplify should call cancel
    from sympy.abc import x, y
    f = Function('f')
    assert simplify((4 * x + 6 * f(y)) / (2 * x + 3 * f(y))) == 2
示例#34
0
def test_simplify_expr():
    x, y, z, k, n, m, w, f, s, A = symbols('x,y,z,k,n,m,w,f,s,A')

    assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I])

    e = 1 / x + 1 / y
    assert e != (x + y) / (x * y)
    assert simplify(e) == (x + y) / (x * y)

    e = A**2 * s**4 / (4 * pi * k * m**3)
    assert simplify(e) == e

    e = (4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)
    assert simplify(e) == 0

    e = (-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2
    assert simplify(e) == -2 * y

    e = -x - y - (x + y)**(-1) * y**2 + (x + y)**(-1) * x**2
    assert simplify(e) == -2 * y

    e = (x + x * y) / x
    assert simplify(e) == 1 + y

    e = (f(x) + y * f(x)) / f(x)
    assert simplify(e) == 1 + y

    e = (2 * (1 / n - cos(n * pi) / n)) / pi
    assert simplify(e) == (-cos(pi * n) + 1) / (pi * n) * 2

    e = integrate(1 / (x**3 + 1), x).diff(x)
    assert simplify(e) == 1 / (x**3 + 1)

    e = integrate(x / (x**2 + 3 * x + 1), x).diff(x)
    assert simplify(e) == x / (x**2 + 3 * x + 1)

    A = Matrix([[2 * k - m * w**2, -k], [-k, k - m * w**2]]).inv()
    assert simplify((A*Matrix([0, f]))[1]) == \
        -f*(2*k - m*w**2)/(k**2 - (k - m*w**2)*(2*k - m*w**2))

    f = -x + y / (z + t) + z * x / (z + t) + z * a / (z + t) + t * x / (z + t)
    assert simplify(f) == (y + a * z) / (z + t)

    # issue 10347
    expr = -x * (y**2 - 1) * (
        2 * y**2 * (x**2 - 1) / (a * (x**2 - y**2)**2) + (x**2 - 1) /
        (a * (x**2 - y**2))) / (a * (x**2 - y**2)) + x * (
            -2 * x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
            (a * (x**2 - y**2)**2) -
            x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
            (a * (x**2 - 1) * (x**2 - y**2)) +
            (x**2 * sqrt((-x**2 + 1) * (y**2 - 1)) *
             sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) / (x**2 - 1) + sqrt(
                 (-x**2 + 1) * (y**2 - 1)) *
             (x * (-x * y**2 + x) / sqrt(-x**2 * y**2 + x**2 + y**2 - 1) +
              sqrt(-x**2 * y**2 + x**2 + y**2 - 1)) * sin(z)) / (a * sqrt(
                  (-x**2 + 1) * (y**2 - 1)) * (x**2 - y**2))
        ) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) / (
            a * (x**2 - y**2)) + x * (
                -2 * x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                (a * (x**2 - y**2)**2) -
                x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                (a * (x**2 - 1) * (x**2 - y**2)) +
                (x**2 * sqrt((-x**2 + 1) *
                             (y**2 - 1)) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1)
                 * cos(z) / (x**2 - 1) + x * sqrt(
                     (-x**2 + 1) * (y**2 - 1)) * (-x * y**2 + x) * cos(z) /
                 sqrt(-x**2 * y**2 + x**2 + y**2 - 1) + sqrt(
                     (-x**2 + 1) *
                     (y**2 - 1)) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) *
                 cos(z)) / (a * sqrt((-x**2 + 1) * (y**2 - 1)) * (x**2 - y**2))
            ) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) / (
                a *
                (x**2 - y**2)) - y * sqrt((-x**2 + 1) * (y**2 - 1)) * (
                    -x * y * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
                    (a * (x**2 - y**2) *
                     (y**2 - 1)) +
                    2 * x * y * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
                    (a * (x**2 - y**2)**2) +
                    (x * y * sqrt((-x**2 + 1) * (y**2 - 1)) *
                     sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
                     (y**2 - 1) + x * sqrt(
                         (-x**2 + 1) * (y**2 - 1)) * (-x**2 * y + y) * sin(z) /
                     sqrt(-x**2 * y**2 + x**2 + y**2 - 1)) / (a * sqrt(
                         (-x**2 + 1) * (y**2 - 1)) * (x**2 - y**2))
                ) * sin(z) / (a * (x**2 - y**2)) + y * (x**2 - 1) * (
                    -2 * x * y *
                    (x**2 - 1) /
                    (a * (x**2 - y**2)**2) + 2 * x * y / (a * (x**2 - y**2))
                ) / (a *
                     (x**2 - y**2)) + y * (x**2 - 1) * (y**2 - 1) * (
                         -x * y * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) *
                         cos(z) / (a * (x**2 - y**2) *
                                   (y**2 - 1)) + 2 * x * y *
                         sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                         (a *
                          (x**2 - y**2)**2) +
                         (x * y * sqrt((-x**2 + 1) * (y**2 - 1)) *
                          sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                          (y**2 - 1) + x * sqrt(
                              (-x**2 + 1) * (y**2 - 1)) * (-x**2 * y + y) *
                          cos(z) / sqrt(-x**2 * y**2 + x**2 + y**2 - 1)) /
                         (a * sqrt((-x**2 + 1) * (y**2 - 1)) *
                          (x**2 - y**2))) * cos(z) / (a * sqrt(
                              (-x**2 + 1) *
                              (y**2 - 1)) * (x**2 - y**2)) - x * sqrt(
                                  (-x**2 + 1) * (y**2 - 1)
                              ) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(
                                  z)**2 / (a**2 * (x**2 - 1) * (x**2 - y**2) *
                                           (y**2 - 1)) - x * sqrt(
                                               (-x**2 + 1) *
                                               (y**2 - 1)) * sqrt(
                                                   -x**2 * y**2 + x**2 + y**2 -
                                                   1) * cos(z)**2 / (
                                                       a**2 * (x**2 - 1) *
                                                       (x**2 - y**2) *
                                                       (y**2 - 1))
    assert simplify(expr) == 2 * x / (a**2 * (x**2 - y**2))

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

    assert simplify(A * B - B * A) == A * B - B * A
    assert simplify(A / (1 + y / x)) == x * A / (x + y)
    assert simplify(A * (1 / x + 1 / y)) == A / x + A / y  #(x + y)*A/(x*y)

    assert simplify(log(2) + log(3)) == log(6)
    assert simplify(log(2 * x) - log(2)) == log(x)

    assert simplify(hyper([], [], x)) == exp(x)
示例#35
0
def test_simplify_fail1():
    x = Symbol('x')
    y = Symbol('y')
    e = (x + y)**2 / (-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y)
    assert simplify(e) == 1 / (-2 * y)
示例#36
0
def test_issue_5652():
    assert simplify(E + exp(-E)) == exp(-E) + E
    n = symbols('n', commutative=False)
    assert simplify(n + n**(-n)) == n + n**(-n)
示例#37
0
def test_simplify_issue_1308():
    assert simplify(exp(-Rational(1, 2)) + exp(-Rational(3, 2))) == \
        (1 + E)*exp(-Rational(3, 2))
示例#38
0
def test_coordinate_vars():
    """
    Tests the coordinate variables functionality with respect to
    reorientation of coordinate systems.
    """
    A = CoordSys3D('A')
    # Note that the name given on the lhs is different from A.x._name
    assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}') == A.x
    assert BaseScalar('A.y', 1, A, 'A_y', r'\mathbf{{y}_{A}}') == A.y
    assert BaseScalar('A.z', 2, A, 'A_z', r'\mathbf{{z}_{A}}') == A.z
    assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}').__hash__() == A.x.__hash__()
    assert isinstance(A.x, BaseScalar) and \
           isinstance(A.y, BaseScalar) and \
           isinstance(A.z, BaseScalar)
    assert A.x*A.y == A.y*A.x
    assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z}
    assert A.x.system == A
    assert A.x.diff(A.x) == 1
    B = A.orient_new_axis('B', q, A.k)
    assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q),
                                 B.x: A.x*cos(q) + A.y*sin(q)}
    assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q),
                                 A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z}
    assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q)
    assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q)
    assert express(B.z, A, variables=True) == A.z
    assert expand(express(B.x*B.y*B.z, A, variables=True)) == \
           expand(A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q)))
    assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \
           (B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + \
           B.y*cos(q))*A.j + B.z*A.k
    assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, \
                            variables=True)) == \
           A.x*A.i + A.y*A.j + A.z*A.k
    assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \
           (A.x*cos(q) + A.y*sin(q))*B.i + \
           (-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k
    assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, \
                            variables=True)) == \
           B.x*B.i + B.y*B.j + B.z*B.k
    N = B.orient_new_axis('N', -q, B.k)
    assert N.scalar_map(A) == \
           {N.x: A.x, N.z: A.z, N.y: A.y}
    C = A.orient_new_axis('C', q, A.i + A.j + A.k)
    mapping = A.scalar_map(C)
    assert mapping[A.x].equals(C.x*(2*cos(q) + 1)/3 +
                            C.y*(-2*sin(q + pi/6) + 1)/3 +
                            C.z*(-2*cos(q + pi/3) + 1)/3)
    assert mapping[A.y].equals(C.x*(-2*cos(q + pi/3) + 1)/3 +
                            C.y*(2*cos(q) + 1)/3 +
                            C.z*(-2*sin(q + pi/6) + 1)/3)
    assert mapping[A.z].equals(C.x*(-2*sin(q + pi/6) + 1)/3 +
                            C.y*(-2*cos(q + pi/3) + 1)/3 +
                            C.z*(2*cos(q) + 1)/3)
    D = A.locate_new('D', a*A.i + b*A.j + c*A.k)
    assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b}
    E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k)
    assert A.scalar_map(E) == {A.z: E.z + c,
                               A.x: E.x*cos(a) - E.y*sin(a) + a,
                               A.y: E.x*sin(a) + E.y*cos(a) + b}
    assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a),
                               E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a),
                               E.z: A.z - c}
    F = A.locate_new('F', Vector.zero)
    assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y}
示例#39
0
def test_issue1893():
    from sympy import simplify, expand_func, polygamma, gamma
    a = Symbol('a', positive=True)
    assert simplify(expand_func(integrate(exp(-x)*log(x)*x**a, (x, 0, oo)))) == \
        (a*polygamma(0, a) + 1)*gamma(a)
示例#40
0
def test_issue_7263():
    assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \
            673.447451402970) < 1e-12
示例#41
0
def test_issue_1277():
    n = Symbol('n', integer=True, positive=True)
    assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) -
                (n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0
示例#42
0
def test_issue1388():
    from sympy import lowergamma, simplify
    assert simplify(integrate(exp(-x)*x**y, x)) == lowergamma(y + 1, x)
示例#43
0
def test_aux_dep():
    # This test is about rolling disc dynamics, comparing the results found
    # with KanesMethod to those found when deriving the equations "manually"
    # with SymPy.
    # The terms Fr, Fr*, and Fr*_steady are all compared between the two
    # methods. Here, Fr*_steady refers to the generalized inertia forces for an
    # equilibrium configuration.
    # Note: comparing to the test of test_rolling_disc() in test_kane.py, this
    # test also tests auxiliary speeds and configuration and motion constraints
    #, seen in  the generalized dependent coordinates q[3], and depend speeds
    # u[3], u[4] and u[5].


    # First, mannual derivation of Fr, Fr_star, Fr_star_steady.

    # Symbols for time and constant parameters.
    # Symbols for contact forces: Fx, Fy, Fz.
    t, r, m, g, I, J = symbols('t r m g I J')
    Fx, Fy, Fz = symbols('Fx Fy Fz')

    # Configuration variables and their time derivatives:
    # q[0] -- yaw
    # q[1] -- lean
    # q[2] -- spin
    # q[3] -- dot(-r*B.z, A.z) -- distance from ground plane to disc center in
    #         A.z direction
    # Generalized speeds and their time derivatives:
    # u[0] -- disc angular velocity component, disc fixed x direction
    # u[1] -- disc angular velocity component, disc fixed y direction
    # u[2] -- disc angular velocity component, disc fixed z direction
    # u[3] -- disc velocity component, A.x direction
    # u[4] -- disc velocity component, A.y direction
    # u[5] -- disc velocity component, A.z direction
    # Auxiliary generalized speeds:
    # ua[0] -- contact point auxiliary generalized speed, A.x direction
    # ua[1] -- contact point auxiliary generalized speed, A.y direction
    # ua[2] -- contact point auxiliary generalized speed, A.z direction
    q = dynamicsymbols('q:4')
    qd = [qi.diff(t) for qi in q]
    u = dynamicsymbols('u:6')
    ud = [ui.diff(t) for ui in u]
    ud_zero = dict(zip(ud, [0.]*len(ud)))
    ua = dynamicsymbols('ua:3')
    ua_zero = dict(zip(ua, [0.]*len(ua)))

    # Reference frames:
    # Yaw intermediate frame: A.
    # Lean intermediate frame: B.
    # Disc fixed frame: C.
    N = ReferenceFrame('N')
    A = N.orientnew('A', 'Axis', [q[0], N.z])
    B = A.orientnew('B', 'Axis', [q[1], A.x])
    C = B.orientnew('C', 'Axis', [q[2], B.y])

    # Angular velocity and angular acceleration of disc fixed frame
    # u[0], u[1] and u[2] are generalized independent speeds.
    C.set_ang_vel(N, u[0]*B.x + u[1]*B.y + u[2]*B.z)
    C.set_ang_acc(N, C.ang_vel_in(N).diff(t, B)
                   + cross(B.ang_vel_in(N), C.ang_vel_in(N)))

    # Velocity and acceleration of points:
    # Disc-ground contact point: P.
    # Center of disc: O, defined from point P with depend coordinate: q[3]
    # u[3], u[4] and u[5] are generalized dependent speeds.
    P = Point('P')
    P.set_vel(N, ua[0]*A.x + ua[1]*A.y + ua[2]*A.z)
    O = P.locatenew('O', q[3]*A.z + r*sin(q[1])*A.y)
    O.set_vel(N, u[3]*A.x + u[4]*A.y + u[5]*A.z)
    O.set_acc(N, O.vel(N).diff(t, A) + cross(A.ang_vel_in(N), O.vel(N)))

    # Kinematic differential equations:
    # Two equalities: one is w_c_n_qd = C.ang_vel_in(N) in three coordinates
    #                 directions of B, for qd0, qd1 and qd2.
    #                 the other is v_o_n_qd = O.vel(N) in A.z direction for qd3.
    # Then, solve for dq/dt's in terms of u's: qd_kd.
    w_c_n_qd = qd[0]*A.z + qd[1]*B.x + qd[2]*B.y
    v_o_n_qd = O.pos_from(P).diff(t, A) + cross(A.ang_vel_in(N), O.pos_from(P))
    kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] +
                      [dot(v_o_n_qd - O.vel(N), A.z)])
    qd_kd = solve(kindiffs, qd)

    # Values of generalized speeds during a steady turn for later substitution
    # into the Fr_star_steady.
    steady_conditions = solve(kindiffs.subs({qd[1] : 0, qd[3] : 0}), u)
    steady_conditions.update({qd[1] : 0, qd[3] : 0})

    # Partial angular velocities and velocities.
    partial_w_C = [C.ang_vel_in(N).diff(ui, N) for ui in u + ua]
    partial_v_O = [O.vel(N).diff(ui, N) for ui in u + ua]
    partial_v_P = [P.vel(N).diff(ui, N) for ui in u + ua]

    # Configuration constraint: f_c, the projection of radius r in A.z direction
    #                                is q[3].
    # Velocity constraints: f_v, for u3, u4 and u5.
    # Acceleration constraints: f_a.
    f_c = Matrix([dot(-r*B.z, A.z) - q[3]])
    f_v = Matrix([dot(O.vel(N) - (P.vel(N) + cross(C.ang_vel_in(N),
        O.pos_from(P))), ai).expand() for ai in A])
    v_o_n = cross(C.ang_vel_in(N), O.pos_from(P))
    a_o_n = v_o_n.diff(t, A) + cross(A.ang_vel_in(N), v_o_n)
    f_a = Matrix([dot(O.acc(N) - a_o_n, ai) for ai in A])

    # Solve for constraint equations in the form of
    #                           u_dependent = A_rs * [u_i; u_aux].
    # First, obtain constraint coefficient matrix:  M_v * [u; ua] = 0;
    # Second, taking u[0], u[1], u[2] as independent,
    #         taking u[3], u[4], u[5] as dependent,
    #         rearranging the matrix of M_v to be A_rs for u_dependent.
    # Third, u_aux ==0 for u_dep, and resulting dictionary of u_dep_dict.
    M_v = zeros(3, 9)
    for i in range(3):
        for j, ui in enumerate(u + ua):
            M_v[i, j] = f_v[i].diff(ui)

    M_v_i = M_v[:, :3]
    M_v_d = M_v[:, 3:6]
    M_v_aux = M_v[:, 6:]
    M_v_i_aux = M_v_i.row_join(M_v_aux)
    A_rs = - M_v_d.inv() * M_v_i_aux

    u_dep = A_rs[:, :3] * Matrix(u[:3])
    u_dep_dict = dict(zip(u[3:], u_dep))

    # Active forces: F_O acting on point O; F_P acting on point P.
    # Generalized active forces (unconstrained): Fr_u = F_point * pv_point.
    F_O = m*g*A.z
    F_P = Fx * A.x + Fy * A.y + Fz * A.z
    Fr_u = Matrix([dot(F_O, pv_o) + dot(F_P, pv_p) for pv_o, pv_p in
            zip(partial_v_O, partial_v_P)])

    # Inertia force: R_star_O.
    # Inertia of disc: I_C_O, where J is a inertia component about principal axis.
    # Inertia torque: T_star_C.
    # Generalized inertia forces (unconstrained): Fr_star_u.
    R_star_O = -m*O.acc(N)
    I_C_O = inertia(B, I, J, I)
    T_star_C = -(dot(I_C_O, C.ang_acc_in(N)) \
                 + cross(C.ang_vel_in(N), dot(I_C_O, C.ang_vel_in(N))))
    Fr_star_u = Matrix([dot(R_star_O, pv) + dot(T_star_C, pav) for pv, pav in
                        zip(partial_v_O, partial_w_C)])

    # Form nonholonomic Fr: Fr_c, and nonholonomic Fr_star: Fr_star_c.
    # Also, nonholonomic Fr_star in steady turning condition: Fr_star_steady.
    Fr_c = Fr_u[:3, :].col_join(Fr_u[6:, :]) + A_rs.T * Fr_u[3:6, :]
    Fr_star_c = Fr_star_u[:3, :].col_join(Fr_star_u[6:, :])\
                + A_rs.T * Fr_star_u[3:6, :]
    Fr_star_steady = Fr_star_c.subs(ud_zero).subs(u_dep_dict)\
            .subs(steady_conditions).subs({q[3]: -r*cos(q[1])}).expand()


    # Second, using KaneMethod in mechanics for fr, frstar and frstar_steady.

    # Rigid Bodies: disc, with inertia I_C_O.
    iner_tuple = (I_C_O, O)
    disc = RigidBody('disc', O, C, m, iner_tuple)
    bodyList = [disc]

    # Generalized forces: Gravity: F_o; Auxiliary forces: F_p.
    F_o = (O, F_O)
    F_p = (P, F_P)
    forceList = [F_o,  F_p]

    # KanesMethod.
    kane = KanesMethod(
        N, q_ind= q[:3], u_ind= u[:3], kd_eqs=kindiffs,
        q_dependent=q[3:], configuration_constraints = f_c,
        u_dependent=u[3:], velocity_constraints= f_v,
        u_auxiliary=ua
        )

    # fr, frstar, frstar_steady and kdd(kinematic differential equations).
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=SymPyDeprecationWarning)
        (fr, frstar)= kane.kanes_equations(forceList, bodyList)
    frstar_steady = frstar.subs(ud_zero).subs(u_dep_dict).subs(steady_conditions)\
                    .subs({q[3]: -r*cos(q[1])}).expand()
    kdd = kane.kindiffdict()

    assert Matrix(Fr_c).expand() == fr.expand()
    assert Matrix(Fr_star_c.subs(kdd)).expand() == frstar.expand()
    assert (simplify(Matrix(Fr_star_steady).expand()) ==
            simplify(frstar_steady.expand()))
示例#44
0
def test_issue1394():
    from sympy import simplify
    assert simplify(integrate(x*sqrt(1 + 2*x), x)) == \
        sqrt(2*x + 1)*(6*x**2 + x - 1)/15
示例#45
0
 def simp(x):
     return simplify(expand_trig(expand_complex(expand(x))))
# print(sym.pretty(equ.coeff(eps**3)))

# A1 = a * sym.exp(-3 * alpha2 / (2 * omega0**5) * T1)
# # Equation for eps0
X0 = A(T1) * sym.exp(sym.I * omega0 * T0) + sym.conjugate(
    A(T1) * sym.exp(sym.I * omega0 * T0))
# X0 = A1(T1) * A2(T2) * sym.exp(sym.I * omega0 * T0) + g / omega0**2
# X0 = A1 * A2(T2) * sym.exp(sym.I * omega0 * T0) + g / omega0**2
# equEps0 = sym.diff(sym.diff(X0, T0), T0) - g + omega0**2 * X0
# equEps0 = equEps0.expand()
# print(sym.pretty(equEps0))

# # Equation for eps1
equEps1RHS = -(2 * sym.diff(sym.diff(X0, T1), T0) + alpha * X0**2 +
               beta * X0**3)
equEps1RHS = sym.simplify(equEps1RHS.expand())
# print(sym.pretty(equEps1RHS))
print(sym.pretty(equEps1RHS.coeff(sym.exp(sym.I * omega0 * T0))))
#
# fid = open('equation.txt', 'w')
# fid.write(sym.latex(equEps1RHS, mode='equation'))
# fid.close()

# A1 = a * sym.exp(-3 * alpha2 / (2 * omega0**5) * T1)
# X1 = -alpha2 * g**3 / omega0**8 - \
#      3 * alpha2 * g * A1**2 * A2**2 / (omega0**2 * (omega0**2 - 4 * omega0**2)) * \
#         sym.exp(2 * sym.I * T0 * omega0) - \
#      alpha2 * A1**3 + A2**3 / (omega0**2 - 9 * omega0**2) * \
#         sym.exp(3 * sym.I * T0 * omega0)
#
# # # Equation for eps2
示例#47
0
def test_inverse_mellin_transform():
    from sympy import (sin, simplify, Max, Min, expand, powsimp, exp_polar,
                       cos, cot)
    IMT = inverse_mellin_transform

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

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

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

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

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

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

    # Now test the inverses of all direct transforms tested above

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

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

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

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

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

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

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

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

    # for coverage

    assert IMT(pi / cos(pi * s), s, x, (0, S(1) / 2)) == sqrt(x) / (x + 1)
result_pattern = "i"  #"i"
kz_zero = False  ## True for xy surface
pretty_print = True

try_parallel = True
gname = "D3d"
Info = get_data(TR=True)[gname]
print(Info["genes"])

multi_orbs_with_arr = []
multi_orbs_with_arr.append([['p, 3/2, 1/2', 'p, 3/2, -1/2'], [1, -1, -1]])
multi_orbs_with_arr.append([['p, 3/2, 1/2', 'p, 3/2, -1/2'], [1, 1, 1]])

order_list = [0, 1, 2]
similar_trans = sp.Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0],
                           [0, 0, 0, 1]]) * sp.diag(1, sp.simplify("I"), 1,
                                                    -sp.simplify("I"))

#-------------------------------------------------------------------------------

if "bandchars" not in locals(): bandchars = []
if "multi_orbs_with_arr" not in locals(): multi_orbs_with_arr = []
if "similar_trans" not in locals(): similar_trans = False

start_time = time.time()
if try_parallel:
    cores = multiprocessing.cpu_count()
    try:
        pool = multiprocessing.Pool(processes=cores)
    except:
        pool = ""
示例#49
0
def test_weibull():
    a, b = symbols('a b', positive=True)
    X = Weibull('x', a, b)

    assert simplify(E(X)) == simplify(a * gamma(1 + 1/b))
    assert simplify(variance(X)) == simplify(a**2 * gamma(1 + 2/b) - E(X)**2)
示例#50
0
 def simp_pows(expr):
     return simplify(powsimp(expand_mul(expr, deep=False),
                             force=True)).replace(exp_polar, exp)
示例#51
0
def actToExpression(act: Activity, extract_activities=None):
    """Computes a symbolic expression of the model, referencing background activities and model parameters as symbols

    Returns
    -------
        (sympy_expr, dict of symbol => activity)
    """

    act_symbols = dict()  # Dict of  act = > symbol

    def act_to_symbol(db_name, code):

        act = _getDb(db_name).get(code)
        name = act['name']
        base_slug = _slugify(name)

        slug = base_slug
        i = 1
        while symbols(slug) in act_symbols.values():
            slug = f"{base_slug}{i}"
            i += 1

        return symbols(slug)

    def rec_func(act: Activity, in_extract_path):

        res = 0
        outputAmount = 1

        for exch in act.exchanges():

            formula = _getAmountOrFormula(exch)

            if isinstance(formula, types.FunctionType):
                # Some amounts in EIDB are functions ... we ignore them
                continue

            #  Production exchange
            if exch['input'] == exch['output']:
                # Not 1 ?
                if exch['amount'] != 1:
                    outputAmount = exch['amount']
                continue

            input_db, input_code = exch['input']
            sub_act = _getDb(input_db).get(input_code)

            # If list of extract activites requested, we only integrate activites below a tracked one
            exch_in_path = in_extract_path
            if extract_activities is not None:
                if sub_act in extract_activities:
                    exch_in_path = in_extract_path or (sub_act
                                                       in extract_activities)

            # Background DB => reference it as a symbol
            if input_db in [BIOSPHERE3_DB_NAME, ECOINVENT_DB_NAME()]:

                if exch_in_path:
                    # Add to dict of background symbols
                    if not (input_db, input_code) in act_symbols:
                        act_symbols[(input_db, input_code)] = act_to_symbol(
                            input_db, input_code)
                    act_expr = act_symbols[(input_db, input_code)]
                else:
                    continue

            # Our model : recursively it to a symbolic expression
            else:

                if input_db == act['database'] and input_code == act['code']:
                    raise Exception("Recursive exchange : %s" % (act.__dict__))

                act_expr = rec_func(sub_act, exch_in_path)

            avoidedBurden = 1
            if exch['type'] == 'production' and not exch['input'] == exch[
                    'output']:
                avoidedBurden = -1

            res += formula * act_expr * avoidedBurden

        return res / outputAmount

    expr = rec_func(act, extract_activities is None)

    if isinstance(expr, float):
        expr = simplify(expr)
    else:
        # Replace fixed params with their default value
        expr = _replace_fixed_params(expr, _fixed_params().values())

    return (expr, _reverse_dict(act_symbols))
示例#52
0
def test_conjugate_priors():
    mu = Normal('mu', 2, 3)
    x = Normal('x', mu, 1)
    assert isinstance(simplify(density(mu, Eq(x, y), evaluate=False)(z)),
            Integral)
h = X[1] - X[0]

coeff = []
coeff.append(Y[0])

n = len(Y)

for i in range(1, n):
    a = (f_diff[i - 1][0] / (factorial(i) * (h**i)))
    coeff.append(a)

# Displaying coefficients

print("\n\n\n\nCoefficients are\n")
for i in range(n):
    print("a" + str(i), " = ", coeff[i])

u = (x - X[0]) / h

# Calcualting P(x)
P = 0
for k in range(1, n):
    U = u
    for i in range(1, k):
        U *= (u - i)
    P += (U * f_diff[k - 1][0]) / factorial(k)
P = P + Y[0]

print("\n\nThe expression of p(x) is ", s.simplify(P))
print("\n\nThe value of p(x) is ", P.subs(x, Xx))
示例#54
0
def test_gumbel():
    beta = Symbol("beta", positive=True)
    mu = Symbol("mu")
    x = Symbol("x")
    X = Gumbel("x", beta, mu)
    assert simplify(density(X)(x)) == exp((beta*exp((mu - x)/beta) + mu - x)/beta)/beta
示例#55
0
def test_simplify():
    y, t, v = symbols('y, t, v')

    assert simplify(Sum(x*y, (x, n, m), (y, a, k)) + \
        Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k))
    assert simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \
        Sum(x, (x, n, a))
    assert simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \
        Sum(x, (x, n, a))
    assert simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \
        Sum(x, (x, n, a)) + Sum(1, (x, n, k))
    assert simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \
        4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6))
    assert simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \
        Sum(x*(3*x + 1), (x, a, b))
    assert simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \
        4 * y * Sum(z, (z, n, k))) + 1 == \
            4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1
    assert simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \
        1 + Sum(x, (x, a, c))
    assert simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \
        Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
    assert simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \
        Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
    assert simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \
        simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c)))
    assert simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \
        Sum(x, (x, a, b)) * Sum(x**2, (x, a, b))
    assert simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \
        == (x + y + z) * Sum(1, (t, a, b))          # issue 8596
    assert simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \
        Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b))  # issue 8596
    assert simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \
        (Sum(x, (x, a, b)) / 3)
    assert simplify(Sum(Function('f')(x) * y * z, (x, a, b)) / (y * z)) \
        == Sum(Function('f')(x), (x, a, b))
    assert simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0
    assert simplify(c * (Sum(x, (x, a, b))  + y)) == c * (y + Sum(x, (x, a, b)))
    assert simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \
        c * (y + 1) * Sum(x, (x, a, b))
    assert simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \
                c * Sum(x, (x, a, b), (y, a, b))
    assert simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \
                c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b))
    assert simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \
                c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b))
    assert simplify(Sum(Sum(d * t, (x, a, b - 1)) + \
                Sum(d * t, (x, b, c)), (t, a, b))) == \
                    d * Sum(1, (x, a, c)) * Sum(t, (t, a, b))
示例#56
0
# Define :math:`y=A\exp(-t/\tau)` and the gaussian IRF.

# %%
y = step(t) * A * exp(-t / tau)
y

# %%
irf = 1 / sqrt(2 * pi * sigma**2) * exp(-t**2 / (2 * sigma**2))
irf

# %%
# Next, we will calculate the covolution integral.

# %%
func = integrate((irf.subs(t, t - ti) * y.subs(t, ti)), (ti, -oo, oo))
func = simplify(func)
func

# %%
# Rewirte the `erf` with the `erfc` function:
#erfc, erf = special.error_functions.erfc, special.error_functions.erf
func2 = func.rewrite(erfc)
func2

# %% [markdown]
# Plot the result to it makes sense:
plot(func2.subs(sigma, 0.2).subs(tau, 2).subs(A, 1), (t, -1, 10))

# %%
# Normalized derivatives of a gaussian
# ------------------------------------
示例#57
0
#We first need the three equations we are going to try and set to zero, i.e. the first partial derivitives wrt e h and F.
print "/*This code was automatically generated by "+str(sys.argv[0])+"*/\n"
print "#include \"allele.h\""
print "#include \"quartet.h\""
print "#include \"typedef.h\""
print "#include \"constants.h\""
print 
#numpy.set_printoptions(precission=18)


for x in range(0, 7):
	system_eq.append(sympy.diff(lnL, params[x]) )
	print "inline float_t H"+str(x)+" (const Genotype_pair &pair, const Constants <float_t, const std::pair<const Genotype_pair &, const Relatedness &> > &con) {"
	sys.stdout.write("\treturn ")
	out=(system_eq[-1])
	out=sympy.simplify(out)
	pre(out)
	keys=dag_sort(keys)
	for key in keys:
		out=exact_sub(out, constants[key], key)
	string=sympy.printing.ccode(out)
	print string, ";\n}\n"

#Then we need to make the Jacobian, which is a matrix with ...
for x in range(0, 7):
	for y in range(0, 7):
		print "inline float_t J"+str(x)+str(y)+" (const Genotype_pair &pair, const Constants <float_t, const std::pair <const Genotype_pair &, const Relatedness &> > &con) {"
		sys.stdout.write("\treturn ")
                out=(sympy.diff(system_eq[x], params[y]))
		#out=sympy.simplify(out)
		pre(out)
示例#58
0
# ASSEMBLE THE LAGRANGIAN!!!
####################################################

## Calculate the Kinetic Energy of each body #################################
# KE = .5 * V.T * I * V

Vp1 = invertTrans(g_wp1) * g_wp1.diff(t)
Vp1 = se3ToVec(Vp1)

Vp2 = invertTrans(g_wp2) * g_wp2.diff(t)
Vp2 = se3ToVec(Vp2)

Vx = invertTrans(g_wb) * g_wb.diff(t)
Vx = se3ToVec(Vx)

KEp1 = sym.simplify(0.5 * Vp1.T * Ipend1 * Vp1)
KEp2 = sym.simplify(0.5 * Vp2.T * Ipend2 * Vp2)
KEx = sym.simplify(0.5 * Vx.T * Icart * Vx)
KE = sym.simplify(KEp1[0] + KEp2[0] + KEx[0])

## Calculate the Potential Energy of each body ###############################
# PE = m * g * h

PEp2 = m * g * g_wp2[1, 3]
PE = sym.simplify(PEp2)

## Calculate the Lagrangian!!! ###############################################

L = sym.simplify(KE - PE)

####################################################
#coding:utf-8
'''
特征值问题
'''

from __future__ import division
from scipy import linalg as la
from scipy import optimize
import sympy
import numpy as np
sympy.init_printing()
import matplotlib.pyplot as plt

# 使用符号方式求解矩阵的特征值
eps, delta = sympy.symbols("epsilon, Delta")
H = sympy.Matrix([[eps, delta], [delta, -eps]])
eigenvalue = H.eigenvals()
results = H.eigenvects()
(eval1, _, evec1), (eval2, _, evec2) = H.eigenvects()
result = sympy.simplify(evec1[0].T * evec2[0])
print('result = ', result)

# 使用scipy求解矩阵特征值
A = np.array([[1, 3, 5], [3, 5, 3], [5, 3, 9]])
evals, evecs = la.eig(A)
eigvalues = la.eigvalsh(A)
示例#60
0
def test_karr_convention():
    # Test the Karr summation convention that we want to hold.
    # See his paper "Summation in Finite Terms" for a detailed
    # reasoning why we really want exactly this definition.
    # The convention is described on page 309 and essentially
    # in section 1.4, definition 3:
    #
    # \sum_{m <= i < n} f(i) 'has the obvious meaning'   for m < n
    # \sum_{m <= i < n} f(i) = 0                         for m = n
    # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i)  for m > n
    #
    # It is important to note that he defines all sums with
    # the upper limit being *exclusive*.
    # In contrast, sympy and the usual mathematical notation has:
    #
    # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b)
    #
    # with the upper limit *inclusive*. So translating between
    # the two we find that:
    #
    # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i)
    #
    # where we intentionally used two different ways to typeset the
    # sum and its limits.

    i = Symbol("i", integer=True)
    k = Symbol("k", integer=True)
    j = Symbol("j", integer=True)

    # A simple example with a concrete summand and symbolic limits.

    # The normal sum: m = k and n = k + j and therefore m < n:
    m = k
    n = k + j

    a = m
    b = n - 1
    S1 = Sum(i**2, (i, a, b)).doit()

    # The reversed sum: m = k + j and n = k and therefore m > n:
    m = k + j
    n = k

    a = m
    b = n - 1
    S2 = Sum(i**2, (i, a, b)).doit()

    assert simplify(S1 + S2) == 0

    # Test the empty sum: m = k and n = k and therefore m = n:
    m = k
    n = k

    a = m
    b = n - 1
    Sz = Sum(i**2, (i, a, b)).doit()

    assert Sz == 0

    # Another example this time with an unspecified summand and
    # numeric limits. (We can not do both tests in the same example.)
    f = Function("f")

    # The normal sum with m < n:
    m = 2
    n = 11

    a = m
    b = n - 1
    S1 = Sum(f(i), (i, a, b)).doit()

    # The reversed sum with m > n:
    m = 11
    n = 2

    a = m
    b = n - 1
    S2 = Sum(f(i), (i, a, b)).doit()

    assert simplify(S1 + S2) == 0

    # Test the empty sum with m = n:
    m = 5
    n = 5

    a = m
    b = n - 1
    Sz = Sum(f(i), (i, a, b)).doit()

    assert Sz == 0

    e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True))
    s = Sum(e, (i, 0, 11))
    assert s.n(3) == s.doit().n(3)