Skip to content

Commit

Permalink
gh-37789: various ruff fixes in groups (PERF, etc)
Browse files Browse the repository at this point in the history
    
This fixes various suggestions of `ruff` in the `groups` folder, mostly
about `PERF` code

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
    
URL: #37789
Reported by: Frédéric Chapoton
Reviewer(s): gmou3
  • Loading branch information
Release Manager committed Apr 25, 2024
2 parents e74a5f3 + 0c49d81 commit a86a710
Show file tree
Hide file tree
Showing 13 changed files with 116 additions and 123 deletions.
31 changes: 17 additions & 14 deletions src/sage/groups/additive_abelian/additive_abelian_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@

from sage.misc.superseded import deprecated_function_alias


class UnwrappingMorphism(Morphism):
r"""
The embedding into the ambient group. Used by the coercion framework.
Expand Down Expand Up @@ -213,7 +214,7 @@ def __init__(self, universe, gens, invariants):
self._universe = universe
self._gen_elements = tuple(universe(x) for x in gens)
self._gen_orders = invariants
cover,rels = addgp.cover_and_relations_from_invariants(invariants)
cover, rels = addgp.cover_and_relations_from_invariants(invariants)
addgp.AdditiveAbelianGroup_fixed_gens.__init__(self, cover, rels, cover.gens())
self._unset_coercions_used()
self.register_embedding(UnwrappingMorphism(self))
Expand Down Expand Up @@ -488,13 +489,13 @@ def torsion_subgroup(self, n=None):
if n <= 0:
raise ValueError('n must be a positive integer')
gens, ords = [], []
for g,o in genords:
for g, o in genords:
if not o:
continue
d = n.gcd(o)
if d == 1:
continue
gens.append(o//d * g)
gens.append(o // d * g)
ords.append(d)
return AdditiveAbelianGroupWrapper(self.universe(), gens, ords)

Expand Down Expand Up @@ -691,9 +692,9 @@ def _expand_basis_pgroup(p, alphas, vals, beta, h, rel):
if not (isinstance(alphas, list) and isinstance(vals, list)):
raise TypeError('alphas and vals must be lists for mutability')
if not len(alphas) == len(vals) == k - 1:
raise ValueError(f'alphas and/or vals have incorrect length')
# assert not sum(r*a for r,a in zip(rel, alphas+[beta]))
# assert all(a.order() == p**v for a,v in zip(alphas,vals))
raise ValueError('alphas and/or vals have incorrect length')
# assert not sum(r*a for r,a in zip(rel, alphas+[beta]))
# assert all(a.order() == p**v for a,v in zip(alphas,vals))

if rel[-1] < 0:
raise ValueError('rel must have nonnegative entries')
Expand Down Expand Up @@ -726,8 +727,8 @@ def _expand_basis_pgroup(p, alphas, vals, beta, h, rel):
return

# step 3
j = next(j for j,r in enumerate(rel) if r == min_r)
alphas[j] = sum(a * (r//rel[j]) for a,r in zip(alphas+[beta], rel))
j = next(j for j, r in enumerate(rel) if r == min_r)
alphas[j] = sum(a * (r // rel[j]) for a, r in zip(alphas + [beta], rel))

# step 4
if not alphas[j]:
Expand All @@ -752,7 +753,8 @@ def _expand_basis_pgroup(p, alphas, vals, beta, h, rel):
else:
alphas.append(beta)
vals.append(h)
# assert alphas[-1].order() == p**vals[-1]
# assert alphas[-1].order() == p**vals[-1]


def basis_from_generators(gens, ords=None):
r"""
Expand Down Expand Up @@ -803,7 +805,8 @@ def basis_from_generators(gens, ords=None):
gammas = []
ms = []
for p in ps:
pgens = [(o.prime_to_m_part(p) * g, o.p_primary_part(p)) for g, o in zip(gens, ords) if not o % p]
pgens = [(o.prime_to_m_part(p) * g, o.p_primary_part(p))
for g, o in zip(gens, ords) if not o % p]
assert pgens
pgens.sort(key=lambda tup: tup[1])

Expand All @@ -814,7 +817,7 @@ def basis_from_generators(gens, ords=None):
while pgens:
beta, ord_beta = pgens.pop()
try:
dlog = _discrete_log_pgroup(p, vals, alphas, beta)
_ = _discrete_log_pgroup(p, vals, alphas, beta)
except ValueError:
pass
else:
Expand Down Expand Up @@ -845,8 +848,8 @@ def basis_from_generators(gens, ords=None):
gammas.append(a)
ms.append(p ** v)

## assert len({sum(i*g for i,g in zip(vec,gammas))
## for vec in __import__('itertools').product(*map(range,ms))}) \
## == __import__('sage').misc.misc_c.prod(ms)
# assert len({sum(i*g for i,g in zip(vec,gammas))
# for vec in __import__('itertools').product(*map(range,ms))}) \
# == __import__('sage').misc.misc_c.prod(ms)

return gammas, ms
4 changes: 2 additions & 2 deletions src/sage/groups/braid.py
Original file line number Diff line number Diff line change
Expand Up @@ -2590,8 +2590,8 @@ def __init__(self, names):
rels = []
for i in range(1, n):
rels.append(free_group([i, i + 1, i, -i - 1, -i, -i - 1]))
for j in range(i + 2, n + 1):
rels.append(free_group([i, j, -i, -j]))
rels.extend(free_group([i, j, -i, -j])
for j in range(i + 2, n + 1))
cat = Groups().Infinite()
FinitelyPresentedGroup.__init__(self, free_group, tuple(rels),
category=cat)
Expand Down
28 changes: 12 additions & 16 deletions src/sage/groups/class_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,10 +605,9 @@ def irreducible_constituents(self):
L = self._gap_classfunction.ConstituentsOfCharacter()
return tuple(ClassFunction(self._group, list(l)) for l in L)

def decompose(self):
def decompose(self) -> tuple:
r"""
Returns a list of the characters that appear in the decomposition
of chi.
Return a list of the characters appearing the decomposition of ``self``.
EXAMPLES::
Expand All @@ -618,14 +617,13 @@ def decompose(self):
((3, Character of Symmetric group of order 5! as a permutation group),
(2, Character of Symmetric group of order 5! as a permutation group))
"""
L = []
for irr in self.irreducible_constituents():
L.append((self.scalar_product(irr), irr))
L = [(self.scalar_product(irr), irr)
for irr in self.irreducible_constituents()]
return tuple(L)

def norm(self):
r"""
Returns the norm of self.
Return the norm of ``self``.
EXAMPLES::
Expand All @@ -635,7 +633,7 @@ def norm(self):
"""
return self._gap_classfunction.Norm()

def values(self):
def values(self) -> list:
r"""
Return the list of values of self on the conjugacy classes.
Expand Down Expand Up @@ -665,7 +663,7 @@ def values(self):

def central_character(self):
r"""
Returns the central character of self.
Return the central character of ``self``.
EXAMPLES::
Expand All @@ -677,7 +675,7 @@ def central_character(self):

def determinant_character(self):
r"""
Returns the determinant character of self.
Return the determinant character of ``self``.
EXAMPLES::
Expand Down Expand Up @@ -1310,10 +1308,9 @@ def irreducible_constituents(self):
L = self._gap_classfunction.ConstituentsOfCharacter()
return tuple(ClassFunction_libgap(self._group, l) for l in L)

def decompose(self):
def decompose(self) -> tuple:
r"""
Return a list of the characters that appear in the decomposition
of ``self``.
Return a list of the characters appearing the decomposition of ``self``.
EXAMPLES::
Expand All @@ -1323,9 +1320,8 @@ def decompose(self):
((3, Character of Symmetric group of order 5! as a permutation group),
(2, Character of Symmetric group of order 5! as a permutation group))
"""
L = []
for irr in self.irreducible_constituents():
L.append((self.scalar_product(irr), irr))
L = [(self.scalar_product(irr), irr)
for irr in self.irreducible_constituents()]
return tuple(L)

def norm(self):
Expand Down
47 changes: 23 additions & 24 deletions src/sage/groups/cubic_braid.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def eliminate_item(tietze_list):
return None
first = tietze_list[0]
second = None
for i in range(1,l):
for i in range(1, l):
if tietze_list[i] in (first, -first):
if i == 1:
second = tietze_list[i]
Expand Down Expand Up @@ -502,17 +502,17 @@ def find_root(domain):
# --------------------------------------------------------------------
cbg_type = self.parent()._cbg_type
if cbg_type == CubicBraidGroup.type.AssionS:
characteristic = 3 # making Assion type S relations vanish
characteristic = 3 # making Assion type S relations vanish
elif cbg_type == CubicBraidGroup.type.AssionU:
characteristic = 2 # making Assion type U relations vanish
characteristic = 2 # making Assion type U relations vanish
else:
characteristic = 0
try:
characteristic = Integer(characteristic)
except ValueError:
raise ValueError('characteristic must be in integer')

if not characteristic.is_zero() and not characteristic.is_prime():
if not characteristic.is_zero() and not characteristic.is_prime():
raise ValueError('characteristic must be a prime')
if characteristic.is_zero():
from sage.rings.number_field.number_field import CyclotomicField
Expand All @@ -526,7 +526,7 @@ def find_root(domain):
root_bur = find_root(domain)
domain = root_bur.parent()

else: # domain is not None
else: # domain is not None
root_bur = find_root(domain)

else: # root_bur is not None
Expand All @@ -550,11 +550,11 @@ def conv2domain(laur_pol):
from sage.matrix.constructor import matrix

d1, d2 = burau_ori.dimensions()
burau_mat = matrix(d1, d2, lambda i,j: conv2domain(burau_ori[i,j]))
burau_mat = matrix(d1, d2, lambda i, j: conv2domain(burau_ori[i, j]))

if unitary:
burau_mat_adj = matrix(d1, d2, lambda i,j: conv2domain(burau_ori_adj[i,j]))
herm_form = matrix(d1, d2, lambda i,j: conv2domain(herm_form_ori[i,j]))
burau_mat_adj = matrix(d1, d2, lambda i, j: conv2domain(burau_ori_adj[i, j]))
herm_form = matrix(d1, d2, lambda i, j: conv2domain(herm_form_ori[i, j]))
return burau_mat, burau_mat_adj, herm_form

return burau_mat
Expand Down Expand Up @@ -764,15 +764,14 @@ def __init__(self, names, cbg_type=None):

# internal naming of elements for convenience
b = [free_group([i]) for i in range(1, n+1)]
t = [free_group([i, i+1]) ** 3 for i in range(1, n)]
t = [free_group([i, i+1]) ** 3 for i in range(1, n)]
ti = [free_group([-i, -i-1]) ** 3 for i in range(1, n)]

# first the braid relation
# first the braid relations
rels = list(self._braid_group.relations())

# than the cubic relation
for i in range(n):
rels.append(b[i]**3)
# than the cubic relations
rels.extend(b[i]**3 for i in range(n))

# than Assion's relation Satz 2.2 for cbg_type=CubicBraidGroup.type.AssionS
# and Satz 2.4 for cbg_type=CubicBraidGroup.type.AssionU
Expand Down Expand Up @@ -1276,7 +1275,7 @@ def create_unitary_realization(self, m):
if pos + 1 < m:
transvections.append(xbas[pos-1]+xbas[pos]+xbas[pos+1]) # t_{3i+1} = x_{3i-1} + x_{3i} + x_{3i+1}
if pos + 3 < m:
transvections.append(xbas[pos+1]+xbas[pos+2]+xbas[pos+3]) # t_{3i+2} = x_{3i+1} + x_{3i+2} + x_{3i+3}
transvections.append(xbas[pos+1]+xbas[pos+2]+xbas[pos+3]) # t_{3i+2} = x_{3i+1} + x_{3i+2} + x_{3i+3}

# -----------------------------------------------------------
# Conversion-Map from transvection vector to transvection
Expand All @@ -1299,15 +1298,14 @@ def transvec2mat(v, bas=bas, bform=bform, fact=a):
set_classical_realization(self, base_group, proj_group, centralizing_matrix, transvec_matrices)
return

#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------
# local functions declaration section finishes here
#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------

# -------------------------------------------------------------------------------
# ----------------------------------------------------------------
# initialization of constants
# -------------------------------------------------------------------------------
# ----------------------------------------------------------------

n = self.strands()

# -------------------------------------------------------------------------------
Expand All @@ -1317,7 +1315,7 @@ def transvec2mat(v, bas=bas, bform=bform, fact=a):
dim_sympl_group = n-1 # S(n-1) = Sp(n-1, 3)
if n % 2 == 0:
dim_sympl_group = n # S(n-1) = subgroup of PSp(n, 3)
create_sympl_realization(self, dim_sympl_group)
create_sympl_realization(self, dim_sympl_group)
elif self._cbg_type == CubicBraidGroup.type.AssionU:
dim_unitary_group = n-1 # U(n-1) = GU(n-1, 2)
if n % 3 == 0:
Expand Down Expand Up @@ -1543,8 +1541,9 @@ def as_matrix_group(self, root_bur=None, domain=None, characteristic=None, var='
unitary = True
gen_list = []
for braid_gen in self.gens():
bur_mat = braid_gen.burau_matrix(root_bur=root_bur, domain=domain, characteristic=characteristic,
var=var, reduced=reduced)
bur_mat = braid_gen.burau_matrix(root_bur=root_bur, domain=domain,
characteristic=characteristic,
var=var, reduced=reduced)
if unitary:
bur_mat, bur_mat_ad, herm_form = bur_mat

Expand Down Expand Up @@ -1809,7 +1808,7 @@ def as_reflection_group(self):
if not is_chevie_available():
raise ImportError("the GAP3 package 'CHEVIE' is needed to obtain the corresponding reflection groups")

if self._cbg_type != CubicBraidGroup.type.Coxeter or self.strands() > 5 or self.strands() < 2:
if self._cbg_type != CubicBraidGroup.type.Coxeter or self.strands() > 5 or self.strands() < 2:
raise ValueError("no reflection group defined")

# -------------------------------------------------------------------------------
Expand Down
7 changes: 3 additions & 4 deletions src/sage/groups/finitely_presented.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,7 @@ def as_permutation_group(self, limit=4096000):
from sage.combinat.permutation import Permutation
from sage.groups.perm_gps.permgroup import PermutationGroup
return PermutationGroup([
Permutation(coset_table[2*i]) for i in range(len(coset_table)//2)])
Permutation(coset_table[2*i]) for i in range(len(coset_table)//2)])

def direct_product(self, H, reduced=False, new_names=True):
r"""
Expand Down Expand Up @@ -1548,14 +1548,13 @@ def sorted_presentation(self):
L1 = []
for rel in L0:
C = [rel]
for j in range(len(rel) - 1):
C.append(rel[j + 1:] + rel[:j + 1])
C.extend(rel[j + 1:] + rel[:j + 1] for j in range(len(rel) - 1))
C1 = [tuple(-j for j in reversed(l)) for l in C]
C += C1
C.sort()
L1.append(C[0])
L1.sort()
return F/L1
return F / L1

def epimorphisms(self, H):
r"""
Expand Down
3 changes: 1 addition & 2 deletions src/sage/groups/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ def discrete_log(a, base, ord=None, bounds=None, operation='*', identity=None, i
power = lambda x, y: multiple(x, y, operation=operation, identity=identity, inverse=inverse, op=op)
if bounds:
lb, ub = map(integer_ring.ZZ, bounds)
if (op is None or identity is None or inverse is None or ord is None) and operation not in addition_names+multiplication_names:
if (op is None or identity is None or inverse is None or ord is None) and operation not in addition_names + multiplication_names:
raise ValueError("ord, op, identity, and inverse must all be specified for this operation")
if ord is None:
if operation in multiplication_names:
Expand Down Expand Up @@ -1500,7 +1500,6 @@ def has_order(P, n, operation='+'):
return False
n = n.factor()

G = P.parent()
if operation in addition_names:
isid = lambda el: not el
mult = lambda el, n: multiple(el, n, operation='+')
Expand Down
1 change: 1 addition & 0 deletions src/sage/groups/kernel_subgroup.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation


class KernelSubgroup(UniqueRepresentation, Parent):
r"""
The kernel (normal) subgroup.
Expand Down
Loading

0 comments on commit a86a710

Please sign in to comment.