示例#1
0
def test_Normal():
    m = Normal('A', [1, 2], [[1, 0], [0, 1]])
    A = MultivariateNormal('A', [1, 2], [[1, 0], [0, 1]])
    assert m == A
    assert density(m)(1, 2) == 1/(2*pi)
    assert m.pspace.distribution.set == ProductSet(S.Reals, S.Reals)
    raises (ValueError, lambda:m[2])
    n = Normal('B', [1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    p = Normal('C',  Matrix([1, 2]), Matrix([[1, 0], [0, 1]]))
    assert density(m)(x, y) == density(p)(x, y)
    assert marginal_distribution(n, 0, 1)(1, 2) == 1/(2*pi)
    raises(ValueError, lambda: marginal_distribution(m))
    assert integrate(density(m)(x, y), (x, -oo, oo), (y, -oo, oo)).evalf() == 1
    N = Normal('N', [1, 2], [[x, 0], [0, y]])
    assert density(N)(0, 0) == exp(-((4*x + y)/(2*x*y)))/(2*pi*sqrt(x*y))

    raises (ValueError, lambda: Normal('M', [1, 2], [[1, 1], [1, -1]]))
    # symbolic
    n = symbols('n', integer=True, positive=True)
    mu = MatrixSymbol('mu', n, 1)
    sigma = MatrixSymbol('sigma', n, n)
    X = Normal('X', mu, sigma)
    assert density(X) == MultivariateNormalDistribution(mu, sigma)
    raises (NotImplementedError, lambda: median(m))
    # Below tests should work after issue #17267 is resolved
    # assert E(X) == mu
    # assert variance(X) == sigma

    # test symbolic multivariate normal densities
    n = 3

    Sg = MatrixSymbol('Sg', n, n)
    mu = MatrixSymbol('mu', n, 1)
    obs = MatrixSymbol('obs', n, 1)

    X = MultivariateNormal('X', mu, Sg)
    density_X = density(X)

    eval_a = density_X(obs).subs({Sg: eye(3),
        mu: Matrix([0, 0, 0]), obs: Matrix([0, 0, 0])}).doit()
    eval_b = density_X(0, 0, 0).subs({Sg: eye(3), mu: Matrix([0, 0, 0])}).doit()

    assert eval_a == sqrt(2)/(4*pi**Rational(3/2))
    assert eval_b == sqrt(2)/(4*pi**Rational(3/2))

    n = symbols('n', integer=True, positive=True)

    Sg = MatrixSymbol('Sg', n, n)
    mu = MatrixSymbol('mu', n, 1)
    obs = MatrixSymbol('obs', n, 1)

    X = MultivariateNormal('X', mu, Sg)
    density_X_at_obs = density(X)(obs)

    expected_density = MatrixElement(
        exp((S(1)/2) * (mu.T - obs.T) * Sg**(-1) * (-mu + obs)) / \
        sqrt((2*pi)**n * Determinant(Sg)), 0, 0)

    assert density_X_at_obs == expected_density
示例#2
0
    def rotation_matrix(self, other):
        """
        Returns the direction cosine matrix(DCM), also known as the
        'rotation matrix' of this coordinate system with respect to
        another system.

        If v_a is a vector defined in system 'A' (in matrix format)
        and v_b is the same vector defined in system 'B', then
        v_a = A.rotation_matrix(B) * v_b.

        A SymPy Matrix is returned.

        Parameters
        ==========

        other : CoordSys3D
            The system which the DCM is generated to.

        Examples
        ========

        >>> from sympy.vector import CoordSys3D
        >>> from sympy import symbols
        >>> q1 = symbols('q1')
        >>> N = CoordSys3D('N')
        >>> A = N.orient_new_axis('A', q1, N.i)
        >>> N.rotation_matrix(A)
        Matrix([
        [1,       0,        0],
        [0, cos(q1), -sin(q1)],
        [0, sin(q1),  cos(q1)]])

        """
        from sympy.vector.functions import _path
        if not isinstance(other, CoordSys3D):
            raise TypeError(str(other) +
                            " is not a CoordSys3D")
        # Handle special cases
        if other == self:
            return eye(3)
        elif other == self._parent:
            return self._parent_rotation_matrix
        elif other._parent == self:
            return other._parent_rotation_matrix.T
        # Else, use tree to calculate position
        rootindex, path = _path(self, other)
        result = eye(3)
        i = -1
        for i in range(rootindex):
            result *= path[i]._parent_rotation_matrix
        i += 2
        while i < len(path):
            result *= path[i]._parent_rotation_matrix.T
            i += 1
        return result
示例#3
0
def test_subs():
    A = ImmutableMatrix([[1, 2], [3, 4]])
    B = ImmutableMatrix([[1, 2], [x, 4]])
    C = ImmutableMatrix([[-x, x * y], [-(x + y), y**2]])
    assert B.subs(x, 3) == A
    assert (x * B).subs(x, 3) == 3 * A
    assert (x * eye(2) + B).subs(x, 3) == 3 * eye(2) + A
    assert C.subs([[x, -1], [y, -2]]) == A
    assert C.subs([(x, -1), (y, -2)]) == A
    assert C.subs({x: -1, y: -2}) == A
    assert C.subs({x: y - 1, y: x - 1}, simultaneous=True) == \
        ImmutableMatrix([[1 - y, (x - 1)*(y - 1)], [2 - x - y, (x - 1)**2]])
示例#4
0
def test_issue_15601():
    if not np:
        skip("Numpy not installed")

    M = MatrixSymbol("M", 3, 3)
    N = MatrixSymbol("N", 3, 3)
    expr = M * N
    f = lambdify((M, N), expr, "numpy")

    with warns_deprecated_sympy():
        ans = f(eye(3), eye(3))
        assert np.array_equal(ans, np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]))
示例#5
0
def test_can_transf_matrix():
    dimsys = DimensionSystem((length, mass, time))
    assert dimsys.can_transf_matrix == eye(3)

    dimsys = DimensionSystem((length, velocity, action))
    assert dimsys.can_transf_matrix == eye(3)

    dimsys = DimensionSystem((length, time), (velocity, ),
                             {velocity: {
                                 length: 1,
                                 time: -1
                             }})
    assert dimsys.can_transf_matrix == eye(2)
示例#6
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
示例#7
0
def test_block_index():
    I = Identity(3)
    Z = ZeroMatrix(3, 3)
    B = BlockMatrix([[I, I], [I, I]])
    e3 = ImmutableMatrix(eye(3))
    BB = BlockMatrix([[e3, e3], [e3, e3]])
    assert B[0, 0] == B[3, 0] == B[0, 3] == B[3, 3] == 1
    assert B[4, 3] == B[5, 1] == 0

    BB = BlockMatrix([[e3, e3], [e3, e3]])
    assert B.as_explicit() == BB.as_explicit()

    BI = BlockMatrix([[I, Z], [Z, I]])

    assert BI.as_explicit().equals(eye(6))
示例#8
0
def test_tensordiagonal():
    from sympy.matrices.dense import eye
    expr = Array(range(9)).reshape(3, 3)
    raises(ValueError, lambda: tensordiagonal(expr, [0], [1]))
    raises(ValueError, lambda: tensordiagonal(expr, [0, 0]))
    assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1])
    assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8])
    x, y, z = symbols("x y z")
    expr2 = tensorproduct([x, y, z], expr)
    assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]])
    assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]])
    assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z])
    # assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0])
    # assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1])
    # assert tensordiagonal(expr2, [2]) == expr2
    # assert tensordiagonal(expr2, [1], [2]) == expr2
    # assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1])

    a, b, c, X, Y, Z = symbols("a b c X Y Z")
    expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z])
    assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z])
    assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z])

    # assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z])
    assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z])

    raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1]))
    raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2]))
def test_Dirac():
    gamma0 = mgamma(0)
    gamma1 = mgamma(1)
    gamma2 = mgamma(2)
    gamma3 = mgamma(3)
    gamma5 = mgamma(5)

    # gamma*I -> I*gamma    (see #354)
    assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I
    assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4)
    assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0]
    assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0]
    assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2]

    assert mgamma(5, True) == \
        mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I
示例#10
0
def test_immutable_evaluation():
    X = ImmutableMatrix(eye(3))
    A = ImmutableMatrix(3, 3, range(9))
    assert isinstance(X + A, ImmutableMatrix)
    assert isinstance(X * A, ImmutableMatrix)
    assert isinstance(X * 2, ImmutableMatrix)
    assert isinstance(2 * X, ImmutableMatrix)
    assert isinstance(A**2, ImmutableMatrix)
示例#11
0
 def _represent_ZGate(self, basis, **options):
     """
     Represent the OracleGate in the computational basis.
     """
     nbasis = 2**self.nqubits  # compute it only once
     matrixOracle = eye(nbasis)
     # Flip the sign given the output of the oracle function
     for i in range(nbasis):
         if self.search_function(IntQubit(i, nqubits=self.nqubits)):
             matrixOracle[i, i] = NegativeOne()
     return matrixOracle
def test_Pauli():
    #this and the following test are testing both Pauli and Dirac matrices
    #and also that the general Matrix class works correctly in a real world
    #situation
    sigma1 = msigma(1)
    sigma2 = msigma(2)
    sigma3 = msigma(3)

    assert sigma1 == sigma1
    assert sigma1 != sigma2

    # sigma*I -> I*sigma    (see #354)
    assert sigma1 * sigma2 == sigma3 * I
    assert sigma3 * sigma1 == sigma2 * I
    assert sigma2 * sigma3 == sigma1 * I

    assert sigma1 * sigma1 == eye(2)
    assert sigma2 * sigma2 == eye(2)
    assert sigma3 * sigma3 == eye(2)

    assert sigma1 * 2 * sigma1 == 2 * eye(2)
    assert sigma1 * sigma3 * sigma1 == -sigma3
示例#13
0
    def pdf(self, x):
        from sympy.matrices.dense import eye
        if isinstance(x, list):
            x = ImmutableMatrix(x)
        if not isinstance(x, (MatrixBase, MatrixSymbol)):
            raise ValueError("%s should be an isinstance of Matrix "
                             "or MatrixSymbol" % str(x))
        nu, M, Omega, Sigma = self.nu, self.location_matrix, self.scale_matrix_1, self.scale_matrix_2
        n, p = M.shape

        K = multigamma((nu + n + p - 1)/2, p) * Determinant(Omega)**(-n/2) * Determinant(Sigma)**(-p/2) \
            / ((pi)**(n*p/2) * multigamma((nu + p - 1)/2, p))
        return K * (Determinant(eye(n) + Inverse(Sigma)*(x - M)*Inverse(Omega)*Transpose(x - M))) \
               **(-(nu + n + p -1)/2)
示例#14
0
def test_issue_11498():
    A = ReferenceFrame('A')
    B = ReferenceFrame('B')

    # Identity transformation
    A.orient(B, 'DCM', eye(3))
    assert A.dcm(B) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    assert B.dcm(A) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

    # x -> y
    # y -> -z
    # z -> -x
    A.orient(B, 'DCM', Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]]))
    assert B.dcm(A) == Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]])
    assert A.dcm(B) == Matrix([[0, 0, -1], [1, 0, 0], [0, -1, 0]])
    assert B.dcm(A).T == A.dcm(B)
示例#15
0
    def rotation_matrix(self, system):
        """
        The rotation matrix corresponding to this orienter
        instance.

        Parameters
        ==========

        system : CoordSys3D
            The coordinate system wrt which the rotation matrix
            is to be computed
        """

        axis = sympy.vector.express(self.axis, system).normalize()
        axis = axis.to_matrix(system)
        theta = self.angle
        parent_orient = (
            (eye(3) - axis * axis.T) * cos(theta) +
            Matrix([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]],
                    [-axis[1], axis[0], 0]]) * sin(theta) + axis * axis.T)
        parent_orient = parent_orient.T
        return parent_orient
示例#16
0
 def doit(self, **hints):
     from sympy.assumptions import ask, Q
     from sympy.matrices.expressions.matmul import MatMul
     from sympy.matrices.expressions.transpose import Transpose
     from sympy.matrices.dense import eye
     from sympy.matrices.matrices import MatrixBase
     vector = self._vector
     # This accounts for shape (1, 1) and identity matrices, among others:
     if ask(Q.diagonal(vector)):
         return vector
     if isinstance(vector, MatrixBase):
         ret = eye(max(vector.shape))
         for i in range(ret.shape[0]):
             ret[i, i] = vector[i]
         return type(vector)(ret)
     if vector.is_MatMul:
         matrices = [arg for arg in vector.args if arg.is_Matrix]
         scalars = [arg for arg in vector.args if arg not in matrices]
         if scalars:
             return Mul.fromiter(scalars) * DiagMatrix(
                 MatMul.fromiter(matrices).doit()).doit()
     if isinstance(vector, Transpose):
         vector = vector.arg
     return DiagMatrix(vector)
示例#17
0
def kahane_simplify(expression):
    r"""
    This function cancels contracted elements in a product of four
    dimensional gamma matrices, resulting in an expression equal to the given
    one, without the contracted gamma matrices.

    Parameters
    ==========

    `expression`    the tensor expression containing the gamma matrices to simplify.

    Notes
    =====

    If spinor indices are given, the matrices must be given in
    the order given in the product.

    Algorithm
    =========

    The idea behind the algorithm is to use some well-known identities,
    i.e., for contractions enclosing an even number of `\gamma` matrices

    `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N}} \gamma_\mu = 2 (\gamma_{a_{2N}} \gamma_{a_1} \cdots \gamma_{a_{2N-1}} + \gamma_{a_{2N-1}} \cdots \gamma_{a_1} \gamma_{a_{2N}} )`

    for an odd number of `\gamma` matrices

    `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N+1}} \gamma_\mu = -2 \gamma_{a_{2N+1}} \gamma_{a_{2N}} \cdots \gamma_{a_{1}}`

    Instead of repeatedly applying these identities to cancel out all contracted indices,
    it is possible to recognize the links that would result from such an operation,
    the problem is thus reduced to a simple rearrangement of free gamma matrices.

    Examples
    ========

    When using, always remember that the original expression coefficient
    has to be handled separately

    >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
    >>> from sympy.physics.hep.gamma_matrices import kahane_simplify
    >>> from sympy.tensor.tensor import tensor_indices
    >>> i0, i1, i2 = tensor_indices('i0:3', LorentzIndex)
    >>> ta = G(i0)*G(-i0)
    >>> kahane_simplify(ta)
    Matrix([
    [4, 0, 0, 0],
    [0, 4, 0, 0],
    [0, 0, 4, 0],
    [0, 0, 0, 4]])
    >>> tb = G(i0)*G(i1)*G(-i0)
    >>> kahane_simplify(tb)
    -2*GammaMatrix(i1)
    >>> t = G(i0)*G(-i0)
    >>> kahane_simplify(t)
    Matrix([
    [4, 0, 0, 0],
    [0, 4, 0, 0],
    [0, 0, 4, 0],
    [0, 0, 0, 4]])
    >>> t = G(i0)*G(-i0)
    >>> kahane_simplify(t)
    Matrix([
    [4, 0, 0, 0],
    [0, 4, 0, 0],
    [0, 0, 4, 0],
    [0, 0, 0, 4]])

    If there are no contractions, the same expression is returned

    >>> tc = G(i0)*G(i1)
    >>> kahane_simplify(tc)
    GammaMatrix(i0)*GammaMatrix(i1)

    References
    ==========

    [1] Algorithm for Reducing Contracted Products of gamma Matrices,
    Joseph Kahane, Journal of Mathematical Physics, Vol. 9, No. 10, October 1968.
    """

    if isinstance(expression, Mul):
        return expression
    if isinstance(expression, TensAdd):
        return TensAdd(*[kahane_simplify(arg) for arg in expression.args])

    if isinstance(expression, Tensor):
        return expression

    assert isinstance(expression, TensMul)

    gammas = expression.args

    for gamma in gammas:
        assert gamma.component == GammaMatrix

    free = expression.free
    # spinor_free = [_ for _ in expression.free_in_args if _[1] != 0]

    # if len(spinor_free) == 2:
    #     spinor_free.sort(key=lambda x: x[2])
    #     assert spinor_free[0][1] == 1 and spinor_free[-1][1] == 2
    #     assert spinor_free[0][2] == 0
    # elif spinor_free:
    #     raise ValueError('spinor indices do not match')

    dum = []
    for dum_pair in expression.dum:
        if expression.index_types[dum_pair[0]] == LorentzIndex:
            dum.append((dum_pair[0], dum_pair[1]))

    dum = sorted(dum)

    if len(dum) == 0:  # or GammaMatrixHead:
        # no contractions in `expression`, just return it.
        return expression

    # find the `first_dum_pos`, i.e. the position of the first contracted
    # gamma matrix, Kahane's algorithm as described in his paper requires the
    # gamma matrix expression to start with a contracted gamma matrix, this is
    # a workaround which ignores possible initial free indices, and re-adds
    # them later.

    first_dum_pos = min(map(min, dum))

    # for p1, p2, a1, a2 in expression.dum_in_args:
    #     if p1 != 0 or p2 != 0:
    #         # only Lorentz indices, skip Dirac indices:
    #         continue
    #     first_dum_pos = min(p1, p2)
    #     break

    total_number = len(free) + len(dum) * 2
    number_of_contractions = len(dum)

    free_pos = [None] * total_number
    for i in free:
        free_pos[i[1]] = i[0]

    # `index_is_free` is a list of booleans, to identify index position
    # and whether that index is free or dummy.
    index_is_free = [False] * total_number

    for i, indx in enumerate(free):
        index_is_free[indx[1]] = True

    # `links` is a dictionary containing the graph described in Kahane's paper,
    # to every key correspond one or two values, representing the linked indices.
    # All values in `links` are integers, negative numbers are used in the case
    # where it is necessary to insert gamma matrices between free indices, in
    # order to make Kahane's algorithm work (see paper).
    links = dict()
    for i in range(first_dum_pos, total_number):
        links[i] = []

    # `cum_sign` is a step variable to mark the sign of every index, see paper.
    cum_sign = -1
    # `cum_sign_list` keeps storage for all `cum_sign` (every index).
    cum_sign_list = [None] * total_number
    block_free_count = 0

    # multiply `resulting_coeff` by the coefficient parameter, the rest
    # of the algorithm ignores a scalar coefficient.
    resulting_coeff = S.One

    # initialize a list of lists of indices. The outer list will contain all
    # additive tensor expressions, while the inner list will contain the
    # free indices (rearranged according to the algorithm).
    resulting_indices = [[]]

    # start to count the `connected_components`, which together with the number
    # of contractions, determines a -1 or +1 factor to be multiplied.
    connected_components = 1

    # First loop: here we fill `cum_sign_list`, and draw the links
    # among consecutive indices (they are stored in `links`). Links among
    # non-consecutive indices will be drawn later.
    for i, is_free in enumerate(index_is_free):
        # if `expression` starts with free indices, they are ignored here;
        # they are later added as they are to the beginning of all
        # `resulting_indices` list of lists of indices.
        if i < first_dum_pos:
            continue

        if is_free:
            block_free_count += 1
            # if previous index was free as well, draw an arch in `links`.
            if block_free_count > 1:
                links[i - 1].append(i)
                links[i].append(i - 1)
        else:
            # Change the sign of the index (`cum_sign`) if the number of free
            # indices preceding it is even.
            cum_sign *= 1 if (block_free_count % 2) else -1
            if block_free_count == 0 and i != first_dum_pos:
                # check if there are two consecutive dummy indices:
                # in this case create virtual indices with negative position,
                # these "virtual" indices represent the insertion of two
                # gamma^0 matrices to separate consecutive dummy indices, as
                # Kahane's algorithm requires dummy indices to be separated by
                # free indices. The product of two gamma^0 matrices is unity,
                # so the new expression being examined is the same as the
                # original one.
                if cum_sign == -1:
                    links[-1 - i] = [-1 - i + 1]
                    links[-1 - i + 1] = [-1 - i]
            if (i - cum_sign) in links:
                if i != first_dum_pos:
                    links[i].append(i - cum_sign)
                if block_free_count != 0:
                    if i - cum_sign < len(index_is_free):
                        if index_is_free[i - cum_sign]:
                            links[i - cum_sign].append(i)
            block_free_count = 0

        cum_sign_list[i] = cum_sign

    # The previous loop has only created links between consecutive free indices,
    # it is necessary to properly create links among dummy (contracted) indices,
    # according to the rules described in Kahane's paper. There is only one exception
    # to Kahane's rules: the negative indices, which handle the case of some
    # consecutive free indices (Kahane's paper just describes dummy indices
    # separated by free indices, hinting that free indices can be added without
    # altering the expression result).
    for i in dum:
        # get the positions of the two contracted indices:
        pos1 = i[0]
        pos2 = i[1]

        # create Kahane's upper links, i.e. the upper arcs between dummy
        # (i.e. contracted) indices:
        links[pos1].append(pos2)
        links[pos2].append(pos1)

        # create Kahane's lower links, this corresponds to the arcs below
        # the line described in the paper:

        # first we move `pos1` and `pos2` according to the sign of the indices:
        linkpos1 = pos1 + cum_sign_list[pos1]
        linkpos2 = pos2 + cum_sign_list[pos2]

        # otherwise, perform some checks before creating the lower arcs:

        # make sure we are not exceeding the total number of indices:
        if linkpos1 >= total_number:
            continue
        if linkpos2 >= total_number:
            continue

        # make sure we are not below the first dummy index in `expression`:
        if linkpos1 < first_dum_pos:
            continue
        if linkpos2 < first_dum_pos:
            continue

        # check if the previous loop created "virtual" indices between dummy
        # indices, in such a case relink `linkpos1` and `linkpos2`:
        if (-1 - linkpos1) in links:
            linkpos1 = -1 - linkpos1
        if (-1 - linkpos2) in links:
            linkpos2 = -1 - linkpos2

        # move only if not next to free index:
        if linkpos1 >= 0 and not index_is_free[linkpos1]:
            linkpos1 = pos1

        if linkpos2 >= 0 and not index_is_free[linkpos2]:
            linkpos2 = pos2

        # create the lower arcs:
        if linkpos2 not in links[linkpos1]:
            links[linkpos1].append(linkpos2)
        if linkpos1 not in links[linkpos2]:
            links[linkpos2].append(linkpos1)

    # This loop starts from the `first_dum_pos` index (first dummy index)
    # walks through the graph deleting the visited indices from `links`,
    # it adds a gamma matrix for every free index in encounters, while it
    # completely ignores dummy indices and virtual indices.
    pointer = first_dum_pos
    previous_pointer = 0
    while True:
        if pointer in links:
            next_ones = links.pop(pointer)
        else:
            break

        if previous_pointer in next_ones:
            next_ones.remove(previous_pointer)

        previous_pointer = pointer

        if next_ones:
            pointer = next_ones[0]
        else:
            break

        if pointer == previous_pointer:
            break
        if pointer >= 0 and free_pos[pointer] is not None:
            for ri in resulting_indices:
                ri.append(free_pos[pointer])

    # The following loop removes the remaining connected components in `links`.
    # If there are free indices inside a connected component, it gives a
    # contribution to the resulting expression given by the factor
    # `gamma_a gamma_b ... gamma_z + gamma_z ... gamma_b gamma_a`, in Kahanes's
    # paper represented as  {gamma_a, gamma_b, ... , gamma_z},
    # virtual indices are ignored. The variable `connected_components` is
    # increased by one for every connected component this loop encounters.

    # If the connected component has virtual and dummy indices only
    # (no free indices), it contributes to `resulting_indices` by a factor of two.
    # The multiplication by two is a result of the
    # factor {gamma^0, gamma^0} = 2 I, as it appears in Kahane's paper.
    # Note: curly brackets are meant as in the paper, as a generalized
    # multi-element anticommutator!

    while links:
        connected_components += 1
        pointer = min(links.keys())
        previous_pointer = pointer
        # the inner loop erases the visited indices from `links`, and it adds
        # all free indices to `prepend_indices` list, virtual indices are
        # ignored.
        prepend_indices = []
        while True:
            if pointer in links:
                next_ones = links.pop(pointer)
            else:
                break

            if previous_pointer in next_ones:
                if len(next_ones) > 1:
                    next_ones.remove(previous_pointer)

            previous_pointer = pointer

            if next_ones:
                pointer = next_ones[0]

            if pointer >= first_dum_pos and free_pos[pointer] is not None:
                prepend_indices.insert(0, free_pos[pointer])
        # if `prepend_indices` is void, it means there are no free indices
        # in the loop (and it can be shown that there must be a virtual index),
        # loops of virtual indices only contribute by a factor of two:
        if len(prepend_indices) == 0:
            resulting_coeff *= 2
        # otherwise, add the free indices in `prepend_indices` to
        # the `resulting_indices`:
        else:
            expr1 = prepend_indices
            expr2 = list(reversed(prepend_indices))
            resulting_indices = [
                expri + ri for ri in resulting_indices
                for expri in (expr1, expr2)
            ]

    # sign correction, as described in Kahane's paper:
    resulting_coeff *= -1 if (number_of_contractions - connected_components +
                              1) % 2 else 1
    # power of two factor, as described in Kahane's paper:
    resulting_coeff *= 2**(number_of_contractions)

    # If `first_dum_pos` is not zero, it means that there are trailing free gamma
    # matrices in front of `expression`, so multiply by them:
    for i in range(0, first_dum_pos):
        [ri.insert(0, free_pos[i]) for ri in resulting_indices]

    resulting_expr = S.Zero
    for i in resulting_indices:
        temp_expr = S.One
        for j in i:
            temp_expr *= GammaMatrix(j)
        resulting_expr += temp_expr

    t = resulting_coeff * resulting_expr
    t1 = None
    if isinstance(t, TensAdd):
        t1 = t.args[0]
    elif isinstance(t, TensMul):
        t1 = t
    if t1:
        pass
    else:
        t = eye(4) * t
    return t
示例#18
0
from sympy.core.relational import (Equality, Unequality)
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.integrals.integrals import integrate
from sympy.matrices.dense import (Matrix, eye, zeros)
from sympy.matrices.immutable import ImmutableMatrix
from sympy.matrices import SparseMatrix
from sympy.matrices.immutable import \
    ImmutableDenseMatrix, ImmutableSparseMatrix
from sympy.abc import x, y
from sympy.testing.pytest import raises

IM = ImmutableDenseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
ISM = ImmutableSparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
ieye = ImmutableDenseMatrix(eye(3))


def test_creation():
    assert IM.shape == ISM.shape == (3, 3)
    assert IM[1, 2] == ISM[1, 2] == 6
    assert IM[2, 2] == ISM[2, 2] == 9


def test_immutability():
    with raises(TypeError):
        IM[2, 2] = 5
    with raises(TypeError):
        ISM[2, 2] = 5

示例#19
0
def test_orient_explicit():
    A = ReferenceFrame('A')
    B = ReferenceFrame('B')
    A.orient_explicit(B, eye(3))
    assert A.dcm(B) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
示例#20
0
from sympy.core.symbol import Symbol
from sympy.matrices.dense import (eye, zeros)
from sympy.solvers.solvers import solve_linear_system

N = 8
M = zeros(N, N + 1)
M[:, :N] = eye(N)
S = [Symbol('A%i' % i) for i in range(N)]


def timeit_linsolve_trivial():
    solve_linear_system(M, *S)
示例#21
0
 def add_delta(ne):
     return ne * eye(4)  # DiracSpinorIndex.delta(DiracSpinorIndex.auto_left, -DiracSpinorIndex.auto_right)
示例#22
0
def test_kahane_simplify1():
    i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15 = tensor_indices('i0:16', LorentzIndex)
    mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
    D = 4
    t = G(i0)*G(i1)
    r = kahane_simplify(t)
    assert r.equals(t)

    t = G(i0)*G(i1)*G(-i0)
    r = kahane_simplify(t)
    assert r.equals(-2*G(i1))
    t = G(i0)*G(i1)*G(-i0)
    r = kahane_simplify(t)
    assert r.equals(-2*G(i1))

    t = G(i0)*G(i1)
    r = kahane_simplify(t)
    assert r.equals(t)
    t = G(i0)*G(i1)
    r = kahane_simplify(t)
    assert r.equals(t)
    t = G(i0)*G(-i0)
    r = kahane_simplify(t)
    assert r.equals(4*eye(4))
    t = G(i0)*G(-i0)
    r = kahane_simplify(t)
    assert r.equals(4*eye(4))
    t = G(i0)*G(-i0)
    r = kahane_simplify(t)
    assert r.equals(4*eye(4))
    t = G(i0)*G(i1)*G(-i0)
    r = kahane_simplify(t)
    assert r.equals(-2*G(i1))
    t = G(i0)*G(i1)*G(-i0)*G(-i1)
    r = kahane_simplify(t)
    assert r.equals((2*D - D**2)*eye(4))
    t = G(i0)*G(i1)*G(-i0)*G(-i1)
    r = kahane_simplify(t)
    assert r.equals((2*D - D**2)*eye(4))
    t = G(i0)*G(-i0)*G(i1)*G(-i1)
    r = kahane_simplify(t)
    assert r.equals(16*eye(4))
    t = (G(mu)*G(nu)*G(-nu)*G(-mu))
    r = kahane_simplify(t)
    assert r.equals(D**2*eye(4))
    t = (G(mu)*G(nu)*G(-nu)*G(-mu))
    r = kahane_simplify(t)
    assert r.equals(D**2*eye(4))
    t = (G(mu)*G(nu)*G(-nu)*G(-mu))
    r = kahane_simplify(t)
    assert r.equals(D**2*eye(4))
    t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
    r = kahane_simplify(t)
    assert r.equals((4*D - 4*D**2 + D**3)*eye(4))
    t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
    r = kahane_simplify(t)
    assert r.equals((-16*D + 24*D**2 - 8*D**3 + D**4)*eye(4))
    t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
    r = kahane_simplify(t)
    assert r.equals((8*D - 12*D**2 + 6*D**3 - D**4)*eye(4))

    # Expressions with free indices:
    t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
    r = kahane_simplify(t)
    assert r.equals(-2*G(sigma)*G(rho)*G(nu))
    t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
    r = kahane_simplify(t)
    assert r.equals(-2*G(sigma)*G(rho)*G(nu))
示例#23
0
def test_KroneckerProduct_identity():
    assert KroneckerProduct(Identity(m), Identity(n)) == Identity(m * n)
    assert KroneckerProduct(eye(2), eye(3)) == eye(6)
示例#24
0
def test_inv_can_transf_matrix():
    dimsys = DimensionSystem((length, mass, time))
    assert dimsys.inv_can_transf_matrix == eye(3)
示例#25
0
    def __new__(cls, name, transformation=None, parent=None, location=None,
                rotation_matrix=None, vector_names=None, variable_names=None):
        """
        The orientation/location parameters are necessary if this system
        is being defined at a certain orientation or location wrt another.

        Parameters
        ==========

        name : str
            The name of the new CoordSys3D instance.

        transformation : Lambda, Tuple, str
            Transformation defined by transformation equations or chosen
            from predefined ones.

        location : Vector
            The position vector of the new system's origin wrt the parent
            instance.

        rotation_matrix : SymPy ImmutableMatrix
            The rotation matrix of the new coordinate system with respect
            to the parent. In other words, the output of
            new_system.rotation_matrix(parent).

        parent : CoordSys3D
            The coordinate system wrt which the orientation/location
            (or both) is being defined.

        vector_names, variable_names : iterable(optional)
            Iterables of 3 strings each, with custom names for base
            vectors and base scalars of the new system respectively.
            Used for simple str printing.

        """

        name = str(name)
        Vector = sympy.vector.Vector
        Point = sympy.vector.Point

        if not isinstance(name, str):
            raise TypeError("name should be a string")

        if transformation is not None:
            if (location is not None) or (rotation_matrix is not None):
                raise ValueError("specify either `transformation` or "
                                 "`location`/`rotation_matrix`")
            if isinstance(transformation, (Tuple, tuple, list)):
                if isinstance(transformation[0], MatrixBase):
                    rotation_matrix = transformation[0]
                    location = transformation[1]
                else:
                    transformation = Lambda(transformation[0],
                                            transformation[1])
            elif isinstance(transformation, Callable):
                x1, x2, x3 = symbols('x1 x2 x3', cls=Dummy)
                transformation = Lambda((x1, x2, x3),
                                        transformation(x1, x2, x3))
            elif isinstance(transformation, str):
                transformation = Str(transformation)
            elif isinstance(transformation, (Str, Lambda)):
                pass
            else:
                raise TypeError("transformation: "
                                "wrong type {}".format(type(transformation)))

        # If orientation information has been provided, store
        # the rotation matrix accordingly
        if rotation_matrix is None:
            rotation_matrix = ImmutableDenseMatrix(eye(3))
        else:
            if not isinstance(rotation_matrix, MatrixBase):
                raise TypeError("rotation_matrix should be an Immutable" +
                                "Matrix instance")
            rotation_matrix = rotation_matrix.as_immutable()

        # If location information is not given, adjust the default
        # location as Vector.zero
        if parent is not None:
            if not isinstance(parent, CoordSys3D):
                raise TypeError("parent should be a " +
                                "CoordSys3D/None")
            if location is None:
                location = Vector.zero
            else:
                if not isinstance(location, Vector):
                    raise TypeError("location should be a Vector")
                # Check that location does not contain base
                # scalars
                for x in location.free_symbols:
                    if isinstance(x, BaseScalar):
                        raise ValueError("location should not contain" +
                                         " BaseScalars")
            origin = parent.origin.locate_new(name + '.origin',
                                              location)
        else:
            location = Vector.zero
            origin = Point(name + '.origin')

        if transformation is None:
            transformation = Tuple(rotation_matrix, location)

        if isinstance(transformation, Tuple):
            lambda_transformation = CoordSys3D._compose_rotation_and_translation(
                transformation[0],
                transformation[1],
                parent
            )
            r, l = transformation
            l = l._projections
            lambda_lame = CoordSys3D._get_lame_coeff('cartesian')
            lambda_inverse = lambda x, y, z: r.inv()*Matrix(
                [x-l[0], y-l[1], z-l[2]])
        elif isinstance(transformation, Str):
            trname = transformation.name
            lambda_transformation = CoordSys3D._get_transformation_lambdas(trname)
            if parent is not None:
                if parent.lame_coefficients() != (S.One, S.One, S.One):
                    raise ValueError('Parent for pre-defined coordinate '
                                 'system should be Cartesian.')
            lambda_lame = CoordSys3D._get_lame_coeff(trname)
            lambda_inverse = CoordSys3D._set_inv_trans_equations(trname)
        elif isinstance(transformation, Lambda):
            if not CoordSys3D._check_orthogonality(transformation):
                raise ValueError("The transformation equation does not "
                                 "create orthogonal coordinate system")
            lambda_transformation = transformation
            lambda_lame = CoordSys3D._calculate_lame_coeff(lambda_transformation)
            lambda_inverse = None
        else:
            lambda_transformation = lambda x, y, z: transformation(x, y, z)
            lambda_lame = CoordSys3D._get_lame_coeff(transformation)
            lambda_inverse = None

        if variable_names is None:
            if isinstance(transformation, Lambda):
                variable_names = ["x1", "x2", "x3"]
            elif isinstance(transformation, Str):
                if transformation.name == 'spherical':
                    variable_names = ["r", "theta", "phi"]
                elif transformation.name == 'cylindrical':
                    variable_names = ["r", "theta", "z"]
                else:
                    variable_names = ["x", "y", "z"]
            else:
                variable_names = ["x", "y", "z"]
        if vector_names is None:
            vector_names = ["i", "j", "k"]

        # All systems that are defined as 'roots' are unequal, unless
        # they have the same name.
        # Systems defined at same orientation/position wrt the same
        # 'parent' are equal, irrespective of the name.
        # This is true even if the same orientation is provided via
        # different methods like Axis/Body/Space/Quaternion.
        # However, coincident systems may be seen as unequal if
        # positioned/oriented wrt different parents, even though
        # they may actually be 'coincident' wrt the root system.
        if parent is not None:
            obj = super().__new__(
                cls, Str(name), transformation, parent)
        else:
            obj = super().__new__(
                cls, Str(name), transformation)
        obj._name = name
        # Initialize the base vectors

        _check_strings('vector_names', vector_names)
        vector_names = list(vector_names)
        latex_vects = [(r'\mathbf{\hat{%s}_{%s}}' % (x, name)) for
                           x in vector_names]
        pretty_vects = ['%s_%s' % (x, name) for x in vector_names]

        obj._vector_names = vector_names

        v1 = BaseVector(0, obj, pretty_vects[0], latex_vects[0])
        v2 = BaseVector(1, obj, pretty_vects[1], latex_vects[1])
        v3 = BaseVector(2, obj, pretty_vects[2], latex_vects[2])

        obj._base_vectors = (v1, v2, v3)

        # Initialize the base scalars

        _check_strings('variable_names', vector_names)
        variable_names = list(variable_names)
        latex_scalars = [(r"\mathbf{{%s}_{%s}}" % (x, name)) for
                         x in variable_names]
        pretty_scalars = ['%s_%s' % (x, name) for x in variable_names]

        obj._variable_names = variable_names
        obj._vector_names = vector_names

        x1 = BaseScalar(0, obj, pretty_scalars[0], latex_scalars[0])
        x2 = BaseScalar(1, obj, pretty_scalars[1], latex_scalars[1])
        x3 = BaseScalar(2, obj, pretty_scalars[2], latex_scalars[2])

        obj._base_scalars = (x1, x2, x3)

        obj._transformation = transformation
        obj._transformation_lambda = lambda_transformation
        obj._lame_coefficients = lambda_lame(x1, x2, x3)
        obj._transformation_from_parent_lambda = lambda_inverse

        setattr(obj, variable_names[0], x1)
        setattr(obj, variable_names[1], x2)
        setattr(obj, variable_names[2], x3)

        setattr(obj, vector_names[0], v1)
        setattr(obj, vector_names[1], v2)
        setattr(obj, vector_names[2], v3)

        # Assign params
        obj._parent = parent
        if obj._parent is not None:
            obj._root = obj._parent._root
        else:
            obj._root = obj

        obj._parent_rotation_matrix = rotation_matrix
        obj._origin = origin

        # Return the instance
        return obj
示例#26
0
def test_matrix_exp():
    from sympy.matrices.dense import Matrix, eye, zeros
    from sympy.solvers.ode.systems import matrix_exp
    t = Symbol('t')

    for n in range(1, 6 + 1):
        assert matrix_exp(zeros(n), t) == eye(n)

    for n in range(1, 6 + 1):
        A = eye(n)
        expAt = exp(t) * eye(n)
        assert matrix_exp(A, t) == expAt

    for n in range(1, 6 + 1):
        A = Matrix(n, n, lambda i, j: i + 1 if i == j else 0)
        expAt = Matrix(n, n, lambda i, j: exp((i + 1) * t) if i == j else 0)
        assert matrix_exp(A, t) == expAt

    A = Matrix([[0, 1], [-1, 0]])
    expAt = Matrix([[cos(t), sin(t)], [-sin(t), cos(t)]])
    assert matrix_exp(A, t) == expAt

    A = Matrix([[2, -5], [2, -4]])
    expAt = Matrix(
        [[3 * exp(-t) * sin(t) + exp(-t) * cos(t), -5 * exp(-t) * sin(t)],
         [2 * exp(-t) * sin(t), -3 * exp(-t) * sin(t) + exp(-t) * cos(t)]])
    assert matrix_exp(A, t) == expAt

    A = Matrix([[21, 17, 6], [-5, -1, -6], [4, 4, 16]])
    # TO update this.
    # expAt = Matrix([
    #     [(8*t*exp(12*t) + 5*exp(12*t) - 1)*exp(4*t)/4,
    #      (8*t*exp(12*t) + 5*exp(12*t) - 5)*exp(4*t)/4,
    #      (exp(12*t) - 1)*exp(4*t)/2],
    #     [(-8*t*exp(12*t) - exp(12*t) + 1)*exp(4*t)/4,
    #      (-8*t*exp(12*t) - exp(12*t) + 5)*exp(4*t)/4,
    #      (-exp(12*t) + 1)*exp(4*t)/2],
    #     [4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)]])
    expAt = Matrix(
        [[
            2 * t * exp(16 * t) + 5 * exp(16 * t) / 4 - exp(4 * t) / 4,
            2 * t * exp(16 * t) + 5 * exp(16 * t) / 4 - 5 * exp(4 * t) / 4,
            exp(16 * t) / 2 - exp(4 * t) / 2
        ],
         [
             -2 * t * exp(16 * t) - exp(16 * t) / 4 + exp(4 * t) / 4,
             -2 * t * exp(16 * t) - exp(16 * t) / 4 + 5 * exp(4 * t) / 4,
             -exp(16 * t) / 2 + exp(4 * t) / 2
         ], [4 * t * exp(16 * t), 4 * t * exp(16 * t),
             exp(16 * t)]])
    assert matrix_exp(A, t) == expAt

    A = Matrix([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, -S(1) / 8],
                [0, 0, S(1) / 2, S(1) / 2]])
    expAt = Matrix(
        [[
            exp(t), t * exp(t), 4 * t * exp(3 * t / 4) + 8 * t * exp(t) +
            48 * exp(3 * t / 4) - 48 * exp(t), -2 * t * exp(3 * t / 4) -
            2 * t * exp(t) - 16 * exp(3 * t / 4) + 16 * exp(t)
        ],
         [
             0,
             exp(t), -t * exp(3 * t / 4) - 8 * exp(3 * t / 4) + 8 * exp(t),
             t * exp(3 * t / 4) / 2 + 2 * exp(3 * t / 4) - 2 * exp(t)
         ],
         [
             0, 0, t * exp(3 * t / 4) / 4 + exp(3 * t / 4),
             -t * exp(3 * t / 4) / 8
         ],
         [
             0, 0, t * exp(3 * t / 4) / 2,
             -t * exp(3 * t / 4) / 4 + exp(3 * t / 4)
         ]])
    assert matrix_exp(A, t) == expAt

    A = Matrix([[0, 1, 0, 0], [-1, 0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0]])

    expAt = Matrix([[cos(t), sin(t), 0, 0], [-sin(t), cos(t), 0, 0],
                    [0, 0, cos(t), sin(t)], [0, 0, -sin(t),
                                             cos(t)]])
    assert matrix_exp(A, t) == expAt

    A = Matrix([[0, 1, 1, 0], [-1, 0, 0, 1], [0, 0, 0, 1], [0, 0, -1, 0]])

    expAt = Matrix([[cos(t), sin(t), t * cos(t), t * sin(t)],
                    [-sin(t), cos(t), -t * sin(t), t * cos(t)],
                    [0, 0, cos(t), sin(t)], [0, 0, -sin(t),
                                             cos(t)]])
    assert matrix_exp(A, t) == expAt

    # This case is unacceptably slow right now but should be solvable...
    #a, b, c, d, e, f = symbols('a b c d e f')
    #A = Matrix([
    #[-a,  b,          c,  d],
    #[ a, -b,          e,  0],
    #[ 0,  0, -c - e - f,  0],
    #[ 0,  0,          f, -d]])

    A = Matrix([[0, I], [I, 0]])
    expAt = Matrix(
        [[exp(I * t) / 2 + exp(-I * t) / 2,
          exp(I * t) / 2 - exp(-I * t) / 2],
         [exp(I * t) / 2 - exp(-I * t) / 2,
          exp(I * t) / 2 + exp(-I * t) / 2]])
    assert matrix_exp(A, t) == expAt
示例#27
0
    def orient_new(self, name, orienters, location=None,
                   vector_names=None, variable_names=None):
        """
        Creates a new CoordSys3D oriented in the user-specified way
        with respect to this system.

        Please refer to the documentation of the orienter classes
        for more information about the orientation procedure.

        Parameters
        ==========

        name : str
            The name of the new CoordSys3D instance.

        orienters : iterable/Orienter
            An Orienter or an iterable of Orienters for orienting the
            new coordinate system.
            If an Orienter is provided, it is applied to get the new
            system.
            If an iterable is provided, the orienters will be applied
            in the order in which they appear in the iterable.

        location : Vector(optional)
            The location of the new coordinate system's origin wrt this
            system's origin. If not specified, the origins are taken to
            be coincident.

        vector_names, variable_names : iterable(optional)
            Iterables of 3 strings each, with custom names for base
            vectors and base scalars of the new system respectively.
            Used for simple str printing.

        Examples
        ========

        >>> from sympy.vector import CoordSys3D
        >>> from sympy import symbols
        >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
        >>> N = CoordSys3D('N')

        Using an AxisOrienter

        >>> from sympy.vector import AxisOrienter
        >>> axis_orienter = AxisOrienter(q1, N.i + 2 * N.j)
        >>> A = N.orient_new('A', (axis_orienter, ))

        Using a BodyOrienter

        >>> from sympy.vector import BodyOrienter
        >>> body_orienter = BodyOrienter(q1, q2, q3, '123')
        >>> B = N.orient_new('B', (body_orienter, ))

        Using a SpaceOrienter

        >>> from sympy.vector import SpaceOrienter
        >>> space_orienter = SpaceOrienter(q1, q2, q3, '312')
        >>> C = N.orient_new('C', (space_orienter, ))

        Using a QuaternionOrienter

        >>> from sympy.vector import QuaternionOrienter
        >>> q_orienter = QuaternionOrienter(q0, q1, q2, q3)
        >>> D = N.orient_new('D', (q_orienter, ))
        """
        if variable_names is None:
            variable_names = self._variable_names
        if vector_names is None:
            vector_names = self._vector_names

        if isinstance(orienters, Orienter):
            if isinstance(orienters, AxisOrienter):
                final_matrix = orienters.rotation_matrix(self)
            else:
                final_matrix = orienters.rotation_matrix()
            # TODO: trigsimp is needed here so that the matrix becomes
            # canonical (scalar_map also calls trigsimp; without this, you can
            # end up with the same CoordinateSystem that compares differently
            # due to a differently formatted matrix). However, this is
            # probably not so good for performance.
            final_matrix = trigsimp(final_matrix)
        else:
            final_matrix = Matrix(eye(3))
            for orienter in orienters:
                if isinstance(orienter, AxisOrienter):
                    final_matrix *= orienter.rotation_matrix(self)
                else:
                    final_matrix *= orienter.rotation_matrix()

        return CoordSys3D(name, rotation_matrix=final_matrix,
                          vector_names=vector_names,
                          variable_names=variable_names,
                          location=location,
                          parent=self)
示例#28
0
from sympy.core.numbers import Integer
from sympy.matrices.dense import (eye, zeros)

i3 = Integer(3)
M = eye(100)


def timeit_Matrix__getitem_ii():
    M[3, 3]


def timeit_Matrix__getitem_II():
    M[i3, i3]


def timeit_Matrix__getslice():
    M[:, :]


def timeit_Matrix_zeronm():
    zeros(100, 100)
示例#29
0
def test_banded():
    raises(TypeError, lambda: banded())
    raises(TypeError, lambda: banded(1))
    raises(TypeError, lambda: banded(1, 2))
    raises(TypeError, lambda: banded(1, 2, 3))
    raises(TypeError, lambda: banded(1, 2, 3, 4))
    raises(ValueError, lambda: banded({0: (1, 2)}, rows=1))
    raises(ValueError, lambda: banded({0: (1, 2)}, cols=1))
    raises(ValueError, lambda: banded(1, {0: (1, 2)}))
    raises(ValueError, lambda: banded(2, 1, {0: (1, 2)}))
    raises(ValueError, lambda: banded(1, 2, {0: (1, 2)}))

    assert isinstance(banded(2, 4, {}), SparseMatrix)
    assert banded(2, 4, {}) == zeros(2, 4)
    assert banded({0: 0, 1: 0}) == zeros(0)
    assert banded({0: Matrix([1, 2])}) == Matrix([1, 2])
    assert banded({1: [1, 2, 3, 0], -1: [4, 5, 6]}) == \
        banded({1: (1, 2, 3), -1: (4, 5, 6)}) == \
        Matrix([
        [0, 1, 0, 0],
        [4, 0, 2, 0],
        [0, 5, 0, 3],
        [0, 0, 6, 0]])
    assert banded(3, 4, {-1: 1, 0: 2, 1: 3}) == \
        Matrix([
        [2, 3, 0, 0],
        [1, 2, 3, 0],
        [0, 1, 2, 3]])
    s = lambda d: (1 + d)**2
    assert banded(5, {0: s, 2: s}) == \
        Matrix([
        [1, 0, 1,  0,  0],
        [0, 4, 0,  4,  0],
        [0, 0, 9,  0,  9],
        [0, 0, 0, 16,  0],
        [0, 0, 0,  0, 25]])
    assert banded(2, {0: 1}) == \
        Matrix([
        [1, 0],
        [0, 1]])
    assert banded(2, 3, {0: 1}) == \
        Matrix([
        [1, 0, 0],
        [0, 1, 0]])
    vert = Matrix([1, 2, 3])
    assert banded({0: vert}, cols=3) == \
        Matrix([
        [1, 0, 0],
        [2, 1, 0],
        [3, 2, 1],
        [0, 3, 2],
        [0, 0, 3]])
    assert banded(4, {0: ones(2)}) == \
        Matrix([
        [1, 1, 0, 0],
        [1, 1, 0, 0],
        [0, 0, 1, 1],
        [0, 0, 1, 1]])
    raises(ValueError, lambda: banded({0: 2, 1: ones(2)}, rows=5))
    assert banded({0: 2, 2: (ones(2),)*3}) == \
        Matrix([
        [2, 0, 1, 1, 0, 0, 0, 0],
        [0, 2, 1, 1, 0, 0, 0, 0],
        [0, 0, 2, 0, 1, 1, 0, 0],
        [0, 0, 0, 2, 1, 1, 0, 0],
        [0, 0, 0, 0, 2, 0, 1, 1],
        [0, 0, 0, 0, 0, 2, 1, 1]])
    raises(ValueError, lambda: banded({0: (2, ) * 5, 1: (ones(2), ) * 3}))
    u2 = Matrix([[1, 1], [0, 1]])
    assert banded({0: (2,)*5, 1: (u2,)*3}) == \
        Matrix([
        [2, 1, 1, 0, 0, 0, 0],
        [0, 2, 1, 0, 0, 0, 0],
        [0, 0, 2, 1, 1, 0, 0],
        [0, 0, 0, 2, 1, 0, 0],
        [0, 0, 0, 0, 2, 1, 1],
        [0, 0, 0, 0, 0, 0, 1]])
    assert banded({0:(0, ones(2)), 2: 2}) == \
        Matrix([
        [0, 0, 2],
        [0, 1, 1],
        [0, 1, 1]])
    raises(ValueError, lambda: banded({0: (0, ones(2)), 1: 2}))
    assert banded({0: 1}, cols=3) == banded({0: 1}, rows=3) == eye(3)
    assert banded({1: 1}, rows=3) == Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]])