本文整理汇总了Python中sage.modules.free_module.VectorSpace类的典型用法代码示例。如果您正苦于以下问题:Python VectorSpace类的具体用法?Python VectorSpace怎么用?Python VectorSpace使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VectorSpace类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ProjectiveGeometryDesign
def ProjectiveGeometryDesign(n, d, F, algorithm=None):
"""
Returns a projective geometry design.
A projective geometry design of parameters `n,d,F` has for points the lines
of `F^{n+1}`, and for blocks the `d+1`-dimensional subspaces of `F^{n+1}`,
each of which contains `\\frac {|F|^{d+1}-1} {|F|-1}` lines.
INPUT:
- ``n`` is the projective dimension
- ``d`` is the dimension of the subspaces of `P = PPn(F)` which
make up the blocks.
- ``F`` is a finite field.
- ``algorithm`` -- set to ``None`` by default, which results in using Sage's
own implementation. In order to use GAP's implementation instead (i.e. its
``PGPointFlatBlockDesign`` function) set ``algorithm="gap"``. Note that
GAP's "design" package must be available in this case, and that it can be
installed with the ``gap_packages`` spkg.
EXAMPLES:
The points of the following design are the `\\frac {2^{2+1}-1} {2-1}=7`
lines of `\mathbb{Z}_2^{2+1}`. It has `7` blocks, corresponding to each
2-dimensional subspace of `\mathbb{Z}_2^{2+1}`::
sage: designs.ProjectiveGeometryDesign(2, 1, GF(2))
Incidence structure with 7 points and 7 blocks
sage: BD = designs.ProjectiveGeometryDesign(2, 1, GF(2), algorithm="gap") # optional - gap_packages (design package)
sage: BD.is_block_design() # optional - gap_packages (design package)
(True, [2, 7, 3, 1])
"""
q = F.order()
from sage.interfaces.gap import gap, GapElement
from sage.sets.set import Set
if algorithm is None:
V = VectorSpace(F, n+1)
points = list(V.subspaces(1))
flats = list(V.subspaces(d+1))
blcks = []
for p in points:
b = []
for i in range(len(flats)):
if p.is_subspace(flats[i]):
b.append(i)
blcks.append(b)
v = (q**(n+1)-1)/(q-1)
return BlockDesign(v, blcks, name="ProjectiveGeometryDesign")
if algorithm == "gap": # Requires GAP's Design
gap.load_package("design")
gap.eval("D := PGPointFlatBlockDesign( %s, %s, %d )"%(n,q,d))
v = eval(gap.eval("D.v"))
gblcks = eval(gap.eval("D.blocks"))
gB = []
for b in gblcks:
gB.append([x-1 for x in b])
return BlockDesign(v, gB, name="ProjectiveGeometryDesign")
示例2: __init__
def __init__(self, surface, label, point, ring = None, limit=None):
self._s = surface
if ring is None:
self._ring = surface.base_ring()
else:
self._ring = ring
p = surface.polygon(label)
point = VectorSpace(self._ring,2)(point)
point.set_immutable()
pos = p.get_point_position(point)
assert pos.is_inside(), \
"Point must be positioned within the polygon with the given label."
# This is the correct thing if point lies in the interior of the polygon with the given label.
self._coordinate_dict = {label: {point}}
if pos.is_in_edge_interior():
label2,e2 = surface.opposite_edge(label, pos.get_edge())
point2 = surface.edge_transformation(label, pos.get_edge())(point)
point2.set_immutable()
if label2 in self._coordinate_dict:
self._coordinate_dict[label2].add(point2)
else:
self._coordinate_dict[label2]={point2}
if pos.is_vertex():
self._coordinate_dict = {}
sing = surface.singularity(label, pos.get_vertex(), limit=limit)
for l,v in sing.vertex_set():
new_point = surface.polygon(l).vertex(v)
new_point.set_immutable()
if l in self._coordinate_dict:
self._coordinate_dict[l].add(new_point)
else:
self._coordinate_dict[l] = {new_point}
# Freeze the sets.
for label,point_set in self._coordinate_dict.iteritems():
self._coordinate_dict[label] = frozenset(point_set)
示例3: nonisomorphic_cubes_Z2
def nonisomorphic_cubes_Z2(n, avoid_complete=False):
"""
Returns a generator for all n-dimensional Cube-like graphs
(Cayley graphs over Z_2^n) with their generators.
With avoid_complete=True avoids the complete graph.
Iterates over tuples (generatorSet, G).
"""
vs = VectorSpace(GF(2), n)
basegens = vs.gens()
optgens = [v for v in vs if sum(map(int,v)) >= 2]
total = 2**len(optgens)
seen_graphs = set()
c = 0
for g in powerset(optgens):
c += 1
gens = tuple(list(basegens) + g)
if c % (total / 100 + 1) == 0:
log.debug("Generating (%d of %d)" % (c, total))
if avoid_complete:
if len(g) >= len(optgens):
continue
G = CayleyGraph(vs, gens)
canon = tuple(Graph(G).canonical_label().edges())
if canon in seen_graphs:
continue
log.debug("Unique graph (%d of %d) gens=%s" % (c, total, gens))
seen_graphs.add(canon)
yield (gens, G)
示例4: _complex_relative
def _complex_relative(self,n,*args):
if len(args)==2:
complex = []
for i in range(args[0],args[1]):
complex.append(self._complex_relative(n,i))
return complex
if n<0 or n>self.poly_ring.ngens():
return []
if n==0:
hom_basis = self._p_graded_module(n).homogeneous_part_basis(self.degree+args[0])
return [LogarithmicDifferentialForm(n,b,self) for b in hom_basis]
base = self._p_graded_module(n).homogeneous_part_basis(self.degree+args[0])
if len(base)==0:
return []
vs_base = VectorSpace(QQ,len(base))
df_base = [LogarithmicDifferentialForm(n,b,self) for b in base]
pre_base = self._p_graded_module(n-1).homogeneous_part_basis(self.degree+args[0])
if len(pre_base)==0:
return df_base
dh = [self.divisor.derivative(g) for g in self.poly_ring.gens()]
dh = LogarithmicDifferentialForm(1,dh,self)
rel_gens = []
for b in pre_base:
b_form = LogarithmicDifferentialForm(n-1,b,self)
w = dh.wedge(b_form)
rel_gens.append(lift_to_basis([w],df_base))
rel = vs_base.subspace(rel_gens)
comp = orth_complement(vs_base,rel)
#Lift
rel_complex = []
for vec in comp.basis():
rel_complex.append(_weighted_sum(vec,df_base,self))
return rel_complex
示例5: homology
def homology(self,varient="complement",*args):
hom = {}
cc = self.chain_complex(varient,(-1,self.poly_ring.ngens()+1),*args)
#Some need wider return range
for i in range(self.poly_ring.ngens()+1):
vs_am = VectorSpace(QQ,len(cc[i]))
if len(cc[i])==0:
hom[i] = []
continue
if len(cc[i-1])!=0:
d_im = []
for b in cc[i-1]:
d_b = self.differential(b,varient,*args)
d_im.append(lift_to_basis(d_b,cc[i]))
img = vs_am.subspace(d_im)
else:
img = vs_am.subspace([vs_am.zero()])
if len(cc[i+1])!=0:
d_ker = []
for b in cc[i]:
d_b = self.differential(b,varient,*args)
d_ker.append(lift_to_basis(d_b,cc[i+1]))
ker = (matrix(QQ,d_ker)).left_kernel()
else:
ker = vs_am
quo = ker.quotient(img)
hom[i] = []
for b in quo.basis():
vec = quo.lift(b)
part_sum = LogarithmicDifferentialForm.make_zero(i,self)
for c,f in zip(vec,cc[i]):
part_sum = part_sum + c*f
hom[i].append(part_sum)
return hom
示例6: test_satisfy_inter
def test_satisfy_inter(self):
v_space = VectorSpace(QQ,4)
sub = v_space.subspace([[1,-1,1,1],[2,-3,4,5]])
comp = orth_complement(v_space,sub)
zero = v_space.subspace([v_space.zero()])
inter = sub.intersection(comp)
self.assertEqual(zero,inter)
示例7: ProjectiveGeometryDesign
def ProjectiveGeometryDesign(n, d, F, algorithm=None):
"""
INPUT:
- ``n`` is the projective dimension
- ``v`` is the number of points `PPn(GF(q))`
- ``d`` is the dimension of the subspaces of `P = PPn(GF(q))` which
make up the blocks
- ``b`` is the number of `d`-dimensional subspaces of `P`
Wraps GAP Design's PGPointFlatBlockDesign. Does *not* require
GAP's Design.
EXAMPLES::
sage: designs.ProjectiveGeometryDesign(2, 1, GF(2))
Incidence structure with 7 points and 7 blocks
sage: BD = designs.ProjectiveGeometryDesign(2, 1, GF(2), algorithm="gap") # optional - gap_packages (design package)
sage: BD.is_block_design() # optional - gap_packages (design package)
(True, [2, 7, 3, 1])
"""
q = F.order()
from sage.interfaces.gap import gap, GapElement
from sage.sets.set import Set
if algorithm == None:
V = VectorSpace(F, n+1)
points = list(V.subspaces(1))
flats = list(V.subspaces(d+1))
blcks = []
for p in points:
b = []
for i in range(len(flats)):
if p.is_subspace(flats[i]):
b.append(i)
blcks.append(b)
v = (q**(n+1)-1)/(q-1)
return BlockDesign(v, blcks, name="ProjectiveGeometryDesign")
if algorithm == "gap": # Requires GAP's Design
gap.load_package("design")
gap.eval("D := PGPointFlatBlockDesign( %s, %s, %d )"%(n,q,d))
v = eval(gap.eval("D.v"))
gblcks = eval(gap.eval("D.blocks"))
gB = []
for b in gblcks:
gB.append([x-1 for x in b])
return BlockDesign(v, gB, name="ProjectiveGeometryDesign")
示例8: _differential_relative
def _differential_relative(self,form,*args):
n = form.degree
deg = self._p_graded_module(n).total_degree(form.vec)
deg -= self.degree
der = form.derivative()
full = self._p_graded_module(n+1).homogeneous_part_basis(self.degree+deg)
full_forms = [LogarithmicDifferentialForm(n+1,b,self) for b in full]
full_space = VectorSpace(QQ,len(full))
target_comp = self._complex_relative(n+1,deg)
comp_vecs = []
for b in target_comp:
comp_vecs.append(lift_to_basis([b],full_forms))
comp_vecs = full_space.subspace(comp_vecs)
lift_full = lift_to_basis([der],full_forms)
lift_prog = comp_vecs.basis_matrix()*vector(lift_full)
return [_weighted_sum(lift_prog,target_comp,self)]
示例9: __init__
def __init__(self, base_field):
self._f=base_field
# The vector space of vectors
self._vs = VectorSpace(self._f,2)
Group.__init__(self, category=Groups().Infinite())
示例10: SimilarityGroup
class SimilarityGroup(UniqueRepresentation,Group):
r'''Group representing all similarities in the plane.
This is the group generated by rotations, translations and dilations.
'''
Element = Similarity
def _element_constructor_(self, *args, **kwds):
if len(args)!=1:
return self.element_class(self, *args, **kwds)
x = args[0]
p=parent(x)
if self._f.has_coerce_map_from(p):
return self.element_class( self,self._f(x), self._f.zero(), self._f.zero(), self._f.zero())
if isinstance(p, SimilarityGroup):
return self.element_class(self, x.a(), x.b(), x.s(), x.t())
if isinstance(p, TranslationGroup):
return self.element_class( self,self._f.one(), self._f.zero(), x.s(), x.t() )
return self.element_class(self, x, **kwds)
def _coerce_map_from_(self, S):
if self._f.has_coerce_map_from(S):
return True
if isinstance(S, SimilarityGroup):
return self._f.has_coerce_map_from(S._f)
if isinstance(S, TranslationGroup):
return self._f.has_coerce_map_from(S.base_field())
def __init__(self, base_field):
self._f=base_field
# The vector space of vectors
self._vs = VectorSpace(self._f,2)
Group.__init__(self, category=Groups().Infinite())
def _repr_(self):
return "SimilarityGroup over field "+str(self._f)
def one(self):
return self.element_class(self,self._f.one(),self._f.zero(),self._f.zero(),self._f.zero())
def an_element(self):
return self.element_class(self,self._f(ZZ_3),self._f(ZZ_4),self._f(ZZ_2),self._f(-ZZ_1))
def is_abelian(self):
return False
def gens(self):
pairs=[
(self._f.one(),self._f.zero()),
(self._f(ZZ_2),self._f.zero()),
(self._f.zero(),self._f(ZZ_2)),
(self._f(ZZ_3),self._f(ZZ_4))]
l=[]
for p in pairs:
for v in self._vs.gens():
l.append(self.element_class(self,p[0],p[1],v[0],v[1]))
return l
# For pickling:
#def __reduce__(self):
# return self.__class__, (self._f,)
#def _cmp_(self, other):
# return self._f == other._f
#__cmp__=_cmp_
def base_field(self):
return self._f
示例11: linear_transformation
#.........这里部分代码省略.........
A Sage symbolic function can come in a variety of forms that are
not representative of a linear transformation. ::
sage: x, y = var('x, y')
sage: f(x, y) = [y, x, y]
sage: linear_transformation(QQ^3, QQ^3, f)
Traceback (most recent call last):
...
ValueError: symbolic function has the wrong number of inputs for domain
sage: linear_transformation(QQ^2, QQ^2, f)
Traceback (most recent call last):
...
ValueError: symbolic function has the wrong number of outputs for codomain
sage: x, y = var('x y')
sage: f(x, y) = [y, x*y]
sage: linear_transformation(QQ^2, QQ^2, f)
Traceback (most recent call last):
...
ValueError: symbolic function must be linear in all the inputs:
unable to convert y to a rational
sage: x, y = var('x y')
sage: f(x, y) = [x, 2*y]
sage: C = (QQ^2).span([vector(QQ, [1, 1])])
sage: linear_transformation(QQ^2, C, f)
Traceback (most recent call last):
...
ArithmeticError: some image of the function is not in the codomain, because
element [1, 0] is not in free module
"""
from sage.matrix.constructor import matrix
from sage.modules.module import is_VectorSpace
from sage.modules.free_module import VectorSpace
from sage.categories.homset import Hom
from sage.symbolic.ring import SymbolicRing
from sage.modules.vector_callable_symbolic_dense import Vector_callable_symbolic_dense
from inspect import isfunction
if not side in ['left', 'right']:
raise ValueError("side must be 'left' or 'right', not {0}".format(side))
if not (is_Matrix(arg0) or is_VectorSpace(arg0)):
raise TypeError('first argument must be a matrix or a vector space, not {0}'.format(arg0))
if is_Matrix(arg0):
R = arg0.base_ring()
if not R.is_field():
try:
R = R.fraction_field()
except (NotImplementedError, TypeError):
msg = 'matrix must have entries from a field, or a ring with a fraction field, not {0}'
raise TypeError(msg.format(R))
if side == 'right':
arg0 = arg0.transpose()
side = 'left'
arg2 = arg0
arg0 = VectorSpace(R, arg2.nrows())
arg1 = VectorSpace(R, arg2.ncols())
elif is_VectorSpace(arg0):
if not is_VectorSpace(arg1):
msg = 'if first argument is a vector space, then second argument must be a vector space, not {0}'
raise TypeError(msg.format(arg1))
if arg0.base_ring() != arg1.base_ring():
msg = 'vector spaces must have the same field of scalars, not {0} and {1}'
raise TypeError(msg.format(arg0.base_ring(), arg1.base_ring()))
示例12: test_comp
def test_comp(self):
v_space = VectorSpace(QQ,4)
sub = v_space.subspace([[1,1,1,1],[2,2,-3,-1]])
comp = orth_complement(v_space,sub)
true_comp = v_space.subspace([[19,-17,3,-5],[1,-1,0,0]])
self.assertEqual(comp,true_comp)
示例13: mcfarland_1973_construction
def mcfarland_1973_construction(q, s):
r"""
Return a difference set.
The difference set returned has the following parameters
.. MATH::
v = \frac{q^{s+1}(q^{s+1}+q-2)}{q-1},
k = \frac{q^s (q^{s+1}-1)}{q-1},
\lambda = \frac{q^s(q^s-1)}{q-1}
This construction is due to [McF1973]_.
INPUT:
- ``q``, ``s`` - (integers) parameters for the difference set (see the above
formulas for the expression of ``v``, ``k``, ``l`` in terms of ``q`` and
``s``)
.. SEEALSO::
The function :func:`are_mcfarland_1973_parameters` makes the translation
between the parameters `(q,s)` corresponding to a given triple
`(v,k,\lambda)`.
REFERENCES:
.. [McF1973] Robert L. McFarland
"A family of difference sets in non-cyclic groups"
Journal of Combinatorial Theory (A) vol 15 (1973).
http://dx.doi.org/10.1016/0097-3165(73)90031-9
EXAMPLES::
sage: from sage.combinat.designs.difference_family import (
....: mcfarland_1973_construction, is_difference_family)
sage: G,D = mcfarland_1973_construction(3, 1)
sage: assert is_difference_family(G, D, 45, 12, 3)
sage: G,D = mcfarland_1973_construction(2, 2)
sage: assert is_difference_family(G, D, 64, 28, 12)
"""
from sage.rings.finite_rings.finite_field_constructor import GF
from sage.modules.free_module import VectorSpace
from sage.rings.finite_rings.integer_mod_ring import Zmod
from sage.categories.cartesian_product import cartesian_product
from itertools import izip
r = (q**(s+1)-1) // (q-1)
F = GF(q,'a')
V = VectorSpace(F, s+1)
K = Zmod(r+1)
G = cartesian_product([F]*(s+1) + [K])
D = []
for k,H in izip(K, V.subspaces(s)):
for v in H:
D.append(G((tuple(v) + (k,))))
return G,[D]
示例14: test_satisfy_sum
def test_satisfy_sum(self):
v_space = VectorSpace(QQ,4)
sub = v_space.subspace([[1,1,1,-1],[2,-3,41,5]])
comp = orth_complement(v_space,sub)
self.assertEqual(v_space,sub+comp)
示例15: algebraic_topological_model
#.........这里部分代码省略.........
# vector}, where idx is the index of an n-cell in the list of
# n-cells in K, and vector is the image of that n-cell, as an
# element in the free module of (n+1)-chains for K.
phi_dict = {}
# For each n, pi_dict[n] is a dictionary of the same form, except
# that the target vectors should be elements of the chain complex M.
pi_dict = {}
# For each n, iota_dict[n] is a dictionary of the form {cell:
# vector}, where cell is one of the generators for M and vector is
# its image in C, as an element in the free module of n-chains.
iota_dict = {}
for n in range(K.dimension()+1):
gens[n] = []
phi_dict[n] = {}
pi_dict[n] = {}
iota_dict[n] = {}
C = K.chain_complex(base_ring=base_ring)
# old_cells: cells one dimension lower.
old_cells = []
for dim in range(K.dimension()+1):
n_cells = K.n_cells(dim)
diff = C.differential(dim)
# diff is sparse and low density. Dense matrices are faster
# over finite fields, but for low density matrices, sparse
# matrices are faster over the rationals.
if base_ring != QQ:
diff = diff.dense_matrix()
rank = len(n_cells)
old_rank = len(old_cells)
V_old = VectorSpace(base_ring, old_rank)
zero = V_old.zero_vector()
for c_idx, c in enumerate(zip(n_cells, VectorSpace(base_ring, rank).gens())):
# c is the pair (cell, the corresponding standard basis
# vector in the free module of chains). Separate its
# components, calling them c and c_vec:
c_vec = c[1]
c = c[0]
# No need to set zero values for any of the maps: we will
# assume any unset values are zero.
# From the paper: phi_dict[c] = 0.
# c_bar = c - phi(bdry(c))
c_bar = c_vec
bdry_c = diff * c_vec
# Apply phi to bdry_c and subtract from c_bar.
for (idx, coord) in bdry_c.iteritems():
try:
c_bar -= coord * phi_dict[dim-1][idx]
except KeyError:
pass
bdry_c_bar = diff * c_bar
# Evaluate pi(bdry(c_bar)).
pi_bdry_c_bar = zero
for (idx, coeff) in bdry_c_bar.iteritems():
try:
pi_bdry_c_bar += coeff * pi_dict[dim-1][idx]
except KeyError:
pass