Skip to content

Commit

Permalink
sagemathgh-37984: Ruff details in algebras and categories
Browse files Browse the repository at this point in the history
various small fixes for ruff suggestions in algebras and categories

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.

URL: sagemath#37984
Reported by: Frédéric Chapoton
Reviewer(s): Matthias Köppe
  • Loading branch information
Release Manager committed May 12, 2024
2 parents 90d41de + 9ec8971 commit ba78c4e
Show file tree
Hide file tree
Showing 17 changed files with 84 additions and 97 deletions.
4 changes: 2 additions & 2 deletions build/pkgs/configure/checksums.ini
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
tarball=configure-VERSION.tar.gz
sha1=dca19f73642b76f1f96b860bb6603499f586380d
sha256=843e060687a9a2360ea3e9499e5c20eb744fcfc2acd4b13c01444ecd961fd43e
sha1=689279c3aaa3659ef819cb0b56651654094cd153
sha256=ef1344714624eb26ea45cba5a64ca5d79308f6e914997fbef3f205a59c7eff2b
2 changes: 1 addition & 1 deletion build/pkgs/configure/package-version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
f5e78840b108412e1e26382910af993f874c6933
405358e3f1f387932ad267caacc4af94b0efa2d0
2 changes: 1 addition & 1 deletion src/sage/algebras/cluster_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1769,7 +1769,7 @@ def d_vector_to_g_vector(self, d) -> tuple:
sage: A.d_vector_to_g_vector((1,0,-1))
(-1, 1, 2)
"""
dm = vector((x if x < 0 else 0 for x in d))
dm = vector(x if x < 0 else 0 for x in d)
dp = vector(d) - dm
return tuple(- dm - self.euler_matrix() * dp)

Expand Down
99 changes: 47 additions & 52 deletions src/sage/algebras/fusion_rings/f_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
from sage.rings.polynomial.polydict import ETuple
from sage.rings.qqbar import AA, QQbar, number_field_elements_from_algebraics


class FMatrix(SageObject):
r"""
An F-matrix for a :class:`FusionRing`.
Expand Down Expand Up @@ -297,7 +298,7 @@ def __init__(self, fusion_ring, fusion_label="f", var_prefix='fx', inject_variab
self.pool = None

#######################
### Class utilities ###
# Class utilities #
#######################

def _repr_(self):
Expand Down Expand Up @@ -434,35 +435,31 @@ def fmat(self, a, b, c, d, x, y, data=True):
(-zeta60^14 + zeta60^6 + zeta60^4 - 1),
(zeta60^14 - zeta60^6 - zeta60^4 + 1)]
"""
if (self._FR.Nk_ij(a, b, x) == 0 or self._FR.Nk_ij(x, c, d) == 0
or self._FR.Nk_ij(b, c, y) == 0 or self._FR.Nk_ij(a, y, d) == 0):
if (self._FR.Nk_ij(a, b, x) == 0
or self._FR.Nk_ij(x, c, d) == 0
or self._FR.Nk_ij(b, c, y) == 0
or self._FR.Nk_ij(a, y, d) == 0):
return 0

# Some known zero F-symbols
if a == self._FR.one():
if x == b and y == d:
return 1
else:
return 0
return 1 if x == b and y == d else 0

if b == self._FR.one():
if x == a and y == c:
return 1
else:
return 0
return 1 if x == a and y == c else 0

if c == self._FR.one():
if x == d and y == b:
return 1
else:
return 0
return 1 if x == d and y == b else 0

if data:
# Better to use try/except for speed. Somewhat trivial, but worth
# hours when method is called ~10^11 times
try:
return self._fvars[a, b, c, d, x, y]
except KeyError:
return 0
else:
return (a, b, c, d, x, y)

return (a, b, c, d, x, y)

def fmatrix(self, a, b, c, d):
r"""
Expand Down Expand Up @@ -583,7 +580,7 @@ def findcases(self, output=False):
idx_map = {}
ret = {}
id_anyon = self._FR.one()
for (a, b, c, d) in product(self._FR.basis(), repeat=4):
for a, b, c, d in product(self._FR.basis(), repeat=4):
if a == id_anyon or b == id_anyon or c == id_anyon:
continue
for x in self.f_from(a, b, c, d):
Expand All @@ -593,10 +590,8 @@ def findcases(self, output=False):
ret[(a, b, c, d, x, y)] = v
idx_map[i] = (a, b, c, d, x, y)
i += 1
if output:
return idx_map, ret
else:
return i

return (idx_map, ret) if output else i

def f_from(self, a, b, c, d):
r"""
Expand Down Expand Up @@ -649,7 +644,7 @@ def f_to(self, a, b, c, d):
if self._FR.Nk_ij(b, c, y) != 0 and self._FR.Nk_ij(a, y, d) != 0]

####################
### Data getters ###
# Data getters #
####################

def get_fvars(self):
Expand Down Expand Up @@ -855,7 +850,7 @@ def get_radical_expression(self):
return {sextuple: val.radical_expression() for sextuple, val in self.get_fvars_in_alg_field().items()}

#######################
### Private helpers ###
# Private helpers #
#######################

def _get_known_vals(self):
Expand Down Expand Up @@ -894,12 +889,12 @@ def _get_known_nonz(self):
100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100)
"""
nonz = {idx: 100 for idx in self._singles}
for idx, v in self._ks.items():
for idx, _ in self._ks.items():
nonz[idx] = 100
return ETuple(nonz, self._poly_ring.ngens())

##############################
### Variables partitioning ###
# Variables partitioning #
##############################

def largest_fmat_size(self):
Expand Down Expand Up @@ -967,7 +962,7 @@ def get_fvars_by_size(self, n, indices=False):
return var_set

############################
### Checkpoint utilities ###
# Checkpoint utilities #
############################

def save_fvars(self, filename):
Expand Down Expand Up @@ -1009,12 +1004,10 @@ def save_fvars(self, filename):
True
sage: os.remove(filename)
"""
final_state = [
self._fvars,
self._non_cyc_roots,
self.get_coerce_map_from_fr_cyclotomic_field(),
self._qqbar_embedding,
]
final_state = [self._fvars,
self._non_cyc_roots,
self.get_coerce_map_from_fr_cyclotomic_field(),
self._qqbar_embedding]
with open(filename, 'wb') as f:
pickle.dump(final_state, f)

Expand Down Expand Up @@ -1212,7 +1205,7 @@ def _restore_state(self, filename):
self._update_reduction_params()

#################
### MapReduce ###
# MapReduce #
#################

def start_worker_pool(self, processes=None):
Expand Down Expand Up @@ -1275,7 +1268,7 @@ class methods.
self._reset_solver_state()
# Set up shared memory resource handlers
n_proc = cpu_count() if processes is None else processes
self._pid_list = shared_memory.ShareableList([0]*(n_proc+1))
self._pid_list = shared_memory.ShareableList([0] * (n_proc+1))
pids_name = self._pid_list.shm.name
self._solved = shared_memory.ShareableList(self._solved)
s_name = self._solved.shm.name
Expand Down Expand Up @@ -1304,7 +1297,7 @@ def init(fmats_id, solved_name, vd_name, ks_names, fvar_names, n_proc, pids_name
self.pool = Pool(processes=n_proc, initializer=init, initargs=args)
self._pid_list[0] = getpid()
for i, p in enumerate(self.pool._pool):
self._pid_list[i+1] = p.pid
self._pid_list[i + 1] = p.pid
# return True

def shutdown_worker_pool(self):
Expand Down Expand Up @@ -1394,7 +1387,7 @@ def _map_triv_reduce(self, mapper, input_iter, worker_pool=None, chunksize=None,
return results

########################
### Equations set up ###
# Equations set up #
########################

def get_orthogonality_constraints(self, output=True):
Expand Down Expand Up @@ -1494,7 +1487,9 @@ def get_defining_equations(self, option, output=True):
self._reset_solver_state()
n_proc = self.pool._processes if self.pool is not None else 1
params = [(child_id, n_proc, output) for child_id in range(n_proc)]
eqns = self._map_triv_reduce('get_reduced_'+option, params, worker_pool=self.pool, chunksize=1, mp_thresh=0)
eqns = self._map_triv_reduce('get_reduced_' + option, params,
worker_pool=self.pool, chunksize=1,
mp_thresh=0)
if output:
F = self._field
for i, eq_tup in enumerate(eqns):
Expand All @@ -1503,7 +1498,7 @@ def get_defining_equations(self, option, output=True):
self.ideal_basis.extend(eqns)

############################
### Equations processing ###
# Equations processing #
############################

def _tup_to_fpoly(self, eq_tup):
Expand Down Expand Up @@ -1611,7 +1606,7 @@ def _triangular_elim(self, eqns=None, verbose=True):
self.ideal_basis = eqns

#####################
### Graph methods ###
# Graph methods #
#####################

def equations_graph(self, eqns=None):
Expand Down Expand Up @@ -1820,7 +1815,7 @@ def _get_component_variety(self, var, eqns):
return [{inv_idx_map[i]: value for i, (key, value) in enumerate(sorted(soln.items()))} for soln in var_in_R]

#######################
### Solution method ###
# Solution method #
#######################

# TODO: this can probably be improved by constructing a set of defining polynomials
Expand Down Expand Up @@ -1919,7 +1914,7 @@ def _get_explicit_solution(self, eqns=None, verbose=True):
for fx, rhs in self._ks.items():
if not self._solved[fx]:
lt = (ETuple({fx: 2}, n), one)
eqns.append(((lt, (ETuple({}, n), -rhs))))
eqns.append((lt, (ETuple({}, n), -rhs)))
eqns_partition = self._partition_eqns(verbose=verbose)

F = self._field
Expand Down Expand Up @@ -1956,20 +1951,20 @@ def _get_explicit_solution(self, eqns=None, verbose=True):
if self.attempt_number_field_computation():
if verbose:
print("Computing appropriate NumberField...")
roots = [self._FR.field().gen()]+[r[1] for r in non_cyclotomic_roots]
roots = [self._FR.field().gen()] + [r[1] for r in non_cyclotomic_roots]
self._field, bf_elts, self._qqbar_embedding = number_field_elements_from_algebraics(roots, minimal=True)
else:
self._field = QQbar
bf_elts = [self._qqbar_embedding(F.gen())]
bf_elts += [rhs for fx, rhs in non_cyclotomic_roots]
self._qqbar_embedding = lambda x : x
self._qqbar_embedding = lambda x: x
self._non_cyc_roots = bf_elts[1:]

# Embed cyclotomic field into newly constructed base field
cyc_gen_as_bf_elt = bf_elts.pop(0)
phi = self._FR.field().hom([cyc_gen_as_bf_elt], self._field)
self._coerce_map_from_cyc_field = phi
numeric_fvars = {k : phi(v) for k, v in numeric_fvars.items()}
numeric_fvars = {k: phi(v) for k, v in numeric_fvars.items()}
for i, elt in enumerate(bf_elts):
numeric_fvars[non_cyclotomic_roots[i][0]] = elt
# Update polynomial ring
Expand Down Expand Up @@ -2114,7 +2109,7 @@ def find_orthogonal_solution(self, checkpoint=False, save_results="", warm_start
print("Set up {} hex and orthogonality constraints...".format(len(self.ideal_basis)))

# Unzip _fvars and link to shared_memory structure if using multiprocessing
if use_mp:# and loads_shared_memory:
if use_mp: # and loads_shared_memory:
self._fvars = self._shared_fvars
else:
n = self._poly_ring.ngens()
Expand Down Expand Up @@ -2164,12 +2159,12 @@ def find_orthogonal_solution(self, checkpoint=False, save_results="", warm_start
self._chkpt_status = 7
self.clear_equations()
if checkpoint:
remove("fmatrix_solver_checkpoint_"+self.get_fr_str()+".pickle")
remove("fmatrix_solver_checkpoint_" + self.get_fr_str() + ".pickle")
if save_results:
self.save_fvars(save_results)

#########################
### Cyclotomic method ###
# Cyclotomic method #
#########################

def _fix_gauge(self, algorithm=""):
Expand Down Expand Up @@ -2202,8 +2197,8 @@ def _fix_gauge(self, algorithm=""):
break

# Fix var = 1, substitute, and solve equations
self.ideal_basis.add(var-1)
print("adding equation...", var-1)
self.ideal_basis.add(var - 1)
print("adding equation...", var - 1)
self.ideal_basis = set(Ideal(list(self.ideal_basis)).groebner_basis(algorithm=algorithm))
self._substitute_degree_one()
self._update_equations()
Expand Down Expand Up @@ -2336,7 +2331,7 @@ def find_cyclotomic_solution(self, equations=None, algorithm="", verbose=True, o
if equations is None:
if verbose:
print("Setting up hexagons and pentagons...")
equations = self.get_defining_equations("hexagons")+self.get_defining_equations("pentagons")
equations = self.get_defining_equations("hexagons") + self.get_defining_equations("pentagons")
if verbose:
print("Finding a Groebner basis...")
self.ideal_basis = set(Ideal(equations).groebner_basis(algorithm=algorithm))
Expand All @@ -2352,7 +2347,7 @@ def find_cyclotomic_solution(self, equations=None, algorithm="", verbose=True, o
return self._fvars

#####################
### Verifications ###
# Verifications #
#####################

def fmats_are_orthogonal(self):
Expand Down
4 changes: 2 additions & 2 deletions src/sage/algebras/lie_algebras/classical_lie_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,8 +447,8 @@ def __init__(self, R, n):
gens = []
for i in range(n):
for j in range(n):
names.append('E_{0}_{1}'.format(i,j))
mat = MS({(i,j):one})
names.append('E_{}_{}'.format(i, j))
mat = MS({(i, j): one})
mat.set_immutable()
gens.append(mat)
self._n = n
Expand Down
2 changes: 1 addition & 1 deletion src/sage/algebras/lie_algebras/free_lie_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def _repr_(self):
sage: L.Lyndon()
Free Lie algebra generated by (x, y) over Rational Field in the Lyndon basis
"""
return "{0} in the {1} basis".format(self.realization_of(), self._basis_name)
return "{} in the {} basis".format(self.realization_of(), self._basis_name)

def _repr_term(self, x):
"""
Expand Down
6 changes: 4 additions & 2 deletions src/sage/algebras/lie_algebras/heisenberg.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,8 @@ def step(self):
class Element(LieAlgebraElement):
pass

class HeisenbergAlgebra_fd():

class HeisenbergAlgebra_fd:
"""
Common methods for finite-dimensional Heisenberg algebras.
"""
Expand Down Expand Up @@ -417,7 +418,8 @@ def _repr_(self):
sage: lie_algebras.Heisenberg(QQ, 3)
Heisenberg algebra of rank 3 over Rational Field
"""
return "Heisenberg algebra of rank {0} over {1}".format(self._n, self.base_ring())
return "Heisenberg algebra of rank {} over {}".format(self._n, self.base_ring())


class InfiniteHeisenbergAlgebra(HeisenbergAlgebra_abstract, LieAlgebraWithGenerators):
r"""
Expand Down
6 changes: 3 additions & 3 deletions src/sage/algebras/lie_algebras/lie_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,7 @@ def __init__(self, R, names=None, index_set=None, category=None):
LieAlgebraWithGenerators.__init__(self, R, names, index_set, category)
self.__ngens = len(self._indices)

def _repr_(self):
def _repr_(self) -> str:
"""
Return a string representation of ``self``.
Expand All @@ -905,9 +905,9 @@ def _repr_(self):
Lie algebra on 2 generators (x, y) over Rational Field
"""
if self.__ngens == 1:
return "Lie algebra on the generator {0} over {1}".format(
return "Lie algebra on the generator {} over {}".format(
self.gen(0), self.base_ring())
return "Lie algebra on {0} generators {1} over {2}".format(
return "Lie algebra on {} generators {} over {}".format(
self.__ngens, self.gens(), self.base_ring())

@lazy_attribute
Expand Down

0 comments on commit ba78c4e

Please sign in to comment.