def test_as_explicit(): Z = MatrixSymbol('Z', 2, 3) assert Z.as_explicit() == ImmutableMatrix([ [Z[0, 0], Z[0, 1], Z[0, 2]], [Z[1, 0], Z[1, 1], Z[1, 2]], ]) raises(ValueError, lambda: A.as_explicit())
def test_UGate_OneQubitGate_combo(): v, w, f, g = symbols('v w f g') uMat1 = ImmutableMatrix([[v, w], [f, g]]) cMat1 = Matrix([[v, w + 1, 0, 0], [f + 1, g, 0, 0], [0, 0, v, w + 1], [0, 0, f + 1, g]]) u1 = X(0) + UGate(0, uMat1) assert represent(u1, nqubits=2) == cMat1 uMat2 = ImmutableMatrix([[1 / sqrt(2), 1 / sqrt(2)], [I / sqrt(2), -I / sqrt(2)]]) cMat2_1 = Matrix([[1 / 2 + I / 2, 1 / 2 - I / 2], [1 / 2 - I / 2, 1 / 2 + I / 2]]) cMat2_2 = Matrix([[1, 0], [0, I]]) u2 = UGate(0, uMat2) assert represent(H(0) * u2, nqubits=1) == cMat2_1 assert represent(u2 * H(0), nqubits=1) == cMat2_2
def test_Trace_MatAdd_doit(): # See issue #9028 X = ImmutableMatrix([[1, 2, 3]] * 3) Y = MatrixSymbol("Y", 3, 3) q = MatAdd(X, 2 * X, Y, -3 * Y) assert Trace(q).arg == q assert Trace(q).doit() == 18 - 2 * Trace(Y)
def test_doit_nonsquare(): X = ImmutableMatrix([[1, 2, 3], [4, 5, 6]]) assert MatPow(X, 1).doit() == X raises(ShapeError, lambda: MatPow(X, 0).doit()) raises(ShapeError, lambda: MatPow(X, 2).doit()) raises(ShapeError, lambda: MatPow(X, -1).doit()) raises(ShapeError, lambda: MatPow(X, pi).doit())
def test_as_explicit_nonsquare(): A = ImmutableMatrix([[1, 2, 3], [4, 5, 6]]) assert MatPow(A, 1).as_explicit() == A raises(ShapeError, lambda: MatPow(A, 0).as_explicit()) raises(ShapeError, lambda: MatPow(A, 2).as_explicit()) raises(ShapeError, lambda: MatPow(A, -1).as_explicit()) raises(ValueError, lambda: MatPow(A, pi).as_explicit())
def pdf(self, *args): mu, sigma = self.mu, self.sigma k = mu.shape[0] args = ImmutableMatrix(args) x = args - mu return (S.One / sqrt((2 * pi)**(k) * det(sigma)) * exp(Rational(-1, 2) * x.transpose() * (sigma.inv() * x))[0])
def test_entry_matrix(): X = ImmutableMatrix([[1, 2], [3, 4]]) assert MatPow(X, 0)[0, 0] == 1 assert MatPow(X, 0)[0, 1] == 0 assert MatPow(X, 1)[0, 0] == 1 assert MatPow(X, 1)[0, 1] == 2 assert MatPow(X, 2)[0, 0] == 7
def test_eq(): A = Matrix([[1]]) B = ImmutableMatrix([[1]]) C = SparseMatrix([[1]]) assert A != object() assert A != "Matrix([[1]])" assert A == B assert A == C
def pdf(self, *args): mu, sigma = self.mu, self.sigma k = len(mu) args = ImmutableMatrix(args) x = args - mu return S(1)/sqrt((2*pi)**(k)*det(sigma))*exp( -S(1)/2*x.transpose()*(sigma.inv()*\ x))[0]
def test_classof(): A = MutableMatrix(3,3,range(9)) B = ImmutableMatrix(3,3,range(9)) C = MatrixSymbol('C', 3,3) assert classof(A,A) == MutableMatrix assert classof(B,B) == ImmutableMatrix assert classof(A,B) == MutableMatrix raises(TypeError, "classof(A,C)")
def pdf(self, *args): mu, sigma = self.mu, self.shape_mat v = S(self.dof) k = S(len(mu)) sigma_inv = sigma.inv() args = ImmutableMatrix(args) x = args - mu return gamma((k + v)/2)/(gamma(v/2)*(v*pi)**(k/2)*sqrt(det(sigma)))\ *(1 + 1/v*(x.transpose()*sigma_inv*x)[0])**((-v - k)/2)
def test_classof(): A = Matrix(3, 3, range(9)) B = ImmutableMatrix(3, 3, range(9)) C = MatrixSymbol("C", 3, 3) assert classof(A, A) == Matrix assert classof(B, B) == ImmutableMatrix assert classof(A, B) == ImmutableMatrix assert classof(B, A) == ImmutableMatrix raises(TypeError, lambda: classof(A, C))
def pdf(self, *args): mu, sigma = self.mu, self.sigma k = mu.shape[0] if len(args) == 1 and args[0].is_Matrix: args = args[0] else: args = ImmutableMatrix(args) x = args - mu density = S.One / sqrt((2 * pi)**(k) * det(sigma)) * exp( Rational(-1, 2) * x.transpose() * (sigma.inv() * x)) return MatrixElement(density, 0, 0)
def pdf(self, x): M , U , V = self.location_matrix, self.scale_matrix_1, self.scale_matrix_2 n, p = M.shape if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) term1 = Inverse(V)*Transpose(x - M)*Inverse(U)*(x - M) num = exp(-Trace(term1)/S(2)) den = (2*pi)**(S(n*p)/2) * Determinant(U)**S(p)/2 * Determinant(V)**S(n)/2 return num/den
def marginal_distribution(self, indices, sym): sym = ImmutableMatrix([Indexed(sym, i) for i in indices]) _mu, _sigma = self.mu, self.sigma k = len(self.mu) for i in range(k): if i not in indices: _mu = _mu.row_del(i) _sigma = _sigma.col_del(i) _sigma = _sigma.row_del(i) return Lambda(sym, S(1)/sqrt((2*pi)**(len(_mu))*det(_sigma))*exp( -S(1)/2*(_mu - sym).transpose()*(_sigma.inv()*\ (_mu - sym)))[0])
def _marginal_distribution(self, indices, sym): sym = ImmutableMatrix([Indexed(sym, i) for i in indices]) _mu, _sigma = self.mu, self.sigma k = self.mu.shape[0] for i in range(k): if i not in indices: _mu = _mu.row_del(i) _sigma = _sigma.col_del(i) _sigma = _sigma.row_del(i) return Lambda(tuple(sym), S.One/sqrt((2*pi)**(len(_mu))*det(_sigma))*exp( Rational(-1, 2)*(_mu - sym).transpose()*(_sigma.inv()*\ (_mu - sym)))[0])
def pdf(self, x): n, scale_matrix = self.n, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / S(2) term1 = exp(Trace(sigma_inv_x))/((2**(p*n/S(2))) * multigamma(n/S(2), p)) term2 = (Determinant(scale_matrix))**(-n/S(2)) term3 = (Determinant(x))**(S(n - p - 1)/2) return term1 * term2 * term3
def pdf(self, x): alpha , beta , scale_matrix = self.alpha, self.beta, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / beta term1 = exp(Trace(sigma_inv_x))/((beta**(p*alpha)) * multigamma(alpha, p)) term2 = (Determinant(scale_matrix))**(-alpha) term3 = (Determinant(x))**(alpha - S(p + 1)/2) return term1 * term2 * term3
def pdf(self, *args): mu, sigma = self.mu, self.sigma mu_T = mu.transpose() k = S(mu.shape[0]) sigma_inv = sigma.inv() args = ImmutableMatrix(args) args_T = args.transpose() x = (mu_T*sigma_inv*mu)[0] y = (args_T*sigma_inv*args)[0] v = 1 - k/2 return (2 * (y/(2 + x))**(v/2) * besselk(v, sqrt((2 + x)*y)) * exp((args_T * sigma_inv * mu)[0]) / ((2 * pi)**(k/2) * sqrt(det(sigma))))
def pdf(self, *args): mu, sigma = self.mu, self.sigma mu_T = mu.transpose() k = S(len(mu)) sigma_inv = sigma.inv() args = ImmutableMatrix(args) args_T = args.transpose() x = (mu_T*sigma_inv*mu)[0] y = (args_T*sigma_inv*args)[0] v = 1 - k/2 return S(2)/((2*pi)**(S(k)/2)*sqrt(det(sigma)))\ *(y/(2 + x))**(S(v)/2)*besselk(v, sqrt((2 + x)*(y)))\ *exp((args_T*sigma_inv*mu)[0])
def pdf(self, x): from sympy import eye if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) nu, M, Omega, Sigma = self.nu, self.location_matrix, self.scale_matrix_1, self.scale_matrix_2 n, p = M.shape K = multigamma((nu + n + p - 1)/2, p) * Determinant(Omega)**(-n/2) * Determinant(Sigma)**(-p/2) \ / ((pi)**(n*p/2) * multigamma((nu + p - 1)/2, p)) return K * (Determinant(eye(n) + Inverse(Sigma)*(x - M)*Inverse(Omega)*Transpose(x - M))) \ **(-(nu + n + p -1)/2)
def MatrixGamma(symbol, alpha, beta, scale_matrix): """ Creates a random variable with Matrix Gamma Distribution. The density of the said distribution can be found at [1]. Parameters ========== alpha: Positive Real number Shape Parameter beta: Positive Real number Scale Parameter scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, MatrixGamma >>> from sympy import MatrixSymbol, symbols >>> a, b = symbols('a b', positive=True) >>> M = MatrixGamma('M', a, b, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(M)(X).doit() 3**(-a)*b**(-2*a)*exp(Trace(Matrix([ [-2/3, 1/3], [ 1/3, -2/3]])*X)/b)*Determinant(X)**(a - 3/2)/(sqrt(pi)*gamma(a)*gamma(a - 1/2)) >>> density(M)([[1, 0], [0, 1]]).doit() 3**(-a)*b**(-2*a)*exp(-4/(3*b))/(sqrt(pi)*gamma(a)*gamma(a - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_gamma_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, MatrixGammaDistribution, (alpha, beta, scale_matrix))
def Wishart(symbol, n, scale_matrix): """ Creates a random variable with Wishart Distribution. The density of the said distribution can be found at [1]. Parameters ========== n: Positive Real number Represents degrees of freedom scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, Wishart >>> from sympy import MatrixSymbol, symbols >>> n = symbols('n', positive=True) >>> W = Wishart('W', n, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(W)(X).doit() 2**(-n)*3**(-n/2)*exp(Trace(Matrix([ [-1/3, 1/6], [ 1/6, -1/3]])*X))*Determinant(X)**(n/2 - 3/2)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) >>> density(W)([[1, 0], [0, 1]]).doit() 2**(-n)*3**(-n/2)*exp(-2/3)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Wishart_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, WishartDistribution, (n, scale_matrix))
def test_nfloat(): from sympy.core.basic import _aresame from sympy.polys.rootoftools import rootof x = Symbol("x") eq = x**Rational(4, 3) + 4 * x**(S.One / 3) / 3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0 / 3) * x**(S.One / 3)) assert _aresame(nfloat(eq, exponent=True), x**(4.0 / 3) + (4.0 / 3) * x**(1.0 / 3)) eq = x**Rational(4, 3) + 4 * x**(x / 3) / 3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0 / 3) * x**(x / 3)) big = 12345678901234567890 # specify precision to match value used in nfloat Float_big = Float(big, 15) assert _aresame(nfloat(big), Float_big) assert _aresame(nfloat(big * x), Float_big * x) assert _aresame(nfloat(x**big, exponent=True), x**Float_big) assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2))) # issue 6342 f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4') assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139))) # issue 6632 assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \ 9.99999999800000e-11 # issue 7122 eq = cos(3 * x**4 + y) * rootof(x**5 + 3 * x**3 + 1, 0) assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)' # issue 10933 for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (S.Half, Float(.5))) for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d, dkeys=True) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5))) d = [S.Half] n = nfloat(d) assert type(n) is list assert _aresame(n[0], Float(.5)) assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5)) assert _aresame(nfloat(S(True)), S(True)) assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5)) assert nfloat(Eq((3 - I)**2 / 2 + I, 0)) == S.false # pass along kwargs assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}] # Issue 17706 A = MutableMatrix([[1, 2], [3, 4]]) B = MutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B) A = ImmutableMatrix([[1, 2], [3, 4]]) B = ImmutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B)
def test_doit_drills_down(): X = ImmutableMatrix([[1, 2], [3, 4]]) Y = ImmutableMatrix([[2, 3], [4, 5]]) assert MatMul(X, MatPow(Y, 2)).doit() == X * Y**2 assert MatMul(C, Transpose(D * C)).doit().args == (C, C.T, D.T)
def test_collapse_MatrixBase(): A = Matrix([[1, 1], [1, 1]]) B = Matrix([[1, 2], [3, 4]]) assert MatMul(A, B).doit() == ImmutableMatrix([[4, 6], [4, 6]])
def test_MatrixElement_doit(): u = MatrixSymbol('u', 2, 1) v = ImmutableMatrix([3, 5]) assert u[0, 0].subs(u, v).doit() == v[0, 0]
def test_matmul_simplify(): A = MatrixSymbol('A', 1, 1) assert simplify(MatMul(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \ MatMul(A, ImmutableMatrix([[1]]))
def test_dense_conversion(): X = MatrixSymbol('X', 2, 2) assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j]) assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j])
def __new__(cls, *args): args = list(map(sympify, args)) for i in range(len(args)): if isinstance(args[i], list): args[i] = ImmutableMatrix(args[i]) return Basic.__new__(cls, *args)