Skip to content

Commit

Permalink
gh-37144: Minor ruff fixes in posets
Browse files Browse the repository at this point in the history
    
This is fixing a few of `ruff` suggestions (UP and PERF and ANN) in
posets.

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: #37144
Reported by: Frédéric Chapoton
Reviewer(s): Alex J Best
  • Loading branch information
Release Manager committed Feb 1, 2024
2 parents 203431c + b41465d commit 27448fe
Show file tree
Hide file tree
Showing 10 changed files with 129 additions and 126 deletions.
4 changes: 2 additions & 2 deletions src/sage/combinat/posets/cartesian_product.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class CartesianProductPoset(CartesianProduct):
:class:`CartesianProduct`
"""

def __init__(self, sets, category, order=None, **kwargs):
def __init__(self, sets, category, order=None, **kwargs) -> None:
r"""
See :class:`CartesianProductPoset` for details.
Expand All @@ -102,7 +102,7 @@ def __init__(self, sets, category, order=None, **kwargs):
try:
self._le_ = getattr(self, 'le_' + order)
except AttributeError:
raise ValueError("no order '%s' known" % (order,))
raise ValueError(f"no order '{order}' known")
else:
self._le_ = order

Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/posets/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

class PosetElement(Element):

def __init__(self, poset, element, vertex):
def __init__(self, poset, element, vertex) -> None:
r"""
Establish the parent-child relationship between ``poset``
and ``element``, where ``element`` is associated to the
Expand Down
69 changes: 33 additions & 36 deletions src/sage/combinat/posets/hasse_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class LatticeError(ValueError):
a and b" instead of "No meet for 1 and 2".
"""

def __init__(self, fail, x, y):
def __init__(self, fail, x, y) -> None:
"""
Initialize the exception.
Expand All @@ -56,7 +56,7 @@ def __init__(self, fail, x, y):
self.x = x
self.y = y

def __str__(self):
def __str__(self) -> str:
"""
Return string representation of the exception.
Expand All @@ -67,7 +67,7 @@ def __str__(self):
sage: error.__str__()
'no meet for 15 and 18'
"""
return "no {} for {} and {}".format(self.fail, self.x, self.y)
return f"no {self.fail} for {self.x} and {self.y}"


class HasseDiagram(DiGraph):
Expand Down Expand Up @@ -792,8 +792,8 @@ def _rank(self):
while not_found:
y = not_found.pop()
rank[y] = 0 # We set some vertex to have rank 0
component = set([y])
queue = set([y])
component = {y}
queue = {y}
while queue:
# look at the neighbors of y and set the ranks;
# then look at the neighbors of the neighbors ...
Expand Down Expand Up @@ -1109,11 +1109,11 @@ def moebius_function_matrix(self, algorithm='cython'):
m[(i, k)] = -ZZ.sum(m[(j, k)]
for j in available
if k in greater_than[j])
M = matrix(ZZ, n, n, m, sparse=True)
M = matrix(ZZ, n, n, m, sparse=True) # noqa: F821
elif algorithm == "matrix":
M = self.lequal_matrix().inverse_of_unit()
elif algorithm == "cython":
M = moebius_matrix_fast(self._leq_storage)
M = moebius_matrix_fast(self._leq_storage) # noqa: F821
else:
raise ValueError("unknown algorithm")
self._moebius_function_matrix = M
Expand Down Expand Up @@ -1187,7 +1187,7 @@ def coxeter_transformation(self, algorithm='cython'):
if algorithm == 'matrix':
return - self.lequal_matrix() * self.moebius_function_matrix().transpose()
elif algorithm == 'cython':
return coxeter_matrix_fast(self._leq_storage)
return coxeter_matrix_fast(self._leq_storage) # noqa: F821
else:
raise ValueError("unknown algorithm")

Expand Down Expand Up @@ -1286,7 +1286,7 @@ def _leq_storage(self):
[{0, 1, 2, 3, 4, 5, 6}, {1, 6}, {2, 6}, {3, 6}, {4, 6}, {5, 6}, {6}]
"""
n = self.order()
greater_than = [set([i]) for i in range(n)]
greater_than = [{i} for i in range(n)]
for i in range(n - 1, -1, -1):
gt = greater_than[i]
for j in self.neighbor_out_iterator(i):
Expand Down Expand Up @@ -1324,11 +1324,11 @@ def _leq_matrix_boolean(self):
Finite Field of size 2
"""
n = self.order()
R = GF(2)
R = GF(2) # noqa: F821
one = R.one()
greater_than = self._leq_storage
D = {(i, j): one for i in range(n) for j in greater_than[i]}
M = matrix(R, n, n, D, sparse=True)
M = matrix(R, n, n, D, sparse=True) # noqa: F821
M.set_immutable()
return M

Expand Down Expand Up @@ -1359,7 +1359,7 @@ def _leq_matrix(self):
n = self.order()
greater_than = self._leq_storage
D = {(i, j): 1 for i in range(n) for j in greater_than[i]}
return matrix(ZZ, n, n, D, sparse=True, immutable=True)
return matrix(ZZ, n, n, D, sparse=True, immutable=True) # noqa: F821

def lequal_matrix(self, boolean=False):
r"""
Expand Down Expand Up @@ -1544,7 +1544,7 @@ def _meet(self):
self._meet_semilattice_failure = ()
n = self.cardinality()
if n == 0:
return matrix(0)
return matrix(0) # noqa: F821
meet = [[-1 for x in range(n)] for x in range(n)]
lc = [self.neighbors_in(x) for x in range(n)] # Lc = lower covers

Expand All @@ -1564,7 +1564,7 @@ def _meet(self):
meet[y][x] = q
if q == -1:
self._meet_semilattice_failure += ((x, y),)
return matrix(ZZ, meet)
return matrix(ZZ, meet) # noqa: F821

def meet_matrix(self):
r"""
Expand Down Expand Up @@ -1708,7 +1708,7 @@ def _join(self):
self._join_semilattice_failure = ()
n = self.cardinality()
if n == 0:
return matrix(0)
return matrix(0) # noqa: F821
join = [[-1 for x in range(n)] for x in range(n)]
uc = [self.neighbors_out(x) for x in range(n)] # uc = upper covers

Expand All @@ -1729,7 +1729,7 @@ def _join(self):
if q == -1:
self._join_semilattice_failure += ((x, y),)

return matrix(ZZ, join)
return matrix(ZZ, join) # noqa: F821

def join_matrix(self):
r"""
Expand Down Expand Up @@ -1857,9 +1857,8 @@ def find_nonsemidistributive_elements(self, meet_or_join):
for x in range(n):
u = M1[e, x]
for y in range(x):
if u == M1[e, y]:
if u != M1[e, M2[x, y]]:
return (u, e, x, y)
if u == M1[e, y] and u != M1[e, M2[x, y]]:
return (u, e, x, y)

return None

Expand Down Expand Up @@ -2151,9 +2150,8 @@ def recursive_fit(orthocomplements, unbinded):
# Every element might have one possible orthocomplement,
# but so that they don't fit together. Must check that.
for lc in self.lower_covers_iterator(e):
if start[lc] is not None:
if not self.has_edge(e_, start[lc]):
return
if not (start[lc] is None or self.has_edge(e_, start[lc])):
return
if start[e_] is None:
start[e] = e_
start[e_] = e
Expand Down Expand Up @@ -2191,10 +2189,7 @@ def find_nonsemimodular_pair(self, upper):
sage: H_.find_nonsemimodular_pair(upper=False) is None
True
"""
if upper:
neighbors = self.neighbors_out
else:
neighbors = self.neighbors_in
neighbors = self.neighbors_out if upper else self.neighbors_in

n = self.order()
for e in range(n):
Expand Down Expand Up @@ -2481,7 +2476,7 @@ def is_linear_interval(self, t_min, t_max) -> bool:
return True
return False

def diamonds(self):
def diamonds(self) -> tuple:
r"""
Return the list of diamonds of ``self``.
Expand Down Expand Up @@ -2525,8 +2520,7 @@ def diamonds(self):
zs = self.common_upper_covers([x, y])
if len(zs) != 1:
all_diamonds_completed = False
for z in zs:
diamonds.append((w, x, y, z))
diamonds.extend((w, x, y, z) for z in zs)
return (diamonds, all_diamonds_completed)

def common_upper_covers(self, vertices):
Expand Down Expand Up @@ -2651,7 +2645,7 @@ def sublattices_iterator(self, elms, min_e):
if e in elms:
continue
current_set = set(elms)
gens = set([e])
gens = {e}
while gens:
g = gens.pop()
if g < e and g not in elms:
Expand Down Expand Up @@ -2684,7 +2678,7 @@ def sublattice(elms, e):
Helper function to get sublattice generated by list
of elements.
"""
gens_remaining = set([e])
gens_remaining = {e}
current_set = set(elms)

while gens_remaining:
Expand All @@ -2700,7 +2694,7 @@ def sublattice(elms, e):

N = self.cardinality()
elms = [0]
sublats = [set([0])]
sublats = [{0}]
result = []
skip = -1

Expand Down Expand Up @@ -2981,7 +2975,7 @@ def neutral_elements(self):
return set(range(n))

todo = set(range(1, n - 1))
neutrals = set([0, n - 1])
neutrals = {0, n - 1}
notneutrals = set()
all_elements = set(range(n))

Expand Down Expand Up @@ -3144,7 +3138,7 @@ def atoms_of_congruence_lattice(self):

return min_congruences

def congruence(self, parts, start=None, stop_pairs=[]):
def congruence(self, parts, start=None, stop_pairs=None):
"""
Return the congruence ``start`` "extended" by ``parts``.
Expand Down Expand Up @@ -3208,6 +3202,9 @@ def congruence(self, parts, start=None, stop_pairs=[]):
from sage.sets.disjoint_set import DisjointSet
from copy import copy

if stop_pairs is None:
stop_pairs = []

n = self.order()
mt = self.meet_matrix()
jn = self.join_matrix()
Expand Down Expand Up @@ -3242,7 +3239,7 @@ def fill_to_interval(S):
for v in fill_to_interval(c):
cong.union(r, v)

todo = set(cong.find(e) for part in parts for e in part)
todo = {cong.find(e) for part in parts for e in part}

while todo:

Expand Down Expand Up @@ -3307,7 +3304,7 @@ def fill_to_interval(S):
d = jn[d, m]

# This removes duplicates from todo.
todo = set(cong.find(x) for x in todo)
todo = {cong.find(x) for x in todo}

return cong

Expand Down
4 changes: 2 additions & 2 deletions src/sage/combinat/posets/incidence_algebras.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class IncidenceAlgebra(CombinatorialFreeModule):
- :wikipedia:`Incidence_algebra`
"""
def __init__(self, R, P, prefix='I'):
def __init__(self, R, P, prefix='I') -> None:
"""
Initialize ``self``.
Expand Down Expand Up @@ -438,7 +438,7 @@ class ReducedIncidenceAlgebra(CombinatorialFreeModule):
`[x, y]` is isomorphic to `[x', y']` as posets. Thus the delta, Möbius,
and zeta functions are all elements of `R_P`.
"""
def __init__(self, I, prefix='R'):
def __init__(self, I, prefix='R') -> None:
"""
Initialize ``self``.
Expand Down
19 changes: 9 additions & 10 deletions src/sage/combinat/posets/lattices.py
Original file line number Diff line number Diff line change
Expand Up @@ -2003,7 +2003,7 @@ def join(L):
return (B, [self._vertex_to_element(e) for e in A])
else:
return B
assert False, "BUG: breadth() in lattices.py have an error."
raise RuntimeError("BUG: breadth() in lattices.py have an error")

def complements(self, element=None):
r"""
Expand Down Expand Up @@ -3089,11 +3089,10 @@ def vertical_decomposition(self, elements_only=False):
self._hasse_diagram.vertical_decomposition(return_list=True) +
[self.cardinality() - 1])
n = len(elms)
result = []
for i in range(n - 1):
result.append(LatticePoset(
self.subposet([self[e] for e in range(elms[i], elms[i + 1] + 1)])))
return result
return [LatticePoset(self.subposet([self[e]
for e in range(elms[i],
elms[i + 1] + 1)]))
for i in range(n - 1)]

def is_vertically_decomposable(self, certificate=False):
r"""
Expand Down Expand Up @@ -3461,8 +3460,8 @@ def frattini_sublattice(self):
sage: sorted(L.frattini_sublattice().list())
[1, 2, 4, 10, 19, 22, 33]
"""
return LatticePoset(self.subposet([self[x] for x in
self._hasse_diagram.frattini_sublattice()]))
return LatticePoset(self.subposet([self[x]
for x in self._hasse_diagram.frattini_sublattice()]))

def moebius_algebra(self, R):
"""
Expand Down Expand Up @@ -3634,9 +3633,9 @@ def adjunct(self, other, a, b):
if not isinstance(other, FiniteLatticePoset):
raise ValueError("other is not a finite lattice")
if not self.is_greater_than(b, a):
raise ValueError("element %s is not greater than %s in the lattice" % (b, a))
raise ValueError(f"element {b} is not greater than {a} in the lattice")
if self.covers(a, b):
raise ValueError("element %s covers element %s in the lattice" % (b, a))
raise ValueError(f"element {b} covers element {a} in the lattice")

if other.cardinality() == 0:
return self.relabel(lambda e: (0, e))
Expand Down
8 changes: 4 additions & 4 deletions src/sage/combinat/posets/linear_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def check(self):
"""
P = self.parent().poset()
if not P.is_linear_extension(self):
raise ValueError("%s is not a linear extension of %s" % (self, P))
raise ValueError(f"{self} is not a linear extension of {P}")

def poset(self):
r"""
Expand Down Expand Up @@ -513,7 +513,7 @@ def __classcall_private__(cls, poset, facade=False):
"""
return super().__classcall__(cls, poset, facade=facade)

def __init__(self, poset, facade):
def __init__(self, poset, facade) -> None:
"""
TESTS::
Expand Down Expand Up @@ -625,7 +625,7 @@ def cardinality(self):
while K[j]:
K.append([b for a in K[j] for b in Jup[a]])
j += 1
K = sorted(set(item for sublist in K for item in sublist))
K = sorted({item for sublist in K for item in sublist})
for j in range(len(K)):
i = m + j + 1
Jup[i] = [m + K.index(a) + 1 for a in Jup[K[j]]]
Expand Down Expand Up @@ -671,7 +671,7 @@ def __iter__(self):
for lin_ext in linear_extension_iterator(self._poset._hasse_diagram):
yield self._element_constructor_([vertex_to_element(_) for _ in lin_ext])

def __contains__(self, obj):
def __contains__(self, obj) -> bool:
"""
Membership testing
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/posets/mobile.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class MobilePoset(FinitePoset):
_lin_ext_type = LinearExtensionsOfMobile
_desc = 'Finite mobile poset'

def __init__(self, hasse_diagram, elements, category, facade, key, ribbon=None, check=True):
def __init__(self, hasse_diagram, elements, category, facade, key, ribbon=None, check=True) -> None:
r"""
Initialize ``self``.
Expand Down
Loading

0 comments on commit 27448fe

Please sign in to comment.