示例#1
1
文件: test_kane.py 项目: 101man/sympy
def test_one_dof():
    # This is for a 1 dof spring-mass-damper case.
    # It is described in more detail in the Kane docstring.
    q, u = dynamicsymbols('q u')
    qd, ud = dynamicsymbols('q u', 1)
    m, c, k = symbols('m c k')
    N = ReferenceFrame('N')
    P = Point('P')
    P.set_vel(N, u * N.x)

    kd = [qd - u]
    FL = [(P, (-k * q - c * u) * N.x)]
    pa = Particle()
    pa.mass = m
    pa.point = P
    BL = [pa]

    KM = Kane(N)
    KM.coords([q])
    KM.speeds([u])
    KM.kindiffeq(kd)
    KM.kanes_equations(FL, BL)
    MM = KM.mass_matrix
    forcing = KM.forcing
    rhs = MM.inv() * forcing
    assert expand(rhs[0]) == expand(-(q * k + u * c) / m)
    assert KM.linearize() == (Matrix([[0, 1], [k, c]]), Matrix([]))
示例#2
1
def test_two_dof():
    # This is for a 2 d.o.f., 2 particle spring-mass-damper.
    # The first coordinate is the displacement of the first particle, and the
    # second is the relative displacement between the first and second
    # particles. Speeds are defined as the time derivatives of the particles.
    q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
    q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
    m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
    N = ReferenceFrame('N')
    P1 = Point('P1')
    P2 = Point('P2')
    P1.set_vel(N, u1 * N.x)
    P2.set_vel(N, (u1 + u2) * N.x)
    kd = [q1d - u1, q2d - u2]

    # Now we create the list of forces, then assign properties to each
    # particle, then create a list of all particles.
    FL = [(P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
        q2 - c2 * u2) * N.x)]
    pa1 = Particle('pa1', P1, m)
    pa2 = Particle('pa2', P2, m)
    BL = [pa1, pa2]

    # Finally we create the KanesMethod object, specify the inertial frame,
    # pass relevant information, and form Fr & Fr*. Then we calculate the mass
    # matrix and forcing terms, and finally solve for the udots.
    KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
    KM.kanes_equations(FL, BL)
    MM = KM.mass_matrix
    forcing = KM.forcing
    rhs = MM.inv() * forcing
    assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
    assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
                                    c2 * u2) / m)
示例#3
1
文件: test_kane.py 项目: 101man/sympy
def test_pend():
    q, u = dynamicsymbols('q u')
    qd, ud = dynamicsymbols('q u', 1)
    m, l, g = symbols('m l g')
    N = ReferenceFrame('N')
    P = Point('P')
    P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y)
    kd = [qd - u]

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

    KM = Kane(N)
    KM.coords([q])
    KM.speeds([u])
    KM.kindiffeq(kd)
    KM.kanes_equations(FL, BL)
    MM = KM.mass_matrix
    forcing = KM.forcing
    rhs = MM.inv() * forcing
    rhs.simplify()
    assert expand(rhs[0]) == expand(-g / l * sin(q))
示例#4
0
 def _solve_recur(expr, rhs=S(0)):
     if expr == var:
         return rhs
     expr = expand(expr)
     if isinstance(expr, Mul):
         lhs = S(1)
         # Try by rank
         l_coeff, var_expr, r_coeff = expr_coeff(expr, var)
         lhs = var_expr
         rhs = Inverse(l_coeff) * rhs * Inverse(r_coeff)
         return _solve_recur(lhs, rhs)
     if isinstance(expr, Add):
         lhs = 0
         for arg in expr.args:
             if var in arg:
                 lhs += arg
             else:
                 rhs -= arg
         if isinstance(lhs, Add):
             coeff = lhs.coeff(var)
             if expand(coeff * var) == lhs:
                 rhs /= coeff
                 lhs = var
         return _solve_recur(lhs, rhs)
     if isinstance(expr, Transpose):
         return _solve_recur(expr.args[0], Transpose(rhs))
     raise NotImplementedError("Can't handle expr of type %s" % type(expr))
示例#5
0
 def test_fast_substitute(self):
     f = generate_variables(2, name="f")
     substitutions = {}
     substitutions[Dagger(f[0]) * f[0]] = -f[0] * Dagger(f[0])
     monomial = Dagger(f[0]) * f[0]
     lhs = Dagger(f[0]) * f[0]
     rhs = -f[0] * Dagger(f[0])
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial.subs(lhs, rhs))
     monomial = Dagger(f[0]) * f[0] ** 2
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial.subs(lhs, rhs))
     monomial = Dagger(f[0]) ** 2 * f[0]
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial.subs(lhs, rhs))
     monomial = Dagger(f[0]) ** 2 * f[0]
     lhs = Dagger(f[0]) ** 2
     rhs = -f[0] * Dagger(f[0])
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial.subs(lhs, rhs))
     g = generate_variables(2, name="g")
     monomial = 2 * g[0] ** 3 * g[1] * Dagger(f[0]) ** 2 * f[0]
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial.subs(lhs, rhs))
     monomial = S.One
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial.subs(lhs, rhs))
     monomial = 5
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial)
     monomial = 2 * g[0] ** 3 * g[1] * Dagger(f[0]) ** 2 * f[0] + f[1]
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == monomial.subs(lhs, rhs))
     monomial = f[1] * Dagger(f[0]) ** 2 * f[0]
     lhs = f[1]
     rhs = 1.0 + f[0]
     self.assertTrue(fast_substitute(monomial, lhs, rhs) == expand(monomial.subs(lhs, rhs)))
     monomial = f[1] ** 2 * Dagger(f[0]) ** 2 * f[0]
     result = fast_substitute(fast_substitute(monomial, lhs, rhs), lhs, rhs)
     self.assertTrue(result == expand(monomial.subs(lhs, rhs)))
示例#6
0
def main():
    print(symbols('a b c d'))
    a, b, c, d = symbols('a b c d')

    group4 = [a, b, c, d]
    print(group4)
    four = group_solve(group4)
    print(four)
    print(expand(four))
    print(four.collect(a))
    print(four.subs(a, 10))
    print()

    group4_ = add1(group4)
    print(group4_)
    four1 = group_solve(group4_)
    print(four1)
    print(expand(four1))
    print(four1.collect(a))
    print()

    print(13717421)

    for i in range(1, 10 ** 4):
        sum_power(i)
示例#7
0
    def test_apply_substitutions(self):

        def apply_correct_substitutions(monomial, substitutions):
            if isinstance(monomial, int) or isinstance(monomial, float):
                return monomial
            original_monomial = monomial
            changed = True
            while changed:
                for lhs, rhs in substitutions.items():
                    monomial = monomial.subs(lhs, rhs)
                if original_monomial == monomial:
                    changed = False
                original_monomial = monomial
            return monomial

        length, h, U, t = 2, 3.8, -6, 1
        fu = generate_operators('fu', length)
        fd = generate_operators('fd', length)
        _b = flatten([fu, fd])
        hamiltonian = 0
        for j in range(length):
            hamiltonian += U * (Dagger(fu[j])*Dagger(fd[j]) * fd[j]*fu[j])
            hamiltonian += -h/2*(Dagger(fu[j])*fu[j] - Dagger(fd[j])*fd[j])
            for k in get_neighbors(j, len(fu), width=1):
                hamiltonian += -t*Dagger(fu[j])*fu[k]-t*Dagger(fu[k])*fu[j]
                hamiltonian += -t*Dagger(fd[j])*fd[k]-t*Dagger(fd[k])*fd[j]
        substitutions = fermionic_constraints(_b)
        monomials = expand(hamiltonian).as_coeff_mul()[1][0].as_coeff_add()[1]
        substituted_hamiltonian = sum([apply_substitutions(monomial,
                                                           substitutions)
                                       for monomial in monomials])
        correct_hamiltonian = sum([apply_correct_substitutions(monomial,
                                                               substitutions)
                                   for monomial in monomials])
        self.assertTrue(substituted_hamiltonian == expand(correct_hamiltonian))
示例#8
0
def case0(f, N=3):
    B = 1 - x ** 3
    dBdx = sm.diff(B, x)

    # Compute basis functions and their derivatives
    phi = {0: [x ** (i + 1) * (1 - x) for i in range(N + 1)]}
    phi[1] = [sm.diff(phi_i, x) for phi_i in phi[0]]

    def integrand_lhs(phi, i, j):
        return phi[1][i] * phi[1][j]

    def integrand_rhs(phi, i):
        return f * phi[0][i] - dBdx * phi[1][i]

    Omega = [0, 1]

    u_bar = solve(integrand_lhs, integrand_rhs, phi, Omega, verbose=True, numint=False)
    u = B + u_bar
    print "solution u:", sm.simplify(sm.expand(u))

    # Calculate analytical solution

    # Solve -u''=f by integrating f twice
    f1 = sm.integrate(f, x)
    f2 = sm.integrate(f1, x)
    # Add integration constants
    C1, C2 = sm.symbols("C1 C2")
    u_e = -f2 + C1 * x + C2
    # Find C1 and C2 from the boundary conditions u(0)=0, u(1)=1
    s = sm.solve([u_e.subs(x, 0) - 1, u_e.subs(x, 1) - 0], [C1, C2])
    # Form the exact solution
    u_e = -f2 + s[C1] * x + s[C2]
    print "analytical solution:", u_e
    # print 'error:', u - u_e  # many terms - which cancel
    print "error:", sm.expand(u - u_e)
示例#9
0
def _interpolate_expression(expr):
    change = False
    expr = sympy.expand(expr)
    res = expr

    if isinstance(expr, sympy.Function):# and not change:
        path = np.array([])
        temp, change = _interpolate_Function(_follow_path(expr, path))
        res = _interchange(expr, temp, path)

    for i in np.arange(len(expr.args)):
        path = np.array([i])
        if isinstance(_follow_path(expr, path), sympy.Function) and not change:
            temp, change = _interpolate_Function(_follow_path(expr, path))
            res = _interchange(expr, temp, path)

        for j in np.arange(len(expr.args[i].args)):
            path = np.array([i, j])
            if isinstance(_follow_path(expr, path), sympy.Function) and not change:
                temp, change = _interpolate_Function(_follow_path(expr, path))
                res = _interchange(expr, temp, path)

    if change:
        res = _interpolate_expression(res)

    return sympy.expand(res)
示例#10
0
def _interpolate_Function(expr):
    path = 'None'
    factor = 'None'
    change = False
    summand_0 = 'None'
    summand_1 = 'None'
    res = expr
    for i in np.arange(len(expr.args)):
        argument = sympy.expand(expr.args[i])
        if argument.func == sympy.Add:
            for j in np.arange(len(argument.args)):
                summand = argument.args[j]
                if summand.func == sympy.Mul:
                    for k in np.arange(len(summand.args)):
                        temp = 0
                        if summand.args[k] == sympy.Symbol('a'):
                            temp = sympy.Mul(sympy.Mul(*summand.args[:k]),
                                             sympy.Mul(*summand.args[k+1:]))
                            #print(temp)
                        if not temp == int(temp):
                            #print('found one')
                            factor = (temp)
                            path = np.array([i, j, k])
    if not factor == 'None':
        change = True

        sign = np.sign(factor)
        offsets = np.array([int(factor), sign * (int(sign * factor) + 1)])
        weights = 1/np.abs(offsets - factor)
        weights = weights/np.sum(weights)

        res = (  weights[0] * _interchange(expr, offsets[0] * sympy.Symbol('a'), path[:-1])
               + weights[1] * _interchange(expr, offsets[1] * sympy.Symbol('a'), path[:-1]))

    return sympy.expand(res), change
示例#11
0
def tests():
    x, y, z = symbols('x,y,z')
    #print(x + x + 1)
    expr = x**2 - y**2
    factors = factor(expr)
    print(factors, " | ", expand(factors))
    pprint(expand(factors))
示例#12
0
 def gen_errs(self, a, b, n, x, y):
     """
     What is the best thing to do here?
     """
     errs = set()
     
     # Generate som obvious candidates
     errs.add(sym.expand(self.gen_prob(-a, -b, n, x, y)))
     if a < 0:
         errs.add(sym.expand(self.gen_prob(-a, b, n, x, y)))
     if b < 0:
         errs.add(sym.expand(self.gen_prob(a, -b, n, x, y)))
    
     
     expr = sym.expand(self.gen_prob(a, b, n, x, y))
     coeffs = sym.Poly(expr).coeffs()
     
     for i in range(4):
         
         expr1 = self.gen_poly(map(lambda l: random.choice([-1, 1]) * l, coeffs), x, y)
         expr2 = self.gen_poly(map(lambda l: random.choice([-2, -1, 0, 1, 2]) * l, coeffs), x, y)
         errs.update([expr1, expr2, expr - (expr2 - sym.LM(expr))])
     
     errs = list(errs)
     errs_ = [err for err in errs if err != expr]
     random.shuffle(errs_)
     return errs
示例#13
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.cancel(sympy.expand(res.v(n2,gnd))),
                 sympy.expand((b0*s*s)/(a0*s*s*s+a1*s*s+a2*s+a3)))
示例#14
0
def alphaBetaToTransfer(adjMat, alphas, betas):
    s = sympy.Symbol('s')
    subs = {}

    # iterate over the columns of the adjacency matrix
    for i, col in enumerate(adjMat.getA()):
        expr = sympy.S(0)
        i += 1
        # iterate over the elements in each column of the adjacency matrix
        # this is to build the replacement expression for what were once "output to env"s
        # but are now the turnover rates of each node
        for j, elem in enumerate(col):
            j += 1
            if elem != 0:
                expr += (-sympy.var('a_%d%d' % (j,i)))

        subs[sympy.var('a_%d%d' % (i,i))] = expr

    #print "*** VAR->EXPR SUBSTITUTIONS: "
    #print subs

    for pos in range(0, len(betas)):
        orderedKeysBeta = getOrderedKeys(betas[pos])
        for key in orderedKeysBeta:
            betas[pos][s**key] = sympy.simplify(sympy.expand(betas[pos][s**key].xreplace(subs)))

        #finished all the betas so add the alphas, but only once
        orderedKeysAlpha = getOrderedKeys(alphas[pos])
        for key in orderedKeysAlpha:
            alphas[pos][s**key] = sympy.simplify(sympy.expand(alphas[pos][s**key].xreplace(subs)))
示例#15
0
def T_exact_symbolic(verbose=False):
    """Compute the exact solution formula via sympy."""
    # sol1: solution for t < t_star,
    # sol2: solution for t > t_star
    import sympy as sym
    T0 = sym.symbols('T0')
    k = sym.symbols('k', positive=True)
    # Piecewise linear T_sunction
    t, t_star, C0, C1 = sym.symbols('t t_star C0 C1')
    T_s = C0
    I = sym.integrate(sym.exp(k*t)*T_s, (t, 0, t))
    sol1 = T0*sym.exp(-k*t) + k*sym.exp(-k*t)*I
    sol1 = sym.simplify(sym.expand(sol1))
    if verbose:
        # Some debugging print
        print 'solution t < t_star:', sol1
        #print sym.latex(sol1)
    T_s = C1
    I = sym.integrate(sym.exp(k*t)*C0, (t, 0, t_star)) + \
        sym.integrate(sym.exp(k*t)*C1, (t, t_star, t))
    sol2 = T0*sym.exp(-k*t) + k*sym.exp(-k*t)*I
    sol2 = sym.simplify(sym.expand(sol2))
    if verbose:
        print 'solution t > t_star:', sol2
        #print sym.latex(sol2)

    # Convert to numerical functions
    exact0 = sym.lambdify([t, C0, k, T0],
                          sol1, modules='numpy')
    exact1 = sym.lambdify([t, C0, C1, t_star, k, T0],
                          sol2, modules='numpy')
    return exact0, exact1
示例#16
0
def test_order_noncommutative():
    A = Symbol("A", commutative=False)
    assert Order(A + A * x, x) == Order(1, x)
    assert (A + A * x) * Order(x) == Order(x)
    assert (A * x) * Order(x) == Order(x ** 2, x)
    assert expand((1 + Order(x)) * A * A * x) == A * A * x + Order(x ** 2, x)
    assert expand((A * A + Order(x)) * x) == A * A * x + Order(x ** 2, x)
    assert expand((A + Order(x)) * A * x) == A * A * x + Order(x ** 2, x)
示例#17
0
def test_piecewise_fold_expand():
    p1 = Piecewise((1,Interval(0,1,False,True)),(0,True))

    p2 = piecewise_fold(expand((1-x)*p1))
    assert p2 == Piecewise((1 - x, Interval(0,1,False,True)), \
        (Piecewise((-x, Interval(0,1,False,True)), (0, True)), True))

    p2 = expand(piecewise_fold((1-x)*p1))
    assert p2 == Piecewise((1 - x, Interval(0,1,False,True)), (0, True))
示例#18
0
def test_meijerint():
    from sympy import symbols, expand, arg

    s, t, mu = symbols("s t mu", real=True)
    assert integrate(
        meijerg([], [], [0], [], s * t) * meijerg([], [], [mu / 2], [-mu / 2], t ** 2 / 4), (t, 0, oo)
    ).is_Piecewise
    s = symbols("s", positive=True)
    assert integrate(x ** s * meijerg([[], []], [[0], []], x), (x, 0, oo)) == gamma(s + 1)
    assert integrate(x ** s * meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=True) == gamma(s + 1)
    assert isinstance(integrate(x ** s * meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=False), Integral)

    assert meijerint_indefinite(exp(x), x) == exp(x)

    # TODO what simplifications should be done automatically?
    # This tests "extra case" for antecedents_1.
    a, b = symbols("a b", positive=True)
    assert simplify(meijerint_definite(x ** a, x, 0, b)[0]) == b ** (a + 1) / (a + 1)

    # This tests various conditions and expansions:
    meijerint_definite((x + 1) ** 3 * exp(-x), x, 0, oo) == (16, True)

    # Again, how about simplifications?
    sigma, mu = symbols("sigma mu", positive=True)
    i, c = meijerint_definite(exp(-((x - mu) / (2 * sigma)) ** 2), x, 0, oo)
    assert simplify(i) == sqrt(pi) * sigma * (erf(mu / (2 * sigma)) + 1)
    assert c is True

    i, _ = meijerint_definite(exp(-mu * x) * exp(sigma * x), x, 0, oo)
    # TODO it would be nice to test the condition
    assert simplify(i) == 1 / (mu - sigma)

    # Test substitutions to change limits
    assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True)
    assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1
    assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == 1 - exp(-exp(I * arg(x)) * abs(x))

    # Test -oo to oo
    assert meijerint_definite(exp(-x ** 2), x, -oo, oo) == (sqrt(pi), True)
    assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True)
    assert meijerint_definite(exp(-(2 * x - 3) ** 2), x, -oo, oo) == (sqrt(pi) / 2, True)
    assert meijerint_definite(exp(-abs(2 * x - 3)), x, -oo, oo) == (1, True)
    assert meijerint_definite(exp(-((x - mu) / sigma) ** 2 / 2) / sqrt(2 * pi * sigma ** 2), x, -oo, oo) == (1, True)

    # Test one of the extra conditions for 2 g-functinos
    assert meijerint_definite(exp(-x) * sin(x), x, 0, oo) == (S(1) / 2, True)

    # Test a bug
    def res(n):
        return (1 / (1 + x ** 2)).diff(x, n).subs(x, 1) * (-1) ** n

    for n in range(6):
        assert integrate(exp(-x) * sin(x) * x ** n, (x, 0, oo), meijerg=True) == res(n)

    # Test trigexpand:
    assert integrate(exp(-x) * sin(x + a), (x, 0, oo), meijerg=True) == sin(a) / 2 + cos(a) / 2
示例#19
0
文件: frame.py 项目: jbm950/sympy
 def _w_diff_dcm(self, otherframe):
     """Angular velocity from time differentiating the DCM. """
     from sympy.physics.vector.functions import dynamicsymbols
     dcm2diff = self.dcm(otherframe)
     diffed = dcm2diff.diff(dynamicsymbols._t)
     angvelmat = diffed * dcm2diff.T
     w1 = trigsimp(expand(angvelmat[7]), recursive=True)
     w2 = trigsimp(expand(angvelmat[2]), recursive=True)
     w3 = trigsimp(expand(angvelmat[3]), recursive=True)
     return -Vector([(Matrix([w1, w2, w3]), self)])
示例#20
0
    def __new__(cls, *args, **old_assumptions):
        from sympy.physics.quantum.state import KetBase, BraBase

        if len(args) != 2:
            raise ValueError('2 parameters expected, got %d' % len(args))

        ket_expr = expand(args[0])
        bra_expr = expand(args[1])

        if (isinstance(ket_expr, (KetBase, Mul)) and
                isinstance(bra_expr, (BraBase, Mul))):
            ket_c, kets = ket_expr.args_cnc()
            bra_c, bras = bra_expr.args_cnc()

            if len(kets) != 1 or not isinstance(kets[0], KetBase):
                raise TypeError('KetBase subclass expected'
                                ', got: %r' % Mul(*kets))

            if len(bras) != 1 or not isinstance(bras[0], BraBase):
                raise TypeError('BraBase subclass expected'
                                ', got: %r' % Mul(*bras))

            if not kets[0].dual_class() == bras[0].__class__:
                raise TypeError(
                    'ket and bra are not dual classes: %r, %r' %
                    (kets[0].__class__, bras[0].__class__)
                    )

            # TODO: make sure the hilbert spaces of the bra and ket are
            # compatible
            obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions)
            obj.hilbert_space = kets[0].hilbert_space
            return Mul(*(ket_c + bra_c)) * obj

        op_terms = []
        if isinstance(ket_expr, Add) and isinstance(bra_expr, Add):
            for ket_term in ket_expr.args:
                for bra_term in bra_expr.args:
                    op_terms.append(OuterProduct(ket_term, bra_term,
                                                 **old_assumptions))
        elif isinstance(ket_expr, Add):
            for ket_term in ket_expr.args:
                op_terms.append(OuterProduct(ket_term, bra_expr,
                                             **old_assumptions))
        elif isinstance(bra_expr, Add):
            for bra_term in bra_expr.args:
                op_terms.append(OuterProduct(ket_expr, bra_term,
                                             **old_assumptions))
        else:
            raise TypeError(
                'Expected ket and bra expression, got: %r, %r' %
                (ket_expr, bra_expr)
                )

        return Add(*op_terms)
示例#21
0
def test_input_format():
    # 1 dof problem from test_one_dof
    q, u = dynamicsymbols('q u')
    qd, ud = dynamicsymbols('q u', 1)
    m, c, k = symbols('m c k')
    N = ReferenceFrame('N')
    P = Point('P')
    P.set_vel(N, u * N.x)

    kd = [qd - u]
    FL = [(P, (-k * q - c * u) * N.x)]
    pa = Particle('pa', P, m)
    BL = [pa]

    KM = KanesMethod(N, [q], [u], kd)
    # test for input format kane.kanes_equations((body1, body2, particle1))
    assert KM.kanes_equations(BL)[0] == Matrix([0])
    # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=(load1,load2))
    assert KM.kanes_equations(bodies=BL, loads=None)[0] == Matrix([0])
    # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=None)
    assert KM.kanes_equations(BL, loads=None)[0] == Matrix([0])
    # test for input format kane.kanes_equations(bodies=(body1, body 2))
    assert KM.kanes_equations(BL)[0] == Matrix([0])
    # test for error raised when a wrong force list (in this case a string) is provided
    from sympy.utilities.pytest import raises
    raises(ValueError, lambda: KM._form_fr('bad input'))

    # 2 dof problem from test_two_dof
    q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
    q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
    m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
    N = ReferenceFrame('N')
    P1 = Point('P1')
    P2 = Point('P2')
    P1.set_vel(N, u1 * N.x)
    P2.set_vel(N, (u1 + u2) * N.x)
    kd = [q1d - u1, q2d - u2]

    FL = ((P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
        q2 - c2 * u2) * N.x))
    pa1 = Particle('pa1', P1, m)
    pa2 = Particle('pa2', P2, m)
    BL = (pa1, pa2)

    KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
    # test for input format
    # kane.kanes_equations((body1, body2), (load1, load2))
    KM.kanes_equations(BL, FL)
    MM = KM.mass_matrix
    forcing = KM.forcing
    rhs = MM.inv() * forcing
    assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
    assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
                                    c2 * u2) / m)
def hermitiana_1D(x, n):
    resultado1 = lagrangiana_1D(x, n)
    resultado2 = []
    puntos2 = np.linspace(-1, 1, n)
    for i in range(np.size(puntos2)):
        A = x - puntos2[i]
        B = (resultado1[i].diff(x)).subs(x, puntos2[i])
        C = resultado1[i]**2
        D = (1 - (A*B))*C
        resultado2.append(expand(D))
        resultado2.append(expand(A*C))
    return resultado2
示例#23
0
def lagrange(nodes):


    tmp_x_nodes = [node['X']for node in nodes]
    tmp_y_nodes = [node['Y']for node in nodes]

    x_nodes = np.asarray(tmp_x_nodes,dtype=np.float)
    y_nodes = np.asarray(tmp_y_nodes,dtype=np.float)

    x = sp.symbols('x')
    y = sp.symbols('y')

    pol_base = []
    pol_lag = []

    for i in range(len(x_nodes)):
        LUp = []
        LDown = []
        for j in range(len(nodes)):
            if j != i:
                express=(x-x_nodes[j])
                express_1=(x_nodes[i]-x_nodes[j])
                LUp.append("{" + str(express) + " \over " + str(express_1) + "}")
                LDown.append(express/express_1)
        pol_base.append([i, LUp])
        pol_lag.append(LDown)

    #print pol_base

    P=0
    product_result = []


    for n1 in range(len(pol_lag)):
        test = 1
        for n2 in range(len(pol_lag[n1])):
            test = test * pol_lag[n1][n2]

        ptoria = sp.expand(test)
        product_result.append([n1, sp.latex(ptoria), y_nodes[n1]])

        P = P + (test * y_nodes[n1])

    expt = sp.expand(P)
    latx = sp.latex(expt)

    response_data = {
            'result': latx,
            'basePol': pol_base,
            'sumProduct': product_result,
    }

    return response_data
示例#24
0
def run_taylor_leastsq_parabola_illconditioning(N=2):
    """
    Test Taylor approx to a parabola and exact symbolics vs
    ill-conditioned numerical approaches.
    """
    f = 10*(x-1)**2 - 1
    u = least_squares(f, psi=[x**i for i in range(N+1)], Omega=[1, 2])
    # Note: in least_squares there is extra code for numerical solution
    # of the systems
    print 'f:', sm.expand(f)
    print 'u:', sm.expand(u)
    comparison_plot(f, u, [1, 2], 'parabola_ls_taylor%d.pdf' % N)
示例#25
0
def case3():
    a, c, x1, x2 = symbols('a c x1 x2')              # Define symbols
    b = 3 * (a - 1)                             # Relation between a and b
    y = a * x1 + b * x2 + 5                     # Given function y
    # Error of x1 and x2
    Sigx1 = 0.8
    Sigx2 = 1.5

    print "In the case that x1 and x2 are partial dependent:\n"
    Sigx1x2 = c     # Correlation coefficient equals to an unknown parameter c
    SigmaXX = np.matrix([[Sigx1**2, Sigx1x2],   # Define covariance
                         [Sigx1x2, Sigx2**2]])  # matrix of x1 and x2

    # Jacobian matrix of y function with respect to x1 and x2
    Jyx = np.matrix([diff(y, x1), diff(y, x2)])

    SigmaYY = Jyx * SigmaXX * Jyx.T   # Compute covariance matrix of y function

    # Compute solution in witch the SigmaYY is minimum
    dc = diff(expand(SigmaYY[0, 0]), c)     # Derivative SigmaYY  with respect
                                            # to c
    a1, a2 = solve(dc)                      # Get two solutions of a

    # Compute results with a = 0
    print "Parameter a has two solutions [%d, %d]\nIf a = %d:" % (a1, a2, a1)

    # Get solution of c with a = 0
    c1 = solve(diff(expand(SigmaYY[0, 0]), a), c)[0].evalf(subs={'a': a1})
    b1 = round(b.evalf(subs={'a': a1}), 8)

    # Compute sigma y with a = 0
    SigmaY1 = sqrt(SigmaYY[0, 0].evalf(subs={'a': a1, 'b': b1, 'c': c1}))
    print "SigmaXX =\n"
    pprint(Matrix(SigmaXX).evalf(subs={'c': round(c1, 4)}))
    print
    print "a = %.4f\nb = %.4f\nc = %.4f" % (a1, b1, c1)
    print "SigmaY = %.4f\n" % float(SigmaY1)

    # Compute results with a = 1
    print "If a = %d:" % a2

    # Get solution of c with a = 1
    c2 = solve(diff(expand(SigmaYY[0, 0]), a), c)[0].evalf(subs={'a': a2})
    b2 = round(b.evalf(subs={'a': a2}), 8)

    # Compute sigma y with a = 1
    SigmaY2 = sqrt(SigmaYY[0, 0].evalf(subs={'a': a2, 'b': b2, 'c': c2}))
    print "SigmaXX =\n"
    pprint(Matrix(SigmaXX).evalf(subs={'c': round(c2, 4)}))
    print
    print "a = %.4f\nb = %.4f\nc = %.4f" % (a2, b2, c2)
    print "SigmaY = %.4f" % float(SigmaY2)
示例#26
0
文件: lt.py 项目: wyom/galgebra
    def adj(self):

        self_adj = []
        self.Ga.dot_mode = '|'
        for e_j in self.Ga.basis:
            s = S(0)
            for (e_i, er_i) in zip(self.Ga.basis, self.Ga.r_basis):
                s += er_i * self.Ga.dot(e_j, self(e_i, obj=True))
            if self.Ga.is_ortho:
                self_adj.append(expand(s))
            else:
                self_adj.append(expand(s) / self.Ga.inorm)
        return Lt(self_adj, ga=self.Ga)
示例#27
0
def main():
    x, y = symbols("x y")
    print(x + y - x)
    print(x + 2 * y - 6 * x - 5 * x)

    expr = (x + x * y) / x
    print(simplify(expr))

    expr = x + y
    expr = x * expr
    print(expr)
    print(expand(expr))
    print(factor(expand(expr)))
示例#28
0
def main(argv):

    _expression = None
    _filePath = None

    try:
        opts, args = getopt.getopt(argv, "he:f:", ["help", "expression=" ,"filePath="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit(2)
        elif opt in ("-e", "--expression"):
            _expression = arg
        elif opt in ("-f", "--filePath"):
            _filePath = arg

    if _expression:
        try:
            s = normalize(_expression)
        except ValueError as errorMessage:
            print(errorMessage)
            return -1

        try:
            s = sympy.expand(s)
        except SyntaxError:
            print("Выражение не может быть приведено к стандартному виду.")
            return -2

        print(prettify(str(s)))

    if _filePath:
        with open(_filePath, 'r') as file:
            for line in file:
                try:
                    s = normalize(line)
                except ValueError as errorMessage:
                    print(errorMessage)
                else:
                    try:
                        s = sympy.expand(s)
                    except SyntaxError:
                        print("Выражение не может быть приведено к стандартному виду.")
                    else:
                        print(prettify(str(s)))

    return 0
示例#29
0
    def compute_cg(self):
        """
        Compute center of gravity
        - return a sympy array with x and y coordinates
        """
        x_cg = sum([self.g.node[n]["area"] * self.g.node[n]["ip"][0] for n in self.g.nodes()]) / sum(
            [self.g.node[n]["area"] for n in self.g.nodes()]
        )

        y_cg = sum([self.g.node[n]["area"] * self.g.node[n]["ip"][1] for n in self.g.nodes()]) / sum(
            [self.g.node[n]["area"] for n in self.g.nodes()]
        )

        return sympy.Matrix([sympy.simplify(sympy.expand(x_cg)), sympy.simplify(sympy.expand(y_cg))])
示例#30
0
for k, v in kde_map.items():
    kde_map[k.diff(t)] = v.diff(t)

# f1, f2 are forces the panes of glass exert on P1, P2 respectively
R1 = f1*B.z + C*E.x - m1*g*B.y
R2 = f2*B.z - C*E.x - m2*g*B.y

forces = [(pP1, R1), (pP2, R2)]
system = [Particle('P1', pP1, m1), Particle('P2', pP2, m2)]

partials = partial_velocities([pP1, pP2], u, A, kde_map)
Fr, _ = generalized_active_forces(partials, forces)
Fr_star, _ = generalized_inertia_forces(partials, system, kde_map)

# dynamical equations
dyn_eq = [x + y for x, y in zip(Fr, Fr_star)]
u1d, u2d, u3d = ud = [x.diff(t) for x in u]
dyn_eq_map = solve(dyn_eq, ud)

for x in ud:
    print('{0} = {1}'.format(msprint(x),
                             msprint(cancel(trigsimp(dyn_eq_map[x])))))

u1d_expected = (-g*sin(q3) + omega**2*q1*cos(q3) + u2*u3 +
                (omega**2*cos(q3)**2 + u3**2)*L*m2/(m1 + m2))
u2d_expected = -g*cos(q3) - (omega**2*q1*sin(q3) + u3*u1)
u3d_expected = -omega**2*sin(q3)*cos(q3)
assert expand(cancel(expand_trig(dyn_eq_map[u1d] - u1d_expected))) == 0
assert expand(cancel(expand_trig(dyn_eq_map[u2d] - u2d_expected))) == 0
assert expand(expand_trig(dyn_eq_map[u3d] - u3d_expected)) == 0
示例#31
0
 def expand(self):
     self.fvalue = expand(self.fvalue)
     return self
示例#32
0
def LSLF(equation, fit_par, ind_var, x_data_point, f_data_point):

    par_sym = [sy.Symbol(fit_par[k]) for k in range(len(fit_par))]
    var_sym = [sy.Symbol(ind_var[k]) for k in range(len(ind_var))]
    f = parse_expr(equation)
    f_true = sy.Symbol('f_true')

    def QE(f):
        return 1 / 2 * (f - f_true)**2

    E = QE(f)
    dE = [sy.diff(E, par_sym[k]) for k in range(len(par_sym))]
    dE_ex = [sy.expand(dE[k]) for k in range(len(par_sym))]
    dE_ex_arg = [dE_ex[k].args for k in range(len(par_sym))]

    A_sym = sy.eye(len(par_sym))
    B_sym = sy.zeros(len(par_sym), 1)
    for k in range(len(par_sym)):
        for i in range(len(dE_ex_arg[k])):
            comp = dE_ex_arg[k][i]
            kk = 0
            for l in range(len(par_sym)):
                if par_sym[l] in comp.free_symbols:
                    A_sym[k, l] = comp / par_sym[l]
                else:
                    kk = kk + 1
            if kk == len(par_sym):
                B_sym[k, 0] = -comp

    A = np.zeros(len(A_sym))
    for i in range(len(A_sym)):
        A_temp2 = 0
        for ii in range(len(x_data_point[0, :])):
            A_temp = A_sym[i]
            for k in range(len(var_sym)):
                A_temp = A_temp.subs(var_sym[k], x_data_point[k, ii])
            A_temp2 = A_temp2 + A_temp
        A[i] = np.float64(A_temp2.evalf())

    A = np.reshape(A, A_sym.shape)

    B = np.zeros(len(B_sym))
    for i in range(len(B_sym)):
        B_temp2 = 0
        for ii in range(len(x_data_point[0, :])):
            B_temp = B_sym[i]
            for k in range(len(var_sym)):
                B_temp = B_temp.subs(var_sym[k], x_data_point[k, ii])
            B_temp2 = B_temp2 + B_temp.subs(f_true, f_data_point[ii])
        B[i] = np.float64(B_temp2.evalf())

    B = np.reshape(B, B_sym.shape)

    C = np.linalg.solve(A, B)

    f_fit = np.zeros_like(f_data_point)
    for ii in range(len(f_data_point)):
        A_temp = f
        for k in range(len(par_sym)):
            A_temp = A_temp.subs(par_sym[k], C[k])
        for k in range(len(var_sym)):
            A_temp = A_temp.subs(var_sym[k], x_data_point[k, ii])
        f_fit[ii] = np.float64(A_temp.evalf())

    Err = np.linalg.norm(f_data_point - f_fit, ord=2) / np.linalg.norm(
        f_data_point, ord=2)

    return C, f_fit, Err
# -*- coding: utf-8 -*-

# Deducción de las funciones de forma del elemento de barra de 2 nodos

import sympy as sp

# Defino las variables simbólicas
u1, u2, x, x1, x2, a1, a0 = sp.symbols('u1 u2 x x1 x2 a1 a0')

r = sp.solve((sp.Eq(u1, a1*x1 + a0),
              sp.Eq(u2, a1*x2 + a0)), (a0, a1))

print('a0 = '); sp.pprint(r[a0])
print('a1 = '); sp.pprint(r[a1])

u = sp.expand(r[a1]*x + r[a0]) # Se define ahora u(x) ya que conocemos a1 y a0
u = sp.collect(u, (u1,u2))     # Se factoriza u2
print('u = '); sp.pprint(u)    # Observe aquí las funciones de forma
示例#34
0
 def generate(self):
     x = symbols('x')
     a, b, c, d, e, f = symbols('a b c d e f')
     substitutions, eqn, LQ = [], None, None
     # HCF
     if self.difficulty == 1:
         expr = expand(random.choice([
             x * (x + a),
             x * (x - a),
         ]))
         if random.random() < 0.3:
             expr *= b
         if random.random() < 0.3:
             expr *= -1
         eqn = Eq(expr, 0)
         substitutions = [
             (a, random.randint(2, 10)),
             (b, random.randint(2, 10)),
             (c, random.randint(2, 10)),
             (d, random.randint(1, 10)),
         ]
     # Cross
     elif self.difficulty == 2:
         expr = expand(
             random.choice([
                 (x + a) * (x + b),
                 (x - a) * (x + b),
                 (x + a) * (x - b),
                 (x - a) * (x - b),
             ]))
         if random.random() < 0.5:
             expr *= c
         eqn = Eq(expr, 0)
         substitutions = [
             (a, random.randint(2, 10)),
             (b, random.randint(1, 6)),
             (c, random.randint(2, 5)),
             (d, random.randint(1, 10)),
         ]
     # DOPS
     elif self.difficulty == 3:
         expr = expand(
             random.choice([
                 (x + a) * (x - a),
                 (a * x + b) * (a * x - b),
             ]))
         if random.random() < 0.3:
             expr *= c
         eqn = Eq(expr, 0)
         substitutions = [
             (a, random.randint(2, 10)),
             (b, random.randint(1, 10)),
             (c, random.randint(2, 5)),
             (d, random.randint(1, 10)),
         ]
     # Non-monic
     elif self.difficulty == 4:
         expr = expand(
             random.choice([
                 (a * x + b) * (x + d),
                 (a * x + b) * (c * x + d),
             ]))
         if random.random() < 0.3:
             expr *= a
         eqn = Eq(expr, 0)
         substitutions = [
             (a, random.randint(2, 4)),
             (b, random.randint(2, 10)),
             (c, random.randint(2, 5)),
             (d, random.randint(2, 5)),
         ]
     for old, new in substitutions:
         with evaluate(True):
             eqn = eqn.replace(old, new)
     try:
         soln = solve(eqn, x)[0], solve(eqn, x)[1]
     except IndexError:
         # no solution
         soln = 'No solution'
     a = substitutions[0][1]
     b = substitutions[1][1]
     c = substitutions[2][1]
     d = substitutions[3][1]
     Q = getPretty(eqn)
     A = getPretty(soln)
     LQ = '$\displaystyle {}$'.format(latex(eqn))
     LA = '$\displaystyle x={}, \ {}$'.format(soln[0], soln[1])
     return Q, A, LQ, LA
示例#35
0
    def setup(base,
              n=None,
              metric=None,
              coords=None,
              curv=(None, None),
              debug=False):
        """
        Generate basis of vector space as tuple of vectors and
        associated metric tensor as Matrix.  See str_array(base,n) for
        usage of base and n and str_array(metric) for usage of metric.

        To overide elements in the default metric use the character '#'
        in the metric string.  For example if one wishes the diagonal
        elements of the metric tensor to be zero enter metric = '0 #,# 0'.

        If the basis vectors are e1 and e2 then the default metric -

            Vector.metric = ((dot(e1,e1),dot(e1,e2)),dot(e2,e1),dot(e2,e2))

        becomes -

            Vector.metric = ((0,dot(e1,e2)),(dot(e2,e1),0)).

        The function dot returns a Symbol and is symmetric.

        The functions 'Bases' calculates the global quantities: -

            Vector.basis
                tuple of basis vectors
            Vector.base_to_index
                dictionary to convert base to base inded
            Vector.metric
                metric tensor represented as a matrix of symbols and numbers

        """
        Vector.is_orthogonal = False
        Vector.coords = coords
        Vector.subscripts = []
        base_name_lst = base.split(' ')

        # Define basis vectors

        if '*' in base:
            base_lst = base.split('*')
            base = base_lst[0]
            Vector.subscripts = base_lst[1].split('|')
            base_name_lst = []
            for subscript in Vector.subscripts:
                base_name_lst.append(base + '_' + subscript)
        else:
            if len(base_name_lst) > 1:
                Vector.subscripts = []
                for base_name in base_name_lst:
                    tmp = base_name.split('_')
                    Vector.subscripts.append(tmp[-1])
            elif len(base_name_lst) == 1 and Vector.coords is not None:
                base_name_lst = []
                for coord in Vector.coords:
                    Vector.subscripts.append(str(coord))
                    base_name_lst.append(base + '_' + str(coord))
            else:
                raise TypeError("'%s' does not define basis vectors" % base)

        basis = []
        base_to_index = {}
        index = 0
        for base_name in base_name_lst:
            basis_vec = Vector(base_name)
            basis.append(basis_vec)
            base_to_index[basis_vec.obj] = index
            index += 1

        Vector.base_to_index = base_to_index
        Vector.basis = tuple(basis)

        # define metric tensor

        default_metric = []
        for bv1 in Vector.basis:
            row = []
            for bv2 in Vector.basis:
                row.append(Vector.basic_dot(bv1, bv2))
            default_metric.append(row)
        Vector.metric = Matrix(default_metric)
        if metric is not None:
            if metric[0] == '[' and metric[-1] == ']':
                Vector.is_orthogonal = True
                metric_str_lst = metric[1:-1].split(',')
                Vector.metric = []
                for g_ii in metric_str_lst:
                    Vector.metric.append(S(g_ii))
                Vector.metric = Matrix(Vector.metric)
            else:
                metric_str_lst = flatten(str_array(metric))
                for index in range(len(metric_str_lst)):
                    if metric_str_lst[index] != '#':
                        Vector.metric[index] = S(metric_str_lst[index])

        Vector.metric_dict = {}  # Used to calculate dot product
        N = range(len(Vector.basis))
        if Vector.is_orthogonal:
            for ii in N:
                Vector.metric_dict[Vector.basis[ii].obj] = Vector.metric[ii]
        else:
            for irow in N:
                for icol in N:
                    Vector.metric_dict[(
                        Vector.basis[irow].obj,
                        Vector.basis[icol].obj)] = Vector.metric[irow, icol]

        # calculate tangent vectors and metric for curvilinear basis

        if curv != (None, None):
            X = S.Zero
            for (coef, base) in zip(curv[0], Vector.basis):
                X += coef * base.obj
            Vector.tangents = []
            for (coord, norm) in zip(Vector.coords, curv[1]):
                tau = diff(X, coord)
                tau = trigsimp(tau)
                tau /= norm
                tau = expand(tau)
                Vtau = Vector()
                Vtau.obj = tau
                Vector.tangents.append(Vtau)
            metric = []
            for tv1 in Vector.tangents:
                row = []
                for tv2 in Vector.tangents:
                    row.append(tv1 * tv2)
                metric.append(row)
            metric = Matrix(metric)
            metric = metric.applyfunc(TrigSimp)
            Vector.metric_dict = {}
            if metric.is_diagonal:
                Vector.is_orthogonal = True
                tmp_metric = []
                for ii in N:
                    tmp_metric.append(metric[ii, ii])
                    Vector.metric_dict[Vector.basis[ii].obj] = metric[ii, ii]
                Vector.metric = Matrix(tmp_metric)
            else:
                Vector.is_orthogonal = False
                Vector.metric = metric
                for irow in N:
                    for icol in N:
                        Vector.metric_dict[(
                            Vector.basis[irow].obj,
                            Vector.basis[icol].obj)] = Vector.metric[irow,
                                                                     icol]
            Vector.norm = curv[1]

            if debug:
                oprint('Tangent Vectors',
                       Vector.tangents,
                       'Metric',
                       Vector.metric,
                       'Metric Dictionary',
                       Vector.metric_dict,
                       'Normalization',
                       Vector.norm,
                       dict_mode=True)

            # calculate derivatives of tangent vectors

            Vector.dtau_dict = None
            dtau_dict = {}

            for x in Vector.coords:
                for (tau, base) in zip(Vector.tangents, Vector.basis):
                    dtau = tau.diff(x).applyfunc(TrigSimp)
                    result = S.Zero
                    for (t, b) in zip(Vector.tangents, Vector.basis):
                        t_dtau = TrigSimp(t * dtau)
                        result += t_dtau * b.obj
                    dtau_dict[(base.obj, x)] = result

            Vector.dtau_dict = dtau_dict

            if debug:
                oprint('Basis Derivatives', Vector.dtau_dict, dict_mode=True)

        return tuple(Vector.basis)
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)
示例#37
0
def getPolynomialCoefficient(coordinates):
    x, y, a = sympy.symbols('x, y, a')

    numberOfPoints = len(coordinates)
    setOfPoints = {}

    #Creates a dictionary setOfPoints of the form
    #  {0: [[1,1], [2,0], [3,0], [4,0]], 1: [[1,0], [2,8], [3,0], [4,0]], 2: ...}
    for i in range(0, numberOfPoints):
        for j in range(0, numberOfPoints):
            if (j == i):
                setOfPoints[i] = setOfPoints.get(
                    i, []) + [[coordinates[i][0], coordinates[i][1]]]
            elif (j != i):
                setOfPoints[i] = setOfPoints.get(i,
                                                 []) + [[coordinates[j][0], 0]]

    #Creates a polynomial for each of the coordinates of the previous dictionary where y is non-zero,
    #subs in the other coordinate to find the constant a
    setOfEquations = {}
    setOfSubbedEquations = {}
    for i in range(0, len(setOfPoints)):
        #print ""
        #print "setOfPoints[{0}]: {1}".format(i, setOfPoints[i])

        setOfEquations[i] = a
        for j in range(0, len(setOfPoints[i])):
            #Constructs initial polynomial
            if (setOfPoints[i][j][1] == 0):
                setOfEquations[i] = setOfEquations[i] * (x -
                                                         setOfPoints[i][j][0])

        #print ""
        #print "setOfPoints[{0}]: {1}".format(i, setOfPoints[i])
        #print "setOfEquations[{0}]: {1}".format(i, setOfEquations[i])

        allZeroBoolean = True
        for j in range(0, len(setOfPoints[i])):
            if (setOfPoints[i][j][1] != 0):
                allZeroBoolean = False
                break
            else:
                continue

        if (allZeroBoolean):
            setOfSubbedEquations[i] = 0 * x
        else:
            #Subs in the non-zero coordinates
            unSubbedEquation = sympy.Eq(y, setOfEquations[i])
            subbedEquation = unSubbedEquation.subs([(y, setOfPoints[i][i][1]),
                                                    (x, setOfPoints[i][i][0])])
            #Solves each polynomial to find the constant a, and subs into the final set
            solutionForA = sympy.solve(subbedEquation, a)[0]
            setOfSubbedEquations[i] = setOfEquations[i].subs(a, solutionForA)
            #print "solutionForA:", solutionForA

        #print "setOfSubbedEquations[{0}]: {1}".format(i, setOfSubbedEquations[i])

    summedEquations = sum(setOfSubbedEquations.itervalues())
    #print ""
    #print "setOfSubbedEquations:", setOfSubbedEquations
    #print "summedEquations:", summedEquations

    #Sums each polynomial and expands it into a simpler form
    finalPolynomial = sympy.expand(summedEquations)

    coefficients = sympy.Poly(finalPolynomial, x).coeffs()
    constant = coefficients[len(coefficients) - 1]
    moddedConstant = constant % MODULUS

    print "finalPolynomial:", finalPolynomial
    return moddedConstant
import sympy as sym
from sympy import symbols
from xlrd import open_workbook
from sympy.plotting import plot
from sympy.plotting import plot3d
# Exercise 1 ___________________________________________________

x = sym.symbols('x')
y, i, n, a, b, z = sym.symbols('y i n a b z')

# a)
expr = x**2 + x**3 + 21 * x**4 + 10 * x + 1
print(expr.subs(x, 7))

# b)
print(sym.expand((x + y)**2))

#c)
simp = 4 * x**3 + 21 * x**2 + 10 * x + 12
print(sym.simplify(simp))

#d

#e)
print(sym.summation(2 * i + i - 1, (i, 5, n)))

#f
print(sym.integrate(sin(x) + exp(x) * cos(x) + tan(x), x))

#g
print(sym.factor(x**3 + 12 * x * y * z + 3 * y**2 * z))
示例#39
0
 def _check(expr, simplified, deep=True, matrix=True):
     assert nc_simplify(expr, deep=deep) == simplified
     assert expand(expr) == expand(simplified)
     if matrix:
         m_simp = _to_matrix(simplified).doit(inv_expand=False)
         assert nc_simplify(_to_matrix(expr), deep=deep) == m_simp
示例#40
0
#centroid ==> the intersection of asympotoes with the real-axis
centroid = ny.real(poles_summation / asymptotes)
plt.plot(centroid, 0, 'ro')
print("Centroid: ", end="")
print(centroid)
for angle in angles:
    endX = 72 * math.cos(angle) + centroid
    endY = 72 * math.sin(angle)
    asmX = [centroid, endX]
    asm_Y = [0, endY]
    plt.plot(asmX, asm_Y, '--', lineWidth=1)
s = sy.symbols('s')
eq = 1
for i in range(len(poles)):
    eq *= (s - complex(poles[i][0], poles[i][1]))
eq = sy.expand(eq)
print("Characteristic Equation: ", end="")
print(eq)
expDiff = sy.Derivative(eq, s).doit()
print("Derivative of the Characteristic Equation: ", end="")
print(expDiff)
roots = sy.solve(expDiff, s)
print("Roots of the Derivative of the Characteristic Equation: ", end="")
print(roots)
realPoles = []
for i in range(len(poles)):
    if poles[i][1] == 0:
        realPoles.append(poles[i][0])
realPoles.sort()
realPoles.reverse()
break_away_points = []
display(h)

# h.subs(x,2) dersem x yerine 2 yazar ve bize sonucu verir
# h.subs(x,z) dersem x yerine z yazar ve bize z türünden sonucu verir

print("H Fonksiyoun sonucu: " + str(h.subs(x, 1.5)))
display(h.subs(x, z))

#sp.simplify(h) idafeyi sadeleştirir.
h = (x**2 - x - 6) / (x**2 - 3 * x)
#print(h.simplify(1)) tercihi kullanım aşağıda
print(sp.simplify(h))

# Verilen Çarpmım ifadesini açar  sp.expand(f)
f = (x + 1)**3 * (x - 2)**2
display(sp.expand(f))

# sp.factor(f)  Dağıtılmış şeklinde verilen ifadeyi çarpanlara ayırır.
f = 3 * x**4 - 36 * x**3 + 99 * x**2 - 6 * x - 144
display(f)
display("ÇARPANLARA AYRILMIŞ HALİ: ", sp.factor(f))

# Örnek: x + x**2/2 + x**3/3 + x**4/4 + .... x**n/n
x = sp.Symbol('x')
# simdilik n = 10 olsun
n = 10
series = x
for i in range(2, n + 1):
    series = series + (x**i) / i
display(series)
sonuc = float(series.subs(x, 2))
示例#42
0
#PROCEDIMIENTO

n = len(xi)
x = sym.Symbol('x')
polinomio = 0
for i in range(0,n,1):
	numerador = 1 
	denominador = 1
	for j in range(0,n,1):
		if (i!=j):
			numerador = numerador*(x-xi[j])
			denominador = denominador*(xi[i]-xi[j])
		termino = (numerador/denominador)*fi[i]
	polinomio = polinomio + termino
polisimple = sym.expand(polinomio)

px = sym.lambdify(x,polinomio)

#VECTORES PARA GRAFICAS

muestras = 51
a = np.min(xi)
b = np.max(xi)
p_xi = np.linspace(a,b,muestras)
pfi = px(p_xi)

#SALIDA

print('polinomio: ')
print(polinomio)
示例#43
0
prob:
max f(x1,x2) = -(x1-2)^2-x1-x2^2
begin at the point (2.5,1.5) 
"""
import sympy as sp

point = [2.5, 1.5]
x1, x2, t0 = sp.symbols("x1 x2 t0")
x = [x1, x2]
f_expr = -(x1 - 2)**2 - x1 - x2**2
f_gradient = [sp.diff(f_expr, x1), sp.diff(f_expr, x2)]
print("f_gradient:", f_gradient)
f_gradient_value = [f_gradient[i].subs(x[i], point[i]) for i in range(2)]
print('gradient:', f_gradient_value)
while f_gradient_value != [0, 0]:

    point = [(x[i] + f_gradient_value[i] * t0).subs([(x1, point[0]),
                                                     (x2, point[1])])
             for i in range(2)]
    f_t0 = sp.expand(f_expr.subs([(x1, point[0]), (x2, point[1])]))
    t0_value = sp.solve(sp.diff(f_t0, t0), t0)
    points = [point[i].subs(t0, t0_value[0]) for i in range(2)]
    f_gradient_value = [f_gradient[i].subs(x[i], points[i]) for i in range(2)]
    print("point:", points)
    print("gradient:", f_gradient_value)

f_gradient: [-2 * x1 + 3, -2 * x2]
gradient: [-2.0, -3.0]
point: [1.5, 0]
gradient: [0, 0]
示例#44
0
def noneuclidian_distance_calculation():
    from sympy import solve,sqrt

    metric = '0 # #,# 0 #,# # 1'
    (X,Y,e) = MV.setup('X Y e',metric)

    print('g_{ij} =',MV.metric)

    print('(X^Y)**2 =',(X^Y)*(X^Y))

    L = X^Y^e
    B = L*e # D&L 10.152
    print('B =',B)
    Bsq = B*B
    print('B**2 =',Bsq)
    Bsq = Bsq.scalar()
    print('#L = X^Y^e is a non-euclidian line')
    print('B = L*e =',B)

    BeBr =B*e*B.rev()
    print('B*e*B.rev() =',BeBr)
    print('B**2 =',B*B)
    print('L**2 =',L*L) # D&L 10.153
    (s,c,Binv,M,S,C,alpha,XdotY,Xdote,Ydote) = symbols('s c (1/B) M S C alpha (X.Y) (X.e) (Y.e)')

    Bhat = Binv*B # D&L 10.154
    R = c+s*Bhat # Rotor R = exp(alpha*Bhat/2)
    print('s = sinh(alpha/2) and c = cosh(alpha/2)')
    print('exp(alpha*B/(2*|B|)) =',R)

    Z = R*X*R.rev() # D&L 10.155
    Z.obj = expand(Z.obj)
    Z.obj = Z.obj.collect([Binv,s,c,XdotY])
    Z.Fmt(3,'R*X*R.rev()')
    W = Z|Y # Extract scalar part of multivector
    # From this point forward all calculations are with sympy scalars
    print('Objective is to determine value of C = cosh(alpha) such that W = 0')
    W = W.scalar()
    print('Z|Y =',W)
    W = expand(W)
    W = simplify(W)
    W = W.collect([s*Binv])

    M = 1/Bsq
    W = W.subs(Binv**2,M)
    W = simplify(W)
    Bmag = sqrt(XdotY**2-2*XdotY*Xdote*Ydote)
    W = W.collect([Binv*c*s,XdotY])

    #Double angle substitutions

    W = W.subs(2*XdotY**2-4*XdotY*Xdote*Ydote,2/(Binv**2))
    W = W.subs(2*c*s,S)
    W = W.subs(c**2,(C+1)/2)
    W = W.subs(s**2,(C-1)/2)
    W = simplify(W)
    W = W.subs(1/Binv,Bmag)
    W = expand(W)

    print('S = sinh(alpha) and C = cosh(alpha)')

    print('W =',W)

    Wd = collect(W,[C,S],exact=True,evaluate=False)

    Wd_1 = Wd[ONE]
    Wd_C = Wd[C]
    Wd_S = Wd[S]

    print('Scalar Coefficient =',Wd_1)
    print('Cosh Coefficient =',Wd_C)
    print('Sinh Coefficient =',Wd_S)

    print('|B| =',Bmag)
    Wd_1 = Wd_1.subs(Bmag,1/Binv)
    Wd_C = Wd_C.subs(Bmag,1/Binv)
    Wd_S = Wd_S.subs(Bmag,1/Binv)

    lhs = Wd_1+Wd_C*C
    rhs = -Wd_S*S
    lhs = lhs**2
    rhs = rhs**2
    W = expand(lhs-rhs)
    W = expand(W.subs(1/Binv**2,Bmag**2))
    W = expand(W.subs(S**2,C**2-1))
    W = W.collect([C,C**2],evaluate=False)

    a = simplify(W[C**2])
    b = simplify(W[C])
    c = simplify(W[ONE])

    print('Require a*C**2+b*C+c = 0')

    print('a =',a)
    print('b =',b)
    print('c =',c)

    x = Symbol('x')
    C =  solve(a*x**2+b*x+c,x)[0]
    print('cosh(alpha) = C = -b/(2*a) =',expand(simplify(expand(C))))
    return
 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)
示例#46
0
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\\cdot e1)/E^{2} =', simplify(w / Esq))
w = (E2 | e2)
w = (w.expand()).scalar()
print('%(E2\\cdot e2)/E^{2} =', simplify(w / Esq))
w = (E3 | e3)
w = (w.expand()).scalar()
print('%(E3\\cdot e3)/E^{2} =', simplify(w / Esq))
xpdf(paper='letter', prog=True)
示例#47
0
def test_expand_function():
    assert expand(x+y) == x + y
    assert expand(x+y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y)
    assert expand((x + y)**11, modulus=11) == x**11 + y**11
示例#48
0
#動点P1,P2がそれぞれC1,C2上を一定の速さで反時計回りに回転している.
#時刻t=0でO,A,P1,P2がこの順に一直線上に並び,また,P1の角速度はP2の2倍とする.
#△A P1 P2 の面積の最大値を求めよ.
###########################################################################
import sympy

#P2の角度をΘ(Θ>0)として,ベクトルAP1とAP2を定義
theta = sympy.Symbol('theta', positive=True)
AP1 = [5 * sympy.cos(2 * theta) - 2, 5 * sympy.sin(2 * theta)]
AP2 = [10 * sympy.cos(theta) - 2, 10 * sympy.sin(theta)]

#△A P1 P2 の面積(後で絶対値を取る)
S = (AP1[0] * AP2[1] - AP1[1] * AP2[0]) / 2

#三角関数を展開して,2ΘをΘで書き換え
S = sympy.expand(S, trig=True)

#SをΘで微分
dS = sympy.diff(S, theta)

#dS=0を解いて,解の候補として,Sが極値を取るときの0を求める
cand = sympy.solve(sympy.diff(S, theta))

#候補についてSを計算し(ここで絶対値を取る),Sの最大値とその時のΘを求める
S_max = 0.0
max_theta = []
for value in cand:
    tmp = float(abs(S.subs(theta, value)))
    if (tmp >= S_max):
        if (tmp > S_max):
            S_max = tmp
示例#49
0
文件: sequences.py 项目: msgoff/sympy
    def find_linear_recurrence(self, n, d=None, gfvar=None):
        r"""
        Finds the shortest linear recurrence that satisfies the first n
        terms of sequence of order `\leq` n/2 if possible.
        If d is specified, find shortest linear recurrence of order
        `\leq` min(d, n/2) if possible.
        Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
        recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
        Returns ``[]`` if no recurrence is found.
        If gfvar is specified, also returns ordinary generating function as a
        function of gfvar.

        Examples
        ========

        >>> from sympy import sequence, sqrt, oo, lucas
        >>> from sympy.abc import n, x, y
        >>> sequence(n**2).find_linear_recurrence(10, 2)
        []
        >>> sequence(n**2).find_linear_recurrence(10)
        [3, -3, 1]
        >>> sequence(2**n).find_linear_recurrence(10)
        [2]
        >>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
        [5, -10, 10, -5, 1]
        >>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
        [1, 1]
        >>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
        [1/2, 1/2]
        >>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
        ([6, -5], 3*(5 - 21*x)/((x - 1)*(5*x - 1)))
        >>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
        ([1, 1], (x - 2)/(x**2 + x - 1))
        """
        from sympy.matrices import Matrix

        x = [simplify(expand(t)) for t in self[:n]]
        lx = len(x)
        if d is None:
            r = lx // 2
        else:
            r = min(d, lx // 2)
        coeffs = []
        for l in range(1, r + 1):
            l2 = 2 * l
            mlist = []
            for k in range(l):
                mlist.append(x[k:k + l])
            m = Matrix(mlist)
            if m.det() != 0:
                y = simplify(m.LUsolve(Matrix(x[l:l2])))
                if lx == l2:
                    coeffs = flatten(y[::-1])
                    break
                mlist = []
                for k in range(l, lx - l):
                    mlist.append(x[k:k + l])
                m = Matrix(mlist)
                if m * y == Matrix(x[l2:]):
                    coeffs = flatten(y[::-1])
                    break
        if gfvar is None:
            return coeffs
        else:
            l = len(coeffs)
            if l == 0:
                return [], None
            else:
                n, d = x[l - 1] * gfvar**(l - 1), 1 - coeffs[l - 1] * gfvar**l
                for i in range(l - 1):
                    n += x[i] * gfvar**i
                    for j in range(l - i - 1):
                        n -= coeffs[i] * x[j] * gfvar**(i + j + 1)
                    d -= coeffs[i] * gfvar**(i + 1)
                return coeffs, simplify(factor(n) / factor(d))
from sympy import Symbol 
from sympy import expand
from sympy import pprint
from sympy import factor
x = Symbol('x')
y = Symbol('y')

print(factor(expr))
factors = factor(expr)
expand = expand(factors)
print(factors,expand)
expr = x**3 + 3*x**2*y + 3*x*y**2 + y**3
factors = factor(expr)
print(factors)
pprint(factors)

x = Symbol('x')
series = x
n = 5
for i in range(2, n+1):
    series = series + (x**i)/i
pprint(series)

expr = x*x + x*y + x*y + y*y
res = expr.subs({x:1,y:2})
print(res)
r = expr.subs({x:1-y})
print(r)

x = Symbol('x')
series = x
示例#51
0
 def generator(self):
     x = sympy.symbols("x")
     self.expression = sympy.expand(self.a * (x + self.h)**2 + self.k)
示例#52
0
文件: sequences.py 项目: msgoff/sympy
 def expand(self, *args, **kwargs):
     return SeqFormula(expand(self.formula, *args, **kwargs), self.args[1])
示例#53
0
                    g = int(u[1])

                    gg = lis[g]

                    ui[ii] = gg
                ii += 1

            user_input = ' '.join(map(str, ui))

# condition that handles symbolic computation
        if any(x in user_input for x in syms):
            if not any(x in user_input for x in mychar_n) and len(neg) == 0:
                if 'expand' in user_input:
                    user_input = user_input.replace('expand', '')

                    lis.append(sym.expand(user_input))
                    print(
                        str(len(lis) - 1) + ': ' + str(sym.expand(user_input)))

                else:
                    li = eval(str(user_input))

                    lis.append(li)
                    print(str(len(lis) - 1) + ': ' + str(li))

# condition that handles basic arithmetic
        else:
            if (x in user_input for x in bsop) and not any(
                    x in user_input for x in mychar) and len(neg) == 0:
                li = eval(user_input)
                if user_input.count('/') > 1:
示例#54
0
def test_Abs():
    raises(TypeError, lambda: Abs(Interval(2, 3)))  # issue 8717

    x, y = symbols('x,y')
    assert sign(sign(x)) == sign(x)
    assert sign(x*y).func is sign
    assert Abs(0) == 0
    assert Abs(1) == 1
    assert Abs(-1) == 1
    assert Abs(I) == 1
    assert Abs(-I) == 1
    assert Abs(nan) is nan
    assert Abs(zoo) is oo
    assert Abs(I * pi) == pi
    assert Abs(-I * pi) == pi
    assert Abs(I * x) == Abs(x)
    assert Abs(-I * x) == Abs(x)
    assert Abs(-2*x) == 2*Abs(x)
    assert Abs(-2.0*x) == 2.0*Abs(x)
    assert Abs(2*pi*x*y) == 2*pi*Abs(x*y)
    assert Abs(conjugate(x)) == Abs(x)
    assert conjugate(Abs(x)) == Abs(x)
    assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)

    a = Symbol('a', positive=True)
    assert Abs(2*pi*x*a) == 2*pi*a*Abs(x)
    assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x)

    x = Symbol('x', real=True)
    n = Symbol('n', integer=True)
    assert Abs((-1)**n) == 1
    assert x**(2*n) == Abs(x)**(2*n)
    assert Abs(x).diff(x) == sign(x)
    assert abs(x) == Abs(x)  # Python built-in
    assert Abs(x)**3 == x**2*Abs(x)
    assert Abs(x)**4 == x**4
    assert (
        Abs(x)**(3*n)).args == (Abs(x), 3*n)  # leave symbolic odd unchanged
    assert (1/Abs(x)).args == (Abs(x), -1)
    assert 1/Abs(x)**3 == 1/(x**2*Abs(x))
    assert Abs(x)**-3 == Abs(x)/(x**4)
    assert Abs(x**3) == x**2*Abs(x)
    assert Abs(I**I) == exp(-pi/2)
    assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4)))
    y = Symbol('y', real=True)
    assert Abs(I**y) == 1
    y = Symbol('y')
    assert Abs(I**y) == exp(-pi*im(y)/2)

    x = Symbol('x', imaginary=True)
    assert Abs(x).diff(x) == -sign(x)

    eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
    # if there is a fast way to know when you can and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert abs(eq).func is Abs or abs(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert abs(d).func is Abs or abs(d) == 0

    assert Abs(4*exp(pi*I/4)) == 4
    assert Abs(3**(2 + I)) == 9
    assert Abs((-3)**(1 - I)) == 3*exp(pi)

    assert Abs(oo) is oo
    assert Abs(-oo) is oo
    assert Abs(oo + I) is oo
    assert Abs(oo + I*oo) is oo

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False
    assert Abs(x).fdiff() == sign(x)
    raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))

    # doesn't have recursion error
    arg = sqrt(acos(1 - I)*acos(1 + I))
    assert abs(arg) == arg

    # special handling to put Abs in denom
    assert abs(1/x) == 1/Abs(x)
    e = abs(2/x**2)
    assert e.is_Mul and e == 2/Abs(x**2)
    assert unchanged(Abs, y/x)
    assert unchanged(Abs, x/(x + 1))
    assert unchanged(Abs, x*y)
    p = Symbol('p', positive=True)
    assert abs(x/p) == abs(x)/p

    # coverage
    assert unchanged(Abs, Symbol('x', real=True)**y)
示例#55
0
def test_sign():
    assert sign(1.2) == 1
    assert sign(-1.2) == -1
    assert sign(3*I) == I
    assert sign(-3*I) == -I
    assert sign(0) == 0
    assert sign(nan) == nan
    assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4
    assert sign(2 + 3*I).simplify() == sign(2 + 3*I)
    assert sign(2 + 2*I).simplify() == sign(1 + I)
    assert sign(im(sqrt(1 - sqrt(3)))) == 1
    assert sign(sqrt(1 - sqrt(3))) == I

    x = Symbol('x')
    assert sign(x).is_bounded is True
    assert sign(x).is_complex is True
    assert sign(x).is_imaginary is None
    assert sign(x).is_integer is None
    assert sign(x).is_real is None
    assert sign(x).is_zero is None
    assert sign(x).doit() == sign(x)
    assert sign(1.2*x) == sign(x)
    assert sign(2*x) == sign(x)
    assert sign(I*x) == I*sign(x)
    assert sign(-2*I*x) == -I*sign(x)
    assert sign(conjugate(x)) == conjugate(sign(x))

    p = Symbol('p', positive=True)
    n = Symbol('n', negative=True)
    m = Symbol('m', negative=True)
    assert sign(2*p*x) == sign(x)
    assert sign(n*x) == -sign(x)
    assert sign(n*m*x) == sign(x)

    x = Symbol('x', imaginary=True)
    assert sign(x).is_imaginary is True
    assert sign(x).is_integer is False
    assert sign(x).is_real is False
    assert sign(x).is_zero is False
    assert sign(x).diff(x) == 2*DiracDelta(-I*x)
    assert sign(x).doit() == x / Abs(x)
    assert conjugate(sign(x)) == -sign(x)

    x = Symbol('x', real=True)
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is None
    assert sign(x).diff(x) == 2*DiracDelta(x)
    assert sign(x).doit() == sign(x)
    assert conjugate(sign(x)) == sign(x)

    x = Symbol('x', nonzero=True)
    assert sign(x).is_imaginary is None
    assert sign(x).is_integer is None
    assert sign(x).is_real is None
    assert sign(x).is_zero is False
    assert sign(x).doit() == x / Abs(x)
    assert sign(Abs(x)) == 1
    assert Abs(sign(x)) == 1

    x = Symbol('x', positive=True)
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is False
    assert sign(x).doit() == x / Abs(x)
    assert sign(Abs(x)) == 1
    assert Abs(sign(x)) == 1

    x = 0
    assert sign(x).is_imaginary is False
    assert sign(x).is_integer is True
    assert sign(x).is_real is True
    assert sign(x).is_zero is True
    assert sign(x).doit() == 0
    assert sign(Abs(x)) == 0
    assert Abs(sign(x)) == 0

    nz = Symbol('nz', nonzero=True, integer=True)
    assert sign(nz).is_imaginary is False
    assert sign(nz).is_integer is True
    assert sign(nz).is_real is True
    assert sign(nz).is_zero is False
    assert sign(nz)**2 == 1
    assert (sign(nz)**3).args == (sign(nz), 3)

    assert sign(Symbol('x', nonnegative=True)).is_nonnegative
    assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
    assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
    assert sign(Symbol('x', nonpositive=True)).is_nonpositive
    assert sign(Symbol('x', real=True)).is_nonnegative is None
    assert sign(Symbol('x', real=True)).is_nonpositive is None
    assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None

    x, y = Symbol('x', real=True), Symbol('y')
    assert sign(x).rewrite(Piecewise) == \
        Piecewise((1, x > 0), (-1, x < 0), (0, True))
    assert sign(y).rewrite(Piecewise) == sign(y)

    # evaluate what can be evaluated
    assert sign(exp_polar(I*pi)*pi) is S.NegativeOne

    eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
    # if there is a fast way to know when and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert sign(eq).func is sign or sign(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert sign(d).func is sign or sign(d) == 0
def test_minimal_polynomial():
    assert minimal_polynomial(-7, x) == x + 7
    assert minimal_polynomial(-1, x) == x + 1
    assert minimal_polynomial(0, x) == x
    assert minimal_polynomial(1, x) == x - 1
    assert minimal_polynomial(7, x) == x - 7

    assert minimal_polynomial(sqrt(2), x) == x**2 - 2
    assert minimal_polynomial(sqrt(5), x) == x**2 - 5
    assert minimal_polynomial(sqrt(6), x) == x**2 - 6

    assert minimal_polynomial(2 * sqrt(2), x) == x**2 - 8
    assert minimal_polynomial(3 * sqrt(5), x) == x**2 - 45
    assert minimal_polynomial(4 * sqrt(6), x) == x**2 - 96

    assert minimal_polynomial(2 * sqrt(2) + 3, x) == x**2 - 6 * x + 1
    assert minimal_polynomial(3 * sqrt(5) + 6, x) == x**2 - 12 * x - 9
    assert minimal_polynomial(4 * sqrt(6) + 7, x) == x**2 - 14 * x - 47

    assert minimal_polynomial(2 * sqrt(2) - 3, x) == x**2 + 6 * x + 1
    assert minimal_polynomial(3 * sqrt(5) - 6, x) == x**2 + 12 * x - 9
    assert minimal_polynomial(4 * sqrt(6) - 7, x) == x**2 + 14 * x - 47

    assert minimal_polynomial(sqrt(1 + sqrt(6)), x) == x**4 - 2 * x**2 - 5
    assert minimal_polynomial(sqrt(I + sqrt(6)), x) == x**8 - 10 * x**4 + 49

    assert minimal_polynomial(2 * I + sqrt(2 + I),
                              x) == x**4 + 4 * x**2 + 8 * x + 37

    assert minimal_polynomial(sqrt(2) + sqrt(3), x) == x**4 - 10 * x**2 + 1
    assert minimal_polynomial(sqrt(2) + sqrt(3) + sqrt(6),
                              x) == x**4 - 22 * x**2 - 48 * x - 23

    a = 1 - 9 * sqrt(2) + 7 * sqrt(3)

    assert minimal_polynomial(
        1 / a, x) == 392 * x**4 - 1232 * x**3 + 612 * x**2 + 4 * x - 1
    assert minimal_polynomial(
        1 / sqrt(a), x) == 392 * x**8 - 1232 * x**6 + 612 * x**4 + 4 * x**2 - 1

    raises(NotAlgebraic, lambda: minimal_polynomial(oo, x))
    raises(NotAlgebraic, lambda: minimal_polynomial(2**y, x))
    raises(NotAlgebraic, lambda: minimal_polynomial(sin(1), x))

    assert minimal_polynomial(sqrt(2)).dummy_eq(x**2 - 2)
    assert minimal_polynomial(sqrt(2), x) == x**2 - 2

    assert minimal_polynomial(sqrt(2), polys=True) == Poly(x**2 - 2)
    assert minimal_polynomial(sqrt(2), x, polys=True) == Poly(x**2 - 2)
    assert minimal_polynomial(sqrt(2), x, polys=True,
                              compose=False) == Poly(x**2 - 2)

    a = AlgebraicNumber(sqrt(2))
    b = AlgebraicNumber(sqrt(3))

    assert minimal_polynomial(a, x) == x**2 - 2
    assert minimal_polynomial(b, x) == x**2 - 3

    assert minimal_polynomial(a, x, polys=True) == Poly(x**2 - 2)
    assert minimal_polynomial(b, x, polys=True) == Poly(x**2 - 3)

    assert minimal_polynomial(sqrt(a / 2 + 17),
                              x) == 2 * x**4 - 68 * x**2 + 577
    assert minimal_polynomial(sqrt(b / 2 + 17),
                              x) == 4 * x**4 - 136 * x**2 + 1153

    a, b = sqrt(2) / 3 + 7, AlgebraicNumber(sqrt(2) / 3 + 7)

    f = 81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 - \
        31608*x**2 - 189648*x + 141358

    assert minimal_polynomial(sqrt(a) + sqrt(sqrt(a)), x) == f
    assert minimal_polynomial(sqrt(b) + sqrt(sqrt(b)), x) == f

    assert minimal_polynomial(a**Q(3, 2),
                              x) == 729 * x**4 - 506898 * x**2 + 84604519

    # issue 5994
    eq = S('''
        -1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
        sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
        sqrt(15)*I/28800000)**(1/3)))''')
    assert minimal_polynomial(eq, x) == 8000 * x**2 - 1

    ex = 1 + sqrt(2) + sqrt(3)
    mp = minimal_polynomial(ex, x)
    assert mp == x**4 - 4 * x**3 - 4 * x**2 + 16 * x - 8

    ex = 1 / (1 + sqrt(2) + sqrt(3))
    mp = minimal_polynomial(ex, x)
    assert mp == 8 * x**4 - 16 * x**3 + 4 * x**2 + 4 * x - 1

    p = (expand((1 + sqrt(2) - 2 * sqrt(3) + sqrt(7))**3))**Rational(1, 3)
    mp = minimal_polynomial(p, x)
    assert mp == x**8 - 8 * x**7 - 56 * x**6 + 448 * x**5 + 480 * x**4 - 5056 * x**3 + 1984 * x**2 + 7424 * x - 3008
    p = expand((1 + sqrt(2) - 2 * sqrt(3) + sqrt(7))**3)
    mp = minimal_polynomial(p, x)
    assert mp == x**8 - 512 * x**7 - 118208 * x**6 + 31131136 * x**5 + 647362560 * x**4 - 56026611712 * x**3 + 116994310144 * x**2 + 404854931456 * x - 27216576512

    assert minimal_polynomial(S("-sqrt(5)/2 - 1/2 + (-sqrt(5)/2 - 1/2)**2"),
                              x) == x - 1
    a = 1 + sqrt(2)
    assert minimal_polynomial((a * sqrt(2) + a)**3, x) == x**2 - 198 * x + 1

    p = 1 / (1 + sqrt(2) + sqrt(3))
    assert minimal_polynomial(
        p, x, compose=False) == 8 * x**4 - 16 * x**3 + 4 * x**2 + 4 * x - 1

    p = 2 / (1 + sqrt(2) + sqrt(3))
    assert minimal_polynomial(
        p, x, compose=False) == x**4 - 4 * x**3 + 2 * x**2 + 4 * x - 2

    assert minimal_polynomial(1 + sqrt(2) * I, x,
                              compose=False) == x**2 - 2 * x + 3
    assert minimal_polynomial(1 / (1 + sqrt(2)) + 1, x,
                              compose=False) == x**2 - 2
    assert minimal_polynomial(sqrt(2) * I + I * (1 + sqrt(2)),
                              x,
                              compose=False) == x**4 + 18 * x**2 + 49

    # minimal polynomial of I
    assert minimal_polynomial(I, x, domain=QQ.algebraic_field(I)) == x - I
    K = QQ.algebraic_field(I * (sqrt(2) + 1))
    assert minimal_polynomial(I, x, domain=K) == x - I
    assert minimal_polynomial(I, x, domain=QQ) == x**2 + 1
    assert minimal_polynomial(I, x, domain='QQ(y)') == x**2 + 1
示例#57
0
def regression(equation,
               fit_par,
               ind_var,
               x_data_point,
               f_data_point,
               mode,
               add_par=[None, None]):

    par_sym = [sy.Symbol(fit_par[k]) for k in range(len(fit_par))]
    var_sym = [sy.Symbol(ind_var[k]) for k in range(len(ind_var))]
    f = parse_expr(equation)
    f_ex = sy.expand(f)
    f_args = f_ex.args

    a_sym = sy.zeros(1, len(par_sym))
    for i in range(len(f_args)):
        comp = f_args[i]
        for l in range(len(par_sym)):
            if par_sym[l] in comp.free_symbols:
                a_sym[l] = comp / par_sym[l]

    A = np.zeros((len(x_data_point[0, :]), len(par_sym)))
    for ii in range(len(x_data_point[0, :])):
        A_temp = a_sym
        for k in range(len(var_sym)):
            A_temp = A_temp.subs(var_sym[k], x_data_point[k, ii])
        A[ii, :] = np.float64(A_temp.evalf())

    #B = (np.matrix(f_data_point)).T
    B = f_data_point

    if mode == 'pinv':

        C = np.linalg.pinv(A) @ B

    elif mode == 'lstsq':

        C = np.linalg.lstsq(A, B, rcond=None)[0]

    elif mode == 'lasso':

        if add_par[0] != None:
            alpha = add_par[0]
        else:
            alpha = 1.0
        regr = linear_model.Lasso(alpha=alpha,
                                  copy_X=True,
                                  max_iter=10**5,
                                  random_state=0)
        regr.fit(A, B)
        C = regr.coef_

    elif mode == 'ridge':

        if add_par[0] != None:
            alpha = add_par[0]
        else:
            alpha = 1.0
        regr = linear_model.Ridge(alpha=alpha,
                                  copy_X=True,
                                  max_iter=10**5,
                                  random_state=0)
        regr.fit(A, B)
        C = regr.coef_

    elif mode == 'elastic':

        if add_par[0] != None:
            alpha = add_par[0]
        else:
            alpha = 1.0
        if add_par[1] != None:
            rho = add_par[1]
        else:
            rho = 0.5
        regr = linear_model.ElasticNet(alpha=alpha,
                                       l1_ratio=rho,
                                       copy_X=True,
                                       max_iter=10**5,
                                       random_state=0)
        regr.fit(A, B)
        C = regr.coef_

    elif mode == 'huber':

        regr = linear_model.HuberRegressor()
        regr.fit(A, B)
        C = regr.coef_

    f_fit = A @ C
    Err = np.linalg.norm(f_data_point - f_fit, ord=2) / np.linalg.norm(
        f_data_point, ord=2)

    return C, f_fit, Err
 def simp(x):
     return simplify(expand_trig(expand_complex(expand(x))))
示例#59
0
def reciprocal_frame_test():

    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
示例#60
-1
def test_one_dof():
    # This is for a 1 dof spring-mass-damper case.
    # It is described in more detail in the KanesMethod docstring.
    q, u = dynamicsymbols('q u')
    qd, ud = dynamicsymbols('q u', 1)
    m, c, k = symbols('m c k')
    N = ReferenceFrame('N')
    P = Point('P')
    P.set_vel(N, u * N.x)

    kd = [qd - u]
    FL = [(P, (-k * q - c * u) * N.x)]
    pa = Particle('pa', P, m)
    BL = [pa]

    KM = KanesMethod(N, [q], [u], kd)
    KM.kanes_equations(FL, BL)
    MM = KM.mass_matrix
    forcing = KM.forcing
    rhs = MM.inv() * forcing
    assert expand(rhs[0]) == expand(-(q * k + u * c) / m)
    assert (KM.linearize(A_and_B=True, new_method=True)[0] ==
            Matrix([[0, 1], [-k/m, -c/m]]))

    # Ensure that the old linearizer still works and that the new linearizer
    # gives the same results. The old linearizer is deprecated and should be
    # removed in >= 0.7.7.
    M_old = KM.mass_matrix_full
    # The old linearizer raises a deprecation warning, so catch it here so
    # it doesn't cause py.test to fail.
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=SymPyDeprecationWarning)
        F_A_old, F_B_old, r_old = KM.linearize()
    M_new, F_A_new, F_B_new, r_new = KM.linearize(new_method=True)
    assert simplify(M_new.inv() * F_A_new - M_old.inv() * F_A_old) == zeros(2)