Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
sagemathgh-36440: trying ruff on some posets files
    
This is changing two files in the posets folder.

- use a smaller doctest in one place
- replace one annoying use of `deepcopy` by the method `copy` of
`DiGraph`
- apply `ruff check --fix --select UP src/sage/combinat/posets` to make
a few automatic modifications, about strings mostly, and about the
syntax of `super`
- avoid one symbolic number in one doctest

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: sagemath#36440
Reported by: Frédéric Chapoton
Reviewer(s): David Coudert
  • Loading branch information
Release Manager committed Oct 15, 2023
2 parents dffe6e5 + 9a9bb58 commit 147dac0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 22 deletions.
5 changes: 2 additions & 3 deletions src/sage/combinat/posets/incidence_algebras.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def __init__(self, R, P, prefix='I'):
TESTS::
sage: P = posets.BooleanLattice(4)
sage: P = posets.BooleanLattice(3)
sage: I = P.incidence_algebra(QQ)
sage: TestSuite(I).run() # long time
"""
Expand Down Expand Up @@ -93,8 +93,7 @@ def _repr_(self):
Incidence algebra of Finite lattice containing 16 elements
over Rational Field
"""
return "Incidence algebra of {} over {}".format(self._poset,
self.base_ring())
return f"Incidence algebra of {self._poset} over {self.base_ring()}"

def _coerce_map_from_(self, R):
"""
Expand Down
35 changes: 16 additions & 19 deletions src/sage/combinat/posets/posets.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# sage.doctest: needs sage.graphs sage.modules
r"""
Finite posets
Expand Down Expand Up @@ -287,9 +286,8 @@
# ****************************************************************************
from __future__ import annotations
from collections import defaultdict
from copy import copy, deepcopy
from copy import copy
from itertools import product
from typing import List

from sage.misc.cachefunc import cached_method
from sage.misc.lazy_attribute import lazy_attribute
Expand Down Expand Up @@ -706,7 +704,7 @@ def Poset(data=None, element_labels=None, cover_relations=False, linear_extensio
if data is None: # type 0
D = DiGraph()
elif isinstance(data, DiGraph): # type 4
D = deepcopy(data)
D = data.copy(immutable=True)
elif isinstance(data, dict): # type 3: dictionary of upper covers
D = DiGraph(data, format="dict_of_lists")
elif isinstance(data, (list, tuple)): # types 1, 2, 3 (list/tuple)
Expand Down Expand Up @@ -1319,7 +1317,7 @@ def __call__(self, element):
"""
if self._is_facade and element in self._element_to_vertex_dict:
return element
return super(FinitePoset, self).__call__(element)
return super().__call__(element)

def hasse_diagram(self):
r"""
Expand Down Expand Up @@ -1403,7 +1401,7 @@ def _repr_(self):
sage: M._repr_()
'Finite meet-semilattice containing 3 elements'
"""
s = "%s containing %s elements" % (self._desc, self._hasse_diagram.order())
s = f"{self._desc} containing {self._hasse_diagram.order()} elements"
if self._with_linear_extension:
s += " with distinguished linear extension"
return s
Expand Down Expand Up @@ -1444,13 +1442,13 @@ def _rich_repr_(self, display_manager, **kwds):
return output
# create text for non-graphical output
if can_plot:
text = '{0} (use the .plot() method to plot)'.format(repr(self))
text = f'{repr(self)} (use the .plot() method to plot)'
else:
text = repr(self)
# latex() produces huge tikz environment, override
tp = display_manager.types
if (prefs.text == 'latex' and tp.OutputLatex in display_manager.supported_output()):
return tp.OutputLatex(r'\text{{{0}}}'.format(text))
return tp.OutputLatex(fr'\text{{{text}}}')
return tp.OutputPlainText(text)

def __iter__(self):
Expand Down Expand Up @@ -2669,7 +2667,7 @@ def relations_number(self):
# Maybe this should also be deprecated.
intervals_number = relations_number

def linear_intervals_count(self) -> List[int]:
def linear_intervals_count(self) -> list[int]:
"""
Return the enumeration of linear intervals w.r.t. their cardinality.
Expand Down Expand Up @@ -2799,10 +2797,10 @@ def is_incomparable_chain_free(self, m, n=None) -> bool:
sage: Q = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})
sage: Q.is_incomparable_chain_free(2, 20/10)
True
sage: Q.is_incomparable_chain_free(2, pi) # needs sage.symbolic
sage: Q.is_incomparable_chain_free(2, 1.5)
Traceback (most recent call last):
...
TypeError: 2 and pi must be integers
TypeError: 2 and 1.5... must be integers
sage: Q.is_incomparable_chain_free(2, -1)
Traceback (most recent call last):
...
Expand Down Expand Up @@ -2850,9 +2848,9 @@ def is_incomparable_chain_free(self, m, n=None) -> bool:
try:
m, n = Integer(m), Integer(n)
except TypeError:
raise TypeError("%s and %s must be integers" % (m, n))
raise TypeError(f"{m} and {n} must be integers")
if m < 1 or n < 1:
raise ValueError("%s and %s must be positive integers" % (m, n))
raise ValueError(f"{m} and {n} must be positive integers")
twochains = digraphs.TransitiveTournament(m) + digraphs.TransitiveTournament(n)
if closure.subgraph_search(twochains, induced=True) is not None:
return False
Expand Down Expand Up @@ -6348,7 +6346,7 @@ def graphviz_string(self, graph_string="graph", edge_string="--"):
s += '"%s";' % v
s += '\n'
for u, v in self.cover_relations_iterator():
s += '"%s"%s"%s";' % (v, edge_string, u)
s += f'"{v}"{edge_string}"{u}";'
s += "\n}"
return s

Expand Down Expand Up @@ -8152,9 +8150,9 @@ def is_eulerian(self, k=None, certificate=False):
try:
k = Integer(k)
except TypeError:
raise TypeError("parameter 'k' must be an integer, not {0}".format(k))
raise TypeError(f"parameter 'k' must be an integer, not {k}")
if k <= 0:
raise ValueError("parameter 'k' must be positive, not {0}".format(k))
raise ValueError(f"parameter 'k' must be positive, not {k}")

if not self.is_bounded():
raise ValueError("the poset is not bounded")
Expand Down Expand Up @@ -8880,7 +8878,7 @@ def _macaulay2_init_(self, macaulay2=None):
H = self._hasse_diagram
txt = 'needsPackage "Posets";'
txt += "poset({%s},{" % ','.join(str(x) for x in H)
txt += ",".join("{%s,%s}" % (str(x), str(y))
txt += ",".join(f"{{{str(x)},{str(y)}}}"
for x, y in H.cover_relations_iterator())
return txt + "})"

Expand Down Expand Up @@ -8993,8 +8991,7 @@ def cardinality(self, from_iterator=False):
68275077901156, 4483130665195087]
if not from_iterator and self._n < len(known_values):
return Integer(known_values[self._n])
else:
return super(FinitePosets_n, self).cardinality()
return super().cardinality()


# For backward compatibility of pickles of the former Posets()
Expand Down

0 comments on commit 147dac0

Please sign in to comment.