Skip to content

Commit

Permalink
sagemathgh-38903: a few details in combinat, following ruff and pycod…
Browse files Browse the repository at this point in the history
…estyle

    
just fixing a few ruff PERF suggestions in 4 files

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [ ] I have linked a relevant issue or discussion.
- [ ] I have created tests covering the changes.
- [ ] I have updated the documentation and checked the documentation
preview.
    
URL: sagemath#38903
Reported by: Frédéric Chapoton
Reviewer(s): Frédéric Chapoton, Martin Rubey, Travis Scrimshaw, Vincent Macri
  • Loading branch information
Release Manager committed Nov 13, 2024
2 parents 2a14c7f + 826f34f commit 0e473f3
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 73 deletions.
63 changes: 30 additions & 33 deletions src/sage/combinat/rigged_configurations/kleber_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,11 @@ def _draw_tree(tree_node, node_label=True, style_point=None, style_node='fill=wh
start = [0., 0.]
if rpos is None:
rpos = [0., 0.]
draw_point = lambda point: '(%.3f, %.3f)' % (point[0],point[1])

if not tree_node.children:
r = ''
node_name = node_prefix + str(node_id)
r = "\\node (%s) at %s" % (node_name, draw_point(start))
r = "\\node (%s) at (%.3f, %.3f)" % (node_name, *start)
if node_label:
r += "{$%s$};\n" % tree_node._latex_()
else:
Expand All @@ -149,7 +149,7 @@ def _draw_tree(tree_node, node_label=True, style_point=None, style_node='fill=wh
nb_children = len(tree_node.children)
half = nb_children // 2
children_str = ''
pos = [start[0],start[1]]
pos = [start[0], start[1]]
start[1] += vspace
lines_str = ''

Expand Down Expand Up @@ -184,7 +184,7 @@ def _draw_tree(tree_node, node_label=True, style_point=None, style_node='fill=wh
rpos[0] = pos[0]
rpos[1] = pos[1]
point_str = ''
node_str = "\\node%s (%s) at %s" % (style_node, node_name, draw_point(pos))
node_str = "\\node%s (%s) at (%.3f, %.3f)" % (style_node, node_name, *pos)
if node_label:
node_str += "{$%s$};\n" % tree_node._latex_()
else:
Expand Down Expand Up @@ -269,7 +269,7 @@ def depth(self):
sage: n2.depth
1
"""
depth = -1 # Offset
depth = -1 # Offset
cur = self
while cur is not None:
depth += 1
Expand Down Expand Up @@ -337,7 +337,7 @@ def multiplicity(self):
mult = Integer(1)
for a, m in self.up_root:
p = self.weight[a]
for r,s in self.parent().B:
for r, s in self.parent().B:
if r == a and s > self.depth:
p -= s - self.depth
mult *= binomial(m + p, m)
Expand All @@ -346,7 +346,7 @@ def multiplicity(self):
cur = self.parent_node
while cur.parent_node is not None:
root_diff = cur.up_root - prev_up_root
for a,m in root_diff:
for a, m in root_diff:
p = cur.weight[a]
for r, s in self.parent().B:
if r == a and s > cur.depth:
Expand Down Expand Up @@ -636,7 +636,8 @@ def __init__(self, cartan_type, B, classical_ct):
self._CM = self._classical_ct.cartan_matrix().dense_matrix()
self._build_tree()
self._latex_options = dict(edge_labels=True, use_vector_notation=False,
hspace=2.5, vspace=min(-2.5, -0.75*self._classical_ct.rank()))
hspace=2.5,
vspace=min(-2.5, -0.75*self._classical_ct.rank()))

def latex_options(self, **options):
"""
Expand Down Expand Up @@ -705,21 +706,19 @@ def _build_tree(self):
# Create an empty node at first step
self.root = KleberTreeNode(self, P.zero(),
self._classical_ct.root_system().root_lattice().zero())
full_list = [self.root] # The list of tree nodes
full_list = [self.root] # The list of tree nodes

n = self._classical_ct.rank()

# Convert the B values into an L matrix
L = []
I = self._classical_ct.index_set()
for i in range(n):
L.append([0])
L = [[0] for _ in range(n)]

for r,s in self.B:
while len(L[0]) < s: # Add more columns if needed
for r, s in self.B:
while len(L[0]) < s: # Add more columns if needed
for row in L:
row.append(0)
L[I.index(r)][s - 1] += 1 # The -1 is for indexing
L[I.index(r)][s - 1] += 1 # The -1 is for indexing

# Perform a special case of the algorithm for the root node
weight_basis = P.basis()
Expand Down Expand Up @@ -751,7 +750,7 @@ def _build_tree(self):
for x in full_list:
growth = True
for a in range(n):
for i in range(depth - 1, len(L[a])): # Subtract 1 for indexing
for i in range(depth - 1, len(L[a])): # Subtract 1 for indexing
x.weight += L[a][i] * weight_basis[I[a]]

new_children = [new_child
Expand Down Expand Up @@ -824,16 +823,16 @@ def _children_iter(self, node):
# Construct the shifted weight cone
root_weight = node.weight.to_vector()
ieqs = [[root_weight[i]] + list(col)
for i,col in enumerate(self._CM.columns())]
for i, col in enumerate(self._CM.columns())]
# Construct the negative weight cone
for i in range(n):
v = [0] * (n+1)
v[i+1] = -1
ieqs.append(v)
ieqs.append([-1]*(n+1)) # For avoiding the origin
ieqs.append([-1]*(n+1)) # For avoiding the origin
# Construct the bounds for the non-root nodes
if node != self.root:
for i,c in enumerate(node.up_root.to_vector()):
for i, c in enumerate(node.up_root.to_vector()):
v = [0] * (n+1)
v[0] = c
v[i+1] = 1
Expand All @@ -849,9 +848,9 @@ def _children_iter(self, node):
# Build the nodes from the polytope
# Sort for a consistent ordering (it is typically a small list)
for pt in sorted(poly.integral_points(), reverse=True):
up_root = Q._from_dict({I[i]: -val for i,val in enumerate(pt) if val != 0},
up_root = Q._from_dict({I[i]: -val for i, val in enumerate(pt) if val != 0},
remove_zeros=False)
wt = node.weight + sum(val * P.simple_root(I[i]) for i,val in enumerate(pt))
wt = node.weight + sum(val * P.simple_root(I[i]) for i, val in enumerate(pt))
yield KleberTreeNode(self, wt, up_root, node)

def _children_iter_vector(self, node):
Expand Down Expand Up @@ -895,9 +894,9 @@ def _children_iter_vector(self, node):
converted_root = sum(cols[i] * c for i, c in enumerate(root)
if c != 0)

if all(wt[i] >= val for i,val in enumerate(converted_root)):
wd = {I[i]: wt[i] - val for i,val in enumerate(converted_root)}
rd = {I[i]: val for i,val in enumerate(root) if val != 0}
if all(wt[i] >= val for i, val in enumerate(converted_root)):
wd = {I[i]: wt[i] - val for i, val in enumerate(converted_root)}
rd = {I[i]: val for i, val in enumerate(root) if val != 0}
yield KleberTreeNode(self,
P._from_dict(wd),
Q._from_dict(rd, remove_zeros=False),
Expand Down Expand Up @@ -1171,14 +1170,12 @@ def __init__(self, cartan_type, B):
sage: TestSuite(KT).run(skip='_test_elements')
"""
self._folded_ct = cartan_type.as_folding()
virtual_dims = []
self.base_dims = B
sigma = self._folded_ct.folding_orbit()
gamma = self._folded_ct.scaling_factors()
classical_ct = self._folded_ct.folding_of().classical()
for r,s in B:
for i in sigma[r]:
virtual_dims.append([i, s * gamma[r]])
virtual_dims = [[i, s * gamma[r]]
for r, s in B for i in sigma[r]]

KleberTree.__init__(self, cartan_type, virtual_dims, classical_ct)

Expand Down Expand Up @@ -1229,8 +1226,9 @@ def _prune(self, new_child, depth):
return True
gamma = self._folded_ct.scaling_factors()
for a in range(1, len(gamma)):
if (depth - 1) % gamma[a] != 0 and new_child.up_root[sigma[a][0]] \
!= new_child.parent_node.up_root[sigma[a][0]]:
s = sigma[a][0]
if ((depth - 1) % gamma[a] != 0 and
new_child.up_root[s] != new_child.parent_node.up_root[s]):
return True
return False

Expand Down Expand Up @@ -1371,12 +1369,11 @@ def __init__(self, cartan_type, B):
self.base_dims = B
sigma = self._folded_ct.folding_orbit()
classical_ct = self._folded_ct.folding_of().classical()
for r,s in B:
for r, s in B:
if r == n:
virtual_dims.extend([[n, s], [n, s]])
else:
for i in sigma[r]:
virtual_dims.append([i, s])
virtual_dims.extend([i, s] for i in sigma[r])

KleberTree.__init__(self, cartan_type, virtual_dims, classical_ct)

Expand Down
32 changes: 13 additions & 19 deletions src/sage/combinat/tableau.py
Original file line number Diff line number Diff line change
Expand Up @@ -2055,14 +2055,14 @@ def k_weight(self, k):
w = self.weight()
s = self.cells()

for l in range(1, len(w)+1):
for l in range(1, len(w) + 1):
new_s = [(i, j) for i, j in s if self[i][j] == l]

# If there are no elements that meet the condition
if new_s == []:
if not new_s:
res.append(0)
continue
x = set((i-j) % (k+1) for i, j in new_s)
x = {(i - j) % (k + 1) for i, j in new_s}
res.append(len(x))

return res
Expand Down Expand Up @@ -2955,9 +2955,8 @@ def row_stabilizer(self):
# tableau, by including the identity permutation on the set [1..k].
k = self.size()
gens = [list(range(1, k + 1))]
for row in self:
for j in range(len(row) - 1):
gens.append((row[j], row[j + 1]))
gens.extend((row[j], row[j + 1])
for row in self for j in range(len(row) - 1))
return PermutationGroup(gens)

def column_stabilizer(self):
Expand Down Expand Up @@ -7675,9 +7674,9 @@ def __contains__(self, x):
"""
if isinstance(x, StandardTableau):
return True
elif Tableaux.__contains__(self, x):
if Tableaux.__contains__(self, x):
flatx = sorted(c for row in x for c in row)
return flatx == list(range(1, len(flatx)+1)) and (len(x) == 0 or
return all(i == fi for i, fi in enumerate(flatx, start=1)) and (len(x) == 0 or
(all(row[i] < row[i+1] for row in x for i in range(len(row)-1)) and
all(x[r][c] < x[r+1][c] for r in range(len(x)-1)
for c in range(len(x[r+1])))
Expand Down Expand Up @@ -8183,25 +8182,20 @@ def random_element(self):
t = [[None] * n for n in p]

# Get the cells in the Young diagram
cells = []
for i in range(len(p)):
for j in range(p[i]):
cells.append((i, j))
cells = [(i, j) for i in range(len(p)) for j in range(p[i])]

m = sum(p)
while m > 0:
while m:
# Choose a cell at random
cell = random.choice(cells)

# Find a corner
inner_corners = p.corners()
while cell not in inner_corners:
hooks = []
for k in range(cell[1] + 1, p[cell[0]]):
hooks.append((cell[0], k))
for k in range(cell[0] + 1, len(p)):
if p[k] > cell[1]:
hooks.append((k, cell[1]))
c0, c1 = cell
hooks = [(c0, k) for k in range(c1 + 1, p[c0])]
hooks.extend((k, c1)
for k in range(c0 + 1, len(p)) if p[k] > c1)
cell = random.choice(hooks)

# Assign m to cell
Expand Down
31 changes: 15 additions & 16 deletions src/sage/combinat/words/finite_word.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,10 +511,10 @@ def fcn(n):
length = exp * self.length()
if length in ZZ and length >= 0:
return self._parent(fcn, length=length)
else:
raise ValueError("Power of the word is not defined on the exponent {}:"
" the length of the word ({}) times the exponent ({}) must"
" be a positive integer".format(exp, self.length(), exp))

raise ValueError("Power of the word is not defined on the exponent {}: "
"the length of the word ({}) times the exponent ({}) must "
"be a positive integer".format(exp, self.length(), exp))

def length(self):
r"""
Expand Down Expand Up @@ -4153,8 +4153,7 @@ def last_position_dict(self):
{'1': 3, '2': 6, '3': 5}
"""
d = {}
for i, letter in enumerate(self):
d[letter] = i
d.update((letter, i) for i, letter in enumerate(self))
return d

def _pos_in(self, other, p):
Expand Down Expand Up @@ -4191,7 +4190,7 @@ def _pos_in(self, other, p):
"""
from sage.misc.superseded import deprecation
deprecation(30187, 'f._pos_in(w, start) is deprecated.'
' Use w.first_occurrence(f, start) instead.')
' Use w.first_occurrence(f, start) instead.')
return other.first_occurrence(self, p)

def first_pos_in(self, other):
Expand Down Expand Up @@ -4219,7 +4218,7 @@ def first_pos_in(self, other):
"""
from sage.misc.superseded import deprecation
deprecation(30187, 'f.first_pos_in(w) is deprecated.'
' Use w.first_occurrence(f) instead.')
' Use w.first_occurrence(f) instead.')
return other.first_occurrence(self)

def find(self, sub, start=0, end=None):
Expand Down Expand Up @@ -4440,7 +4439,7 @@ def factor_occurrences_in(self, other):
"""
from sage.misc.superseded import deprecation
deprecation(30187, 'f.factor_occurrences_in(w) is deprecated.'
' Use w.factor_occurrences_iterator(f) instead.')
' Use w.factor_occurrences_iterator(f) instead.')
return other.factor_occurrences_iterator(self)

def nb_factor_occurrences_in(self, other):
Expand Down Expand Up @@ -4475,7 +4474,7 @@ def nb_factor_occurrences_in(self, other):
"""
from sage.misc.superseded import deprecation
deprecation(30187, 'f.nb_factor_occurrences_in(w) is deprecated.'
' Use w.number_of_factor_occurrences(f) instead.')
' Use w.number_of_factor_occurrences(f) instead.')
return other.number_of_factor_occurrences(self)

def nb_subword_occurrences_in(self, other):
Expand Down Expand Up @@ -4544,7 +4543,7 @@ def nb_subword_occurrences_in(self, other):
"""
from sage.misc.superseded import deprecation
deprecation(30187, 'f.nb_subword_occurrences_in(w) is deprecated.'
' Use w.number_of_subword_occurrences(f) instead.')
' Use w.number_of_subword_occurrences(f) instead.')
return other.number_of_subword_occurrences(self)

def number_of_factor_occurrences(self, other):
Expand Down Expand Up @@ -5675,7 +5674,7 @@ def abelian_vectors(self, n):
size = alphabet.cardinality()
if size == float('inf'):
raise TypeError("The alphabet of the parent is infinite; define"
" the word with a parent on a finite alphabet")
" the word with a parent on a finite alphabet")
S = set()
if n > self.length():
return S
Expand Down Expand Up @@ -6105,8 +6104,8 @@ def abelian_vector(self):
alphabet = self.parent().alphabet()
if alphabet.cardinality() is Infinity:
raise TypeError("The alphabet of the parent is infinite; define "
"the word with a parent on a finite alphabet or use "
"evaluation_dict() instead")
"the word with a parent on a finite alphabet "
"or use evaluation_dict() instead")
ev_dict = self.evaluation_dict()
return [ev_dict.get(a, 0) for a in alphabet]

Expand Down Expand Up @@ -6803,8 +6802,8 @@ def colored_vector(self, x=0, y=0, width='default', height=1, cmap='hsv', thickn
else:
ordered_alphabet = self.parent().alphabet()
dim = float(self.parent().alphabet().cardinality())
letter_to_integer_dict = {a: i for i, a in
enumerate(ordered_alphabet)}
letter_to_integer_dict = {a: i
for i, a in enumerate(ordered_alphabet)}
xp = x
for a in self:
i = letter_to_integer_dict[a]
Expand Down
9 changes: 4 additions & 5 deletions src/sage/combinat/words/morphism.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,8 +1048,7 @@ def extend_by(self, other):
raise TypeError("other (=%s) is not a WordMorphism" % other)

nv = dict(other._morph)
for k, v in self._morph.items():
nv[k] = v
nv.update(self._morph)
return WordMorphism(nv)

def restrict_domain(self, alphabet):
Expand Down Expand Up @@ -2467,9 +2466,9 @@ def dual_map(self, k=1):
if k == 1:
from sage.combinat.e_one_star import E1Star
return E1Star(self)
else:
raise NotImplementedError("the dual map E_k^*" +
" is implemented only for k = 1 (not %s)" % k)

raise NotImplementedError("the dual map E_k^* is implemented only "
"for k = 1 (not %s)" % k)

@cached_method
def rauzy_fractal_projection(self, eig=None, prec=53):
Expand Down

0 comments on commit 0e473f3

Please sign in to comment.