Skip to content

Commit

Permalink
gh-37397: fix some ruff suggestions in cluster_algebra_quiver
Browse files Browse the repository at this point in the history
    
this was scripted using `ruff` for the codes `UP` and `C4` in the
cluster folder.

Plus a few hand-made changes about pep8

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: #37397
Reported by: Frédéric Chapoton
Reviewer(s): Travis Scrimshaw
  • Loading branch information
Release Manager committed Feb 21, 2024
2 parents ccd3f8b + 6633a9f commit 5bda2e2
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 54 deletions.
47 changes: 23 additions & 24 deletions src/sage/combinat/cluster_algebra_quiver/cluster_seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ def __init__(self, data, frozen=None, is_principal=False, user_labels=None, user
self._init_exch = dict(islice(self._init_vars.items(), self._n))
self._U = PolynomialRing(QQ, [f'y{i}' for i in range(self._n)])
self._F = {i: self._U(1) for i in self._init_exch.values()}
self._R = PolynomialRing(QQ, [val for val in self._init_vars.values()])
self._R = PolynomialRing(QQ, list(self._init_vars.values()))
self._y = {self._U.gen(j): prod([self._R.gen(i)**self._M[i, j] for i in range(self._n, self._n + self._m)])
for j in range(self._n)}
self._yhat = {self._U.gen(j): prod([self._R.gen(i)**self._M[i, j] for i in range(self._n + self._m)])
Expand Down Expand Up @@ -695,7 +695,7 @@ def use_fpolys(self, use=True, user_labels=None, user_labels_prefix=None):
self._init_exch = dict(islice(self._init_vars.items(), self._n))
self._U = PolynomialRing(QQ, [f'y{i}' for i in range(self._n)])
self._F = {i: self._U(1) for i in self._init_exch.values()}
self._R = PolynomialRing(QQ, [val for val in self._init_vars.values()])
self._R = PolynomialRing(QQ, list(self._init_vars.values()))
self._y = {self._U.gen(j): prod([self._R.gen(i)**self._M[i, j] for i in range(self._n, self._n + self._m)])
for j in range(self._n)}
self._yhat = {self._U.gen(j): prod([self._R.gen(i)**self._M[i, j] for i in range(self._n + self._m)])
Expand Down Expand Up @@ -3556,7 +3556,7 @@ def mutation_class_iter(self, depth=infinity, show_depth=False,
dc += ' ' * (5 - len(dc))
nr = str(len(clusters))
nr += ' ' * (10 - len(nr))
print("Depth: %s found: %s Time: %.2f s" % (dc, nr, timer2 - timer))
print(f"Depth: {dc} found: {nr} Time: {timer2 - timer:.2f} s")

# Each time we get bigger and we haven't hit the full depth
while gets_bigger and depth_counter < depth:
Expand Down Expand Up @@ -3592,11 +3592,11 @@ def mutation_class_iter(self, depth=infinity, show_depth=False,
if only_sink_source:
orbits = list(range(n))
else:
orbits = [index for index in range(n) if index > i or sd2._M[index,i] != 0]
orbits = [index for index in range(n) if index > i or sd2._M[index, i] != 0]

clusters[cl2] = [sd2, orbits, clusters[key][2]+[i]]
if return_paths:
yield (sd2,clusters[cl2][2])
yield (sd2, clusters[cl2][2])
else:
yield sd2
depth_counter += 1
Expand All @@ -3606,7 +3606,7 @@ def mutation_class_iter(self, depth=infinity, show_depth=False,
dc += ' ' * (5-len(dc))
nr = str(len(clusters))
nr += ' ' * (10-len(nr))
print("Depth: %s found: %s Time: %.2f s" % (dc,nr,timer2-timer))
print(f"Depth: {dc} found: {nr} Time: {timer2-timer:.2f} s")

def mutation_class(self, depth=infinity, show_depth=False, return_paths=False,
up_to_equivalence=True, only_sink_source=False):
Expand Down Expand Up @@ -3773,7 +3773,7 @@ def cluster_class(self, depth=infinity, show_depth=False, up_to_equivalence=True
if depth is infinity and not self.is_finite():
raise ValueError('The variable class can - for infinite types - only be computed up to a given depth')

return [c for c in self.cluster_class_iter(depth=depth, show_depth=show_depth, up_to_equivalence=up_to_equivalence)]
return list(self.cluster_class_iter(depth=depth, show_depth=show_depth, up_to_equivalence=up_to_equivalence))

def b_matrix_class_iter(self, depth=infinity, up_to_equivalence=True):
r"""
Expand Down Expand Up @@ -3989,51 +3989,51 @@ def variable_class_iter(self, depth=infinity, ignore_bipartite_belt=False):
(x0^8 + 4*x0^6 + 3*x0^4*x1^2 + 2*x0^2*x1^4 + x1^6 + 6*x0^4 + 6*x0^2*x1^2 + 3*x1^4 + 4*x0^2 + 3*x1^2 + 1)/(x0^3*x1^4)
(x0^6 + 3*x0^4 + 2*x0^2*x1^2 + x1^4 + 3*x0^2 + 2*x1^2 + 1)/(x0^2*x1^3)
"""
mut_iter = self.mutation_class_iter(depth=depth,show_depth=False)
mut_iter = self.mutation_class_iter(depth=depth, show_depth=False)
var_class = set()

for seed in mut_iter:
if seed is self:
seed = ClusterSeed(seed)
if not ignore_bipartite_belt and seed.is_bipartite():
bipartition = seed.is_bipartite(return_bipartition=True)
bipartition = (list(bipartition[0]),list(bipartition[1]))
bipartition = (list(bipartition[0]), list(bipartition[1]))
if depth is not infinity:
print("Found a bipartite seed - restarting the depth counter at zero and constructing the variable class using its bipartite belt.")
depth_counter = 0
end = False
seed2 = ClusterSeed(seed)
for c in seed.cluster():
if c not in var_class:
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable',xdim=seed._n)
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable', xdim=seed._n)
var_class = var_class.union(seed.cluster())

init_cluster = set(seed.cluster())
while not end and depth_counter < depth:
depth_counter += 1
seed.mutate(bipartition[0])
seed.mutate(bipartition[1])
if set(seed.cluster()) in [set(seed2.cluster()),init_cluster]:
if set(seed.cluster()) in [set(seed2.cluster()), init_cluster]:
end = True
if not end:
for c in seed.cluster():
if c not in var_class:
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable',xdim=seed._n)
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable', xdim=seed._n)
var_class = var_class.union(seed.cluster())
seed2.mutate(bipartition[1])
seed2.mutate(bipartition[0])
if set(seed2.cluster()) in [set(seed.cluster()),init_cluster]:
if set(seed2.cluster()) in [set(seed.cluster()), init_cluster]:
end = True
if not end:
for c in seed2.cluster():
if c not in var_class:
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable',xdim=seed._n)
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable', xdim=seed._n)
var_class = var_class.union(seed2.cluster())
return
else:
for c in seed.cluster():
if c not in var_class:
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable',xdim=seed._n)
yield ClusterVariable(FractionField(seed._R), c.numerator(), c.denominator(), mutation_type=self._mutation_type, variable_type='cluster variable', xdim=seed._n)
var_class = var_class.union(seed.cluster())

def variable_class(self, depth=infinity, ignore_bipartite_belt=False):
Expand Down Expand Up @@ -4120,7 +4120,7 @@ def is_mutation_finite(self, nr_of_checks=None, return_path=False):
sage: S.is_mutation_finite()
False
"""
is_finite, path = is_mutation_finite(copy(self._M),nr_of_checks=nr_of_checks)
is_finite, path = is_mutation_finite(copy(self._M), nr_of_checks=nr_of_checks)
if return_path:
return is_finite, path
else:
Expand Down Expand Up @@ -4403,8 +4403,8 @@ def find_upper_bound(self, verbose=False):
"""
rank = self.n()

xvars = ['x{}'.format(t) for t in range(rank)]
xpvars = ['x{}p'.format(t) for t in range(rank)]
xvars = [f'x{t}' for t in range(rank)]
xpvars = [f'x{t}p' for t in range(rank)]
gens = xvars + xpvars
initial_product = '*'.join(g for g in xvars)

Expand All @@ -4418,8 +4418,7 @@ def find_upper_bound(self, verbose=False):
for s in range(rank))
deep_gens += [neighbor_product]

rels = ["-{}*{}+{}".format(gens[t], gens[t + rank],
lower_var[t + rank].numerator())
rels = [f"-{gens[t]}*{gens[t + rank]}+{lower_var[t + rank].numerator()}"
for t in range(rank)]

while True:
Expand Down Expand Up @@ -4509,9 +4508,9 @@ def get_upper_cluster_algebra_element(self, a):
if len(a) != B.ncols():
raise ValueError('The length of the input vector must be the same as the number of columns of B.')
# Runs helper functions.
v = _vector_decomposition(a,B.nrows())
v = _vector_decomposition(a, B.nrows())
c = self._compute_compatible_vectors(v)
return self._produce_upper_cluster_algebra_element(v,c)
return self._produce_upper_cluster_algebra_element(v, c)

def LLM_gen_set(self, size_limit=-1):
r"""
Expand Down Expand Up @@ -4793,7 +4792,7 @@ def PathSubset(n, m):
sage: PathSubset(4,4)
{0, 1, 2, 3, 4, 5, 6, 7}
"""
S = set(2 * i + 1 for i in range(n))
S = {2 * i + 1 for i in range(n)}
if m > 0:
for j in range(n):
if ((j+1)*m) // n - (j*m) // n == 1:
Expand Down Expand Up @@ -4831,7 +4830,7 @@ def SetToPath(T):
return ans


def is_LeeLiZel_allowable(T,n,m,b,c):
def is_LeeLiZel_allowable(T, n, m, b, c):
"""
Check if the subset `T` contributes to the computation of the greedy element `x[m,n]` in the rank two `(b,c)`-cluster algebra.
Expand Down
40 changes: 20 additions & 20 deletions src/sage/combinat/cluster_algebra_quiver/mutation_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ def _digraph_mutate(dg, k, frozen=None):
edge_it = dg.incoming_edge_iterator(dg, True)
edges = {(v1, v2): label for v1, v2, label in edge_it}
edge_it = dg.incoming_edge_iterator([k], True)
in_edges = [(v1, v2, label) for v1, v2, label in edge_it]
in_edges = list(edge_it)
edge_it = dg.outgoing_edge_iterator([k], True)
out_edges = [(v1, v2, label) for v1, v2, label in edge_it]
out_edges = list(edge_it)

in_edges_new = [(v2, v1, (-label[1], -label[0]))
for (v1, v2, label) in in_edges]
Expand Down Expand Up @@ -151,7 +151,7 @@ def _digraph_mutate(dg, k, frozen=None):
return dg_new


def _matrix_to_digraph( M ):
def _matrix_to_digraph(M):
"""
Return the digraph obtained from the matrix ``M``.
Expand All @@ -166,15 +166,15 @@ def _matrix_to_digraph( M ):
n = M.ncols()

dg = DiGraph(sparse=True)
for i,j in M.nonzero_positions():
for i, j in M.nonzero_positions():
if i >= n:
a, b = M[i, j], -M[i, j]
else:
a, b = M[i, j], M[j, i]
if a > 0:
dg._backend.add_edge(i,j,(a,b),True)
dg._backend.add_edge(i, j, (a, b), True)
elif i >= n:
dg._backend.add_edge(j,i,(-a,-b),True)
dg._backend.add_edge(j, i, (-a, -b), True)
for i in range(M.nrows()):
if i not in dg:
dg.add_vertex(i)
Expand Down Expand Up @@ -310,7 +310,7 @@ def _mutation_class_iter( dg, n, m, depth=infinity, return_dig6=False, show_dept
depth_counter = 0
if up_to_equivalence:
iso, orbits = _dg_canonical_form( dg, mlist )
iso_inv = dict( (iso[a],a) for a in iso )
iso_inv = { iso[a]: a for a in iso }

dig6 = _digraph_to_dig6( dg, hashable=True )
dig6s = {}
Expand All @@ -328,10 +328,10 @@ def _mutation_class_iter( dg, n, m, depth=infinity, return_dig6=False, show_dept
if show_depth:
timer2 = time.time()
dc = str(depth_counter)
dc += ' ' * (5-len(dc))
dc += ' ' * (5 - len(dc))
nr = str(len(dig6s))
nr += ' ' * (10-len(nr))
print("Depth: %s found: %s Time: %.2f s" % (dc, nr, timer2 - timer))
nr += ' ' * (10 - len(nr))
print(f"Depth: {dc} found: {nr} Time: {timer2 - timer:.2f} s")

while gets_bigger and depth_counter < depth:
gets_bigger = False
Expand All @@ -346,7 +346,7 @@ def _mutation_class_iter( dg, n, m, depth=infinity, return_dig6=False, show_dept
if up_to_equivalence:
iso, orbits = _dg_canonical_form( dg_new, mlist )
i_new = iso[i]
iso_inv = dict( (iso[a],a) for a in iso )
iso_inv = { iso[a]: a for a in iso }
else:
i_new = i
dig6_new = _digraph_to_dig6( dg_new, hashable=True )
Expand All @@ -357,7 +357,7 @@ def _mutation_class_iter( dg, n, m, depth=infinity, return_dig6=False, show_dept
gets_bigger = True
if up_to_equivalence:
orbits = [ orbit[0] for orbit in orbits if i_new not in orbit ]
iso_history = dict( (a, dig6s[key][2][iso_inv[a]]) for a in iso )
iso_history = { a: dig6s[key][2][iso_inv[a]] for a in iso }
i_history = iso_history[i_new]
history = dig6s[key][1] + [i_history]
dig6s[dig6_new] = [orbits,history,iso_history]
Expand All @@ -374,13 +374,13 @@ def _mutation_class_iter( dg, n, m, depth=infinity, return_dig6=False, show_dept
if show_depth and gets_bigger:
timer2 = time.time()
dc = str(depth_counter)
dc += ' ' * (5-len(dc))
dc += ' ' * (5 - len(dc))
nr = str(len(dig6s))
nr += ' ' * (10-len(nr))
print("Depth: %s found: %s Time: %.2f s" % (dc, nr, timer2 - timer))
nr += ' ' * (10 - len(nr))
print(f"Depth: {dc} found: {nr} Time: {timer2 - timer:.2f} s")


def _digraph_to_dig6( dg, hashable=False ):
def _digraph_to_dig6(dg, hashable=False):
"""
Return the dig6 and edge data of the digraph dg.
Expand Down Expand Up @@ -487,8 +487,8 @@ def _dg_is_sink_source( dg, v ):
sage: _dg_is_sink_source(dg, 2)
False
"""
in_edges = [ edge for edge in dg._backend.iterator_in_edges([v],True) ]
out_edges = [ edge for edge in dg._backend.iterator_out_edges([v],True) ]
in_edges = list(dg._backend.iterator_in_edges([v],True))
out_edges = list(dg._backend.iterator_out_edges([v],True))
return not ( in_edges and out_edges )


Expand All @@ -515,8 +515,8 @@ def _graph_without_edge_labels(dg, vertices):
"""
vertices = list(vertices)
edges = dg.edge_iterator(labels=True)
edge_labels = tuple(sorted(set(label for _, _, label in edges
if label != (1, -1))))
edge_labels = tuple(sorted({label for _, _, label in edges
if label != (1, -1)}))
edge_partition = [[] for _ in edge_labels]
i = 0
while i in vertices:
Expand Down
18 changes: 9 additions & 9 deletions src/sage/combinat/cluster_algebra_quiver/quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ def __init__(self, data, frozen=None, user_labels=None):
user_labels = [tuple(x) if isinstance(x, list) else x for x in user_labels]
elif isinstance(user_labels, dict):
values = [tuple(user_labels[x]) if isinstance(user_labels[x], list) else user_labels[x] for x in user_labels]
user_labels = {key: val for key, val in zip(user_labels.keys(),
values)}
user_labels = dict(zip(user_labels.keys(),
values))

# constructs a quiver from a mutation type
if type( data ) in [QuiverMutationType_Irreducible,QuiverMutationType_Reducible]:
Expand Down Expand Up @@ -635,10 +635,10 @@ def _graphs_concentric_circles(n, m):
'lightgreen': partition[2]}

options = {
'graph_border' : True,
'graph_border': True,
'edge_colors': color_dict,
'vertex_colors': vertex_color_dict,
'edge_labels' : True,
'edge_labels': True,
'vertex_labels': True,
}
if circular:
Expand Down Expand Up @@ -1854,11 +1854,11 @@ def mutation_class(self, depth=infinity, show_depth=False, return_paths=False,
if depth is infinity and not self.is_mutation_finite():
raise ValueError('the mutation class can - for infinite mutation'
' types - only be computed up to a given depth')
return [Q for Q in self.mutation_class_iter(depth=depth, show_depth=show_depth,
return_paths=return_paths,
data_type=data_type,
up_to_equivalence=up_to_equivalence,
sink_source=sink_source)]
return list(self.mutation_class_iter(depth=depth, show_depth=show_depth,
return_paths=return_paths,
data_type=data_type,
up_to_equivalence=up_to_equivalence,
sink_source=sink_source))

def is_finite(self):
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1686,7 +1686,7 @@ def irreducible_components(self):
sage: mut_type.irreducible_components()
(['A', 3],)
"""
return tuple([self])
return (self,)

@cached_method
def class_size(self):
Expand Down

0 comments on commit 5bda2e2

Please sign in to comment.