示例#1
0
def demo_corr_bound(n):
    def corr(i, j):
        if i == j:
            return 1
        else:
            return rho
    Rho = Matrix(n, n, corr)
    print "what's the bound of rho to make below a correlation matrix?\n"
    pprint(Rho)
    print "\ncan be viewed as the sum of 2 matrices Rho = A + B:\n"
    A = (1-rho)*eye(n)
    B = rho*ones(n,n)
    pprint(A)
    pprint(B)
    print "\nthe eigen value and its dimention of first matrix A is:"
    pprint(A.eigenvects())
    print "\nas for the seconde matrix B\n"\
            "it's product of any vector v:"
    v = IndexedBase('v')
    vec = Matrix(n, 1, lambda i, j: v[i+1])
    pprint(vec)
    pprint(B*vec)
    print "\nin order for it's to equal to a linear transform of v\n"\
            "we can see its eigen values, vectors and dimentions are:"
    pprint(B.eigenvects())
    print "\nfor any eigen vector of B v, we have Rho*v :\n"
    pprint(Rho*vec)
    print "\nwhich means v is also an eigen vector of Rho,\n"\
            "the eigen values, vectors and dimentions of Rho are:\n"
    pprint(Rho.eigenvects())
    print "\nsince have no negative eigen values <=> positive semidefinite:\n"\
            "the boundaries for rho are: [1/(%d-1),1]" %n
示例#2
0
def fidelity(statevec, dm, u_dm, ustatevec=np.array([0,0])):
    '''
    returns the fidelity (and its uncertainty) of the measured density
    matrix with a given state vector.
    '''
   
    f = error.Formula()
    beta,a,x,b,alpha = sympy.symbols('beta,a,x,b,alpha')
    v = Matrix([alpha, beta])
    rho = Matrix([[x,a+1j*b],[a-1j*b, 1-x]])    
    f.formula = (v.conjugate().transpose() * rho * v)[0]
    
    f.values[alpha] = statevec[0]
    f.values[beta] = statevec[1]
    f.values[a]=float(np.real(dm[0,1]))
    f.values[x]=float(dm[0,0])
    f.values[b]=float(np.imag(dm[0,1]))

    f.uncertainties[alpha]=ustatevec[0]
    f.uncertainties[beta]=ustatevec[1]
    f.uncertainties[x]=u_dm[0,0]
    f.uncertainties[a]=float(np.real(u_dm[0,1]))
    f.uncertainties[b]=float(np.imag(u_dm[0,1]))
    
    _fid,_ufid = f.num_eval()
    fid = float(_fid.as_real_imag()[0])
    ufid = float(_ufid.as_real_imag()[0])
   
    return (fid,ufid)
示例#3
0
文件: plane.py 项目: ruishi/sympy
    def distance(self, o):
        """Distance beteen the plane and another geometric entity.

        Parameters
        ==========

        Point3D, LinearEntity3D, Plane.

        Returns
        =======

        distance

        Notes
        =====

        This method accepts only 3D entities as it's parameter, but if you want
        to calculate the distance between a 2D entity and a plane you should
        first convert to a 3D entity by projecting onto a desired plane and
        then proceed to calculate the distance.

        Examples
        ========

        >>> from sympy import Point, Point3D, Line, Line3D, Plane
        >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
        >>> b = Point3D(1, 2, 3)
        >>> a.distance(b)
        sqrt(3)
        >>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2))
        >>> a.distance(c)
        0

        """
        from sympy.geometry.line3d import LinearEntity3D
        x, y, z = map(Dummy, 'xyz')
        if self.intersection(o) != []:
            return S.Zero

        if isinstance(o, Point3D):
           x, y, z = map(Dummy, 'xyz')
           k = self.equation(x, y, z)
           a, b, c = [k.coeff(i) for i in (x, y, z)]
           d = k.xreplace({x: o.args[0], y: o.args[1], z: o.args[2]})
           t = abs(d/sqrt(a**2 + b**2 + c**2))
           return t
        if isinstance(o, LinearEntity3D):
            a, b = o.p1, self.p1
            c = Matrix(a.direction_ratio(b))
            d = Matrix(self.normal_vector)
            e = c.dot(d)
            f = sqrt(sum([i**2 for i in self.normal_vector]))
            return abs(e / f)
        if isinstance(o, Plane):
            a, b = o.p1, self.p1
            c = Matrix(a.direction_ratio(b))
            d = Matrix(self.normal_vector)
            e = c.dot(d)
            f = sqrt(sum([i**2 for i in self.normal_vector]))
            return abs(e / f)
示例#4
0
def demo_symetricA_Msquare(A):
    print "\n1)Any symmetric matrix A can be written as A = M^2:\n"\
            "<= any symetric matrix A can be diagonalized as A = Q * D * Q.inv()\n"\
            "<= D is diagonal matrix with eigen values\n"\
            "   Q is eigen vectors with norm 1\n"\
            "   Q.inv() == Q.T\n"\
            "first take a look as eigen vectors:\n"
    pprint(A.eigenvects())
    print "\nthen sympy diagonalized result:\n"
    pprint(A.diagonalize())
    d = A.diagonalize()[1]
    q = A.diagonalize()[0]
    q = Matrix(q.rows, q.cols, lambda i, j: q[:,j].normalized()[i])
    print "\nthen normalized Q:\n"
    pprint(q)
    print "\nthen the transpose of Q:\n"
    pprint(q.T)
    print "\nthen the inverse of Q:\n"
    pprint(q.inv())
    print "\nthen Q * D * Q.inv():\n"
    pprint(q*d*q.inv())
    print "\nif we define a new diagonal matrix Droot:\n"
    d = d.applyfunc(lambda x: x**.5)
    pprint(d)
    print "\nthen let M = Q * Droot * Q.inv():\n"
    m = q*d*q.inv()
    pprint(m)
    print "\nthen A = M*M:\n"
    pprint(q*d*d*q.inv())
示例#5
0
文件: plane.py 项目: akshayah3/sympy
    def perpendicular_plane(self, pt):
        """
        Plane perpendicular to the given plane and passing through the point pt.

        Parameters
        ==========

        pt: Point3D

        Returns
        =======

        Plane

        Examples
        ========

        >>> from sympy import Plane, Point3D
        >>> a = Plane(Point3D(1,4,6), normal_vector=[2, 4, 6])
        >>> a.perpendicular_plane(Point3D(2, 3, 5))
        Plane(Point3D(2, 3, 5), [2, 8, -6])

        """
        a = Matrix(self.normal_vector)
        b, c = pt, self.p1
        d = Matrix(b.direction_ratio(c))
        e = list(d.cross(a))
        return Plane(pt, normal_vector=e)
示例#6
0
 def _eval_transpose(self):
     # Flip all the individual matrices
     matrices = [Transpose(matrix) for matrix in self.blocks]
     # Make a copy
     M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
     # Transpose the block structure
     M = M.transpose()
     return BlockMatrix(M)
def evalMat( Mlist,  blist  ):
	M = Matrix(Mlist)
	b = Matrix(blist)
	c = M.LUsolve( b )
	print 
	print " ================= Case: ",b.transpose()
	print 
	print c
	return c
示例#8
0
def test_eigenvals():
    M = EigenOnlyMatrix([[0, 1, 1],
                [1, 0, 0],
                [1, 1, 1]])
    assert M.eigenvals() == {2*S.One: 1, -S.One: 1, S.Zero: 1}

    # if we cannot factor the char poly, we raise an error
    m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
    raises(MatrixError, lambda: m.eigenvals())
示例#9
0
	def cleanup(self):
		self.cleanState           = symbols(self.dofNames)
		self.cleanVelocity        = symbols(['d'+name for name in self.dofNames])
		symdict                   = dict(zip(self.state+self.velocity, self.cleanState+self.cleanVelocity))
		cleanMatrix               = Matrix([simplify(element).subs(symdict) for element in  self.mass])
		self.cleanMass            = list([cleanMatrix.reshape(self.degreesOfFreedom, self.degreesOfFreedom)])
		self.cleanForce           = [simplify(element).subs(symdict) for element in self.force]
		self.cleanConstraint      = simplify(self.constraint_equation.subs(symdict))
		self.cleanConstraintForce = [simplify(element).subs(symdict) for element in self.virtualForce]
		self.cleanNullForce       = self.nullForce
示例#10
0
	def cleanup(self):
		symbolDictionary = dict(zip(self.state + self.velocity, self.cleanState + self.cleanVelocity))
		N                = len(self._fullCoordinate)
		cleanMatrix      = Matrix([simplify(element).subs(symbolDictionary) for element in  self.mass])
		self._cleanMass  = list([cleanMatrix.reshape(N, N)])
		self._cleanForce = [simplify(element).subs(symbolDictionary) for element in self.force]
		self.SpecialFunctions(symbolDictionary)
		self.cleanConstraint      = simplify(self.constraint_equation.subs(symbolDictionary))
		self.cleanConstraintForce = [simplify(element).subs(symbolDictionary) for element in self.virtualForce]
		self.cleanNullForce       = self.nullForce
示例#11
0
 def is_scalar_multiple(p1, p2):
     """Returns whether `p1` and `p2` are scalar multiples
     of eachother.
     """
     # if the vectors p1 and p2 are linearly dependent, then they must
     # be scalar multiples of eachother
     m = Matrix([p1.args, p2.args])
     # XXX: issue #9480 we need `simplify=True` otherwise the
     # rank may be computed incorrectly
     return m.rank(simplify=True) < 2
示例#12
0
def euler101():
    #actual function that generates polynomials
    def u(n):
        return n ** 3

    order = 3  # largest polynomial order of u
    seq = [u(x) for x in range(1, order + 2)]
    A = Matrix([[1 ** 1, 1], [8 ** 1, 1]][::-1])
    b = Matrix([[x] for x in seq[:2]])
    return A.inv() * b
示例#13
0
    def is_concyclic(self, *args):
        """Do `self` and the given sequence of points lie in a circle?

        Returns True if the set of points are concyclic and
        False otherwise. A trivial value of True is returned
        if there are fewer than 2 other points.

        Parameters
        ==========

        args : sequence of Points

        Returns
        =======

        is_concyclic : boolean


        Examples
        ========

        >>> from sympy import Point

        Define 4 points that are on the unit circle:

        >>> p1, p2, p3, p4 = Point(1, 0), (0, 1), (-1, 0), (0, -1)

        >>> p1.is_concyclic() == p1.is_concyclic(p2, p3, p4) == True
        True

        Define a point not on that circle:

        >>> p = Point(1, 1)

        >>> p.is_concyclic(p1, p2, p3)
        False

        """
        points = (self,) + args
        points = Point._normalize_dimension(*[Point(i) for i in points])
        points = list(uniq(points))
        if not Point.affine_rank(*points) <= 2:
            return False
        origin = points[0]
        points = [p - origin for p in points]
        # points are concyclic if they are coplanar and
        # there is a point c so that ||p_i-c|| == ||p_j-c|| for all
        # i and j.  Rearranging this equation gives us the following
        # condition: the matrix `mat` must not a pivot in the last
        # column.
        mat = Matrix([list(i) + [i.dot(i)] for i in points])
        rref, pivots = mat.rref()
        if len(origin) not in pivots:
            return True
        return False
示例#14
0
文件: tree.py 项目: luviiit/research
 def as_density_matrix(self):
     """
     NOT USED ANYMORE (but works fine)
     Represent this pure state as density matrix.
     """
     coeffs = self.get_coefficients_as_general_state()
     matrix = Matrix(coeffs)
     matrix = matrix * matrix.conjugate().transpose()
     coeff_comm = self.coeff_comm
     matrix = matrix * coeff_comm * coeff_comm
     return matrix
示例#15
0
def test_1xN_vecs():
    gl = glsl_code
    for i in range(1,10):
        A = Matrix(range(i))
        assert gl(A.transpose()) == gl(A)
        assert gl(A,mat_transpose=True) == gl(A)
        if i > 1:
            if i <= 4:
                assert gl(A) == 'vec%s(%s)' % (i,', '.join(str(s) for s in range(i)))
            else:
                assert gl(A) == 'float[%s](%s)' % (i,', '.join(str(s) for s in range(i)))
示例#16
0
def msolve(args, f, x0, tol=None, maxsteps=None, verbose=False, norm=None,
           modules=['mpmath', 'sympy']):
    """
    Solves a nonlinear equation system numerically.

    f is a vector function of symbolic expressions representing the system.
    args are the variables.
    x0 is a starting vector close to a solution.

    Be careful with x0, not using floats might give unexpected results.

    Use modules to specify which modules should be used to evaluate the
    function and the Jacobian matrix. Make sure to use a module that supports
    matrices. For more information on the syntax, please see the docstring
    of lambdify.

    Currently only fully determined systems are supported.

    >>> from sympy import Symbol, Matrix
    >>> x1 = Symbol('x1')
    >>> x2 = Symbol('x2')
    >>> f1 = 3 * x1**2 - 2 * x2**2 - 1
    >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
    >>> msolve((x1, x2), (f1, f2), (-1., 1.))
    [-1.19287309935246]
    [ 1.27844411169911]
    """
    if isinstance(f,  (list,  tuple)):
        f = Matrix(f).T
    if len(args) != f.cols:
        raise NotImplementedError('need exactly as many variables as equations')
    if verbose:
        print 'f(x):'
        print f
    # derive Jacobian
    J = f.jacobian(args)
    if verbose:
        print 'J(x):'
        print J
    # create functions
    f = lambdify(args, f.T, modules)
    J = lambdify(args, J, modules)
    # solve system using Newton's method
    kwargs = {}
    if tol:
        kwargs['tol'] = tol
    if maxsteps:
        kwargs['maxsteps'] = maxsteps
    kwargs['verbose'] = verbose
    if norm:
        kwargs['norm'] = norm
    x = newton(f, x0, J, **kwargs)
    return x
示例#17
0
def vcv2corr(vcv):
    n = vcv.rows
    m = vcv.cols
    if n != m:
        raise ValueError('variance mattrix has to be square matrix')
    def var(i, j):
        if i == j:
            return vcv[i, j]**.5
        else:
            return 0
    D = Matrix(n, n, var)
    corr = D.inv() * vcv * D.inv()
    return corr, D
示例#18
0
    def are_coplanar(*points):
        """

        This function tests whether passed points are coplanar or not.
        It uses the fact that the triple scalar product of three vectors
        vanishes if the vectors are coplanar. Which means that the volume
        of the solid described by them will have to be zero for coplanarity.

        Parameters
        ==========

        A set of points 3D points

        Returns
        =======

        boolean

        Examples
        ========

        >>> from sympy import Point3D
        >>> p1 = Point3D(1, 2, 2)
        >>> p2 = Point3D(2, 7, 2)
        >>> p3 = Point3D(0, 0, 2)
        >>> p4 = Point3D(1, 1, 2)
        >>> p5 = Point3D(1, 2, 2)
        >>> p1.are_coplanar(p2, p3, p4, p5)
        True
        >>> p6 = Point3D(0, 1, 3)
        >>> p1.are_coplanar(p2, p3, p4, p5, p6)
        False

        """
        if not all(isinstance(p, Point3D) for p in points):
            raise TypeError('Must pass only 3D Point objects')
        if(len(points) < 4):
            return True # These cases are always True
        points = list(set(points))
        for i in range(len(points) - 3):
            pv1 = [j - k for j, k in zip(points[i].args,   \
                points[i + 1].args)]
            pv2 = [j - k for j, k in zip(points[i + 1].args,
                points[i + 2].args)]
            pv3 = [j - k for j, k in zip(points[i + 2].args,
                points[i + 3].args)]
            pv1, pv2, pv3 = Matrix(pv1), Matrix(pv2), Matrix(pv3)
            stp = pv1.dot(pv2.cross(pv3))
            if stp != 0:
                return False
        return True
def test_converting_functions():
    arr_list = [1, 2, 3, 4]
    arr_matrix = Matrix(((1, 2), (3, 4)))

    # list
    arr_ndim_array = MutableDenseNDimArray(arr_list, (2, 2))
    assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
    assert arr_matrix.tolist() == arr_ndim_array.tolist()

    # Matrix
    arr_ndim_array = MutableDenseNDimArray(arr_matrix)
    assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
    assert arr_matrix.tolist() == arr_ndim_array.tolist()
    assert arr_matrix.shape == arr_ndim_array.shape
示例#20
0
文件: 07_27.py 项目: keipa/bsuir-labs
def verification_of_sufficient_second_order_conditions(K, df, x, l):
    if not K:
        print "The sufficient optimality condition of second kind is made."
    else:
        ddf = []
        for xi in x:
            ddf.append([ddfi.diff(xi) for ddfi in df])
        
        ddf = Matrix(ddf)
        ll = Matrix(l)
        if Matrix(ddf.dot(ll.T)).dot(ll).subs(K) > 0:
            print "The sufficient optimality condition of second kind is made."
        else:
            print "The sufficient optimality condition of second kind is not made."
            return
def sylvester_det(p4, p2):
    p4degree = len(p4) - 1
    p2degree = len(p2) - 1
    smatsize = p4degree + p2degree
    nzeros4 = (smatsize - len(p4))
    nzeroes2 = (smatsize - len(p2))
    smatlist = []
    for i in range(nzeros4 + 1):
        smatlist.append([0]*i + p4 + [0]*(nzeros4 - i))
    for i in range(nzeroes2 + 1):
        smatlist.append([0]*i + p2 + [0]*(nzeroes2 - i))

    smat = Matrix(smatlist)
    det = smat.det(method='berkowitz')
    det = sympy.expand(det)
    return det
示例#22
0
def demo_eigen_number():
    m = Matrix(3,3,[2,1,0,0,2,1,0,0,2])
    pprint(m)
    print "\nany n*n matrix has n complex eigen values, counted with multiplications\n"\
            "since the characteritic polynomial is n-dim\n"\
            "and Fundamental Theorem of Algebra gives us exactly n roots:"
    pprint(m.charpoly().as_expr())
    print"\neach distinct eigen value as at least 1 at most multiplication eigen vectors\n"\
            "but it's possible to have less than multiplication number of eigen vectors\n"\
            "the given matrix is an example with only 1 eigen vector:\n"
    pprint(m.eigenvects())
    print "to see this for any vector v we can compute M * v:\n"
    v = IndexedBase('v')
    vec = Matrix(m.rows, 1, lambda i, j: v[i+1])
    pprint(vec)
    pprint(m*vec)
示例#23
0
文件: plane.py 项目: jcrist/sympy
    def angle_between(self, o):
        """Angle between the plane and other geometric entity.

        Parameters
        ==========

        LinearEntity3D, Plane.

        Returns
        =======

        angle : angle in radians

        Notes
        =====

        This method accepts only 3D entities as it's parameter, but if you want
        to calculate the angle between a 2D entity and a plane you should
        first convert to a 3D entity by projecting onto a desired plane and
        then proceed to calculate the angle.

        Examples
        ========

        >>> from sympy import Point3D, Line3D, Plane
        >>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3))
        >>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2))
        >>> a.angle_between(b)
        -asin(sqrt(21)/6)

        """
        from sympy.geometry.line3d import LinearEntity3D

        if isinstance(o, LinearEntity3D):
            a = Matrix(self.normal_vector)
            b = Matrix(o.direction_ratio)
            c = a.dot(b)
            d = sqrt(sum([i ** 2 for i in self.normal_vector]))
            e = sqrt(sum([i ** 2 for i in o.direction_ratio]))
            return asin(c / (d * e))
        if isinstance(o, Plane):
            a = Matrix(self.normal_vector)
            b = Matrix(o.normal_vector)
            c = a.dot(b)
            d = sqrt(sum([i ** 2 for i in self.normal_vector]))
            e = sqrt(sum([i ** 2 for i in o.normal_vector]))
            return acos(c / (d * e))
示例#24
0
    def is_scalar_multiple(self, p):
        """Returns whether each coordinate of `self` is a scalar
        multiple of the corresponding coordinate in point p.
        """
        s, o = Point._normalize_dimension(self, Point(p))
        # 2d points happen a lot, so optimize this function call
        if s.ambient_dimension == 2:
            (x1, y1), (x2, y2) = s.args, o.args
            rv = (x1*y2 - x2*y1).equals(0)
            if rv is None:
                raise Undecidable(filldedent(
                    '''can't determine if %s is a scalar multiple of
                    %s''' % (s, o)))

        # if the vectors p1 and p2 are linearly dependent, then they must
        # be scalar multiples of each other
        m = Matrix([s.args, o.args])
        return m.rank() < 2
示例#25
0
    def affine_rank(*args):
        """The affine rank of a set of points is the dimension
        of the smallest affine space containing all the points.
        For example, if the points lie on a line (and are not all
        the same) their affine rank is 1.  If the points lie on a plane
        but not a line, their affine rank is 2.  By convention, the empty
        set has affine rank -1."""

        if len(args) == 0:
            return -1
        # make sure we're genuinely points
        # and translate every point to the origin
        points = Point._normalize_dimension(*[Point(i) for i in args])
        origin = points[0]
        points = [i - origin for i in points[1:]]

        m = Matrix([i.args for i in points])
        return m.rank()
示例#26
0
 def _eval_expand_basic(self, **hints):
     summand = self.function.expand(**hints)
     if summand.is_Add and summand.is_commutative:
         return Add(*[ self.func(i, *self.limits) for i in summand.args ])
     elif summand.is_Matrix:
         return Matrix._new(summand.rows, summand.cols,
             [self.func(i, *self.limits) for i in summand._mat])
     elif summand != self.function:
         return self.func(summand, *self.limits)
     return self
示例#27
0
def deblock(B):
    """ Flatten a BlockMatrix of BlockMatrices """
    if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix):
        return B
    wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]])
    bb = B.blocks.applyfunc(wrap)  # everything is a block

    from sympy import Matrix
    try:
        MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])
        for row in range(0, bb.shape[0]):
            M = Matrix(bb[row, 0].blocks)
            for col in range(1, bb.shape[1]):
                M = M.row_join(bb[row, col].blocks)
            MM = MM.col_join(M)

        return BlockMatrix(MM)
    except ShapeError:
        return B
示例#28
0
def test_hstack():
    m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
    m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
    assert m == m.hstack(m)
    assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([
                [0,  1,  2, 0,  1,  2, 0,  1,  2],
                [3,  4,  5, 3,  4,  5, 3,  4,  5],
                [6,  7,  8, 6,  7,  8, 6,  7,  8],
                [9, 10, 11, 9, 10, 11, 9, 10, 11]])
    raises(ShapeError, lambda: m.hstack(m, m2))
    assert Matrix.hstack() == Matrix()

    # test regression #12938
    M1 = Matrix.zeros(0, 0)
    M2 = Matrix.zeros(0, 1)
    M3 = Matrix.zeros(0, 2)
    M4 = Matrix.zeros(0, 3)
    m = ShapingOnlyMatrix.hstack(M1, M2, M3, M4)
    assert m.rows == 0 and m.cols == 6
示例#29
0
def test_hstack():
    m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
    m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
    assert m == m.hstack(m)
    assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([
                [0,  1,  2, 0,  1,  2, 0,  1,  2],
                [3,  4,  5, 3,  4,  5, 3,  4,  5],
                [6,  7,  8, 6,  7,  8, 6,  7,  8],
                [9, 10, 11, 9, 10, 11, 9, 10, 11]])
    raises(ShapeError, lambda: m.hstack(m, m2))
    assert Matrix.hstack() == Matrix()
示例#30
0
文件: plane.py 项目: jcrist/sympy
    def is_perpendicular(self, l):
        """is the given geometric entity perpendicualar to the given plane?

        Parameters
        ==========

        LinearEntity3D or Plane

        Returns
        =======

        Boolean

        Examples
        ========

        >>> from sympy import Plane, Point3D
        >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
        >>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1))
        >>> a.is_perpendicular(b)
        True

        """
        from sympy.geometry.line3d import LinearEntity3D

        if isinstance(l, LinearEntity3D):
            a = Matrix(l.direction_ratio)
            b = Matrix(self.normal_vector)
            if a.cross(b).is_zero:
                return True
            else:
                return False
        elif isinstance(l, Plane):
            a = Matrix(l.normal_vector)
            b = Matrix(self.normal_vector)
            if a.dot(b) == 0:
                return True
            else:
                return False
        else:
            return False
示例#31
0
def test_point3D():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    x1 = Symbol('x1', real=True)
    x2 = Symbol('x2', real=True)
    x3 = Symbol('x3', real=True)
    y1 = Symbol('y1', real=True)
    y2 = Symbol('y2', real=True)
    y3 = Symbol('y3', real=True)
    half = Rational(1, 2)
    p1 = Point3D(x1, x2, x3)
    p2 = Point3D(y1, y2, y3)
    p3 = Point3D(0, 0, 0)
    p4 = Point3D(1, 1, 1)
    p5 = Point3D(0, 1, 2)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
    assert p4*5 == Point3D(5, 5, 5)
    assert -p2 == Point3D(-y1, -y2, -y3)

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
    assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
                                         half + half*x3)
    assert Point3D.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point3D.distance(p3, p4) == sqrt(3)
    assert Point3D.distance(p1, p1) == 0
    assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)

    p1_1 = Point3D(x1, x1, x1)
    p1_2 = Point3D(y2, y2, y2)
    p1_3 = Point3D(x1 + 1, x1, x1)
    # according to the description in the docs, points are collinear
    # if they like on a single line.  Thus a single point should always
    # be collinear
    assert Point3D.are_collinear(p3)
    assert Point3D.are_collinear(p3, p4)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
    assert Point3D.are_collinear(p3, p3, p4, p5) is False

    assert p3.intersection(Point3D(0, 0, 0)) == [p3]
    assert p3.intersection(p4) == []


    assert p4 * 5 == Point3D(5, 5, 5)
    assert p4 / 5 == Point3D(0.2, 0.2, 0.2)

    raises(ValueError, lambda: Point3D(0, 0, 0) + 10)

    # Point differences should be simplified
    assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
        Point3D(0, -1, 1)

    a, b = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test transformations
    p = Point3D(1, 1, 1)
    assert p.scale(2, 3) == Point3D(2, 3, 1)
    assert p.translate(1, 2) == Point3D(2, 3, 1)
    assert p.translate(1) == Point3D(2, 1, 1)
    assert p.translate(z=1) == Point3D(1, 1, 2)
    assert p.translate(*p.args) == Point3D(2, 2, 2)

    # Test __new__
    assert Point3D(Point3D(1, 2, 3), 4, 5, evaluate=False) ==  Point3D(1, 2, 3)


    # Test length property returns correctly
    assert p.length == 0
    assert p1_1.length == 0
    assert p1_2.length == 0

    # Test are_colinear type error
    raises(TypeError, lambda: Point3D.are_collinear(p, x))

    # Test are_coplanar
    planar2 = Point3D(1, -1, 1)
    planar3 = Point3D(-1, 1, 1)
    assert Point3D.are_coplanar(p, planar2, planar3) == True
    assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
    raises(ValueError, lambda: Point3D.are_coplanar(p, planar2))
    planar2 = Point3D(1, 1, 2)
    planar3 = Point3D(1, 1, 3)
    raises(ValueError, lambda: Point3D.are_coplanar(p, planar2, planar3))

    # Test Intersection
    assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]

    # Test Scale
    assert planar2.scale(1, 1, 1) == planar2
    assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
    assert planar2.scale(1, 1, 1, p3) == planar2

    # Test Transform
    identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
    assert p.transform(identity) == p
    trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
    assert p.transform(trans) == Point3D(2, 2, 2)
    raises(ValueError, lambda: p.transform(p))
    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))

    # Test Equals
    assert p.equals(x1) == False

    # Test __sub__
    p_2d = Point(0, 0)
    raises(ValueError, lambda: (p - p_2d))
示例#32
0
 def _print_SparseMatrix(self, expr):
     from sympy.matrices import Matrix
     return self._print(Matrix(expr))
示例#33
0
def test_octave_matrix_assign_to():
    A = Matrix([[1, 2, 3]])
    assert mcode(A, assign_to="a") == "a = [1 2 3];"
    A = Matrix([[1, 2], [3, 4]])
    assert mcode(A, assign_to="A") == "A = [1 2; 3 4];"
def test_represent_hadamard():
    """Test the representation of the hadamard gate."""
    circuit = HadamardGate(0)*Qubit('00')
    answer = represent(circuit, nqubits=2)
    # Check that the answers are same to within an epsilon.
    assert answer == Matrix([sqrt2_inv, sqrt2_inv, 0, 0])
def test_represent_zgate():
    """Test the representation of the Z gate."""
    circuit = ZGate(0)*Qubit('00')
    answer = represent(circuit, nqubits=2)
    assert Matrix([1, 0, 0, 0]) == answer
示例#36
0
def test_bifid7_square():
    A = alphabet_of_cipher() + [str(a) for a in range(23)]
    f = lambda i, j: symbols(A[7 * i + j])
    M = Matrix(7, 7, f)
    assert bifid7_square("") == M
示例#37
0
def test_Matrices_1x7_array_type_int():
    gl = glsl_code
    A = Matrix([1, 2, 3, 4, 5, 6, 7])
    assert gl(A, array_type='int') == 'int[7](1, 2, 3, 4, 5, 6, 7)'
示例#38
0
Created on Fri Jun 12 11:41:57 2020

@author: usth2
"""

#!/usr/bin/env python
from sympy import symbols, cos, sin, pi, sqrt
from sympy.matrices import Matrix
import numpy as np

### Create symbols for joint variables
q1, q2 = symbols('q1:3')

# Create a symbolic matrix representing an intrinsic sequence of rotations
# about the Y and then Z axes. Let the rotation about the Y axis be described
# by q1 and the rotation about Z by q2.
####### TO DO ########
# Replace R_y and R_z with the appropriate (symbolic) elementary rotation matrices
# and then compute YZ_intrinsic.
R_y = Matrix([[cos(q1), 0, sin(q1)], [0, 1, 0], [-sin(q1), 0, cos(q1)]])
R_z = Matrix([[cos(q2), -sin(q2), 0], [sin(q2), cos(q2), 0], [0, 0, 1]])
YZ_intrinsic_sym = R_y * R_z

####### TO DO ########
# Numerically evaluate YZ_intrinsic assuming:
# q1 = 45 degrees and q2 = 60 degrees.
# NOTE: Trigonometric functions in Python assume the input is in radians!

dtr = np.pi / 180.0

YZ_intrinsic_num = YZ_intrinsic_sym.evalf(subs={q1: 45 * dtr, q2: 60 * dtr})
示例#39
0
def test_bifid5_square():
    A = alphabet_of_cipher()
    A.remove("J")
    f = lambda i, j: symbols(A[5 * i + j])
    M = Matrix(5, 5, f)
    assert bifid5_square("") == M
示例#40
0
def rotate_x(rads):
    rotated = Matrix([[1, 0, 0, 0], [0, cos(rads), -sin(rads), 0],
                      [0, sin(rads), cos(rads), 0], [0, 0, 0, 1]])

    return rotated
示例#41
0
def test_vector_entries_hadamard():
    # For a row or column, user might to use the other dimension
    A = Matrix([[1, sin(2 / x), 3 * pi / x / 5]])
    assert mcode(A) == "[1 sin(2./x) 3*pi./(5*x)]"
    assert mcode(A.T) == "[1; sin(2./x); 3*pi./(5*x)]"
示例#42
0
def test_point():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    x1 = Symbol('x1', real=True)
    x2 = Symbol('x2', real=True)
    y1 = Symbol('y1', real=True)
    y2 = Symbol('y2', real=True)
    half = Rational(1, 2)
    p1 = Point(x1, x2)
    p2 = Point(y1, y2)
    p3 = Point(0, 0)
    p4 = Point(1, 1)
    p5 = Point(0, 1)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point(y1 - x1, y2 - x2)
    assert p4*5 == Point(5, 5)
    assert -p2 == Point(-y1, -y2)
    raises(ValueError, lambda: Point(3, I))
    raises(ValueError, lambda: Point(2*I, I))
    raises(ValueError, lambda: Point(3 + I, I))

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point.midpoint(p3, p4) == Point(half, half)
    assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2)
    assert Point.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point.distance(p3, p4) == sqrt(2)
    assert Point.distance(p1, p1) == 0
    assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)

    assert Point.taxicab_distance(p4, p3) == 2

    p1_1 = Point(x1, x1)
    p1_2 = Point(y2, y2)
    p1_3 = Point(x1 + 1, x1)
    assert Point.is_collinear(p3)
    assert Point.is_collinear(p3, p4)
    assert Point.is_collinear(p3, p4, p1_1, p1_2)
    assert Point.is_collinear(p3, p4, p1_1, p1_3) is False
    assert Point.is_collinear(p3, p3, p4, p5) is False
    line = Line(Point(1,0), slope = 1)
    raises(TypeError, lambda: Point.is_collinear(line))
    raises(TypeError, lambda: p1_1.is_collinear(line))

    assert p3.intersection(Point(0, 0)) == [p3]
    assert p3.intersection(p4) == []

    x_pos = Symbol('x', real=True, positive=True)
    p2_1 = Point(x_pos, 0)
    p2_2 = Point(0, x_pos)
    p2_3 = Point(-x_pos, 0)
    p2_4 = Point(0, -x_pos)
    p2_5 = Point(x_pos, 5)
    assert Point.is_concyclic(p2_1)
    assert Point.is_concyclic(p2_1, p2_2)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_5) is False
    assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False

    assert p4.scale(2, 3) == Point(2, 3)
    assert p3.scale(2, 3) == p3

    assert p4.rotate(pi, Point(0.5, 0.5)) == p3
    assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
    assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)

    assert p4 * 5 == Point(5, 5)
    assert p4 / 5 == Point(0.2, 0.2)

    raises(ValueError, lambda: Point(0, 0) + 10)

    # Point differences should be simplified
    assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1)

    a, b = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test transformations
    p = Point(1, 0)
    assert p.rotate(pi/2) == Point(0, 1)
    assert p.rotate(pi/2, p) == p
    p = Point(1, 1)
    assert p.scale(2, 3) == Point(2, 3)
    assert p.translate(1, 2) == Point(2, 3)
    assert p.translate(1) == Point(2, 1)
    assert p.translate(y=1) == Point(1, 2)
    assert p.translate(*p.args) == Point(2, 2)

    # Check invalid input for transform
    raises(ValueError, lambda: p3.transform(p3))
    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
示例#43
0
def test_Matrices_1x7():
    gl = glsl_code
    A = Matrix([1, 2, 3, 4, 5, 6, 7])
    assert gl(A) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
    assert gl(A.transpose()) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
示例#44
0
def test_matrix_sum():
    A = Matrix([[0, 1], [n, 0]])
    assert Sum(A, (n, 0, 3)).doit() == Matrix([[0, 4], [6, 0]])
def test_represent_phasegate():
    """Test the representation of the S gate."""
    circuit = PhaseGate(0)*Qubit('01')
    answer = represent(circuit, nqubits=2)
    assert Matrix([0, I, 0, 0]) == answer
示例#46
0
def rotate_z(rads):
    rotated = Matrix([[cos(rads), -sin(rads), 0, 0],
                      [sin(rads), cos(rads), 0, 0], [0, 0, 1, 0], [0, 0, 0,
                                                                   1]])

    return rotated
示例#47
0
    def composition(self, expr, *args):
        """
        Returns the annihilator after composition of a holonomic function with
        an algebraic function. Initial conditions for the annihilator after composition
        can be also be provided to the function.

        Examples
        ========

        >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
        >>> from sympy.polys.domains import ZZ, QQ
        >>> from sympy import symbols
        >>> x = symbols('x')
        >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')

        >>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1])  # e^(x**2)
        HolonomicFunction((-2*x) + (1)Dx, x), f(0) = 1

        >>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0])
        HolonomicFunction((4*x**3) + (-1)Dx + (x)Dx**2, x), f(1) = 1 , f'(1) = 0

        See Also
        ========

        from_hyper
        """

        R = self.annihilator.parent
        a = self.annihilator.order
        diff = expr.diff()
        listofpoly = self.annihilator.listofpoly

        for i, j in enumerate(listofpoly):
            if isinstance(j, self.annihilator.parent.base.dtype):
                listofpoly[i] = self.annihilator.parent.base.to_sympy(j)

        r = listofpoly[a].subs({self.x: expr})
        subs = [-listofpoly[i].subs({self.x: expr}) / r for i in range(a)]
        coeffs = [S(0) for i in range(a)
                  ]  # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a))
        coeffs[0] = S(1)
        system = [coeffs]
        homogeneous = Matrix([[S(0) for i in range(a)]]).transpose()
        sol = S(0)

        while sol.is_zero:
            coeffs_next = [p.diff() for p in coeffs]
            for i in range(a - 1):
                coeffs_next[i + 1] += (coeffs[i] * diff)

            for i in range(a):
                coeffs_next[i] += (coeffs[-1] * subs[i] * diff)
            coeffs = coeffs_next

            # check for linear relations
            system.append(coeffs)
            sol_tuple = (
                Matrix(system).transpose()).gauss_jordan_solve(homogeneous)
            sol = sol_tuple[0]

        tau = sol.atoms(Dummy).pop()
        sol = sol.subs(tau, 1)
        sol = _normalize(sol[0:], R, negative=False)

        # if initial conditions are given for the resulting function
        if args:
            return HolonomicFunction(sol, self.x, args[0], args[1])
        return HolonomicFunction(sol, self.x)
示例#48
0
    alpha5: -pi / 2,
    a5: 0,
    d6: 0,
    alpha6: 0,
    a6: 0,
    d7: 0.303,
    q7: 0
}

# Homogeneous transforms
T0_1 = Matrix([[cos(q1), -sin(q1), 0, a0],
               [
                   sin(q1) * cos(alpha0),
                   cos(q1) * cos(alpha0), -sin(alpha0), -sin(alpha0) * d1
               ],
               [
                   sin(q1) * sin(alpha0),
                   cos(q1) * sin(alpha0),
                   cos(alpha0),
                   cos(alpha0) * d1
               ], [0, 0, 0, 1]])

T0_1 = T0_1.subs(s)

T1_2 = Matrix([[cos(q2), -sin(q2), 0, a1],
               [
                   sin(q2) * cos(alpha1),
                   cos(q2) * cos(alpha1), -sin(alpha1), -sin(alpha1) * d2
               ],
               [
                   sin(q2) * sin(alpha1),
示例#49
0
def cse(exprs,
        symbols=None,
        optimizations=None,
        postprocess=None,
        order='canonical',
        ignore=()):
    """ Perform common subexpression elimination on an expression.

    Parameters
    ==========

    exprs : list of sympy expressions, or a single sympy expression
        The expressions to reduce.
    symbols : infinite iterator yielding unique Symbols
        The symbols used to label the common subexpressions which are pulled
        out. The ``numbered_symbols`` generator is useful. The default is a
        stream of symbols of the form "x0", "x1", etc. This must be an
        infinite iterator.
    optimizations : list of (callable, callable) pairs
        The (preprocessor, postprocessor) pairs of external optimization
        functions. Optionally 'basic' can be passed for a set of predefined
        basic optimizations. Such 'basic' optimizations were used by default
        in old implementation, however they can be really slow on larger
        expressions. Now, no pre or post optimizations are made by default.
    postprocess : a function which accepts the two return values of cse and
        returns the desired form of output from cse, e.g. if you want the
        replacements reversed the function might be the following lambda:
        lambda r, e: return reversed(r), e
    order : string, 'none' or 'canonical'
        The order by which Mul and Add arguments are processed. If set to
        'canonical', arguments will be canonically ordered. If set to 'none',
        ordering will be faster but dependent on expressions hashes, thus
        machine dependent and variable. For large expressions where speed is a
        concern, use the setting order='none'.
    ignore : iterable of Symbols
        Substitutions containing any Symbol from ``ignore`` will be ignored.

    Returns
    =======

    replacements : list of (Symbol, expression) pairs
        All of the common subexpressions that were replaced. Subexpressions
        earlier in this list might show up in subexpressions later in this
        list.
    reduced_exprs : list of sympy expressions
        The reduced expressions with all of the replacements above.

    Examples
    ========

    >>> from sympy import cse, SparseMatrix
    >>> from sympy.abc import x, y, z, w
    >>> cse(((w + x + y + z)*(w + y + z))/(w + x)**3)
    ([(x0, y + z), (x1, w + x)], [(w + x0)*(x0 + x1)/x1**3])

    Note that currently, y + z will not get substituted if -y - z is used.

     >>> cse(((w + x + y + z)*(w - y - z))/(w + x)**3)
     ([(x0, w + x)], [(w - y - z)*(x0 + y + z)/x0**3])

    List of expressions with recursive substitutions:

    >>> m = SparseMatrix([x + y, x + y + z])
    >>> cse([(x+y)**2, x + y + z, y + z, x + z + y, m])
    ([(x0, x + y), (x1, x0 + z)], [x0**2, x1, y + z, x1, Matrix([
    [x0],
    [x1]])])

    Note: the type and mutability of input matrices is retained.

    >>> isinstance(_[1][-1], SparseMatrix)
    True

    The user may disallow substitutions containing certain symbols:

    >>> cse([y**2*(x + 1), 3*y**2*(x + 1)], ignore=(y,))
    ([(x0, x + 1)], [x0*y**2, 3*x0*y**2])

    """
    from sympy.matrices import (MatrixBase, Matrix, ImmutableMatrix,
                                SparseMatrix, ImmutableSparseMatrix)

    # Handle the case if just one expression was passed.
    if isinstance(exprs, (Basic, MatrixBase)):
        exprs = [exprs]

    copy = exprs
    temp = []
    for e in exprs:
        if isinstance(e, (Matrix, ImmutableMatrix)):
            temp.append(Tuple(*e._mat))
        elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
            temp.append(Tuple(*e._smat.items()))
        else:
            temp.append(e)
    exprs = temp
    del temp

    if optimizations is None:
        optimizations = list()
    elif optimizations == 'basic':
        optimizations = basic_optimizations

    # Preprocess the expressions to give us better optimization opportunities.
    reduced_exprs = [preprocess_for_cse(e, optimizations) for e in exprs]

    if symbols is None:
        symbols = numbered_symbols(cls=Symbol)
    else:
        # In case we get passed an iterable with an __iter__ method instead of
        # an actual iterator.
        symbols = iter(symbols)

    # Find other optimization opportunities.
    opt_subs = opt_cse(reduced_exprs, order)

    # Main CSE algorithm.
    replacements, reduced_exprs = tree_cse(reduced_exprs, symbols, opt_subs,
                                           order, ignore)

    # Postprocess the expressions to return the expressions to canonical form.
    exprs = copy
    for i, (sym, subtree) in enumerate(replacements):
        subtree = postprocess_for_cse(subtree, optimizations)
        replacements[i] = (sym, subtree)
    reduced_exprs = [
        postprocess_for_cse(e, optimizations) for e in reduced_exprs
    ]

    # Get the matrices back
    for i, e in enumerate(exprs):
        if isinstance(e, (Matrix, ImmutableMatrix)):
            reduced_exprs[i] = Matrix(e.rows, e.cols, reduced_exprs[i])
            if isinstance(e, ImmutableMatrix):
                reduced_exprs[i] = reduced_exprs[i].as_immutable()
        elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
            m = SparseMatrix(e.rows, e.cols, {})
            for k, v in reduced_exprs[i]:
                m[k] = v
            if isinstance(e, ImmutableSparseMatrix):
                m = m.as_immutable()
            reduced_exprs[i] = m

    if postprocess is None:
        return replacements, reduced_exprs

    return postprocess(replacements, reduced_exprs)
示例#50
0
def test_point3D():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    x1 = Symbol('x1', real=True)
    x2 = Symbol('x2', real=True)
    x3 = Symbol('x3', real=True)
    y1 = Symbol('y1', real=True)
    y2 = Symbol('y2', real=True)
    y3 = Symbol('y3', real=True)
    half = S.Half
    p1 = Point3D(x1, x2, x3)
    p2 = Point3D(y1, y2, y3)
    p3 = Point3D(0, 0, 0)
    p4 = Point3D(1, 1, 1)
    p5 = Point3D(0, 1, 2)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
    assert -p2 == Point3D(-y1, -y2, -y3)

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
    assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
                                         half + half*x3)
    assert Point3D.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2

    assert Point3D.distance(p3, p4) == sqrt(3)
    assert Point3D.distance(p1, p1) == 0
    assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)

    p1_1 = Point3D(x1, x1, x1)
    p1_2 = Point3D(y2, y2, y2)
    p1_3 = Point3D(x1 + 1, x1, x1)
    Point3D.are_collinear(p3)
    assert Point3D.are_collinear(p3, p4)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
    assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
    assert Point3D.are_collinear(p3, p3, p4, p5) is False

    assert p3.intersection(Point3D(0, 0, 0)) == [p3]
    assert p3.intersection(p4) == []


    assert p4 * 5 == Point3D(5, 5, 5)
    assert p4 / 5 == Point3D(0.2, 0.2, 0.2)
    assert 5 * p4 == Point3D(5, 5, 5)

    raises(ValueError, lambda: Point3D(0, 0, 0) + 10)

    # Test coordinate properties
    assert p1.coordinates == (x1, x2, x3)
    assert p2.coordinates == (y1, y2, y3)
    assert p3.coordinates == (0, 0, 0)
    assert p4.coordinates == (1, 1, 1)
    assert p5.coordinates == (0, 1, 2)
    assert p5.x == 0
    assert p5.y == 1
    assert p5.z == 2

    # Point differences should be simplified
    assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
        Point3D(0, -1, 1)

    a, b, c = S.Half, Rational(1, 3), Rational(1, 4)
    assert Point3D(a, b, c).evalf(2) == \
        Point(a.n(2), b.n(2), c.n(2), evaluate=False)
    raises(ValueError, lambda: Point3D(1, 2, 3) + 1)

    # test transformations
    p = Point3D(1, 1, 1)
    assert p.scale(2, 3) == Point3D(2, 3, 1)
    assert p.translate(1, 2) == Point3D(2, 3, 1)
    assert p.translate(1) == Point3D(2, 1, 1)
    assert p.translate(z=1) == Point3D(1, 1, 2)
    assert p.translate(*p.args) == Point3D(2, 2, 2)

    # Test __new__
    assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float

    # Test length property returns correctly
    assert p.length == 0
    assert p1_1.length == 0
    assert p1_2.length == 0

    # Test are_colinear type error
    raises(TypeError, lambda: Point3D.are_collinear(p, x))

    # Test are_coplanar
    assert Point.are_coplanar()
    assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0))
    assert Point.are_coplanar((1, 2, 0), (1, 2, 3))
    with warns(UserWarning):
        raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3)))
    assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3))
    assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False
    planar2 = Point3D(1, -1, 1)
    planar3 = Point3D(-1, 1, 1)
    assert Point3D.are_coplanar(p, planar2, planar3) == True
    assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
    assert Point.are_coplanar(p, planar2)
    planar2 = Point3D(1, 1, 2)
    planar3 = Point3D(1, 1, 3)
    assert Point3D.are_coplanar(p, planar2, planar3)  # line, not plane
    plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2))
    assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)])

    # all 2D points are coplanar
    assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True

    # Test Intersection
    assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]

    # Test Scale
    assert planar2.scale(1, 1, 1) == planar2
    assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
    assert planar2.scale(1, 1, 1, p3) == planar2

    # Test Transform
    identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
    assert p.transform(identity) == p
    trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
    assert p.transform(trans) == Point3D(2, 2, 2)
    raises(ValueError, lambda: p.transform(p))
    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))

    # Test Equals
    assert p.equals(x1) == False

    # Test __sub__
    p_4d = Point(0, 0, 0, 1)
    with warns(UserWarning):
        assert p - p_4d == Point(1, 1, 1, -1)
    p_4d3d = Point(0, 0, 1, 0)
    with warns(UserWarning):
        assert p - p_4d3d == Point(1, 1, 0, 0)
示例#51
0
def test_bifid6_square():
    A = alphabet_of_cipher() + [str(a) for a in range(10)]
    f = lambda i, j: symbols(A[6 * i + j])
    M = Matrix(6, 6, f)
    assert bifid6_square("") == M
示例#52
0
def test_point():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)
    x1 = Symbol('x1', real=True)
    x2 = Symbol('x2', real=True)
    y1 = Symbol('y1', real=True)
    y2 = Symbol('y2', real=True)
    half = S.Half
    p1 = Point(x1, x2)
    p2 = Point(y1, y2)
    p3 = Point(0, 0)
    p4 = Point(1, 1)
    p5 = Point(0, 1)
    line = Line(Point(1, 0), slope=1)

    assert p1 in p1
    assert p1 not in p2
    assert p2.y == y2
    assert (p3 + p4) == p4
    assert (p2 - p1) == Point(y1 - x1, y2 - x2)
    assert -p2 == Point(-y1, -y2)
    raises(TypeError, lambda: Point(1))
    raises(ValueError, lambda: Point([1]))
    raises(ValueError, lambda: Point(3, I))
    raises(ValueError, lambda: Point(2*I, I))
    raises(ValueError, lambda: Point(3 + I, I))

    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
    assert Point.midpoint(p3, p4) == Point(half, half)
    assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2)
    assert Point.midpoint(p2, p2) == p2
    assert p2.midpoint(p2) == p2
    assert p1.origin == Point(0, 0)

    assert Point.distance(p3, p4) == sqrt(2)
    assert Point.distance(p1, p1) == 0
    assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)
    raises(TypeError, lambda: Point.distance(p1, 0))
    raises(TypeError, lambda: Point.distance(p1, GeometryEntity()))

    # distance should be symmetric
    assert p1.distance(line) == line.distance(p1)
    assert p4.distance(line) == line.distance(p4)

    assert Point.taxicab_distance(p4, p3) == 2

    assert Point.canberra_distance(p4, p5) == 1
    raises(ValueError, lambda: Point.canberra_distance(p3, p3))

    p1_1 = Point(x1, x1)
    p1_2 = Point(y2, y2)
    p1_3 = Point(x1 + 1, x1)
    assert Point.is_collinear(p3)

    with warns(UserWarning):
        assert Point.is_collinear(p3, Point(p3, dim=4))
    assert p3.is_collinear()
    assert Point.is_collinear(p3, p4)
    assert Point.is_collinear(p3, p4, p1_1, p1_2)
    assert Point.is_collinear(p3, p4, p1_1, p1_3) is False
    assert Point.is_collinear(p3, p3, p4, p5) is False

    raises(TypeError, lambda: Point.is_collinear(line))
    raises(TypeError, lambda: p1_1.is_collinear(line))

    assert p3.intersection(Point(0, 0)) == [p3]
    assert p3.intersection(p4) == []
    assert p3.intersection(line) == []
    assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)]

    x_pos = Symbol('x', positive=True)
    p2_1 = Point(x_pos, 0)
    p2_2 = Point(0, x_pos)
    p2_3 = Point(-x_pos, 0)
    p2_4 = Point(0, -x_pos)
    p2_5 = Point(x_pos, 5)
    assert Point.is_concyclic(p2_1)
    assert Point.is_concyclic(p2_1, p2_2)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
    for pts in permutations((p2_1, p2_2, p2_3, p2_5)):
        assert Point.is_concyclic(*pts) is False
    assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False
    assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False
    assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False

    assert p1.is_scalar_multiple(p1)
    assert p1.is_scalar_multiple(2*p1)
    assert not p1.is_scalar_multiple(p2)
    assert Point.is_scalar_multiple(Point(1, 1), (-1, -1))
    assert Point.is_scalar_multiple(Point(0, 0), (0, -1))
    # test when is_scalar_multiple can't be determined
    raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1)))

    assert Point(0, 1).orthogonal_direction == Point(1, 0)
    assert Point(1, 0).orthogonal_direction == Point(0, 1)

    assert p1.is_zero is None
    assert p3.is_zero
    assert p4.is_zero is False
    assert p1.is_nonzero is None
    assert p3.is_nonzero is False
    assert p4.is_nonzero

    assert p4.scale(2, 3) == Point(2, 3)
    assert p3.scale(2, 3) == p3

    assert p4.rotate(pi, Point(0.5, 0.5)) == p3
    assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
    assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)

    assert p4 * 5 == Point(5, 5)
    assert p4 / 5 == Point(0.2, 0.2)
    assert 5 * p4 == Point(5, 5)

    raises(ValueError, lambda: Point(0, 0) + 10)

    # Point differences should be simplified
    assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1)

    a, b = S.Half, Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2), evaluate=False)
    raises(ValueError, lambda: Point(1, 2) + 1)

    # test project
    assert Point.project((0, 1), (1, 0)) == Point(0, 0)
    assert Point.project((1, 1), (1, 0)) == Point(1, 0)
    raises(ValueError, lambda: Point.project(p1, Point(0, 0)))

    # test transformations
    p = Point(1, 0)
    assert p.rotate(pi/2) == Point(0, 1)
    assert p.rotate(pi/2, p) == p
    p = Point(1, 1)
    assert p.scale(2, 3) == Point(2, 3)
    assert p.translate(1, 2) == Point(2, 3)
    assert p.translate(1) == Point(2, 1)
    assert p.translate(y=1) == Point(1, 2)
    assert p.translate(*p.args) == Point(2, 2)

    # Check invalid input for transform
    raises(ValueError, lambda: p3.transform(p3))
    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))

    # test __contains__
    assert 0 in Point(0, 0, 0, 0)
    assert 1 not in Point(0, 0, 0, 0)

    # test affine_rank
    assert Point.affine_rank() == -1
示例#53
0
def test_misc_mats():

    mat = Matrix([[0]])

    gl = '''0'''
    glTransposed = '''0'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1]])

    gl = '''vec2(0, 1)'''
    glTransposed = '''vec2(0, 1)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2]])

    gl = '''vec3(0, 1, 2)'''
    glTransposed = '''vec3(0, 1, 2)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3]])

    gl = '''vec4(0, 1, 2, 3)'''
    glTransposed = '''vec4(0, 1, 2, 3)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4]])

    gl = '''float[5](0, 1, 2, 3, 4)'''
    glTransposed = '''float[5](0, 1, 2, 3, 4)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0], [1]])

    gl = '''vec2(0, 1)'''
    glTransposed = '''vec2(0, 1)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3]])

    gl = '''mat2(0, 1, 2, 3)'''
    glTransposed = '''mat2(0, 2, 1, 3)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5]])

    gl = '''mat3x2(0, 1, 2, 3, 4, 5)'''
    glTransposed = '''mat2x3(0, 3, 1, 4, 2, 5)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7]])

    gl = '''mat4x2(0, 1, 2, 3, 4, 5, 6, 7)'''
    glTransposed = '''mat2x4(0, 4, 1, 5, 2, 6, 3, 7)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])

    gl = '''float[10](
   0, 1, 2, 3, 4,
   5, 6, 7, 8, 9
) /* a 2x5 matrix */'''
    glTransposed = '''float[10](
   0, 5,
   1, 6,
   2, 7,
   3, 8,
   4, 9
) /* a 5x2 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[2][5](
   float[](0, 1, 2, 3, 4),
   float[](5, 6, 7, 8, 9)
)'''
    glNestedTransposed = '''float[5][2](
   float[](0, 5),
   float[](1, 6),
   float[](2, 7),
   float[](3, 8),
   float[](4, 9)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0], [1], [2]])

    gl = '''vec3(0, 1, 2)'''
    glTransposed = '''vec3(0, 1, 2)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3], [4, 5]])

    gl = '''mat2x3(0, 1, 2, 3, 4, 5)'''
    glTransposed = '''mat3x2(0, 2, 4, 1, 3, 5)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

    gl = '''mat3(0, 1, 2, 3, 4, 5, 6, 7, 8)'''
    glTransposed = '''mat3(0, 3, 6, 1, 4, 7, 2, 5, 8)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])

    gl = '''mat4x3(0, 1,  2,  3, 4, 5,  6,  7, 8, 9, 10, 11)'''
    glTransposed = '''mat3x4(0, 4,  8, 1, 5,  9, 2, 6, 10, 3, 7, 11)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])

    gl = '''float[15](
   0,  1,  2,  3,  4,
   5,  6,  7,  8,  9,
   10, 11, 12, 13, 14
) /* a 3x5 matrix */'''
    glTransposed = '''float[15](
   0, 5, 10,
   1, 6, 11,
   2, 7, 12,
   3, 8, 13,
   4, 9, 14
) /* a 5x3 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[3][5](
   float[]( 0,  1,  2,  3,  4),
   float[]( 5,  6,  7,  8,  9),
   float[](10, 11, 12, 13, 14)
)'''
    glNestedTransposed = '''float[5][3](
   float[](0, 5, 10),
   float[](1, 6, 11),
   float[](2, 7, 12),
   float[](3, 8, 13),
   float[](4, 9, 14)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0], [1], [2], [3]])

    gl = '''vec4(0, 1, 2, 3)'''
    glTransposed = '''vec4(0, 1, 2, 3)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3], [4, 5], [6, 7]])

    gl = '''mat2x4(0, 1, 2, 3, 4, 5, 6, 7)'''
    glTransposed = '''mat4x2(0, 2, 4, 6, 1, 3, 5, 7)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])

    gl = '''mat3x4(0,  1,  2, 3,  4,  5, 6,  7,  8, 9, 10, 11)'''
    glTransposed = '''mat4x3(0, 3, 6,  9, 1, 4, 7, 10, 2, 5, 8, 11)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14,
                                                               15]])

    gl = '''mat4( 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15)'''
    glTransposed = '''mat4(0, 4,  8, 12, 1, 5,  9, 13, 2, 6, 10, 14, 3, 7, 11, 15)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14],
                  [15, 16, 17, 18, 19]])

    gl = '''float[20](
   0,  1,  2,  3,  4,
   5,  6,  7,  8,  9,
   10, 11, 12, 13, 14,
   15, 16, 17, 18, 19
) /* a 4x5 matrix */'''
    glTransposed = '''float[20](
   0, 5, 10, 15,
   1, 6, 11, 16,
   2, 7, 12, 17,
   3, 8, 13, 18,
   4, 9, 14, 19
) /* a 5x4 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[4][5](
   float[]( 0,  1,  2,  3,  4),
   float[]( 5,  6,  7,  8,  9),
   float[](10, 11, 12, 13, 14),
   float[](15, 16, 17, 18, 19)
)'''
    glNestedTransposed = '''float[5][4](
   float[](0, 5, 10, 15),
   float[](1, 6, 11, 16),
   float[](2, 7, 12, 17),
   float[](3, 8, 13, 18),
   float[](4, 9, 14, 19)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0], [1], [2], [3], [4]])

    gl = '''float[5](0, 1, 2, 3, 4)'''
    glTransposed = '''float[5](0, 1, 2, 3, 4)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]])

    gl = '''float[10](
   0, 1,
   2, 3,
   4, 5,
   6, 7,
   8, 9
) /* a 5x2 matrix */'''
    glTransposed = '''float[10](
   0, 2, 4, 6, 8,
   1, 3, 5, 7, 9
) /* a 2x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][2](
   float[](0, 1),
   float[](2, 3),
   float[](4, 5),
   float[](6, 7),
   float[](8, 9)
)'''
    glNestedTransposed = '''float[2][5](
   float[](0, 2, 4, 6, 8),
   float[](1, 3, 5, 7, 9)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]])

    gl = '''float[15](
   0,  1,  2,
   3,  4,  5,
   6,  7,  8,
   9, 10, 11,
   12, 13, 14
) /* a 5x3 matrix */'''
    glTransposed = '''float[15](
   0, 3, 6,  9, 12,
   1, 4, 7, 10, 13,
   2, 5, 8, 11, 14
) /* a 3x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][3](
   float[]( 0,  1,  2),
   float[]( 3,  4,  5),
   float[]( 6,  7,  8),
   float[]( 9, 10, 11),
   float[](12, 13, 14)
)'''
    glNestedTransposed = '''float[3][5](
   float[](0, 3, 6,  9, 12),
   float[](1, 4, 7, 10, 13),
   float[](2, 5, 8, 11, 14)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15],
                  [16, 17, 18, 19]])

    gl = '''float[20](
   0,  1,  2,  3,
   4,  5,  6,  7,
   8,  9, 10, 11,
   12, 13, 14, 15,
   16, 17, 18, 19
) /* a 5x4 matrix */'''
    glTransposed = '''float[20](
   0, 4,  8, 12, 16,
   1, 5,  9, 13, 17,
   2, 6, 10, 14, 18,
   3, 7, 11, 15, 19
) /* a 4x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][4](
   float[]( 0,  1,  2,  3),
   float[]( 4,  5,  6,  7),
   float[]( 8,  9, 10, 11),
   float[](12, 13, 14, 15),
   float[](16, 17, 18, 19)
)'''
    glNestedTransposed = '''float[4][5](
   float[](0, 4,  8, 12, 16),
   float[](1, 5,  9, 13, 17),
   float[](2, 6, 10, 14, 18),
   float[](3, 7, 11, 15, 19)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14],
                  [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])

    gl = '''float[25](
   0,  1,  2,  3,  4,
   5,  6,  7,  8,  9,
   10, 11, 12, 13, 14,
   15, 16, 17, 18, 19,
   20, 21, 22, 23, 24
) /* a 5x5 matrix */'''
    glTransposed = '''float[25](
   0, 5, 10, 15, 20,
   1, 6, 11, 16, 21,
   2, 7, 12, 17, 22,
   3, 8, 13, 18, 23,
   4, 9, 14, 19, 24
) /* a 5x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][5](
   float[]( 0,  1,  2,  3,  4),
   float[]( 5,  6,  7,  8,  9),
   float[](10, 11, 12, 13, 14),
   float[](15, 16, 17, 18, 19),
   float[](20, 21, 22, 23, 24)
)'''
    glNestedTransposed = '''float[5][5](
   float[](0, 5, 10, 15, 20),
   float[](1, 6, 11, 16, 21),
   float[](2, 7, 12, 17, 22),
   float[](3, 8, 13, 18, 23),
   float[](4, 9, 14, 19, 24)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed
示例#54
0
T0_2 = simplify(T0_1 * T1_2)
T0_3 = simplify(T0_2 * T2_3)
T0_4 = simplify(T0_3 * T3_4)
T0_5 = simplify(T0_4 * T4_5)
T0_6 = simplify(T0_5 * T5_6)
T0_G = simplify(T0_6 * T6_G)

print("T0_1: ", T0_1.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))
print("T0_2: ", T0_2.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))
print("T0_3: ", T0_3.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))
print("T0_4: ", T0_4.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))
print("T0_5: ", T0_5.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))
print("T0_6: ", T0_6.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))
print("T0_G: ", T0_G.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))

R_z = Matrix([[cos(pi), -sin(pi), 0, 0], [sin(pi), cos(pi), 0, 0],
              [0, 0, 1, 0], [0, 0, 0, 1]])

R_y = Matrix([[cos(-pi / 2), 0, sin(-pi / 2), 0], [0, 1, 0, 0],
              [-sin(-pi / 2), 0, cos(-pi / 2), 0], [0, 0, 0, 1]])
R_corr = simplify(R_z * R_y)

T_gripper = simplify(T0_G * R_corr)

print("T_gripper: ",
      T_gripper.evalf(subs={
          q1: 0,
          q2: 0,
          q3: 0,
          q4: 0,
          q5: 0,
          q6: 0
def test_compound_gates():
    """Test a compound gate representation."""
    circuit = YGate(0)*ZGate(0)*XGate(0)*HadamardGate(0)*Qubit('00')
    answer = represent(circuit, nqubits=2)
    assert Matrix([I/sqrt(2), I/sqrt(2), 0, 0]) == answer
示例#56
0
def rotate_y(rads):
    rotated = Matrix([[cos(rads), 0, sin(rads), 0], [0, 1, 0, 0],
                      [-sin(rads), 0, cos(rads), 0], [0, 0, 0, 1]])

    return rotated
示例#57
0
def test_sparse_matrix():
    def sparse_eye(n):
        return SparseMatrix.eye(n)

    def sparse_zeros(n):
        return SparseMatrix.zeros(n)

    # creation args
    raises(TypeError, lambda: SparseMatrix(1, 2))

    a = SparseMatrix(((1, 0), (0, 1)))
    assert SparseMatrix(a) == a

    from sympy.matrices import MutableSparseMatrix, MutableDenseMatrix

    a = MutableSparseMatrix([])
    b = MutableDenseMatrix([1, 2])
    assert a.row_join(b) == b
    assert a.col_join(b) == b
    assert type(a.row_join(b)) == type(a)
    assert type(a.col_join(b)) == type(a)

    # make sure 0 x n matrices get stacked correctly
    sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]
    assert SparseMatrix.hstack(*sparse_matrices) == Matrix(0, 6, [])
    sparse_matrices = [SparseMatrix.zeros(n, 0) for n in range(4)]
    assert SparseMatrix.vstack(*sparse_matrices) == Matrix(6, 0, [])

    # test element assignment
    a = SparseMatrix(((1, 0), (0, 1)))

    a[3] = 4
    assert a[1, 1] == 4
    a[3] = 1

    a[0, 0] = 2
    assert a == SparseMatrix(((2, 0), (0, 1)))
    a[1, 0] = 5
    assert a == SparseMatrix(((2, 0), (5, 1)))
    a[1, 1] = 0
    assert a == SparseMatrix(((2, 0), (5, 0)))
    assert a._smat == {(0, 0): 2, (1, 0): 5}

    # test_multiplication
    a = SparseMatrix((
        (1, 2),
        (3, 1),
        (0, 6),
    ))

    b = SparseMatrix((
        (1, 2),
        (3, 0),
    ))

    c = a * b
    assert c[0, 0] == 7
    assert c[0, 1] == 2
    assert c[1, 0] == 6
    assert c[1, 1] == 6
    assert c[2, 0] == 18
    assert c[2, 1] == 0

    try:
        eval("c = a @ b")
    except SyntaxError:
        pass
    else:
        assert c[0, 0] == 7
        assert c[0, 1] == 2
        assert c[1, 0] == 6
        assert c[1, 1] == 6
        assert c[2, 0] == 18
        assert c[2, 1] == 0

    x = Symbol("x")

    c = b * Symbol("x")
    assert isinstance(c, SparseMatrix)
    assert c[0, 0] == x
    assert c[0, 1] == 2 * x
    assert c[1, 0] == 3 * x
    assert c[1, 1] == 0

    c = 5 * b
    assert isinstance(c, SparseMatrix)
    assert c[0, 0] == 5
    assert c[0, 1] == 2 * 5
    assert c[1, 0] == 3 * 5
    assert c[1, 1] == 0

    # test_power
    A = SparseMatrix([[2, 3], [4, 5]])
    assert (A**5)[:] == [6140, 8097, 10796, 14237]
    A = SparseMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
    assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]

    # test_creation
    x = Symbol("x")
    a = SparseMatrix([[x, 0], [0, 0]])
    m = a
    assert m.cols == m.rows
    assert m.cols == 2
    assert m[:] == [x, 0, 0, 0]
    b = SparseMatrix(2, 2, [x, 0, 0, 0])
    m = b
    assert m.cols == m.rows
    assert m.cols == 2
    assert m[:] == [x, 0, 0, 0]

    assert a == b
    S = sparse_eye(3)
    S.row_del(1)
    assert S == SparseMatrix([[1, 0, 0], [0, 0, 1]])
    S = sparse_eye(3)
    S.col_del(1)
    assert S == SparseMatrix([[1, 0], [0, 0], [0, 1]])
    S = SparseMatrix.eye(3)
    S[2, 1] = 2
    S.col_swap(1, 0)
    assert S == SparseMatrix([[0, 1, 0], [1, 0, 0], [2, 0, 1]])

    a = SparseMatrix(1, 2, [1, 2])
    b = a.copy()
    c = a.copy()
    assert a[0] == 1
    a.row_del(0)
    assert a == SparseMatrix(0, 2, [])
    b.col_del(1)
    assert b == SparseMatrix(1, 1, [1])

    assert SparseMatrix([[1, 2, 3], [1, 2], [1]]) == Matrix([[1, 2, 3],
                                                             [1, 2, 0],
                                                             [1, 0, 0]])
    assert SparseMatrix(4, 4, {(1, 1): sparse_eye(2)}) == Matrix([[0, 0, 0, 0],
                                                                  [0, 1, 0, 0],
                                                                  [0, 0, 1, 0],
                                                                  [0, 0, 0,
                                                                   0]])
    raises(ValueError, lambda: SparseMatrix(1, 1, {(1, 1): 1}))
    assert SparseMatrix(1, 2, [1, 2]).tolist() == [[1, 2]]
    assert SparseMatrix(2, 2, [1, [2, 3]]).tolist() == [[1, 0], [2, 3]]
    raises(ValueError, lambda: SparseMatrix(2, 2, [1]))
    raises(ValueError, lambda: SparseMatrix(1, 1, [[1, 2]]))
    assert SparseMatrix([0.1]).has(Float)
    # autosizing
    assert SparseMatrix(None, {(0, 1): 0}).shape == (0, 0)
    assert SparseMatrix(None, {(0, 1): 1}).shape == (1, 2)
    assert SparseMatrix(None, None, {(0, 1): 1}).shape == (1, 2)
    raises(ValueError, lambda: SparseMatrix(None, 1, [[1, 2]]))
    raises(ValueError, lambda: SparseMatrix(1, None, [[1, 2]]))
    raises(ValueError, lambda: SparseMatrix(3, 3, {
        (0, 0): ones(2),
        (1, 1): 2
    }))

    # test_determinant
    x, y = Symbol("x"), Symbol("y")

    assert SparseMatrix(1, 1, [0]).det() == 0

    assert SparseMatrix([[1]]).det() == 1

    assert SparseMatrix(((-3, 2), (8, -5))).det() == -1

    assert SparseMatrix(((x, 1), (y, 2 * y))).det() == 2 * x * y - y

    assert SparseMatrix(((1, 1, 1), (1, 2, 3), (1, 3, 6))).det() == 1

    assert (SparseMatrix(((3, -2, 0, 5), (-2, 1, -2, 2), (0, -2, 5, 0),
                          (5, 0, 3, 4))).det() == -289)

    assert (SparseMatrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
                          (13, 14, 15, 16))).det() == 0)

    assert (SparseMatrix((
        (3, 2, 0, 0, 0),
        (0, 3, 2, 0, 0),
        (0, 0, 3, 2, 0),
        (0, 0, 0, 3, 2),
        (2, 0, 0, 0, 3),
    )).det() == 275)

    assert (SparseMatrix((
        (1, 0, 1, 2, 12),
        (2, 0, 1, 1, 4),
        (2, 1, 1, -1, 3),
        (3, 2, -1, 1, 8),
        (1, 1, 1, 0, 6),
    )).det() == -55)

    assert (SparseMatrix((
        (-5, 2, 3, 4, 5),
        (1, -4, 3, 4, 5),
        (1, 2, -3, 4, 5),
        (1, 2, 3, -2, 5),
        (1, 2, 3, 4, -1),
    )).det() == 11664)

    assert (SparseMatrix((
        (2, 7, -1, 3, 2),
        (0, 0, 1, 0, 1),
        (-2, 0, 7, 0, 2),
        (-3, -2, 4, 5, 3),
        (1, 0, 0, 0, 1),
    )).det() == 123)

    # test_slicing
    m0 = sparse_eye(4)
    assert m0[:3, :3] == sparse_eye(3)
    assert m0[2:4, 0:2] == sparse_zeros(2)

    m1 = SparseMatrix(3, 3, lambda i, j: i + j)
    assert m1[0, :] == SparseMatrix(1, 3, (0, 1, 2))
    assert m1[1:3, 1] == SparseMatrix(2, 1, (2, 3))

    m2 = SparseMatrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11],
                       [12, 13, 14, 15]])
    assert m2[:, -1] == SparseMatrix(4, 1, [3, 7, 11, 15])
    assert m2[-2:, :] == SparseMatrix([[8, 9, 10, 11], [12, 13, 14, 15]])

    assert SparseMatrix([[1, 2], [3, 4]])[[1], [1]] == Matrix([[4]])

    # test_submatrix_assignment
    m = sparse_zeros(4)
    m[2:4, 2:4] = sparse_eye(2)
    assert m == SparseMatrix([(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 1, 0),
                              (0, 0, 0, 1)])
    assert len(m._smat) == 2
    m[:2, :2] = sparse_eye(2)
    assert m == sparse_eye(4)
    m[:, 0] = SparseMatrix(4, 1, (1, 2, 3, 4))
    assert m == SparseMatrix([(1, 0, 0, 0), (2, 1, 0, 0), (3, 0, 1, 0),
                              (4, 0, 0, 1)])
    m[:, :] = sparse_zeros(4)
    assert m == sparse_zeros(4)
    m[:, :] = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))
    assert m == SparseMatrix(
        ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
    m[:2, 0] = [0, 0]
    assert m == SparseMatrix(
        ((0, 2, 3, 4), (0, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))

    # test_reshape
    m0 = sparse_eye(3)
    assert m0.reshape(1, 9) == SparseMatrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
    m1 = SparseMatrix(3, 4, lambda i, j: i + j)
    assert m1.reshape(4, 3) == SparseMatrix([(0, 1, 2), (3, 1, 2), (3, 4, 2),
                                             (3, 4, 5)])
    assert m1.reshape(2, 6) == SparseMatrix([(0, 1, 2, 3, 1, 2),
                                             (3, 4, 2, 3, 4, 5)])

    # test_applyfunc
    m0 = sparse_eye(3)
    assert m0.applyfunc(lambda x: 2 * x) == sparse_eye(3) * 2
    assert m0.applyfunc(lambda x: 0) == sparse_zeros(3)

    # test__eval_Abs
    assert abs(SparseMatrix(((x, 1), (y, 2 * y)))) == SparseMatrix(
        ((Abs(x), 1), (Abs(y), 2 * Abs(y))))

    # test_LUdecomp
    testmat = SparseMatrix([[0, 2, 5, 3], [3, 3, 7, 4], [8, 4, 0, 2],
                            [-2, 6, 3, 4]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, "backward") - testmat == sparse_zeros(4)

    testmat = SparseMatrix([[6, -2, 7, 4], [0, 3, 6, 7], [1, -2, 7, 4],
                            [-9, 2, 6, 3]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, "backward") - testmat == sparse_zeros(4)

    x, y, z = Symbol("x"), Symbol("y"), Symbol("z")
    M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z)))
    L, U, p = M.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, "backward") - M == sparse_zeros(3)

    # test_LUsolve
    A = SparseMatrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]])
    x = SparseMatrix(3, 1, [3, 7, 5])
    b = A * x
    soln = A.LUsolve(b)
    assert soln == x
    A = SparseMatrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]])
    x = SparseMatrix(3, 1, [-1, 2, 5])
    b = A * x
    soln = A.LUsolve(b)
    assert soln == x

    # test_inverse
    A = sparse_eye(4)
    assert A.inv() == sparse_eye(4)
    assert A.inv(method="CH") == sparse_eye(4)
    assert A.inv(method="LDL") == sparse_eye(4)

    A = SparseMatrix([[2, 3, 5], [3, 6, 2], [7, 2, 6]])
    Ainv = SparseMatrix(Matrix(A).inv())
    assert A * Ainv == sparse_eye(3)
    assert A.inv(method="CH") == Ainv
    assert A.inv(method="LDL") == Ainv

    A = SparseMatrix([[2, 3, 5], [3, 6, 2], [5, 2, 6]])
    Ainv = SparseMatrix(Matrix(A).inv())
    assert A * Ainv == sparse_eye(3)
    assert A.inv(method="CH") == Ainv
    assert A.inv(method="LDL") == Ainv

    # test_cross
    v1 = Matrix(1, 3, [1, 2, 3])
    v2 = Matrix(1, 3, [3, 4, 5])
    assert v1.cross(v2) == Matrix(1, 3, [-2, 4, -2])
    assert v1.norm(2)**2 == 14

    # conjugate
    a = SparseMatrix(((1, 2 + I), (3, 4)))
    assert a.C == SparseMatrix([[1, 2 - I], [3, 4]])

    # mul
    assert a * Matrix(2, 2, [1, 0, 0, 1]) == a
    assert a + Matrix(2, 2, [1, 1, 1, 1]) == SparseMatrix([[2, 3 + I], [4, 5]])

    # col join
    assert a.col_join(sparse_eye(2)) == SparseMatrix([[1, 2 + I], [3, 4],
                                                      [1, 0], [0, 1]])

    # symmetric
    assert not a.is_symmetric(simplify=False)

    # test_cofactor
    assert sparse_eye(3) == sparse_eye(3).cofactor_matrix()
    test = SparseMatrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
    assert test.cofactor_matrix() == SparseMatrix([[27, -6, -6], [-12, 2, 3],
                                                   [-3, 1, 0]])
    test = SparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    assert test.cofactor_matrix() == SparseMatrix([[-3, 6, -3], [6, -12, 6],
                                                   [-3, 6, -3]])

    # test_jacobian
    x = Symbol("x")
    y = Symbol("y")
    L = SparseMatrix(1, 2, [x**2 * y, 2 * y**2 + x * y])
    syms = [x, y]
    assert L.jacobian(syms) == Matrix([[2 * x * y, x**2], [y, 4 * y + x]])

    L = SparseMatrix(1, 2, [x, x**2 * y**3])
    assert L.jacobian(syms) == SparseMatrix([[1, 0],
                                             [2 * x * y**3, x**2 * 3 * y**2]])

    # test_QR
    A = Matrix([[1, 2], [2, 3]])
    Q, S = A.QRdecomposition()
    R = Rational
    assert Q == Matrix([
        [5**R(-1, 2), (R(2) / 5) * (R(1) / 5)**R(-1, 2)],
        [2 * 5**R(-1, 2), (-R(1) / 5) * (R(1) / 5)**R(-1, 2)],
    ])
    assert S == Matrix([[5**R(1, 2), 8 * 5**R(-1, 2)],
                        [0, (R(1) / 5)**R(1, 2)]])
    assert Q * S == A
    assert Q.T * Q == sparse_eye(2)

    R = Rational
    # test nullspace
    # first test reduced row-ech form

    M = SparseMatrix([[5, 7, 2, 1], [1, 6, 2, -1]])
    out, tmp = M.rref()
    assert out == Matrix([[1, 0, -R(2) / 23, R(13) / 23],
                          [0, 1, R(8) / 23, R(-6) / 23]])

    M = SparseMatrix([
        [1, 3, 0, 2, 6, 3, 1],
        [-2, -6, 0, -2, -8, 3, 1],
        [3, 9, 0, 0, 6, 6, 2],
        [-1, -3, 0, 1, 0, 9, 3],
    ])

    out, tmp = M.rref()
    assert out == Matrix([
        [1, 3, 0, 0, 2, 0, 0],
        [0, 0, 0, 1, 2, 0, 0],
        [0, 0, 0, 0, 0, 1, R(1) / 3],
        [0, 0, 0, 0, 0, 0, 0],
    ])
    # now check the vectors
    basis = M.nullspace()
    assert basis[0] == Matrix([-3, 1, 0, 0, 0, 0, 0])
    assert basis[1] == Matrix([0, 0, 1, 0, 0, 0, 0])
    assert basis[2] == Matrix([-2, 0, 0, -2, 1, 0, 0])
    assert basis[3] == Matrix([0, 0, 0, 0, 0, R(-1) / 3, 1])

    # test eigen
    x = Symbol("x")
    y = Symbol("y")
    sparse_eye3 = sparse_eye(3)
    assert sparse_eye3.charpoly(x) == PurePoly(((x - 1)**3))
    assert sparse_eye3.charpoly(y) == PurePoly(((y - 1)**3))

    # test values
    M = Matrix([(0, 1, -1), (1, 1, 0), (-1, 0, 1)])
    vals = M.eigenvals()
    assert sorted(vals.keys()) == [-1, 1, 2]

    R = Rational
    M = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    assert M.eigenvects() == [
        (1, 3, [Matrix([1, 0, 0]),
                Matrix([0, 1, 0]),
                Matrix([0, 0, 1])])
    ]
    M = Matrix([[5, 0, 2], [3, 2, 0], [0, 0, 1]])
    assert M.eigenvects() == [
        (1, 1, [Matrix([R(-1) / 2, R(3) / 2, 1])]),
        (2, 1, [Matrix([0, 1, 0])]),
        (5, 1, [Matrix([1, 1, 0])]),
    ]

    assert M.zeros(3, 5) == SparseMatrix(3, 5, {})
    A = SparseMatrix(
        10,
        10,
        {
            (0, 0): 18,
            (0, 9): 12,
            (1, 4): 18,
            (2, 7): 16,
            (3, 9): 12,
            (4, 2): 19,
            (5, 7): 16,
            (6, 2): 12,
            (9, 7): 18,
        },
    )
    assert A.row_list() == [
        (0, 0, 18),
        (0, 9, 12),
        (1, 4, 18),
        (2, 7, 16),
        (3, 9, 12),
        (4, 2, 19),
        (5, 7, 16),
        (6, 2, 12),
        (9, 7, 18),
    ]
    assert A.col_list() == [
        (0, 0, 18),
        (4, 2, 19),
        (6, 2, 12),
        (1, 4, 18),
        (2, 7, 16),
        (5, 7, 16),
        (9, 7, 18),
        (0, 9, 12),
        (3, 9, 12),
    ]
    assert SparseMatrix.eye(2).nnz() == 2
示例#58
0
def test_QRsolve():
    A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]])
    x = Matrix(3, 1, [3, 7, 5])
    b = A * x
    soln = A.QRsolve(b)
    assert soln == x
    x = Matrix([[1, 2], [3, 4], [5, 6]])
    b = A * x
    soln = A.QRsolve(b)
    assert soln == x

    A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]])
    x = Matrix(3, 1, [-1, 2, 5])
    b = A * x
    soln = A.QRsolve(b)
    assert soln == x
    x = Matrix([[7, 8], [9, 10], [11, 12]])
    b = A * x
    soln = A.QRsolve(b)
    assert soln == x
def test_represent_tgate():
    """Test the representation of the T gate."""
    circuit = TGate(0)*Qubit('01')
    assert Matrix([0, exp(I*pi/4), 0, 0]) == represent(circuit, nqubits=2)
示例#60
0
def test_matrix():
    assert rust_code(Matrix([1, 2, 3])) == '[1, 2, 3]'
    with raises(ValueError):
        rust_code(Matrix([[1, 2, 3]]))