Skip to content

Commit

Permalink
Trac #34930: a few pep8 details in modules
Browse files Browse the repository at this point in the history
mostly about spaces

URL: https://trac.sagemath.org/34930
Reported by: chapoton
Ticket author(s): Frédéric Chapoton
Reviewer(s): Matthias Koeppe
  • Loading branch information
Release Manager committed Feb 11, 2023
2 parents f0a7ebb + 705606a commit c898228
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 49 deletions.
43 changes: 21 additions & 22 deletions src/sage/modules/filtered_vector_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@
in Vector space of dimension 3 over Algebraic Field
"""

#*****************************************************************************
# ***************************************************************************
# Copyright (C) 2013 Volker Braun <vbraun.name@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
# https://www.gnu.org/licenses/
# ***************************************************************************

from sage.rings.all import QQ, ZZ, RDF, RR, Integer
from sage.rings.infinity import InfinityRing, infinity, minus_infinity
Expand Down Expand Up @@ -275,7 +275,7 @@ def construct_from_dim_degree(dim, max_degree, base_ring, check):
dim = ZZ(dim)
from sage.matrix.constructor import identity_matrix
generators = identity_matrix(base_ring, dim).columns()
filtration = dict()
filtration = {}
if max_degree is None:
max_degree = infinity
filtration[normalize_degree(max_degree)] = range(dim)
Expand Down Expand Up @@ -314,7 +314,7 @@ def normalize_gen(v):
generators = tuple(sorted(generators))

# normalize filtration data
normalized = dict()
normalized = {}
for deg, gens_deg in filtration.items():
indices = [generators.index(normalize_gen(v)) for v in gens_deg]
normalized[deg] = tuple(indices)
Expand Down Expand Up @@ -373,13 +373,13 @@ def construct_from_generators_indices(generators, filtration, base_ring, check):
v.set_immutable()

# normalize filtration data
normalized = dict()
normalized = {}
for deg, gens in filtration.items():
deg = normalize_degree(deg)
gens = [ZZ(i) for i in gens]
if any(i < 0 or i >= len(generators) for i in gens):
gens = tuple(sorted(ZZ(i) for i in gens))
if gens and (gens[0] < 0 or gens[-1] >= len(generators)):
raise ValueError('generator index out of bounds')
normalized[deg] = tuple(sorted(gens))
normalized[deg] = gens
try:
del normalized[minus_infinity]
except KeyError:
Expand All @@ -389,8 +389,6 @@ def construct_from_generators_indices(generators, filtration, base_ring, check):
return FilteredVectorSpace_class(base_ring, dim, generators, filtration, check=check)




class FilteredVectorSpace_class(FreeModule_ambient_field):

def __init__(self, base_ring, dim, generators, filtration, check=True):
Expand Down Expand Up @@ -734,7 +732,7 @@ def graded(self, d):
Basis matrix:
[1 1]
"""
return self.get_degree(d).quotient(self.get_degree(d+1))
return self.get_degree(d).quotient(self.get_degree(d + 1))

def presentation(self):
"""
Expand All @@ -760,7 +758,7 @@ def presentation(self):
generators.update(V.echelonized_basis())
generators = tuple(sorted(generators))

filtration = dict()
filtration = {}
for d, V in filt:
indices = [ZZ(generators.index(v)) for v in V.echelonized_basis()]
filtration[d] = tuple(indices)
Expand All @@ -770,6 +768,8 @@ def _repr_field_name(self):
"""
Return an abbreviated field name as string
.. NOTE: This should rather be a method of fields and rings.
RAISES:
``NotImplementedError``: The field does not have an
Expand Down Expand Up @@ -1001,15 +1001,15 @@ def direct_sum(self, other):
self_gens, self_filt = self.presentation()
other_gens, other_filt = other.presentation()
generators = \
[ list(v) + [base_ring.zero()]*other.dimension() for v in self_gens ] + \
[ [base_ring.zero()]*self.dimension() + list(v) for v in other_gens ]
[list(v) + [base_ring.zero()] * other.dimension() for v in self_gens] + \
[[base_ring.zero()] * self.dimension() + list(v) for v in other_gens]

# construct the filtration dictionary
def join_indices(self_indices, other_indices):
self_indices = tuple(self_indices)
other_indices = tuple(i + len(self_gens) for i in other_indices)
return self_indices + other_indices
filtration = dict()
filtration = {}
self_indices = set()
other_indices = set()
degrees = list(self_filt) + list(other_filt)
Expand Down Expand Up @@ -1071,7 +1071,7 @@ def tensor_product(self, other):
W_coll = VectorCollection(W_generators, base_ring, W.dimension())
T = TensorOperation([V_coll, W_coll], 'product')

filtration = dict()
filtration = {}
for V_deg in V.support():
for W_deg in W.support():
deg = V_deg + W_deg
Expand Down Expand Up @@ -1112,7 +1112,7 @@ def _power_operation(self, n, operation):
T = TensorOperation([V] * n, operation)

iters = [self.support()] * n
filtration = dict()
filtration = {}
from sage.categories.cartesian_product import cartesian_product
for degrees in cartesian_product(iters):
deg = sum(degrees)
Expand All @@ -1124,7 +1124,6 @@ def _power_operation(self, n, operation):
filtration[deg] = filt_deg
return FilteredVectorSpace(T.vectors(), filtration, base_ring=self.base_ring())


def exterior_power(self, n):
"""
Return the `n`-th graded exterior power.
Expand Down Expand Up @@ -1204,7 +1203,7 @@ def dual(self):
sage: F.dual().support()
(-2, 0)
"""
filtration = dict()
filtration = {}
prev_deg = minus_infinity
for deg, V in self._filt[1:]:
filtration[-prev_deg] = V.complement().echelonized_basis()
Expand All @@ -1226,7 +1225,7 @@ def shift(self, deg):
(-5, -3)
"""
generators, filtration = self.presentation()
shifted = dict()
shifted = {}
for d, indices in filtration.items():
shifted[d + deg] = indices
return FilteredVectorSpace(generators, shifted, base_ring=self.base_ring())
Expand Down Expand Up @@ -1269,7 +1268,7 @@ def random_deformation(self, epsilon=None):
R = self.base_ring()
if epsilon is None:
epsilon = R.one()
filtration = dict()
filtration = {}
for deg, filt in self._filt[1:]:
generators = [v + epsilon * random_vector(R, self.rank())
for v in filt.echelonized_basis()]
Expand Down
6 changes: 3 additions & 3 deletions src/sage/modules/free_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -4611,7 +4611,7 @@ def span_of_basis(self, basis, base_ring=None, check=True, already_echelonized=F
M = self.change_ring(base_ring)
except TypeError:
raise ValueError("Argument base_ring (= %s) is not compatible with the base field (= %s)." % (
base_ring, self.base_field() ))
base_ring, self.base_field()))
try:
return M.span_of_basis(basis)
except TypeError:
Expand Down Expand Up @@ -5653,7 +5653,7 @@ def basis(self):
"""
try:
return self.__basis
except AttributeError:
except AttributeError:
ZERO = self(0)
one = self.coordinate_ring().one()
w = []
Expand Down Expand Up @@ -6600,7 +6600,7 @@ def _echelon_matrix_richcmp(self, other, op):
lx = self.ambient_vector_space()
rx = other.ambient_vector_space()
if lx != rx:
return lx._echelon_matrix_richcmp( rx, op)
return lx._echelon_matrix_richcmp(rx, op)

lx = self.dimension()
rx = other.dimension()
Expand Down
5 changes: 3 additions & 2 deletions src/sage/modules/free_quadratic_module_integer_symmetric.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def IntegralLatticeDirectSum(Lattices, return_embeddings=False):
basis = [matrix.block(1, 3, [matrix.zero(dims[i], sum_degree[i]),
Lattices[i].basis_matrix(),
matrix.zero(dims[i], sum_degree[-1] - sum_degree[i+1])
]) for i in range(N)]
]) for i in range(N)]
basis_matrix = matrix.block(N, 1, basis)
ipm = ambient.inner_product_matrix()
direct_sum = FreeQuadraticModule_integer_symmetric(ambient=ambient,
Expand All @@ -363,6 +363,7 @@ def IntegralLatticeDirectSum(Lattices, return_embeddings=False):
for i in range(N)]
return [direct_sum, phi]


def IntegralLatticeGluing(Lattices, glue, return_embeddings=False):
r"""
Return an overlattice of the direct sum as defined by ``glue``.
Expand Down Expand Up @@ -1092,7 +1093,7 @@ def maximal_overlattice(self, p=None):
for t in D:
if t != 0 and t.q() == 0:
break
if t.q() != 0 :
if t.q() != 0:
# no isotropic vector left
break
L = L.overlattice([t.lift()])
Expand Down
4 changes: 2 additions & 2 deletions src/sage/modules/matrix_morphism.py
Original file line number Diff line number Diff line change
Expand Up @@ -1236,7 +1236,7 @@ def is_identity(self):
# testing for the identity matrix will only work for
# endomorphisms which have the same basis for domain and codomain
# so we test equality on a basis, which is sufficient
return all( self(u) == u for u in self.domain().basis() )
return all(self(u) == u for u in self.domain().basis())

def is_zero(self):
r"""
Expand Down Expand Up @@ -1369,7 +1369,7 @@ def is_equal_function(self, other):
if self.codomain() != other.codomain():
return False
# check agreement on any basis of the domain
return all( self(u) == other(u) for u in self.domain().basis() )
return all(self(u) == other(u) for u in self.domain().basis())

def restrict_domain(self, sub):
"""
Expand Down
11 changes: 5 additions & 6 deletions src/sage/modules/torsion_quadratic_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def _mul_(self, other):
1/4
"""
value_module = self.parent().value_module()
return value_module( self.lift().inner_product(other.lift()) )
return value_module(self.lift().inner_product(other.lift()))

inner_product = _mul_
b = _mul_
Expand Down Expand Up @@ -296,7 +296,6 @@ def __init__(self, V, W, gens, modulus, modulus_qf):
self._modulus = modulus
self._modulus_qf = modulus_qf


def _repr_(self):
r"""
Return a string representation of ``self``.
Expand All @@ -313,10 +312,10 @@ def _repr_(self):
[0 0 0]
[0 0 0]
"""
return ( "Finite quadratic module over %s with invariants %s\n"
% (self.base_ring(), self.invariants()) +
"Gram matrix of the quadratic form with values in %r:\n%r"
% (self.value_module_qf(), self.gram_matrix_quadratic()))
return ("Finite quadratic module over %s with invariants %s\n"
% (self.base_ring(), self.invariants()) +
"Gram matrix of the quadratic form with values in %r:\n%r"
% (self.value_module_qf(), self.gram_matrix_quadratic()))

def _module_constructor(self, V, W, check=False):
r"""
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modules/with_basis/cell_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def _acted_upon_(self, scalar, self_on_left=False):
# Temporary needed by coercion (see Polynomial/FractionField tests).
if not P._algebra.has_coerce_map_from(scalar.parent()):
return None
scalar = P._algebra( scalar )
scalar = P._algebra(scalar)

if self_on_left:
raise NotImplementedError
Expand Down
26 changes: 13 additions & 13 deletions src/sage/modules/with_basis/morphism.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,18 +403,19 @@ def __call__(self, *args):
mc = x.monomial_coefficients(copy=False)
if self._is_module_with_basis_over_same_base_ring:
return self.codomain().linear_combination(
(self._on_basis(*(before+(index,)+after)), coeff )
for (index, coeff) in mc.items())
(self._on_basis(*(before + (index,) + after)), coeff)
for (index, coeff) in mc.items())
else:
return sum((coeff * self._on_basis(*(before+(index,)+after))
for (index, coeff) in mc.items()), self._zero)
return sum((coeff * self._on_basis(*(before + (index,) + after))
for (index, coeff) in mc.items()), self._zero)

# As per the specs of Map, we should in fact implement _call_.
# However we currently need to abuse Map.__call__ (which strict
# type checking) for multi-parameter module morphisms
# To be cleaned up
_call_ = __call__


class TriangularModuleMorphism(ModuleMorphism):
r"""
An abstract class for triangular module morphisms
Expand Down Expand Up @@ -683,10 +684,9 @@ def __init__(self, triangular="upper", unitriangular=False,
self._inverse = inverse

if inverse_on_support == "compute":
inverse_on_support = {
self._dominant_item(on_basis(i))[0] : i
for i in self.domain().basis().keys()
}.get
inverse_on_support = {self._dominant_item(on_basis(i))[0]: i
for i in self.domain().basis().keys()
}.get

self._inverse_on_support = inverse_on_support

Expand Down Expand Up @@ -883,7 +883,7 @@ def _invert_on_basis(self, i):
sage: phi._invert_on_basis(2)
B[2] - B[3]
"""
return self.preimage( self.codomain().monomial(i) )
return self.preimage(self.codomain().monomial(i))

def preimage(self, f):
r"""
Expand Down Expand Up @@ -1351,13 +1351,13 @@ def __init__(self, domain, matrix, codomain=None, category=None, side="left"):
matrix = matrix.transpose()
if matrix.nrows() != len(indices):
raise ValueError("The dimension of the matrix (%s) does not match with the dimension of the domain (%s)"
%(matrix.nrows(), len(indices)))
% (matrix.nrows(), len(indices)))
if matrix.ncols() != codomain.dimension():
raise ValueError("The dimension of the matrix (%s) does not match with the dimension of the codomain (%s)"
%(matrix.ncols(), codomain.dimension()))
% (matrix.ncols(), codomain.dimension()))
self._matrix = matrix
d = { xt: codomain.from_vector(matrix.row(rank_domain(xt)))
for xt in domain.basis().keys() }
d = {xt: codomain.from_vector(matrix.row(rank_domain(xt)))
for xt in domain.basis().keys()}

ModuleMorphismByLinearity.__init__(self, on_basis=d.__getitem__,
domain=domain, codomain=codomain,
Expand Down

0 comments on commit c898228

Please sign in to comment.