From c6a2f0736cc8e82eb07b09827a54317b9c0553e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 6 Jul 2023 12:17:23 +0200 Subject: [PATCH 1/3] some pep8 fixes in homology/ --- .../homology/algebraic_topological_model.py | 8 ++-- src/sage/homology/cell_complex.py | 2 +- src/sage/homology/chain_complex.py | 41 +++++++++--------- src/sage/homology/chain_complex_homspace.py | 4 +- src/sage/homology/chain_complex_morphism.py | 42 +++++++++---------- src/sage/homology/chain_homotopy.py | 1 + src/sage/homology/chains.py | 16 +++---- src/sage/homology/cubical_complex.py | 6 +-- src/sage/homology/delta_complex.py | 6 +-- src/sage/homology/graded_resolution.py | 10 ++--- src/sage/homology/hochschild_complex.py | 17 ++++---- src/sage/homology/homology_group.py | 3 +- src/sage/homology/homology_morphism.py | 16 +++---- .../homology_vector_space_with_basis.py | 10 +++-- src/sage/homology/koszul_complex.py | 10 ++--- src/sage/homology/matrix_utils.py | 16 +++---- .../homology/simplicial_complex_homset.py | 4 +- .../homology/simplicial_complex_morphism.py | 4 +- src/sage/homology/simplicial_set_morphism.py | 4 +- src/sage/homology/tests.py | 7 +++- 20 files changed, 118 insertions(+), 109 deletions(-) diff --git a/src/sage/homology/algebraic_topological_model.py b/src/sage/homology/algebraic_topological_model.py index aa539d90126..e198a14d7fe 100644 --- a/src/sage/homology/algebraic_topological_model.py +++ b/src/sage/homology/algebraic_topological_model.py @@ -33,6 +33,7 @@ from .chain_homotopy import ChainContraction from sage.rings.rational_field import QQ + def algebraic_topological_model(K, base_ring=None): r""" Algebraic topological model for cell complex ``K`` @@ -336,6 +337,7 @@ def algebraic_topological_model(K, base_ring=None): phi = ChainContraction(phi_data, pi, iota) return phi, M + def algebraic_topological_model_delta_complex(K, base_ring=None): r""" Algebraic topological model for cell complex ``K`` @@ -486,7 +488,7 @@ def conditionally_sparse(m): iota_cols = {} pi_cols_old = pi_cols pi_cols = [] - phi_old = MatrixSpace(base_ring, rank, old_rank, sparse=(base_ring==QQ)).zero() + phi_old = MatrixSpace(base_ring, rank, old_rank, sparse=(base_ring == QQ)).zero() phi_old_cols = phi_old.columns() phi_old = conditionally_sparse(phi_old) to_be_deleted = [] @@ -543,8 +545,8 @@ def conditionally_sparse(m): # The matrices involved have many zero entries. For # such matrices, using sparse matrices is faster over # the rationals, slower over finite fields. - phi_old = matrix(base_ring, phi_old_cols, sparse=(base_ring==QQ)).transpose() - keep = vector(base_ring, pi_nrows, {i:1 for i in range(pi_nrows) + phi_old = matrix(base_ring, phi_old_cols, sparse=(base_ring == QQ)).transpose() + keep = vector(base_ring, pi_nrows, {i: 1 for i in range(pi_nrows) if i not in to_be_deleted}) cols = [v.pairwise_product(keep) for v in pi_cols_old] pi_old = MS_pi_t.matrix(cols).transpose() diff --git a/src/sage/homology/cell_complex.py b/src/sage/homology/cell_complex.py index 23292d902e3..df3dcba6552 100644 --- a/src/sage/homology/cell_complex.py +++ b/src/sage/homology/cell_complex.py @@ -9,4 +9,4 @@ import sage.topology.cell_complex GenericCellComplex = deprecated_function_alias(31925, - sage.topology.cell_complex.GenericCellComplex) + sage.topology.cell_complex.GenericCellComplex) diff --git a/src/sage/homology/chain_complex.py b/src/sage/homology/chain_complex.py index 6b318dce6ee..f6409c5ae4b 100644 --- a/src/sage/homology/chain_complex.py +++ b/src/sage/homology/chain_complex.py @@ -64,6 +64,7 @@ from sage.misc.superseded import deprecation from sage.rings.fast_arith import prime_range from sage.homology.homology_group import HomologyGroup +from sage.misc.persist import register_unpickle_override def _latex_module(R, m): @@ -248,7 +249,7 @@ def ChainComplex(data=None, base_ring=None, grading_group=None, data_dict = {} elif isinstance(data, dict): # data is dictionary data_dict = data - else: # data is list/tuple/iterable + else: # data is list/tuple/iterable data_matrices = [x for x in data if isinstance(x, Matrix)] if degree != 1: raise ValueError('degree must be +1 if the data argument is a list or tuple') @@ -667,8 +668,8 @@ def __init__(self, grading_group, degree_of_differential, base_ring, differentia sage: TestSuite(C).run() """ if any(d.base_ring() != base_ring or not d.is_immutable() or - (d.ncols(), d.nrows()) == (0, 0) - for d in differentials.values()): + (d.ncols(), d.nrows()) == (0, 0) + for d in differentials.values()): raise ValueError('invalid differentials') if degree_of_differential.parent() is not grading_group: raise ValueError('the degree_of_differential.parent() must be grading_group') @@ -1349,15 +1350,15 @@ def change_ring(X): d_out_nullity = d_out.ncols() - d_out_rank if d_in.is_zero(): - if generators: #Include the generators of the nullspace - return [(HomologyGroup(1, base_ring), self({deg:gen})) + if generators: # Include the generators of the nullspace + return [(HomologyGroup(1, base_ring), self({deg: gen})) for gen in d_out.right_kernel().basis()] else: return HomologyGroup(d_out_nullity, base_ring) if generators: orders, gens = self._homology_generators_snf(d_in, d_out, d_out_rank) - answer = [(HomologyGroup(1, base_ring, [order]), self({deg:gen})) + answer = [(HomologyGroup(1, base_ring, [order]), self({deg: gen})) for order, gen in zip(orders, gens)] else: if base_ring.is_field(): @@ -1552,7 +1553,7 @@ def torsion_list(self, max_prime, min_prime=2): for i in diff_dict: if diff_dict[i] != 0: differences.append(i) - answer.append((p,differences)) + answer.append((p, differences)) return answer def _Hom_(self, other, category=None): @@ -1690,7 +1691,7 @@ def _chomp_repr_(self): deprecation(33777, "the CHomP interface is deprecated; hence so is this function") deg = self.degree_of_differential() if (self.grading_group() != ZZ or - (deg != 1 and deg != -1)): + (deg != 1 and deg != -1)): raise ValueError('CHomP only works on Z-graded chain complexes with ' 'differential of degree 1 or -1') base_ring = self.base_ring() @@ -1702,7 +1703,7 @@ def _chomp_repr_(self): diffs = self._flip_().differential() if len(diffs) == 0: - diffs = {0: matrix(ZZ, 0,0)} + diffs = {0: matrix(ZZ, 0, 0)} maxdim = max(diffs) mindim = min(diffs) @@ -2017,7 +2018,7 @@ def cartesian_product(self, *factors, **kwds): diffs = [D.differential() for D in factors] keys = reduce(lambda X, d: X.union(d.keys()), diffs, set()) ret = {k: matrix.block_diagonal([d.get(k, zero) for d in diffs], - subdivide=subdivide) + subdivide=subdivide) for k in keys} return ChainComplex(ret, degree_of_differential=deg_diff, grading_group=self._grading_group) @@ -2182,32 +2183,32 @@ def scalar(a): # Our choice for tensor products will be x # y = x1 * y + x2 * y + ... # Generate the data for the differential - for a,r in deg: - for b,s in degD: + for a, r in deg: + for b, s in degD: rp = d[a].nrows() sp = dD[b].nrows() if a+b not in diff: diff[a+b] = {} mor = diff[a+b] cur = {} - cur[(a+deg_diff,b)] = [] - cur[(a,b+deg_diff)] = [] + cur[(a+deg_diff, b)] = [] + cur[(a, b+deg_diff)] = [] for i in range(r): for j in range(s): # \partial x_i \otimes y_j vec = [zero]*(rp*s) - for k,val in enumerate(d[a].column(i)): + for k, val in enumerate(d[a].column(i)): vec[s*k+j] += val - cur[(a+deg_diff,b)].append(vec) + cur[(a+deg_diff, b)].append(vec) # (-1)^a x_i \otimes \partial y_j vec = [zero]*(r*sp) - for k,val in enumerate(dD[b].column(j)): + for k, val in enumerate(dD[b].column(j)): vec[sp*i+k] += scalar(a) * val - cur[(a,b+deg_diff)].append(vec) + cur[(a, b+deg_diff)].append(vec) - mor[a,b] = cur + mor[a, b] = cur # Parse the data into matrices to_delete = [] @@ -2250,5 +2251,5 @@ def scalar(a): return ret -from sage.misc.persist import register_unpickle_override + register_unpickle_override('sage.homology.chain_complex', 'ChainComplex', ChainComplex_class) diff --git a/src/sage/homology/chain_complex_homspace.py b/src/sage/homology/chain_complex_homspace.py index 0d2d82a8bba..7bda59b8416 100644 --- a/src/sage/homology/chain_complex_homspace.py +++ b/src/sage/homology/chain_complex_homspace.py @@ -86,7 +86,7 @@ """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2009 D. Benjamin Antieau # # Distributed under the terms of the GNU General Public License (GPL) @@ -100,7 +100,7 @@ # # https://www.gnu.org/licenses/ # -#***************************************************************************** +# **************************************************************************** import sage.categories.homset from sage.homology.chain_complex_morphism import ChainComplexMorphism diff --git a/src/sage/homology/chain_complex_morphism.py b/src/sage/homology/chain_complex_morphism.py index 085530fea9d..c37f4854fe0 100644 --- a/src/sage/homology/chain_complex_morphism.py +++ b/src/sage/homology/chain_complex_morphism.py @@ -35,7 +35,7 @@ [0 0 0]} """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2009 D. Benjamin Antieau # # Distributed under the terms of the GNU General Public License (GPL) @@ -49,7 +49,7 @@ # # https://www.gnu.org/licenses/ # -#***************************************************************************** +# **************************************************************************** from sage.matrix.constructor import block_diagonal_matrix, zero_matrix from sage.categories.morphism import Morphism @@ -165,8 +165,8 @@ def __init__(self, matrices, C, D, check=True): # Check sizes of matrices. for i in matrices: if (matrices[i].nrows() != D.free_module_rank(i) or - matrices[i].ncols() != C.free_module_rank(i)): - raise ValueError('matrix in degree {} is not the right size'.format(i)) + matrices[i].ncols() != C.free_module_rank(i)): + raise ValueError(f'matrix in degree {i} is not the right size') # Check commutativity. for i in degrees: if i - d not in degrees: @@ -187,7 +187,7 @@ def __init__(self, matrices, C, D, check=True): # Use immutable matrices because they're hashable. m.set_immutable() self._matrix_dictionary[i] = m - Morphism.__init__(self, Hom(C,D, ChainComplexes(C.base_ring()))) + Morphism.__init__(self, Hom(C, D, ChainComplexes(C.base_ring()))) def in_degree(self, n): """ @@ -324,7 +324,7 @@ def __neg__(self): f[i] = -self._matrix_dictionary[i] return ChainComplexMorphism(f, self.domain(), self.codomain()) - def __add__(self,x): + def __add__(self, x): """ Return ``self + x``. @@ -431,7 +431,7 @@ def __mul__(self, x): sage: g._matrix_dictionary {1: [], 2: []} """ - if not isinstance(x,ChainComplexMorphism) or self.domain() != x.codomain(): + if not isinstance(x, ChainComplexMorphism) or self.domain() != x.codomain(): try: y = self.domain().base_ring()(x) except TypeError: @@ -439,13 +439,13 @@ def __mul__(self, x): f = dict() for i in self._matrix_dictionary: f[i] = self._matrix_dictionary[i] * y - return ChainComplexMorphism(f,self.domain(),self.codomain()) - f = dict() + return ChainComplexMorphism(f, self.domain(), self.codomain()) + f = {} for i in self._matrix_dictionary: f[i] = self._matrix_dictionary[i]*x.in_degree(i) - return ChainComplexMorphism(f,x.domain(),self.codomain()) + return ChainComplexMorphism(f, x.domain(), self.codomain()) - def __rmul__(self,x): + def __rmul__(self, x): """ Return ``x * self`` if ``x`` is an element of the base ring. @@ -465,11 +465,11 @@ def __rmul__(self,x): except TypeError: raise TypeError("multiplication is not defined") f = dict() - for i in self._matrix_dictionary.keys(): + for i in self._matrix_dictionary: f[i] = y * self._matrix_dictionary[i] - return ChainComplexMorphism(f,self.domain(),self.codomain()) + return ChainComplexMorphism(f, self.domain(), self.codomain()) - def __sub__(self,x): + def __sub__(self, x): """ Return ``self - x``. @@ -498,7 +498,7 @@ def __sub__(self,x): """ return self + (-x) - def __eq__(self,x): + def __eq__(self, x): """ Return ``True`` if and only if ``self == x``. @@ -518,12 +518,12 @@ def __eq__(self,x): sage: x == y # optional - sage.graphs True """ - return isinstance(x,ChainComplexMorphism) \ - and self.codomain() == x.codomain() \ - and self.domain() == x.domain() \ - and self._matrix_dictionary == x._matrix_dictionary + return isinstance(x, ChainComplexMorphism) \ + and self.codomain() == x.codomain() \ + and self.domain() == x.domain() \ + and self._matrix_dictionary == x._matrix_dictionary - def is_identity(self): + def is_identity(self) -> bool: """ Return ``True`` if this is the identity map. @@ -538,7 +538,7 @@ def is_identity(self): """ return self.to_matrix().is_one() - def is_surjective(self): + def is_surjective(self) -> bool: """ Return ``True`` if this map is surjective. diff --git a/src/sage/homology/chain_homotopy.py b/src/sage/homology/chain_homotopy.py index 326f512b305..a20b9bc854b 100644 --- a/src/sage/homology/chain_homotopy.py +++ b/src/sage/homology/chain_homotopy.py @@ -385,6 +385,7 @@ def _repr_(self): s += '\n and {}'.format('\n '.join(self._g._repr_().split('\n'))) return s + class ChainContraction(ChainHomotopy): r""" A chain contraction. diff --git a/src/sage/homology/chains.py b/src/sage/homology/chains.py index 86e2eaec897..ee514bd604c 100644 --- a/src/sage/homology/chains.py +++ b/src/sage/homology/chains.py @@ -10,14 +10,14 @@ complex. """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2016 Volker Braun # # 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.combinat.free_module import CombinatorialFreeModule @@ -672,9 +672,9 @@ def cup_product(self, cochain): accumulator = codomain.zero() for cell in codomain.indices(): for (coeff, left_cell, right_cell) in cx.alexander_whitney(cell, left_deg): - if not coeff: - continue - left = left_chains(left_cell) - right = right_chains(right_cell) - accumulator += codomain(cell) * coeff * self.eval(left) * cochain.eval(right) + if not coeff: + continue + left = left_chains(left_cell) + right = right_chains(right_cell) + accumulator += codomain(cell) * coeff * self.eval(left) * cochain.eval(right) return accumulator diff --git a/src/sage/homology/cubical_complex.py b/src/sage/homology/cubical_complex.py index 1149da028c0..8402d6518fd 100644 --- a/src/sage/homology/cubical_complex.py +++ b/src/sage/homology/cubical_complex.py @@ -10,8 +10,8 @@ Cube = deprecated_function_alias(31925, sage.topology.cubical_complex.Cube) CubicalComplex = deprecated_function_alias(31925, - sage.topology.cubical_complex.CubicalComplex) + sage.topology.cubical_complex.CubicalComplex) CubicalComplexExamples = deprecated_function_alias(31925, - sage.topology.cubical_complex.CubicalComplexExamples) + sage.topology.cubical_complex.CubicalComplexExamples) cubical_complexes = deprecated_function_alias(31925, - sage.topology.cubical_complex.cubical_complexes) + sage.topology.cubical_complex.cubical_complexes) diff --git a/src/sage/homology/delta_complex.py b/src/sage/homology/delta_complex.py index cfd5fc6119f..9b8bf6a2fcf 100644 --- a/src/sage/homology/delta_complex.py +++ b/src/sage/homology/delta_complex.py @@ -8,8 +8,8 @@ import sage.topology.delta_complex DeltaComplex = deprecated_function_alias(31925, - sage.topology.delta_complex.DeltaComplex) + sage.topology.delta_complex.DeltaComplex) DeltaComplexExamples = deprecated_function_alias(31925, - sage.topology.delta_complex.DeltaComplexExamples) + sage.topology.delta_complex.DeltaComplexExamples) delta_complexes = deprecated_function_alias(31925, - sage.topology.delta_complex.delta_complexes) + sage.topology.delta_complex.delta_complexes) diff --git a/src/sage/homology/graded_resolution.py b/src/sage/homology/graded_resolution.py index 58fa8285fd7..b661d5fb2e5 100644 --- a/src/sage/homology/graded_resolution.py +++ b/src/sage/homology/graded_resolution.py @@ -86,6 +86,7 @@ from sage.homology.free_resolution import (FiniteFreeResolution, FiniteFreeResolution_free_module, FiniteFreeResolution_singular) +from sage.misc.superseded import deprecated_function_alias class GradedFiniteFreeResolution(FiniteFreeResolution): @@ -142,7 +143,7 @@ def __init__(self, module, degrees=None, shifts=None, name='S', **kwds): if degrees[0] in ZZ: zero_deg = 0 multigrade = False - else: # degrees are integer vectors + else: # degrees are integer vectors degrees = tuple([vector(v) for v in degrees]) zero_deg = degrees[0].parent().zero() multigrade = True @@ -402,7 +403,7 @@ def compute_degree(base, i): def find_deg(i): for j in range(M.nrows()): - ret = M[j,i].degree() + ret = M[j, i].degree() if ret != -1: return ret raise NotImplementedError("a generator maps to 0") @@ -518,8 +519,8 @@ def _maps(self): from sage.libs.singular.singular import si2sa_resolution_graded from sage.libs.singular.function import singular_function - #cdef int i, j, k, ncols, nrows - #cdef list res_shifts, prev_shifts, new_shifts + # cdef int i, j, k, ncols, nrows + # cdef list res_shifts, prev_shifts, new_shifts # This ensures the first component of the Singular resolution to be a # module, like the later components. This is important when the @@ -572,5 +573,4 @@ def _maps(self): return res_mats -from sage.misc.superseded import deprecated_function_alias GradedFreeResolution = deprecated_function_alias(34873, GradedFiniteFreeResolution_singular) diff --git a/src/sage/homology/hochschild_complex.py b/src/sage/homology/hochschild_complex.py index 05af2b6cbce..8f6041a597e 100644 --- a/src/sage/homology/hochschild_complex.py +++ b/src/sage/homology/hochschild_complex.py @@ -273,13 +273,13 @@ def boundary(self, d): def on_basis(k): p = self._M.monomial(k[0]) * self._A.monomial(k[1]) - ret = Fd._from_dict({(m,) + k[2:]: c for m,c in p}, remove_zeros=False) + ret = Fd._from_dict({(m,) + k[2:]: c for m, c in p}, remove_zeros=False) for i in range(1, d): p = self._A.monomial(k[i]) * self._A.monomial(k[i+1]) ret += mone**i * Fd._from_dict({k[:i] + (m,) + k[i+2:]: c - for m,c in p}, remove_zeros=False) + for m, c in p}, remove_zeros=False) p = self._A.monomial(k[-1]) * self._M.monomial(k[0]) - ret += mone**d * Fd._from_dict({(m,) + k[1:-1]: c for m,c in p}, + ret += mone**d * Fd._from_dict({(m,) + k[1:-1]: c for m, c in p}, remove_zeros=False) return ret return Fd1.module_morphism(on_basis, codomain=Fd) @@ -493,7 +493,7 @@ def _element_constructor_(self, vectors): return self.element_class(self, {0: vec}) if isinstance(vectors, (Chain_class, self.element_class)): vectors = vectors._vec - data = dict() + data = {} if not isinstance(vectors, dict): raise ValueError("cannot construct an element from {}".format(vectors)) # Special handling for the 0 free module @@ -624,10 +624,9 @@ def _repr_(self): if n == 1: (deg, vec), = self._vec.items() - return 'Chain({0}: {1})'.format(deg, vec) + return f'Chain({deg}: {vec})' - return 'Chain with {0} nonzero terms over {1}'.format(n, - self.parent().base_ring()) + return f'Chain with {n} nonzero terms over {self.parent().base_ring()}' def _ascii_art_(self): """ @@ -691,7 +690,7 @@ def _add_(self, other): 3*F[1] # F[1] + 2*F[1] # F[x] + 3*F[1] # F[y], 3*F[1] # F[1] # F[1] + 2*F[1] # F[1] # F[x] + 3*F[1] # F[1] # F[y]] """ - vectors = dict(self._vec) # Make a (shallow) copy + vectors = dict(self._vec) # Make a (shallow) copy for d in other._vec: if d in vectors: vectors[d] += other._vec[d] @@ -719,7 +718,7 @@ def _lmul_(self, scalar): """ if scalar == 0: return self.zero() - vectors = dict() + vectors = {} for d in self._vec: vec = scalar * self._vec[d] if vec: diff --git a/src/sage/homology/homology_group.py b/src/sage/homology/homology_group.py index 5948d206371..67745b0cb94 100644 --- a/src/sage/homology/homology_group.py +++ b/src/sage/homology/homology_group.py @@ -114,7 +114,7 @@ def _latex_(self): eldv = self._original_invts if len(eldv) == 0: return "0" - rank = len([x for x in eldv if x == 0]) + rank = len([1 for x in eldv if x == 0]) torsion = sorted(x for x in eldv if x) if rank > 4: g = ["\\ZZ^{{{}}}".format(rank)] @@ -134,6 +134,7 @@ def _latex_(self): times = " \\times " return times.join(g) + def HomologyGroup(n, base_ring, invfac=None): """ Abelian group on `n` generators which represents a homology group in a diff --git a/src/sage/homology/homology_morphism.py b/src/sage/homology/homology_morphism.py index 9cd1c7a4a82..e43cc5eb9f0 100644 --- a/src/sage/homology/homology_morphism.py +++ b/src/sage/homology/homology_morphism.py @@ -166,8 +166,8 @@ def __init__(self, map, base_ring=None, cohomology=False): sage: h = g.induced_homology_morphism(QQ) """ if (isinstance(map.domain(), SimplicialComplex) - and (map.domain().is_mutable() or map.codomain().is_mutable())): - raise ValueError('the domain and codomain complexes must be immutable') + and (map.domain().is_mutable() or map.codomain().is_mutable())): + raise ValueError('the domain and codomain complexes must be immutable') if base_ring is None: base_ring = QQ if not base_ring.is_field(): @@ -244,9 +244,9 @@ def to_matrix(self, deg=None): H_domain, H_codomain = H_codomain, H_domain if deg is None: betti_domain = [H_domain.free_module_rank(n) - for n in range(domain.dimension()+1)] + for n in range(domain.dimension() + 1)] betti_codomain = [H_codomain.free_module_rank(n) - for n in range(codomain.dimension()+1)] + for n in range(codomain.dimension() + 1)] # Compute cumulative sums of Betti numbers to get subdivisions: row_subdivs = list(itertools.accumulate(betti_codomain[:-1])) col_subdivs = list(itertools.accumulate(betti_domain[:-1])) @@ -288,7 +288,7 @@ def __call__(self, elt): return codomain.from_vector(self.to_matrix() * elt.to_vector()) - def __eq__(self, other): + def __eq__(self, other) -> bool: """ Return ``True`` if and only if this map agrees with ``other``. @@ -321,12 +321,12 @@ def __eq__(self, other): if (self._map.domain() != other._map.domain() or self._map.codomain() != other._map.codomain() or self.base_ring() != other.base_ring() - or self._cohomology != other._cohomology): + or self._cohomology != other._cohomology): return False dim = min(self._map.domain().dimension(), self._map.codomain().dimension()) - return all(self.to_matrix(d) == other.to_matrix(d) for d in range(dim+1)) + return all(self.to_matrix(d) == other.to_matrix(d) for d in range(dim + 1)) - def is_identity(self): + def is_identity(self) -> bool: """ Return ``True`` if this is the identity map on (co)homology. diff --git a/src/sage/homology/homology_vector_space_with_basis.py b/src/sage/homology/homology_vector_space_with_basis.py index fd5e2fbdc0d..f9a388b0f87 100644 --- a/src/sage/homology/homology_vector_space_with_basis.py +++ b/src/sage/homology/homology_vector_space_with_basis.py @@ -409,7 +409,8 @@ def to_cycle(self): """ if not self.is_homogeneous(): raise ValueError("only defined for homogeneous elements") - return sum(c * self.parent()._to_cycle_on_basis(i) for i,c in self) + return sum(c * self.parent()._to_cycle_on_basis(i) for i, c in self) + class CohomologyRing(HomologyVectorSpaceWithBasis): """ @@ -508,7 +509,7 @@ def one(self): True """ one = self.base_ring().one() - d = {(0,i): one for i in self._graded_indices[0]} + d = {(0, i): one for i in self._graded_indices[0]} return self._from_dict(d, remove_zeros=False) @cached_method @@ -755,7 +756,7 @@ def Sq(self, i): ret = P.zero() H = scomplex.homology_with_basis(base_ring) deg_comp = {} - for index,coeff in self: + for index, coeff in self: d = deg_comp.get(index[0], {}) d[index] = coeff deg_comp[index[0]] = d @@ -828,7 +829,7 @@ def Sq(self, i): if ((hasattr(left, 'is_nondegenerate') and left.is_nondegenerate() and right.is_nondegenerate()) - or not hasattr(left, 'is_nondegenerate')): + or not hasattr(left, 'is_nondegenerate')): left = n_chains(left) right = n_chains(right) gamma_coeff += coeff * cycle.eval(left) * cycle.eval(right) @@ -837,6 +838,7 @@ def Sq(self, i): ret += P._from_dict(result, remove_zeros=False) return ret + def sum_indices(k, i_k_plus_one, S_k_plus_one): r""" This is a recursive function for computing the indices for the diff --git a/src/sage/homology/koszul_complex.py b/src/sage/homology/koszul_complex.py index af480a9c8db..a8b050e09bc 100644 --- a/src/sage/homology/koszul_complex.py +++ b/src/sage/homology/koszul_complex.py @@ -108,12 +108,12 @@ def __classcall_private__(cls, R=None, elements=None): R = () elements = R if not elements: - R = ZZ # default to ZZ as the base ring if no elements are given + R = ZZ # default to ZZ as the base ring if no elements are given elif isinstance(R, Parent): elements = () else: R = elements[0].parent() - elif R is None: # elements is not None + elif R is None: # elements is not None R = elements[0].parent() return super(KoszulComplex, cls).__classcall__(cls, R, tuple(elements)) @@ -134,12 +134,12 @@ def __init__(self, R, elements): diff = {} zero = R.zero() for i in I: - M = matrix(R, binomial(n,i), binomial(n,i+1), zero) + M = matrix(R, binomial(n, i), binomial(n, i+1), zero) j = 0 for comb in itertools.combinations(I, i+1): - for k,val in enumerate(comb): + for k, val in enumerate(comb): r = rank(comb[:k] + comb[k+1:], n, False) - M[r,j] = (-1)**k * elements[val] + M[r, j] = (-1)**k * elements[val] j += 1 M.set_immutable() diff[i+1] = M diff --git a/src/sage/homology/matrix_utils.py b/src/sage/homology/matrix_utils.py index b1edc656e58..4f10ae415a3 100644 --- a/src/sage/homology/matrix_utils.py +++ b/src/sage/homology/matrix_utils.py @@ -96,11 +96,11 @@ def dhsw_snf(mat, verbose=False): check_leading = True while check_leading: i = new_col.nonzero_positions_in_column(0)[0] - entry = new_col[i,0] + entry = new_col[i, 0] check_leading = False if i in leading_positions: for c in leading_positions[i]: - earlier = new_mat[i,c] + earlier = new_mat[i, c] # right now we don't check to see if entry divides # earlier, because we don't want to modify the # earlier columns of the matrix. Deal with this @@ -137,7 +137,7 @@ def dhsw_snf(mat, verbose=False): j = leading_positions[i][0] jth = new_mat[i, j] for n in leading_positions[i][1:]: - nth = new_mat[i,n] + nth = new_mat[i, n] if jth.divides(nth): quo = nth.divide_knowing_divisible_by(jth) new_mat.add_multiple_of_column(n, j, -quo) @@ -147,8 +147,8 @@ def dhsw_snf(mat, verbose=False): new_mat.swap_columns(n, j) new_mat.add_multiple_of_column(n, j, -quo) else: - (g,r,s) = jth.xgcd(nth) - (unit,A,B) = r.xgcd(-s) # unit ought to be 1 here + g, r, s = jth.xgcd(nth) + unit, A, B = r.xgcd(-s) # unit ought to be 1 here jth_col = new_mat.column(j) nth_col = new_mat.column(n) new_mat.set_column(j, r*jth_col + s*nth_col) @@ -176,15 +176,15 @@ def dhsw_snf(mat, verbose=False): max_leading = 1 for i in leading_positions: j = leading_positions[i][0] - entry = new_mat[i,j] + entry = new_mat[i, j] if entry.abs() == 1: add_to_rank += 1 keep_columns.remove(j) for c in new_mat.nonzero_positions_in_row(i): if c in keep_columns: - new_mat.add_multiple_of_column(c, j, -entry * new_mat[i,c]) + new_mat.add_multiple_of_column(c, j, -entry * new_mat[i, c]) else: - max_leading = max(max_leading, new_mat[i,j].abs()) + max_leading = max(max_leading, new_mat[i, j].abs()) # form the new matrix if max_leading != 1: new_mat = new_mat.matrix_from_columns(keep_columns) diff --git a/src/sage/homology/simplicial_complex_homset.py b/src/sage/homology/simplicial_complex_homset.py index f5b54a59dc2..fcb184c7fe0 100644 --- a/src/sage/homology/simplicial_complex_homset.py +++ b/src/sage/homology/simplicial_complex_homset.py @@ -7,6 +7,6 @@ import sage.topology.simplicial_complex_homset is_SimplicialComplexHomset = deprecated_function_alias(31925, - sage.topology.simplicial_complex_homset.is_SimplicialComplexHomset) + sage.topology.simplicial_complex_homset.is_SimplicialComplexHomset) SimplicialComplexHomset = deprecated_function_alias(31925, - sage.topology.simplicial_complex_homset.SimplicialComplexHomset) + sage.topology.simplicial_complex_homset.SimplicialComplexHomset) diff --git a/src/sage/homology/simplicial_complex_morphism.py b/src/sage/homology/simplicial_complex_morphism.py index 889c266dc0a..addf111e564 100644 --- a/src/sage/homology/simplicial_complex_morphism.py +++ b/src/sage/homology/simplicial_complex_morphism.py @@ -7,6 +7,6 @@ import sage.topology.simplicial_complex_morphism is_SimplicialComplexMorphism = deprecated_function_alias(31925, - sage.topology.simplicial_complex_morphism.is_SimplicialComplexMorphism) + sage.topology.simplicial_complex_morphism.is_SimplicialComplexMorphism) SimplicialComplexMorphism = deprecated_function_alias(31925, - sage.topology.simplicial_complex_morphism.SimplicialComplexMorphism) + sage.topology.simplicial_complex_morphism.SimplicialComplexMorphism) diff --git a/src/sage/homology/simplicial_set_morphism.py b/src/sage/homology/simplicial_set_morphism.py index 9df5cb9a40d..1f90dda0d9c 100644 --- a/src/sage/homology/simplicial_set_morphism.py +++ b/src/sage/homology/simplicial_set_morphism.py @@ -7,6 +7,6 @@ import sage.topology.simplicial_set_morphism deprecated_function_alias(31925, - sage.topology.simplicial_set_morphism.SimplicialSetHomset) + sage.topology.simplicial_set_morphism.SimplicialSetHomset) deprecated_function_alias(31925, - sage.topology.simplicial_set_morphism.SimplicialSetMorphism) + sage.topology.simplicial_set_morphism.SimplicialSetMorphism) diff --git a/src/sage/homology/tests.py b/src/sage/homology/tests.py index 10ef05e9c77..0915ebbfb03 100644 --- a/src/sage/homology/tests.py +++ b/src/sage/homology/tests.py @@ -32,6 +32,7 @@ from sage.rings.integer_ring import ZZ from sage.topology.simplicial_complex_examples import RandomComplex + def random_chain_complex(level=1): """ Return a random chain complex, defined by specifying a single @@ -54,7 +55,7 @@ def random_chain_complex(level=1): sage: C.degree_of_differential() in [-1, 1] True """ - bound = 50*level + bound = 50 * level nrows = randint(0, bound) ncols = randint(0, bound) sparseness = bool(randint(0, 1)) @@ -100,6 +101,7 @@ def test_random_chain_complex(level=1, trials=1, verbose=False): print("Chain complex: %s" % C.differential()) raise ValueError + def random_simplicial_complex(level=1, p=0.5): """ Return a random simplicial complex. @@ -120,10 +122,11 @@ def random_simplicial_complex(level=1, p=0.5): sage: X.dimension() < 11 True """ - n = randint(2, 4*level) + n = randint(2, 4 * level) dim = randint(1, n) return RandomComplex(n, dim, p) + @random_testing def test_random_simplicial_complex(level=1, trials=1, verbose=False): """ From c9a825a2a4fa21f0e11dff1b8b71333d40fab3a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Fri, 7 Jul 2023 11:57:52 +0200 Subject: [PATCH 2/3] details as suggested --- src/sage/homology/homology_morphism.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sage/homology/homology_morphism.py b/src/sage/homology/homology_morphism.py index e43cc5eb9f0..5403fe7722b 100644 --- a/src/sage/homology/homology_morphism.py +++ b/src/sage/homology/homology_morphism.py @@ -319,8 +319,8 @@ def __eq__(self, other) -> bool: False """ if (self._map.domain() != other._map.domain() - or self._map.codomain() != other._map.codomain() - or self.base_ring() != other.base_ring() + or self._map.codomain() != other._map.codomain() + or self.base_ring() != other.base_ring() or self._cohomology != other._cohomology): return False dim = min(self._map.domain().dimension(), self._map.codomain().dimension()) @@ -345,7 +345,7 @@ def is_identity(self) -> bool: """ return self.to_matrix().is_one() - def is_surjective(self): + def is_surjective(self) -> bool: """ Return ``True`` if this map is surjective on (co)homology. @@ -363,7 +363,7 @@ def is_surjective(self): m = self.to_matrix() return m.rank() == m.nrows() - def is_injective(self): + def is_injective(self) -> bool: """ Return ``True`` if this map is injective on (co)homology. From 3dc4ac3ab8f2d1a48108da35a060610b2dadbf5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Sat, 8 Jul 2023 12:10:30 +0200 Subject: [PATCH 3/3] Update homology_group.py undo one little change --- src/sage/homology/homology_group.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/homology/homology_group.py b/src/sage/homology/homology_group.py index 67745b0cb94..53db12c1828 100644 --- a/src/sage/homology/homology_group.py +++ b/src/sage/homology/homology_group.py @@ -114,13 +114,13 @@ def _latex_(self): eldv = self._original_invts if len(eldv) == 0: return "0" - rank = len([1 for x in eldv if x == 0]) + rank = len([x for x in eldv if x == 0]) torsion = sorted(x for x in eldv if x) if rank > 4: g = ["\\ZZ^{{{}}}".format(rank)] else: g = ["\\ZZ"] * rank - if len(torsion) != 0: + if torsion: printed = [] for t in torsion: numfac = torsion.count(t)