python类Matrix()的实例源码

test_commonmatrix.py 文件源码 项目:Python-iBeacon-Scan 作者: NikNitro 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_conjugate():
    M = OperationsOnlyMatrix([[0, I, 5],
                [1, 2, 0]])

    assert M.T == Matrix([[0, 1],
                          [I, 2],
                          [5, 0]])

    assert M.C == Matrix([[0, -I, 5],
                          [1,  2, 0]])
    assert M.C == M.conjugate()

    assert M.H == M.T.C
    assert M.H == Matrix([[ 0, 1],
                          [-I, 2],
                          [ 5, 0]])
test_tensor.py 文件源码 项目:Python-iBeacon-Scan 作者: NikNitro 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_valued_tensor_get_matrix():
    numpy = import_module("numpy")
    if numpy is None:
        skip("numpy not installed.")

    (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
     n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()

    matab = AB(i0, i1).get_matrix()
    assert matab == Matrix([
                            [1,  0,  0,  0],
                            [0, -1,  0,  0],
                            [0,  0, -1,  0],
                            [0,  0,  0, -1],
                            ])
    # when alternating contravariant/covariant with [1, -1, -1, -1] metric
    # it becomes the identity matrix:
    assert AB(i0, -i1).get_matrix() == eye(4)

    # covariant and contravariant forms:
    assert A(i0).get_matrix() == Matrix([E, px, py, pz])
    assert A(-i0).get_matrix() == Matrix([E, -px, -py, -pz])
tableform.py 文件源码 项目:Python-iBeacon-Scan 作者: NikNitro 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def as_matrix(self):
        """Returns the data of the table in Matrix form.

        Examples
        ========

        >>> from sympy import TableForm
        >>> t = TableForm([[5, 7], [4, 2], [10, 3]], headings='automatic')
        >>> t
          | 1  2
        --------
        1 | 5  7
        2 | 4  2
        3 | 10 3
        >>> t.as_matrix()
        Matrix([
        [ 5, 7],
        [ 4, 2],
        [10, 3]])
        """
        from sympy import Matrix
        return Matrix(self._lines)
test_numpy.py 文件源码 项目:Python-iBeacon-Scan 作者: NikNitro 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_Matrix_mul():
    M = Matrix([[1, 2, 3], [x, y, x]])
    m = matrix([[2, 4], [x, 6], [x, z**2]])
    assert M*m == Matrix([
        [         2 + 5*x,        16 + 3*z**2],
        [2*x + x*y + x**2, 4*x + 6*y + x*z**2],
    ])

    assert m*M == Matrix([
        [   2 + 4*x,      4 + 4*y,      6 + 4*x],
        [       7*x,    2*x + 6*y,          9*x],
        [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
    ])
    a = array([2])
    assert a[0] * M == 2 * M
    assert M * a[0] == 2 * M
test_cyl_innerproducts.py 文件源码 项目:discretize 作者: simpeg 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def fcts(self):
        j = sympy.Matrix([
            r**2 * z,
            r * z**2
        ])

        # Create an isotropic sigma vector
        Sig = sympy.Matrix([
            [420/(sympy.pi)*(r*z)**2, 0],
            [0, 420/(sympy.pi)*(r*z)**2],
        ])

        return j, Sig
test_cyl_innerproducts.py 文件源码 项目:discretize 作者: simpeg 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def fcts(self):
        j = sympy.Matrix([
            r**2 * z,
            r * z**2
        ])

        # Create an isotropic sigma vector
        Sig = sympy.Matrix([
            [120/(sympy.pi)*(r*z)**2, 0],
            [0, 420/(sympy.pi)*(r*z)**2],
        ])

        return j, Sig
test_cyl_innerproducts.py 文件源码 项目:discretize 作者: simpeg 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def fcts(self):
        h = sympy.Matrix([r**2 * z])

        # Create an isotropic sigma vector
        Sig = sympy.Matrix([200/(sympy.pi)*(r*z)**2])

        return h, Sig
observer.py 文件源码 项目:pymoskito 作者: cklb 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, settings):
        settings.update(output_dim=4)
        super().__init__(settings)

        params = sp.symbols('x1, x2, x3, x4, tau')
        x1, x2, x3, x4, tau = params
        x = [x1, x2, x3, x4]
        h = sp.Matrix([[x1]])
        f = sp.Matrix([[x2],
                       [st.B * x1 * x4 ** 2 - st.B * st.G * sin(x3)],
                       [x4],
                       [(tau - 2 * st.M * x1 * x2 * x4
                         - st.M * st.G * x1 * cos(x3)) / (
                        st.M * x1 ** 2 + st.J + st.Jb)]])

        q = sp.Matrix(pm.lie_derivatives(h, f, x, len(x) - 1))
        dq = q.jacobian(x)

        if dq.rank() != len(x):
            raise Exception("System might not be observable")

        # gets p = [p0, p1, ... pn-1]
        p = pm.char_coefficients(self._settings["poles"])

        k = p[::-1]
        l = dq.inv() @ k

        mat2array = [{'ImmutableMatrix': np.array}, 'numpy']
        self.h_func = sp.lambdify((x1, x2, x3, x4, tau), h, modules=mat2array)
        self.l_func = sp.lambdify((x1, x2, x3, x4, tau), l, modules=mat2array)
        self.f_func = sp.lambdify((x1, x2, x3, x4, tau), f, modules=mat2array)

        self.output = np.array(self._settings["initial state"], dtype=float)
test_tools.py 文件源码 项目:pymoskito 作者: cklb 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def setUp(self):
        self._x1, self._x2 = sp.symbols("x y")
        self.x = sp.Matrix([self._x1, self._x2])
        self.f = sp.Matrix([-self._x2**2, sp.sin(self._x1)])
        self.h = sp.Matrix([self._x1**2 - sp.sin(self._x2)])
routines.py 文件源码 项目:triflow 作者: locie 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def __repr__(self):
        return sp.Matrix(self.matrix.tolist()).__repr__()
paramselect.py 文件源码 项目:ESPEI 作者: PhasesResearchLab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _build_feature_matrix(prop, features, desired_data):
    transformed_features = sympy.Matrix([feature_transforms[prop](i) for i in features])
    all_samples = get_samples(desired_data)
    feature_matrix = np.empty((len(all_samples), len(transformed_features)), dtype=np.float)
    feature_matrix[:, :] = [transformed_features.subs({v.T: temp, 'YS': compf[0],
                                                       'Z': compf[1]}).evalf()
                            for temp, compf in all_samples]
    return feature_matrix
hyperexpand.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _compute_basis(self, closed_form):
        """
        Compute a set of functions B=(f1, ..., fn), a nxn matrix M
        and a 1xn matrix C such that:
           closed_form = C B
           z d/dz B = M B.
        """
        from sympy.matrices import Matrix, eye, zeros

        afactors = [_x + a for a in self.func.ap]
        bfactors = [_x + b - 1 for b in self.func.bq]
        expr = _x*Mul(*bfactors) - self.z*Mul(*afactors)
        poly = Poly(expr, _x)

        n = poly.degree() - 1
        b = [closed_form]
        for _ in xrange(n):
            b.append(self.z*b[-1].diff(self.z))

        self.B = Matrix(b)
        self.C = Matrix([[1] + [0]*n])

        m = eye(n)
        m = m.col_insert(0, zeros(n, 1))
        l = poly.all_coeffs()[1:]
        l.reverse()
        self.M = m.row_insert(n, -Matrix([l])/poly.all_coeffs()[0])
test_containers.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_iterable_is_sequence():
    ordered = [list(), tuple(), Tuple(), Matrix([[]])]
    unordered = [set()]
    not_sympy_iterable = [{}, '', u('')]
    assert all(is_sequence(i) for i in ordered)
    assert all(not is_sequence(i) for i in unordered)
    assert all(iterable(i) for i in ordered + unordered)
    assert all(not iterable(i) for i in not_sympy_iterable)
    assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
test_numeric.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_nsolve():
    # onedimensional
    x = Symbol('x')
    assert nsolve(sin(x), 2) - pi.evalf() < 1e-15
    assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10)
    # Testing checks on number of inputs
    raises(TypeError, lambda: nsolve(Eq(2*x, 2)))
    raises(TypeError, lambda: nsolve(Eq(2*x, 2), x, 1, 2))
    # issue 4829
    assert nsolve(x**2/(1 - x)/(1 - 2*x)**2 - 100, x, 0)  # doesn't fail
    # multidimensional
    x1 = Symbol('x1')
    x2 = Symbol('x2')
    f1 = 3 * x1**2 - 2 * x2**2 - 1
    f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    f = Matrix((f1, f2)).T
    F = lambdify((x1, x2), f.T, modules='mpmath')
    for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
        x = nsolve(f, (x1, x2), x0, tol=1.e-8)
        assert mnorm(F(*x), 1) <= 1.e-10
    # The Chinese mathematician Zhu Shijie was the very first to solve this
    # nonlinear system 700 years ago (z was added to make it 3-dimensional)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    f1 = -x + 2*y
    f2 = (x**2 + x*(y**2 - 2) - 4*y) / (x + 4)
    f3 = sqrt(x**2 + y**2)*z
    f = Matrix((f1, f2, f3)).T
    F = lambdify((x, y, z), f.T, modules='mpmath')

    def getroot(x0):
        root = nsolve(f, (x, y, z), x0)
        assert mnorm(F(*root), 1) <= 1.e-8
        return root
    assert list(map(round, getroot((1, 1, 1)))) == [2.0, 1.0, 0.0]
    assert nsolve([Eq(
        f1), Eq(f2), Eq(f3)], [x, y, z], (1, 1, 1))  # just see that it works
    a = Symbol('a')
    assert nsolve(1/(0.001 + a)**3 - 6/(0.9 - a)**3, a, 0.3).ae(
        mpf('0.31883011387318591'))
test_diophantine.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def is_normal_transformation_ok(eq):

    A = transformation_to_normal(eq)
    X, Y, Z = A*Matrix([x, y, z])
    simplified = _mexpand(Subs(eq, (x, y, z), (X, Y, Z)).doit())

    coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
    for term in [X*Y, Y*Z, X*Z]:
        if term in coeff.keys():
            return False

    return True
qft.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_target_matrix(self, format='sympy'):
        if format == 'sympy':
            return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]])
        raise NotImplementedError(
            'Invalid format for the R_k gate: %r' % format)
qft.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _represent_ZGate(self, basis, **options):
        """
            Represents the (I)QFT In the Z Basis
        """
        nqubits = options.get('nqubits', 0)
        if nqubits == 0:
            raise QuantumError(
                'The number of qubits must be given as nqubits.')
        if nqubits < self.min_qubits:
            raise QuantumError(
                'The number of qubits %r is too small for the gate.' % nqubits
            )
        size = self.size
        omega = self.omega

        #Make a matrix that has the basic Fourier Transform Matrix
        arrayFT = [[omega**(
            i*j % size)/sqrt(size) for i in range(size)] for j in range(size)]
        matrixFT = Matrix(arrayFT)

        #Embed the FT Matrix in a higher space, if necessary
        if self.label[0] != 0:
            matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT)
        if self.min_qubits < nqubits:
            matrixFT = matrix_tensor_product(
                matrixFT, eye(2**(nqubits - self.min_qubits)))

        return matrixFT
matrixutils.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def sympy_to_numpy(m, **options):
    """Convert a sympy Matrix/complex number to a numpy matrix or scalar."""
    if not np:
        raise ImportError
    dtype = options.get('dtype', 'complex')
    if isinstance(m, Matrix):
        return np.matrix(m.tolist(), dtype=dtype)
    elif isinstance(m, Expr):
        if m.is_Number or m.is_NumberSymbol or m == I:
            return complex(m)
    raise TypeError('Expected Matrix or complex scalar, got: %r' % m)
matrixutils.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def sympy_to_scipy_sparse(m, **options):
    """Convert a sympy Matrix/complex number to a numpy matrix or scalar."""
    if not np or not sparse:
        raise ImportError
    dtype = options.get('dtype', 'complex')
    if isinstance(m, Matrix):
        return sparse.csr_matrix(np.matrix(m.tolist(), dtype=dtype))
    elif isinstance(m, Expr):
        if m.is_Number or m.is_NumberSymbol or m == I:
            return complex(m)
    raise TypeError('Expected Matrix or complex scalar, got: %r' % m)
matrixutils.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def scipy_sparse_to_sympy(m, **options):
    """Convert a scipy.sparse matrix to a sympy matrix."""
    return Matrix(m.todense())


问题


面经


文章

微信
公众号

扫码关注公众号