本文整理汇总了Python中sage.structure.element.is_Matrix函数的典型用法代码示例。如果您正苦于以下问题:Python is_Matrix函数的具体用法?Python is_Matrix怎么用?Python is_Matrix使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_Matrix函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, parent, A, b=0, convert=True, check=True):
r"""
Create element of an affine group.
TESTS::
sage: G = AffineGroup(4, GF(5))
sage: g = G.random_element()
sage: TestSuite(g).run()
"""
try:
A = A.matrix()
except AttributeError:
pass
if is_Matrix(A) and A.nrows() == A.ncols() == parent.degree()+1:
g = A
d = parent.degree()
A = g.submatrix(0, 0, d, d)
b = [ g[i,d] for i in range(d) ]
convert = True
if convert:
A = parent.matrix_space()(A)
b = parent.vector_space()(b)
if check:
# Note: the coercion framework expects that we raise TypeError for invalid input
if not is_Matrix(A):
raise TypeError('A must be a matrix')
if not (A.parent() is parent.matrix_space()):
raise TypeError('A must be an element of '+str(parent.matrix_space()))
if not (b.parent() is parent.vector_space()):
raise TypeError('b must be an element of '+str(parent.vector_space()))
parent._element_constructor_check(A, b)
super(AffineGroupElement, self).__init__(parent)
self._A = A
self._b = b
示例2: __classcall_private__
def __classcall_private__(self, arg0, arg1=None, names=None):
"""
Choose the correct parent based upon input.
TESTS:
We check arguments with passing in an associative algebra::
sage: cat = Algebras(QQ).WithBasis().FiniteDimensional()
sage: C = CombinatorialFreeModule(QQ, ['x','y','z'], category=cat)
sage: J1 = JordanAlgebra(C, names=['a','b','c'])
sage: J2.<a,b,c> = JordanAlgebra(C)
sage: J1 is J2
True
We check with passing in a symmetric bilinear form::
sage: m = matrix([[0,1],[1,1]])
sage: J1 = JordanAlgebra(m)
sage: J2 = JordanAlgebra(QQ, m)
sage: J3 = JordanAlgebra(m, QQ)
sage: J1 is J2
False
sage: J2 is J3
True
sage: J4 = JordanAlgebra(ZZ, m)
sage: J1 is J4
True
sage: m = matrix(QQ, [[0,1],[1,1]])
sage: J1 = JordanAlgebra(m)
sage: J1 is J2
True
"""
if names is not None:
if isinstance(names, str):
names = names.split(',')
names = tuple(names)
if arg1 is None:
if not is_Matrix(arg0):
if arg0.base_ring().characteristic() == 2:
raise ValueError("the base ring cannot have characteristic 2")
return SpecialJordanAlgebra(arg0, names)
arg0, arg1 = arg0.base_ring(), arg0
elif is_Matrix(arg0):
arg0, arg1 = arg1, arg0
# arg0 is the base ring and arg1 is a matrix
if not arg1.is_symmetric():
raise ValueError("the bilinear form is not symmetric")
arg1 = arg1.change_ring(arg0) # This makes a copy
arg1.set_immutable()
return JordanAlgebraSymmetricBilinear(arg0, arg1, names=names)
示例3: __call__
def __call__(self, f, check=True, unitary=True):
"""
Construct a homomorphism.
.. TODO::
Implement taking generator images and converting them to a matrix.
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(QQ, [Matrix([1])])
sage: B = FiniteDimensionalAlgebra(QQ, [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: H = Hom(A, B)
sage: H(Matrix([[1, 0]]))
Morphism from Finite-dimensional algebra of degree 1 over Rational Field to
Finite-dimensional algebra of degree 2 over Rational Field given by matrix
[1 0]
"""
if isinstance(f, FiniteDimensionalAlgebraMorphism):
if f.parent() is self:
return f
if f.parent() == self:
return FiniteDimensionalAlgebraMorphism(self, f._matrix, check, unitary)
elif is_Matrix(f):
return FiniteDimensionalAlgebraMorphism(self, f, check, unitary)
try:
from sage.matrix.constructor import Matrix
return FiniteDimensionalAlgebraMorphism(self, Matrix(f), check, unitary)
except Exception:
return RingHomset_generic.__call__(self, f, check)
示例4: __init__
def __init__(self, A, gens=None, given_by_matrix=False):
"""
EXAMPLES::
sage: A = FiniteDimensionalAlgebra(GF(3), [Matrix([[1, 0], [0, 1]]), Matrix([[0, 1], [0, 0]])])
sage: I = A.ideal(A([0,1]))
sage: TestSuite(I).run(skip="_test_category") # Currently ideals are not using the category framework
"""
k = A.base_ring()
n = A.degree()
if given_by_matrix:
self._basis_matrix = gens
gens = gens.rows()
elif gens is None:
self._basis_matrix = Matrix(k, 0, n)
elif isinstance(gens, (list, tuple)):
B = [FiniteDimensionalAlgebraIdeal(A, x).basis_matrix() for x in gens]
B = reduce(lambda x, y: x.stack(y), B, Matrix(k, 0, n))
self._basis_matrix = B.echelon_form().image().basis_matrix()
elif is_Matrix(gens):
gens = FiniteDimensionalAlgebraElement(A, gens)
elif isinstance(gens, FiniteDimensionalAlgebraElement):
gens = gens.vector()
B = Matrix([(gens * b).list() for b in A.table()])
self._basis_matrix = B.echelon_form().image().basis_matrix()
Ideal_generic.__init__(self, A, gens)
示例5: __rmul__
def __rmul__(self, other):
r"""
Implement the action of matrices on points of hyperbolic space.
EXAMPLES::
sage: A = matrix(2, [0, 1, 1, 0])
sage: A = HyperbolicPlane().UHP().get_isometry(A)
sage: A * HyperbolicPlane().UHP().get_point(2 + I)
Point in UHP 1/5*I + 2/5
We also lift matrices into isometries::
sage: B = diagonal_matrix([-1, -1, 1])
sage: B = HyperbolicPlane().HM().get_isometry(B)
sage: B * HyperbolicPlane().HM().get_point((0, 1, sqrt(2)))
Point in HM (0, -1, sqrt(2))
"""
if isinstance(other, HyperbolicIsometry):
return other(self)
elif is_Matrix(other):
# TODO: Currently the __mul__ from the matrices gets called first
# and returns an error instead of calling this method
A = self.parent().get_isometry(other)
return A(self)
else:
raise TypeError("unsupported operand type(s) for *:"
"{0} and {1}".format(self, other))
示例6: sudoku
def sudoku(m):
r"""
Solves Sudoku puzzles described by matrices.
INPUT:
- ``m`` - a square Sage matrix over `\ZZ`, where zeros are blank entries
OUTPUT:
A Sage matrix over `\ZZ` containing the first solution found,
otherwise ``None``.
This function matches the behavior of the prior Sudoku solver
and is included only to replicate that behavior. It could be
safely deprecated, since all of its functionality is included in the :class:`~sage.games.sudoku.Sudoku` class.
EXAMPLES:
An example that was used in previous doctests. ::
sage: A = matrix(ZZ,9,[5,0,0, 0,8,0, 0,4,9, 0,0,0, 5,0,0, 0,3,0, 0,6,7, 3,0,0, 0,0,1, 1,5,0, 0,0,0, 0,0,0, 0,0,0, 2,0,8, 0,0,0, 0,0,0, 0,0,0, 0,1,8, 7,0,0, 0,0,4, 1,5,0, 0,3,0, 0,0,2, 0,0,0, 4,9,0, 0,5,0, 0,0,3])
sage: A
[5 0 0 0 8 0 0 4 9]
[0 0 0 5 0 0 0 3 0]
[0 6 7 3 0 0 0 0 1]
[1 5 0 0 0 0 0 0 0]
[0 0 0 2 0 8 0 0 0]
[0 0 0 0 0 0 0 1 8]
[7 0 0 0 0 4 1 5 0]
[0 3 0 0 0 2 0 0 0]
[4 9 0 0 5 0 0 0 3]
sage: sudoku(A)
[5 1 3 6 8 7 2 4 9]
[8 4 9 5 2 1 6 3 7]
[2 6 7 3 4 9 5 8 1]
[1 5 8 4 6 3 9 7 2]
[9 7 4 2 1 8 3 6 5]
[3 2 6 7 9 5 4 1 8]
[7 8 2 9 3 4 1 5 6]
[6 3 5 1 7 2 8 9 4]
[4 9 1 8 5 6 7 2 3]
Using inputs that are possible with the
:class:`~sage.games.sudoku.Sudoku` class,
other than a matrix, will cause an error. ::
sage: sudoku('.4..32....14..3.')
Traceback (most recent call last):
...
ValueError: sudoku function expects puzzle to be a matrix, perhaps use the Sudoku class
"""
from sage.structure.element import is_Matrix
if not is_Matrix(m):
raise ValueError('sudoku function expects puzzle to be a matrix, perhaps use the Sudoku class')
solution = next(Sudoku(m).solve(algorithm='dlx'))
return (solution.to_matrix() if solution else None)
示例7: normalize_square_matrices
def normalize_square_matrices(matrices):
"""
Find a common space for all matrices.
OUTPUT:
A list of matrices, all elements of the same matrix space.
EXAMPLES::
sage: from sage.groups.matrix_gps.finitely_generated import normalize_square_matrices
sage: m1 = [[1,2],[3,4]]
sage: m2 = [2, 3, 4, 5]
sage: m3 = matrix(QQ, [[1/2,1/3],[1/4,1/5]])
sage: m4 = MatrixGroup(m3).gen(0)
sage: normalize_square_matrices([m1, m2, m3, m4])
[
[1 2] [2 3] [1/2 1/3] [1/2 1/3]
[3 4], [4 5], [1/4 1/5], [1/4 1/5]
]
"""
deg = []
gens = []
for m in matrices:
if is_MatrixGroupElement(m):
deg.append(m.parent().degree())
gens.append(m.matrix())
continue
if is_Matrix(m):
if not m.is_square():
raise TypeError('matrix must be square')
deg.append(m.ncols())
gens.append(m)
continue
try:
m = list(m)
except TypeError:
gens.append(m)
continue
if isinstance(m[0], (list, tuple)):
m = [list(_) for _ in m]
degree = ZZ(len(m))
else:
degree, rem = ZZ(len(m)).sqrtrem()
if rem!=0:
raise ValueError('list of plain numbers must have square integer length')
deg.append(degree)
gens.append(matrix(degree, degree, m))
deg = set(deg)
if len(set(deg)) != 1:
raise ValueError('not all matrices have the same size')
gens = Sequence(gens, immutable=True)
MS = gens.universe()
if not is_MatrixSpace(MS):
raise TypeError('all generators must be matrices')
if MS.nrows() != MS.ncols():
raise ValueError('matrices must be square')
return gens
示例8: from_incidence_matrix
def from_incidence_matrix(G, M, loops=False, multiedges=False, weighted=False):
r"""
Fill ``G`` with the data of an incidence matrix.
INPUT:
- ``G`` -- a graph
- ``M`` -- an incidence matrix
- ``loops``, ``multiedges``, ``weighted`` -- booleans (default: ``False``);
whether to consider the graph as having loops, multiple edges, or weights
EXAMPLES::
sage: from sage.graphs.graph_input import from_incidence_matrix
sage: g = Graph()
sage: from_incidence_matrix(g, graphs.PetersenGraph().incidence_matrix())
sage: g.is_isomorphic(graphs.PetersenGraph())
True
"""
from sage.structure.element import is_Matrix
assert is_Matrix(M)
oriented = any(M[pos] < 0 for pos in M.nonzero_positions(copy=False))
positions = []
for i in range(M.ncols()):
NZ = M.nonzero_positions_in_column(i)
if len(NZ) == 1:
if oriented:
raise ValueError("column {} of the (oriented) incidence "
"matrix contains only one nonzero value".format(i))
elif M[NZ[0],i] != 2:
raise ValueError("each column of a non-oriented incidence "
"matrix must sum to 2, but column {} does not".format(i))
if loops is None:
loops = True
positions.append((NZ[0], NZ[0]))
elif len(NZ) != 2 or \
(oriented and not ((M[NZ[0], i] == +1 and M[NZ[1], i] == -1) or \
(M[NZ[0], i] == -1 and M[NZ[1], i] == +1))) or \
(not oriented and (M[NZ[0], i] != 1 or M[NZ[1], i] != 1)):
msg = "there must be one or two nonzero entries per column in an incidence matrix, "
msg += "got entries {} in column {}".format([M[j, i] for j in NZ], i)
raise ValueError(msg)
else:
positions.append(tuple(NZ))
if weighted is None: G._weighted = False
if multiedges is None:
total = len(positions)
multiedges = len(set(positions)) < total
G.allow_loops(False if loops is None else loops, check=False)
G.allow_multiple_edges(multiedges, check=False)
G.add_vertices(range(M.nrows()))
G.add_edges(positions)
示例9: from_oriented_incidence_matrix
def from_oriented_incidence_matrix(G, M, loops=False, multiedges=False, weighted=False):
r"""
Fill ``G`` with the data of an *oriented* incidence matrix.
An oriented incidence matrix is the incidence matrix of a directed graph, in
which each non-loop edge corresponds to a `+1` and a `-1`, indicating its
source and destination.
INPUT:
- ``G`` -- a :class:`DiGraph`
- ``M`` -- an incidence matrix
- ``loops``, ``multiedges``, ``weighted`` -- booleans (default: ``False``);
whether to consider the graph as having loops, multiple edges, or weights
EXAMPLES::
sage: from sage.graphs.graph_input import from_oriented_incidence_matrix
sage: g = DiGraph()
sage: from_oriented_incidence_matrix(g, digraphs.Circuit(10).incidence_matrix())
sage: g.is_isomorphic(digraphs.Circuit(10))
True
TESTS:
Fix bug reported in :trac:`22985`::
sage: DiGraph(matrix ([[1,0,0,1],[0,0,1,1],[0,0,1,1]]).transpose())
Traceback (most recent call last):
...
ValueError: each column represents an edge: -1 goes to 1
"""
from sage.structure.element import is_Matrix
assert is_Matrix(M)
positions = []
for c in M.columns():
NZ = c.nonzero_positions()
if len(NZ) != 2:
raise ValueError("there must be two nonzero entries (-1 & 1) per column")
L = sorted(set(c.list()))
if L != [-1, 0, 1]:
raise ValueError("each column represents an edge: -1 goes to 1")
if c[NZ[0]] == -1:
positions.append(tuple(NZ))
else:
positions.append((NZ[1], NZ[0]))
if weighted is None: weighted = False
if multiedges is None:
total = len(positions)
multiedges = len(set(positions)) < total
G.allow_loops(True if loops else False, check=False)
G.allow_multiple_edges(multiedges, check=False)
G.add_vertices(range(M.nrows()))
G.add_edges(positions)
示例10: from_seidel_adjacency_matrix
def from_seidel_adjacency_matrix(G, M):
r"""
Fill ``G`` with the data of a Seidel adjacency matrix.
INPUT:
- ``G`` -- a graph
- ``M`` -- a Seidel adjacency matrix
EXAMPLES::
sage: from sage.graphs.graph_input import from_seidel_adjacency_matrix
sage: g = Graph()
sage: from_seidel_adjacency_matrix(g, graphs.PetersenGraph().seidel_adjacency_matrix())
sage: g.is_isomorphic(graphs.PetersenGraph())
True
"""
from sage.structure.element import is_Matrix
from sage.rings.integer_ring import ZZ
assert is_Matrix(M)
if M.base_ring() != ZZ:
try:
M = M.change_ring(ZZ)
except TypeError:
raise ValueError("the adjacency matrix of a Seidel graph must" +
" have only 0,1,-1 integer entries")
if M.is_sparse():
entries = set(M[i,j] for i,j in M.nonzero_positions())
else:
entries = set(M.list())
if any(e < -1 or e > 1 for e in entries):
raise ValueError("the adjacency matrix of a Seidel graph must" +
" have only 0,1,-1 integer entries")
if any(i == j for i, j in M.nonzero_positions()):
raise ValueError("the adjacency matrix of a Seidel graph must" +
" have 0s on the main diagonal")
if not M.is_symmetric():
raise ValueError("the adjacency matrix of a Seidel graph must be symmetric")
G.add_vertices(range(M.nrows()))
G.add_edges((i, j) for i, j in M.nonzero_positions() if i <= j and M[i,j] < 0)
示例11: __contains__
def __contains__(self, x):
r"""
Tests if ``x`` is an element of ``self``.
INPUT:
- ``x`` -- matrix
EXAMPLES::
sage: from sage.combinat.integer_matrices import IntegerMatrices
sage: IM = IntegerMatrices([4], [1,2,1])
sage: matrix([[1, 2, 1]]) in IM
True
sage: matrix(QQ, [[1, 2, 1]]) in IM
True
sage: matrix([[2, 1, 1]]) in IM
False
TESTS::
sage: from sage.combinat.integer_matrices import IntegerMatrices
sage: IM = IntegerMatrices([4], [1,2,1])
sage: [1, 2, 1] in IM
False
sage: matrix([[-1, 3, 1]]) in IM
False
"""
from sage.structure.element import is_Matrix
if not is_Matrix(x):
return False
row_sums = [ZZ.zero()] * x.nrows()
col_sums = [ZZ.zero()] * x.ncols()
for i in range(x.nrows()):
for j in range(x.ncols()):
x_ij = x[i, j]
if x_ij not in ZZ or x_ij < 0:
return False
row_sums[i] += x_ij
col_sums[j] += x_ij
if row_sums[i] != self._row_sums[i]:
return False
if col_sums != self._col_sums:
return False
return True
示例12: __rmul__
def __rmul__(self,matrix):
r"""
EXAMPLES::
sage: from flatsurf import *
sage: s=translation_surfaces.infinite_staircase()
sage: s.underlying_surface()
The infinite staircase
sage: m=Matrix([[1,2],[0,1]])
sage: s2=m*s
sage: TestSuite(s2).run(skip='_test_pickling')
sage: s2.polygon(0)
Polygon: (0, 0), (1, 0), (3, 1), (2, 1)
"""
if not is_Matrix(matrix):
raise NotImplementedError("Only implemented for matrices.")
if not matrix.dimensions!=(2,2):
raise NotImplementedError("Only implemented for 2x2 matrices.")
return self.__class__(GL2RImageSurface(self,matrix)).copy()
示例13: jacobian
def jacobian(functions, variables):
"""
Return the Jacobian matrix, which is the matrix of partial
derivatives in which the i,j entry of the Jacobian matrix is the
partial derivative diff(functions[i], variables[j]).
EXAMPLES::
sage: x,y = var('x,y')
sage: g=x^2-2*x*y
sage: jacobian(g, (x,y))
[2*x - 2*y -2*x]
The Jacobian of the Jacobian should give us the "second derivative", which is the Hessian matrix::
sage: jacobian(jacobian(g, (x,y)), (x,y))
[ 2 -2]
[-2 0]
sage: g.hessian()
[ 2 -2]
[-2 0]
sage: f=(x^3*sin(y), cos(x)*sin(y), exp(x))
sage: jacobian(f, (x,y))
[ 3*x^2*sin(y) x^3*cos(y)]
[-sin(x)*sin(y) cos(x)*cos(y)]
[ e^x 0]
sage: jacobian(f, (y,x))
[ x^3*cos(y) 3*x^2*sin(y)]
[ cos(x)*cos(y) -sin(x)*sin(y)]
[ 0 e^x]
"""
if is_Matrix(functions) and (functions.nrows()==1 or functions.ncols()==1):
functions = functions.list()
elif not (isinstance(functions, (tuple, list)) or is_Vector(functions)):
functions = [functions]
if not isinstance(variables, (tuple, list)) and not is_Vector(variables):
variables = [variables]
return matrix([[diff(f, v) for v in variables] for f in functions])
示例14: is_generalized_cartan_matrix
def is_generalized_cartan_matrix(M):
"""
Return ``True`` if ``M`` is a generalized Cartan matrix. For a definition
of a generalized Cartan matrix, see :class:`CartanMatrix`.
EXAMPLES::
sage: from sage.combinat.root_system.cartan_matrix import is_generalized_cartan_matrix
sage: M = matrix([[2,-1,-2], [-1,2,-1], [-2,-1,2]])
sage: is_generalized_cartan_matrix(M)
True
sage: M = matrix([[2,-1,-2], [-1,2,-1], [0,-1,2]])
sage: is_generalized_cartan_matrix(M)
False
sage: M = matrix([[1,-1,-2], [-1,2,-1], [-2,-1,2]])
sage: is_generalized_cartan_matrix(M)
False
A non-symmetrizable example::
sage: M = matrix([[2,-1,-2], [-1,2,-1], [-1,-1,2]])
sage: is_generalized_cartan_matrix(M)
True
"""
if not is_Matrix(M):
return False
if not M.is_square():
return False
n = M.ncols()
for i in range(n):
if M[i,i] != 2:
return False
for j in range(i+1, n):
if M[i,j] > 0 or M[j,i] > 0:
return False
elif M[i,j] == 0 and M[j,i] != 0:
return False
elif M[j,i] == 0 and M[i,j] != 0:
return False
return True
示例15: is_borcherds_cartan_matrix
def is_borcherds_cartan_matrix(M):
"""
Return ``True`` if ``M`` is an even, integral Borcherds-Cartan matrix.
For a definition of such a matrix, see :class:`CartanMatrix`.
EXAMPLES::
sage: from sage.combinat.root_system.cartan_matrix import is_borcherds_cartan_matrix
sage: M = Matrix([[2,-1],[-1,2]])
sage: is_borcherds_cartan_matrix(M)
True
sage: N = Matrix([[2,-1],[-1,0]])
sage: is_borcherds_cartan_matrix(N)
False
sage: O = Matrix([[2,-1],[-1,-2]])
sage: is_borcherds_cartan_matrix(O)
True
sage: O = Matrix([[2,-1],[-1,-3]])
sage: is_borcherds_cartan_matrix(O)
False
"""
if not is_Matrix(M):
return False
if not M.is_square():
return False
n = M.ncols()
for i in range(n):
if M[i,i] == 0:
return False
if M[i,i] % 2 == 1:
return False
for j in range(i+1, n):
if M[i,j] > 0 or M[j,i] > 0:
return False
elif M[i,j] == 0 and M[j,i] != 0:
return False
elif M[j,i] == 0 and M[i,j] != 0:
return False
return True