예제 #1
0
def test_polymatrix_from_Matrix():
    assert PolyMatrix.from_Matrix(Matrix([1, 2]), x) == PolyMatrix([1, 2], x, ring=QQ[x])
    assert PolyMatrix.from_Matrix(Matrix([1]), ring=QQ[x]) == PolyMatrix([1], x)
    pmx = PolyMatrix([1, 2], x)
    pmy = PolyMatrix([1, 2], y)
    assert pmx != pmy
    assert pmx.set_gens(y) == pmy
예제 #2
0
 def pdf(self, *args):
     mu, sigma = Matrix(self.mu), Matrix(self.sigma)
     k = len(mu)
     args = Matrix(args)
     return  S(1)/sqrt((2*pi)**(k)*det(sigma))*exp(
         -S(1)/2*(mu - args).transpose()*(sigma**(-1)*\
             (mu - args)))[0]
예제 #3
0
def is_pell_transformation_ok(eq):
    """
    Test whether X*Y, X, or Y terms are present in the equation
    after transforming the equation using the transformation returned
    by transformation_to_pell(). If they are not present we are good.
    Moreover, coefficient of X**2 should be a divisor of coefficient of
    Y**2 and the constant term.
    """
    A, B = transformation_to_DN(eq)
    u = (A * Matrix([X, Y]) + B)[0]
    v = (A * Matrix([X, Y]) + B)[1]
    simplified = diop_simplify(eq.subs(zip((x, y), (u, v))))

    coeff = dict(
        [reversed(t.as_independent(*[X, Y])) for t in simplified.args])

    for term in [X * Y, X, Y]:
        if term in coeff.keys():
            return False

    for term in [X**2, Y**2, 1]:
        if term not in coeff.keys():
            coeff[term] = 0

    if coeff[X**2] != 0:
        return divisible(coeff[Y**2], coeff[X**2]) and \
        divisible(coeff[1], coeff[X**2])

    return True
예제 #4
0
def test_DomainMatrix_from_Matrix():
    sdm = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
    A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]]))
    assert A.rep == sdm
    assert A.shape == (2, 2)
    assert A.domain == ZZ

    K = QQ.algebraic_field(sqrt(2))
    sdm = SDM(
        {
            0: {
                0: K.convert(1 + sqrt(2)),
                1: K.convert(2 + sqrt(2))
            },
            1: {
                0: K.convert(3 + sqrt(2)),
                1: K.convert(4 + sqrt(2))
            }
        }, (2, 2), K)
    A = DomainMatrix.from_Matrix(Matrix([[1 + sqrt(2), 2 + sqrt(2)],
                                         [3 + sqrt(2), 4 + sqrt(2)]]),
                                 extension=True)
    assert A.rep == sdm
    assert A.shape == (2, 2)
    assert A.domain == K

    A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)],
                                         [QQ(0, 1), QQ(0, 1)]]),
                                 fmt='dense')
    ddm = DDM([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]], (2, 2), QQ)

    assert A.rep == ddm
    assert A.shape == (2, 2)
    assert A.domain == QQ
    def get_dixon_polynomial(self):
        r"""
        Returns
        =======

        dixon_polynomial: polynomial
            Dixon's polynomial is calculated as:

            delta = Delta(A) / ((x_1 - a_1) ... (x_n - a_n)) where,

            A =  |p_1(x_1,... x_n), ..., p_n(x_1,... x_n)|
                 |p_1(a_1,... x_n), ..., p_n(a_1,... x_n)|
                 |...             , ...,              ...|
                 |p_1(a_1,... a_n), ..., p_n(a_1,... a_n)|
        """
        if self.m != (self.n + 1):
            raise ValueError('Method invalid for given combination.')

        # First row
        rows = [self.polynomials]

        temp = list(self.variables)

        for idx in range(self.n):
            temp[idx] = self.dummy_variables[idx]
            substitution = {var: t for var, t in zip(self.variables, temp)}
            rows.append([f.subs(substitution) for f in self.polynomials])

        A = Matrix(rows)

        terms = zip(self.variables, self.dummy_variables)
        product_of_differences = Mul(*[a - b for a, b in terms])
        dixon_polynomial = (A.det() / product_of_differences).factor()

        return poly_from_expr(dixon_polynomial, self.dummy_variables)[0]
예제 #6
0
def test_apart_matrix():
    M = Matrix(2, 2, lambda i, j: 1 / (x + i + 1) / (x + j))

    assert apart(M) == Matrix([
        [1 / x - 1 / (x + 1), (x + 1)**(-2)],
        [1 / (2 * x) - (S.Half) / (x + 2), 1 / (x + 1) - 1 / (x + 2)],
    ])
예제 #7
0
def test_invertible_BlockMatrix():
    assert ask(Q.invertible(BlockMatrix([Identity(3)]))) == True
    assert ask(Q.invertible(BlockMatrix([ZeroMatrix(3, 3)]))) == False

    X = Matrix([[1, 2, 3], [3, 5, 4]])
    Y = Matrix([[4, 2, 7], [2, 3, 5]])
    # non-invertible A block
    assert ask(
        Q.invertible(
            BlockMatrix([
                [Matrix.ones(3, 3), Y.T],
                [X, Matrix.eye(2)],
            ]))) == True
    # non-invertible B block
    assert ask(
        Q.invertible(
            BlockMatrix([
                [Y.T, Matrix.ones(3, 3)],
                [Matrix.eye(2), X],
            ]))) == True
    # non-invertible C block
    assert ask(
        Q.invertible(
            BlockMatrix([
                [X, Matrix.eye(2)],
                [Matrix.ones(3, 3), Y.T],
            ]))) == True
    # non-invertible D block
    assert ask(
        Q.invertible(
            BlockMatrix([
                [Matrix.eye(2), X],
                [Y.T, Matrix.ones(3, 3)],
            ]))) == True
예제 #8
0
def test_nonminimal_pendulum():
    q1, q2 = dynamicsymbols('q1:3')
    q1d, q2d = dynamicsymbols('q1:3', level=1)
    L, m, t = symbols('L, m, t')
    g = 9.8
    # Compose World Frame
    N = ReferenceFrame('N')
    pN = Point('N*')
    pN.set_vel(N, 0)
    # Create point P, the pendulum mass
    P = pN.locatenew('P1', q1 * N.x + q2 * N.y)
    P.set_vel(N, P.pos_from(pN).dt(N))
    pP = Particle('pP', P, m)
    # Constraint Equations
    f_c = Matrix([q1**2 + q2**2 - L**2])
    # Calculate the lagrangian, and form the equations of motion
    Lag = Lagrangian(N, pP)
    LM = LagrangesMethod(Lag, [q1, q2],
                         hol_coneqs=f_c,
                         forcelist=[(P, m * g * N.x)],
                         frame=N)
    LM.form_lagranges_equations()
    # Check solution
    lam1 = LM.lam_vec[0, 0]
    eom_sol = Matrix([[m * Derivative(q1, t, t) - 9.8 * m + 2 * lam1 * q1],
                      [m * Derivative(q2, t, t) + 2 * lam1 * q2]])
    assert LM.eom == eom_sol
    # Check multiplier solution
    lam_sol = Matrix([
        (19.6 * q1 + 2 * q1d**2 + 2 * q2d**2) / (4 * q1**2 / m + 4 * q2**2 / m)
    ])
    assert simplify(
        LM.solve_multipliers(sol_type='Matrix')) == simplify(lam_sol)
예제 #9
0
def test_bracelets():
    bc = [i for i in bracelets(2, 4)]
    assert Matrix(bc) == Matrix([[0, 0], [0, 1], [0, 2], [0, 3], [1, 1],
                                 [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]])
    bc = [i for i in bracelets(4, 2)]
    assert Matrix(bc) == Matrix([[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1],
                                 [0, 1, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1]])
예제 #10
0
def test_Matrix_array():
    class matarray:
        def __array__(self):
            from numpy import array
            return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    matarr = matarray()
    assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
예제 #11
0
def test_sample_stochastic_process():
    if not import_module('scipy'):
        skip('SciPy Not installed. Skip sampling tests')
    import random
    random.seed(0)
    numpy = import_module('numpy')
    if numpy:
        numpy.random.seed(0)  # scipy uses numpy to sample so to set its seed
    T = Matrix([[0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]])
    Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
    for samps in range(10):
        assert next(sample_stochastic_process(Y)) in Y.state_space
    Z = DiscreteMarkovChain("Z", ['1', 1, 0], T)
    for samps in range(10):
        assert next(sample_stochastic_process(Z)) in Z.state_space

    T = Matrix([[S.Half, Rational(1, 4),
                 Rational(1, 4)], [Rational(1, 3), 0,
                                   Rational(2, 3)], [S.Half, S.Half, 0]])
    X = DiscreteMarkovChain('X', [0, 1, 2], T)
    for samps in range(10):
        assert next(sample_stochastic_process(X)) in X.state_space
    W = DiscreteMarkovChain('W', [1, pi, oo], T)
    for samps in range(10):
        assert next(sample_stochastic_process(W)) in W.state_space
예제 #12
0
def test_CondSet():
    sin_sols_principal = ConditionSet(x, Eq(sin(x), 0),
                                      Interval(0, 2*pi, False, True))
    assert pi in sin_sols_principal
    assert pi/2 not in sin_sols_principal
    assert 3*pi not in sin_sols_principal
    assert oo not in sin_sols_principal
    assert 5 in ConditionSet(x, x**2 > 4, S.Reals)
    assert 1 not in ConditionSet(x, x**2 > 4, S.Reals)
    # in this case, 0 is not part of the base set so
    # it can't be in any subset selected by the condition
    assert 0 not in ConditionSet(x, y > 5, Interval(1, 7))
    # since 'in' requires a true/false, the following raises
    # an error because the given value provides no information
    # for the condition to evaluate (since the condition does
    # not depend on the dummy symbol): the result is `y > 5`.
    # In this case, ConditionSet is just acting like
    # Piecewise((Interval(1, 7), y > 5), (S.EmptySet, True)).
    raises(TypeError, lambda: 6 in ConditionSet(x, y > 5,
        Interval(1, 7)))

    X = MatrixSymbol('X', 2, 2)
    matrix_set = ConditionSet(X, Eq(X*Matrix([[1, 1], [1, 1]]), X))
    Y = Matrix([[0, 0], [0, 0]])
    assert matrix_set.contains(Y).doit() is S.true
    Z = Matrix([[1, 2], [3, 4]])
    assert matrix_set.contains(Z).doit() is S.false

    assert isinstance(ConditionSet(x, x < 1, {x, y}).base_set,
        FiniteSet)
    raises(TypeError, lambda: ConditionSet(x, x + 1, {x, y}))
    raises(TypeError, lambda: ConditionSet(x, x, 1))

    I = S.Integers
    U = S.UniversalSet
    C = ConditionSet
    assert C(x, False, I) is S.EmptySet
    assert C(x, True, I) is I
    assert C(x, x < 1, C(x, x < 2, I)
        ) == C(x, (x < 1) & (x < 2), I)
    assert C(y, y < 1, C(x, y < 2, I)
        ) == C(x, (x < 1) & (y < 2), I), C(y, y < 1, C(x, y < 2, I))
    assert C(y, y < 1, C(x, x < 2, I)
        ) == C(y, (y < 1) & (y < 2), I)
    assert C(y, y < 1, C(x, y < x, I)
        ) == C(x, (x < 1) & (y < x), I)
    assert unchanged(C, y, x < 1, C(x, y < x, I))
    assert ConditionSet(x, x < 1).base_set is U
    # arg checking is not done at instantiation but this
    # will raise an error when containment is tested
    assert ConditionSet((x,), x < 1).base_set is U

    c = ConditionSet((x, y), x < y, I**2)
    assert (1, 2) in c
    assert (1, pi) not in c

    raises(TypeError, lambda: C(x, x > 1, C((x, y), x > 1, I**2)))
    # signature mismatch since only 3 args are accepted
    raises(TypeError, lambda: C((x, y), x + y < 2, U, U))
예제 #13
0
def test_Derivative__new__():
    raises(TypeError, lambda: f(x).diff((x, 2), 0))
    assert f(x, y).diff([(x, y), 0]) == f(x, y)
    assert f(x, y).diff([(x, y), 1]) == NDimArray([
        Derivative(f(x, y), x), Derivative(f(x, y), y)])
    assert f(x,y).diff(y, (x, z), y, x) == Derivative(
        f(x, y), (x, z + 1), (y, 2))
    assert Matrix([x]).diff(x, 2) == Matrix([0])  # is_zero exit
예제 #14
0
 def check(self, mu, sigma):
     mu, sigma = Matrix([mu]), Matrix(sigma)
     _value_check(
         len(mu) == len(sigma.col(0)),
         "Size of the mean vector and covariance matrix are incorrect.")
     #check if covariance matrix is positive definite or not.
     _value_check(all([i > 0 for i in sigma.eigenvals().keys()]),
                  "The covariance matrix must be positive definite. ")
예제 #15
0
 def pdf(self, *args):
     mu, sigma = Matrix(self.mu), Matrix(self.sigma)
     k = len(mu)
     args = Matrix(args)
     x = args - mu
     return  S(1)/sqrt((2*pi)**(k)*det(sigma))*exp(
         -S(1)/2*x.transpose()*(sigma.inv()*\
             x))[0]
예제 #16
0
def test_issue_15129_trigsimp_methods():
    t1 = Matrix([sin(Rational(1, 50)), cos(Rational(1, 50)), 0])
    t2 = Matrix([sin(Rational(1, 25)), cos(Rational(1, 25)), 0])
    t3 = Matrix([cos(Rational(1, 25)), sin(Rational(1, 25)), 0])
    r1 = t1.dot(t2)
    r2 = t1.dot(t3)
    assert trigsimp(r1) == cos(Rational(1, 50))
    assert trigsimp(r2) == sin(Rational(3, 50))
예제 #17
0
def test_as_immutable():
    data = [[1, 2], [3, 4]]
    X = Matrix(data)
    assert sympify(X) == X.as_immutable() == ImmutableMatrix(data)

    data = {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4}
    X = SparseMatrix(2, 2, data)
    assert sympify(X) == X.as_immutable() == ImmutableSparseMatrix(2, 2, data)
예제 #18
0
def test_CodeBlock_cse__issue_14118():
    # see https://github.com/sympy/sympy/issues/14118
    c = CodeBlock(
        Assignment(A22, Matrix([[x, sin(y)], [3, 4]])),
        Assignment(B22, Matrix([[sin(y), 2 * sin(y)], [sin(y)**2, 7]])))
    assert c.cse() == CodeBlock(
        Assignment(x0, sin(y)), Assignment(A22, Matrix([[x, x0], [3, 4]])),
        Assignment(B22, Matrix([[x0, 2 * x0], [x0**2, 7]])))
예제 #19
0
def test_JointEigenDistribution():
    A = Matrix([[Normal('A00', 0, 1), Normal('A01', 1, 1)],
                [Beta('A10', 1, 1), Beta('A11', 1, 1)]])
    assert JointEigenDistribution(A) == \
    JointDistributionHandmade(-sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)/2 +
    A[0, 0]/2 + A[1, 1]/2, sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)/2 + A[0, 0]/2 + A[1, 1]/2)
    raises(ValueError,
           lambda: JointEigenDistribution(Matrix([[1, 0], [2, 1]])))
예제 #20
0
def test_pin_joint_chaos_pendulum():
    mA, mB, lA, lB, h = symbols('mA, mB, lA, lB, h')
    theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
    N = ReferenceFrame('N')
    A = ReferenceFrame('A')
    B = ReferenceFrame('B')
    lA = (lB - h / 2) / 2
    lC = (lB / 2 + h / 4)
    rod = Body('rod', frame=A, mass=mA)
    plate = Body('plate', mass=mB, frame=B)
    C = Body('C', frame=N)
    J1 = PinJoint('J1',
                  C,
                  rod,
                  coordinates=theta,
                  speeds=omega,
                  child_joint_pos=lA * A.z,
                  parent_axis=N.y,
                  child_axis=A.y)
    J2 = PinJoint('J2',
                  rod,
                  plate,
                  coordinates=phi,
                  speeds=alpha,
                  parent_joint_pos=lC * A.z,
                  parent_axis=A.z,
                  child_axis=B.z)

    # Check orientation
    assert A.dcm(N) == Matrix([[cos(theta), 0, -sin(theta)], [0, 1, 0],
                               [sin(theta), 0, cos(theta)]])
    assert A.dcm(B) == Matrix([[cos(phi), -sin(phi), 0],
                               [sin(phi), cos(phi), 0], [0, 0, 1]])
    assert B.dcm(N) == Matrix(
        [[cos(phi) * cos(theta),
          sin(phi), -sin(theta) * cos(phi)],
         [-sin(phi) * cos(theta),
          cos(phi), sin(phi) * sin(theta)], [sin(theta), 0,
                                             cos(theta)]])

    # Check Angular Velocity
    assert A.ang_vel_in(N) == omega * N.y
    assert A.ang_vel_in(B) == -alpha * A.z
    assert N.ang_vel_in(B) == -omega * N.y - alpha * A.z

    # Check kde
    assert J1.kdes == [omega - theta.diff(t)]
    assert J2.kdes == [alpha - phi.diff(t)]

    # Check pos of masscenters
    assert C.masscenter.pos_from(rod.masscenter) == lA * A.z
    assert rod.masscenter.pos_from(plate.masscenter) == -lC * A.z

    # Check Linear Velocities
    assert rod.masscenter.vel(N) == (h / 4 - lB / 2) * omega * A.x
    assert plate.masscenter.vel(N) == ((h / 4 - lB / 2) * omega +
                                       (h / 4 + lB / 2) * omega) * A.x
예제 #21
0
 def check(self, mu, sigma, v):
     mu, sigma = Matrix([mu]), Matrix(sigma)
     _value_check(
         len(mu) == len(sigma.col(0)),
         "Size of the location vector and shape matrix are incorrect.")
     #check if covariance matrix is positive definite or not.
     _value_check(
         all([Gt(i, 0) != False for i in sigma.eigenvals().keys()]),
         "The shape matrix must be positive definite. ")
예제 #22
0
def test_necklaces():
    def count(n, k, f):
        return len(list(necklaces(n, k, f)))

    m = []
    for i in range(1, 8):
        m.append((i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1)))
    assert Matrix(m) == Matrix([[1, 2, 2, 3], [2, 3, 3, 6], [3, 4, 4, 10],
                                [4, 6, 6, 21], [5, 8, 8, 39], [6, 14, 13, 92],
                                [7, 20, 18, 198]])
예제 #23
0
def test_nsolve_complex():
    x, y = symbols('x y')

    assert nsolve(x**2 + 2, 1j) == sqrt(2.) * I
    assert nsolve(x**2 + 2, I) == sqrt(2.) * I

    assert nsolve([x**2 + 2, y**2 + 2], [x, y],
                  [I, I]) == Matrix([sqrt(2.) * I, sqrt(2.) * I])
    assert nsolve([x**2 + 2, y**2 + 2], [x, y],
                  [I, I]) == Matrix([sqrt(2.) * I, sqrt(2.) * I])
예제 #24
0
 def pdf(self, *args):
     from sympy.functions.special.gamma_functions import gamma
     mu, sigma = Matrix(self.mu), Matrix(self.shape_mat)
     v = S(self.dof)
     k = S(len(mu))
     sigma_inv = sigma.inv()
     args = Matrix(args)
     x = args - mu
     return gamma((k + v)/2)/(gamma(v/2)*(v*pi)**(k/2)*sqrt(det(sigma)))\
     *(1 + 1/v*(x.transpose()*sigma_inv*x)[0])**((-v - k)/2)
예제 #25
0
def test_matrix2numpy_conversion():
    a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
    b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
    assert (matrix2numpy(a) == b).all()
    assert matrix2numpy(a).dtype == numpy.dtype('object')

    c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
    d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
    assert c.dtype == numpy.dtype('int8')
    assert d.dtype == numpy.dtype('float64')
예제 #26
0
def test_refraction_angle():
    n1, n2 = symbols('n1, n2')
    m1 = Medium('m1')
    m2 = Medium('m2')
    r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
    i = Matrix([1, 1, 1])
    n = Matrix([0, 0, 1])
    normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
    P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
    assert refraction_angle(r1, 1, 1, n) == Matrix([[1], [1], [-1]])
    assert refraction_angle([1, 1, 1], 1, 1, n) == Matrix([[1], [1], [-1]])
    assert refraction_angle((1, 1, 1), 1, 1, n) == Matrix([[1], [1], [-1]])
    assert refraction_angle(i, 1, 1, [0, 0, 1]) == Matrix([[1], [1], [-1]])
    assert refraction_angle(i, 1, 1, (0, 0, 1)) == Matrix([[1], [1], [-1]])
    assert refraction_angle(i, 1, 1, normal_ray) == Matrix([[1], [1], [-1]])
    assert refraction_angle(i, 1, 1, plane=P) == Matrix([[1], [1], [-1]])
    assert refraction_angle(r1, 1, 1, plane=P) == \
        Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
    assert refraction_angle(r1, m1, 1.33, plane=P) == \
        Ray3D(Point3D(0, 0, 0), Point3D(Rational(100, 133), Rational(100, 133), -789378201649271*sqrt(3)/1000000000000000))
    assert refraction_angle(r1, 1, m2, plane=P) == \
        Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
    assert refraction_angle(r1, n1, n2, plane=P) == \
        Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
    assert refraction_angle(r1, 1.33, 1, plane=P) == 0  # TIR
    assert refraction_angle(r1, 1, 1, normal_ray) == \
        Ray3D(Point3D(0, 0, 0), direction_ratio=[1, 1, -1])
    assert ae(refraction_angle(0.5, 1, 2), 0.24207, 5)
    assert ae(refraction_angle(0.5, 2, 1), 1.28293, 5)
    raises(ValueError, lambda: refraction_angle(r1, m1, m2, normal_ray, P))
    raises(TypeError, lambda: refraction_angle(m1, m1, m2)
           )  # can add other values for arg[0]
    raises(TypeError, lambda: refraction_angle(r1, m1, m2, None, i))
    raises(TypeError, lambda: refraction_angle(r1, m1, m2, m2))
예제 #27
0
def test_mdft():
    with warns_deprecated_sympy():
        assert mdft(1) == Matrix([[1]])
    with warns_deprecated_sympy():
        assert mdft(2) == 1 / sqrt(2) * Matrix([[1, 1], [1, -1]])
    with warns_deprecated_sympy():
        assert mdft(4) == Matrix(
            [[S.Half, S.Half, S.Half, S.Half],
             [S.Half, -I / 2, Rational(-1, 2), I / 2],
             [S.Half, Rational(-1, 2), S.Half,
              Rational(-1, 2)], [S.Half, I / 2,
                                 Rational(-1, 2), -I / 2]])
예제 #28
0
def test_Matrix_str():
    M = Matrix([[x**+1, 1], [y, x + y]])
    assert str(M) == "Matrix([[x, 1], [y, x + y]])"
    assert sstr(M) == "Matrix([\n[x,     1],\n[y, x + y]])"
    M = Matrix([[1]])
    assert str(M) == sstr(M) == "Matrix([[1]])"
    M = Matrix([[1, 2]])
    assert str(M) == sstr(M) ==  "Matrix([[1, 2]])"
    M = Matrix()
    assert str(M) == sstr(M) == "Matrix(0, 0, [])"
    M = Matrix(0, 1, lambda i, j: 0)
    assert str(M) == sstr(M) == "Matrix(0, 1, [])"
예제 #29
0
def test_pin_joint_double_pendulum():
    q1, q2 = dynamicsymbols('q1 q2')
    u1, u2 = dynamicsymbols('u1 u2')
    m, l = symbols('m l')
    N = ReferenceFrame('N')
    A = ReferenceFrame('A')
    B = ReferenceFrame('B')
    C = Body('C', frame=N)  # ceiling
    PartP = Body('P', frame=A, mass=m)
    PartR = Body('R', frame=B, mass=m)

    J1 = PinJoint('J1',
                  C,
                  PartP,
                  speeds=u1,
                  coordinates=q1,
                  child_joint_pos=-l * A.x,
                  parent_axis=C.frame.z,
                  child_axis=PartP.frame.z)
    J2 = PinJoint('J2',
                  PartP,
                  PartR,
                  speeds=u2,
                  coordinates=q2,
                  child_joint_pos=-l * B.x,
                  parent_axis=PartP.frame.z,
                  child_axis=PartR.frame.z)

    # Check orientation
    assert N.dcm(A) == Matrix([[cos(q1), -sin(q1), 0], [sin(q1),
                                                        cos(q1), 0], [0, 0,
                                                                      1]])
    assert A.dcm(B) == Matrix([[cos(q2), -sin(q2), 0], [sin(q2),
                                                        cos(q2), 0], [0, 0,
                                                                      1]])
    assert _simplify_matrix(N.dcm(B)) == Matrix(
        [[cos(q1 + q2), -sin(q1 + q2), 0], [sin(q1 + q2),
                                            cos(q1 + q2), 0], [0, 0, 1]])

    # Check Angular Velocity
    assert A.ang_vel_in(N) == u1 * N.z
    assert B.ang_vel_in(A) == u2 * A.z
    assert B.ang_vel_in(N) == u1 * N.z + u2 * A.z

    # Check kde
    assert J1.kdes == [u1 - q1.diff(t)]
    assert J2.kdes == [u2 - q2.diff(t)]

    # Check Linear Velocity
    assert PartP.masscenter.vel(N) == l * u1 * A.y
    assert PartR.masscenter.vel(A) == l * u2 * B.y
    assert PartR.masscenter.vel(N) == l * u1 * A.y + l * (u1 + u2) * B.y
예제 #30
0
 def __mul__(self, other):
     if isinstance(other, RayTransferMatrix):
         return RayTransferMatrix(Matrix.__mul__(self, other))
     elif isinstance(other, GeometricRay):
         return GeometricRay(Matrix.__mul__(self, other))
     elif isinstance(other, BeamParameter):
         temp = self * Matrix(((other.q, ), (1, )))
         q = (temp[0] / temp[1]).expand(complex=True)
         return BeamParameter(other.wavelen,
                              together(re(q)),
                              z_r=together(im(q)))
     else:
         return Matrix.__mul__(self, other)
예제 #31
0
def row_proper(A):
    """
    Reduction of a polynomial matrix to row proper polynomial matrix

    Implementation of the algorithm as shown in page 7 of 
    Vardulakis, A.I.G. (Antonis I.G). Linear Multivariable Control: Algebraic Analysis and Synthesis Methods. 
    Chichester,New York,Brisbane,Toronto,Singapore: John Wiley & Sons, 1991.

    INPUT:
        Polynomial Matrix A
    OUTPUT:
        T:An equivalent matrix in row proper form
        TL the unimodular transformation matrix
    Christos Tsolakis
    
    Example:  TODO
    T=Matrix([[1, s**2, 0], [0, s, 1]])
    is_row_proper(T)
    
    see also Wolovich Linear Multivariable Systems Springer
    """
    T=A.copy()
    Transfomation_Matrix=eye(T.rows)     #initialize transformation matrix
    while  not is_row_proper(T):
        #for i in range(3):
        Thr=mc.highest_row_degree_matrix(T,s)
        #pprint(Thr)
        x=symbols('x0:%d'%(Thr.rows+1))
        Thr=Thr.transpose()
        Thr0=Thr.col_insert(Thr.cols,zeros(Thr.rows,1))
        SOL=solve_linear_system(Thr0,*x)      # solve the system 
        a=Matrix(x)
        D={var:1 for var in x if var not in SOL.keys()}   # put free variables equal to 1
        D.update({var:SOL[var].subs(D) for var in x if var in SOL.keys()})
        a=a.subs(D)
        r0=mc.find_degree(T,s) 
        row_degrees=mc.row_degrees(T,s)                               
        i0=row_degrees.index(max(row_degrees))
        ast=Matrix(1,T.rows,[a[i]*s**(r0-row_degrees[i]) for i in range(T.rows)])
        #pprint (ast)
        TL=eye(T.rows)
        TL[i0*TL.cols]=ast
        #pprint (TL)
        T=TL*T
        T.simplify()
        Transfomation_Matrix=TL*Transfomation_Matrix
        Transfomation_Matrix.simplify()
        #pprint (T)
        #print('----------------------------')
            
    return  Transfomation_Matrix,T