Skip to content

Commit 53890d1

Browse files
authored
Merge pull request #29 from petercorke/chore/mypy-clean
fix: plot()/highlight_edge() crashes found by mypy; mypy to zero
2 parents 0566a68 + 5b2e25f commit 53890d1

4 files changed

Lines changed: 169 additions & 29 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,6 @@ jobs:
4040
python -m pip install --upgrade pip
4141
pip install .[dev]
4242
- name: Run mypy
43-
# Informational only for now: the type-hinting pass surfaced a
44-
# baseline of pre-existing design tensions (Liskov-incompatible
45-
# overrides, embedded-graph invariants not visible to the type
46-
# checker) that are tracked separately, not fixed here. Don't fail
47-
# the build on them yet.
48-
continue-on-error: true
4943
run: mypy src/pgraph/PGraph.py
5044

5145
all-tests-passed:

‎pyproject.toml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ target-version = ['py311']
7676
omit = []
7777

7878
[tool.mypy]
79-
python_version = "3.9"
8079
ignore_missing_imports = true
8180
warn_unused_ignores = true
8281
warn_redundant_casts = true

‎src/pgraph/PGraph.py‎

Lines changed: 57 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,10 +1062,10 @@ def plot(
10621062
self,
10631063
colorcomponents: bool = True,
10641064
force2d: bool = False,
1065-
vopt: dict = {},
1066-
eopt: dict = {},
1067-
text: dict | bool = {},
1068-
block: bool = False,
1065+
vopt: dict | None = None,
1066+
eopt: dict | None = None,
1067+
text: dict | bool | None = None,
1068+
block: bool | None = False,
10691069
grid: bool = True,
10701070
ax: Any = None,
10711071
) -> None:
@@ -1074,23 +1074,34 @@ def plot(
10741074
10751075
:param vopt: vertex format, defaults to 12pt o-marker
10761076
:type vopt: dict, optional
1077-
:param eopt: edge format, defaults to None
1077+
:param eopt: edge format, defaults to 3pt line width
10781078
:type eopt: dict, optional
10791079
:param text: text label format, defaults to None
1080-
:type text: False or dict, optional
1081-
:param colorcomponents: color vertices and edges by component, defaults to None
1082-
:type color: bool, optional
1083-
:param block: block until figure is dismissed, defaults to True
1084-
:type block: bool, optional
1080+
:type text: dict, bool or None, optional
1081+
:param colorcomponents: color vertices and edges by component, defaults to True
1082+
:type colorcomponents: bool, optional
1083+
:param force2d: plot only the first two coordinates of each vertex
1084+
even if they have more, defaults to False
1085+
:type force2d: bool, optional
1086+
:param block: block until figure is dismissed, defaults to False. If
1087+
None the figure is not shown at all, which is useful when
1088+
adding to the plot or saving it.
1089+
:type block: bool or None, optional
1090+
:raises ValueError: the graph is empty, or a vertex has no coordinate
1091+
or fewer than two coordinate values
10851092
10861093
The graph is plotted using matplotlib.
10871094
10881095
If ``colorcomponents`` is True then each component is assigned a unique
10891096
color. ``vertex`` and ``edge`` cannot include a color keyword.
10901097
10911098
If ``text`` is a dict it is used to format text labels for the vertices
1092-
which are the vertex names. If ``text`` is None default formatting is
1093-
used. If ``text`` is False no labels are added.
1099+
which are the vertex names. If ``text`` is None or True default
1100+
formatting is used. If ``text`` is False no labels are added.
1101+
1102+
.. note:: Only embedded graphs can be plotted: every vertex must have
1103+
a coordinate of at least two values. A coordinate of more than
1104+
two values is drawn in 3D, using the first three.
10941105
10951106
.. runblock:: pycon
10961107
@@ -1112,21 +1123,37 @@ def plot(
11121123
11131124
:seealso: :meth:`highlight_path`
11141125
"""
1115-
vopt = {**dict(marker="o", markersize=12), **vopt}
1116-
eopt = {**dict(linewidth=3), **eopt}
1126+
if self.n == 0:
1127+
raise ValueError("cannot plot an empty graph")
1128+
ndim = 0 # number of coordinate values, taken from the first vertex
1129+
for i, vertex in enumerate(self):
1130+
if vertex.coord is None or len(vertex.coord) < 2:
1131+
raise ValueError(
1132+
f"cannot plot: vertex {vertex.name} needs a coordinate "
1133+
"of at least two values"
1134+
)
1135+
if i == 0:
1136+
ndim = len(vertex.coord)
1137+
1138+
vopt = {**dict(marker="o", markersize=12), **(vopt or {})}
1139+
eopt = {**dict(linewidth=3), **(eopt or {})}
1140+
# text labels: None or True is default formatting, False is no labels
1141+
textopt: dict | None = None
1142+
if text is not False:
1143+
textopt = text if isinstance(text, dict) else {}
11171144

11181145
if colorcomponents:
11191146
color = plt.cm.coolwarm(np.linspace(0, 1, self.nc))
11201147

1121-
if len(self[0].coord) == 2 or force2d:
1148+
if ndim == 2 or force2d:
11221149
# 2D plotting
11231150
if ax is None:
11241151
ax = axes_logic(ax, 2)
11251152
for c in range(self.nc):
11261153
# for each component
11271154
for vertex in self.component(c):
1128-
if text is not False:
1129-
ax.text(vertex.x, vertex.y, " " + vertex.name, **text)
1155+
if textopt is not None:
1156+
ax.text(vertex.x, vertex.y, f" {vertex.name}", **textopt)
11301157
if colorcomponents:
11311158
ax.plot(vertex.x, vertex.y, color=color[c, :], **vopt)
11321159
for v in vertex.neighbours():
@@ -1147,9 +1174,9 @@ def plot(
11471174
for c in range(self.nc):
11481175
# for each component
11491176
for vertex in self.component(c):
1150-
if text is not False:
1177+
if textopt is not None:
11511178
ax.text(
1152-
vertex.x, vertex.y, vertex.z, " " + vertex.name, **text
1179+
vertex.x, vertex.y, vertex.z, f" {vertex.name}", **textopt
11531180
)
11541181
if colorcomponents:
11551182
ax.plot(
@@ -1166,7 +1193,7 @@ def plot(
11661193
**{**dict(color=color[c, :]), **eopt},
11671194
)
11681195
else:
1169-
ax.plot(vertex.x, vertex.y, **vopt)
1196+
ax.plot(vertex.x, vertex.y, vertex.z, **vopt)
11701197
for v in vertex.neighbours():
11711198
ax.plot(
11721199
[vertex.x, v.x],
@@ -1181,13 +1208,17 @@ def plot(
11811208
if block is not None:
11821209
plt.show(block=block)
11831210

1184-
def highlight_path(self, path: list[BaseVertex], block: bool = False, **kwargs: Any) -> None:
1211+
def highlight_path(
1212+
self, path: list[BaseVertex], block: bool | None = False, **kwargs: Any
1213+
) -> None:
11851214
"""
11861215
Highlight a path through the graph
11871216
11881217
:param path: sequence of vertices forming a path
11891218
:type path: list of BaseVertex subclass
1190-
:param block: block until figure is dismissed, defaults to False
1219+
:param block: block until figure is dismissed, defaults to False. If
1220+
None the figure is not shown.
1221+
:type block: bool or None, optional
11911222
:param kwargs: arguments passed to :meth:`highlight_edge` and
11921223
:meth:`highlight_vertex`
11931224
@@ -1243,6 +1274,8 @@ def highlight_edge(
12431274
:type color: str, optional
12441275
:param alpha: Transparency of the highlight, defaults to 0.5
12451276
:type alpha: float, optional
1277+
:raises ValueError: ``edge`` does not connect two vertices, for
1278+
example because it has been removed from the graph
12461279
:rtype: None
12471280
12481281
.. runblock:: pycon
@@ -1271,6 +1304,8 @@ def highlight_edge(
12711304
"""
12721305
p1 = edge.v1
12731306
p2 = edge.v2
1307+
if p1 is None or p2 is None:
1308+
raise ValueError("edge does not connect two vertices")
12741309
plt.plot(
12751310
[p1.x, p2.x], [p1.y, p2.y], color=color, linewidth=3 * scale, alpha=alpha
12761311
)

‎tests/test_plot_args.py‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
"""
2+
plot() / highlight_*() argument handling and the errors they give for graphs
3+
that cannot be drawn. These were found by mypy: ``text=None`` and
4+
``text=True`` crashed although the docstring documents ``None`` as "default
5+
formatting", and unplottable graphs gave a bare TypeError/IndexError.
6+
"""
7+
8+
import unittest
9+
10+
import matplotlib
11+
12+
matplotlib.use("Agg")
13+
import matplotlib.pyplot as plt
14+
15+
from pgraph import DGraph, UGraph
16+
17+
18+
class TestPlotArgs(unittest.TestCase):
19+
def setUp(self):
20+
self.g = UGraph()
21+
a = self.g.add_vertex([0, 0], name="a")
22+
b = self.g.add_vertex([1, 1], name="b")
23+
self.edge = self.g.add_edge(a, b)
24+
25+
def tearDown(self):
26+
plt.close("all")
27+
28+
def texts(self):
29+
return [t.get_text().strip() for t in plt.gca().texts]
30+
31+
def test_text_default_labels_vertices(self):
32+
self.g.plot(block=None)
33+
self.assertEqual(sorted(self.texts()), ["a", "b"])
34+
35+
def test_text_none_means_default_formatting(self):
36+
self.g.plot(text=None, block=None)
37+
self.assertEqual(sorted(self.texts()), ["a", "b"])
38+
39+
def test_text_true_means_default_formatting(self):
40+
self.g.plot(text=True, block=None)
41+
self.assertEqual(sorted(self.texts()), ["a", "b"])
42+
43+
def test_text_false_means_no_labels(self):
44+
self.g.plot(text=False, block=None)
45+
self.assertEqual(self.texts(), [])
46+
47+
def test_text_dict_is_the_format(self):
48+
self.g.plot(text={"color": "r"}, block=None)
49+
self.assertEqual({t.get_color() for t in plt.gca().texts}, {"r"})
50+
51+
def test_vopt_eopt_none(self):
52+
self.g.plot(vopt=None, eopt=None, block=None)
53+
54+
def test_options_are_not_shared_between_calls(self):
55+
# a mutable default argument must not accumulate state
56+
self.g.plot(vopt={"markersize": 3}, block=None)
57+
plt.close("all")
58+
self.g.plot(block=None)
59+
sizes = {line.get_markersize() for line in plt.gca().lines}
60+
self.assertNotIn(3, sizes)
61+
62+
def test_3d_text_none(self):
63+
g = UGraph()
64+
a = g.add_vertex([0, 0, 0], name="a")
65+
b = g.add_vertex([1, 1, 1], name="b")
66+
g.add_edge(a, b)
67+
g.plot(text=None, block=None)
68+
self.assertEqual(sorted(self.texts()), ["a", "b"])
69+
70+
def test_3d_vertices_plotted_at_their_z(self):
71+
# without component colouring the vertex marker dropped z (plotted at 0)
72+
g = UGraph()
73+
a = g.add_vertex([0, 0, 5], name="a")
74+
b = g.add_vertex([1, 1, 7], name="b")
75+
g.add_edge(a, b)
76+
g.plot(colorcomponents=False, block=None)
77+
zs = set()
78+
for line in plt.gca().lines:
79+
x, y, z = line.get_data_3d()
80+
if len(x) == 1: # a vertex marker, not an edge
81+
zs.add(float(z[0]))
82+
self.assertEqual(zs, {5.0, 7.0})
83+
84+
def test_plot_graph_without_coordinates(self):
85+
g = UGraph()
86+
g.add_edge(g.add_vertex(), g.add_vertex())
87+
with self.assertRaises(ValueError):
88+
g.plot(block=None)
89+
90+
def test_plot_graph_with_one_coordinate(self):
91+
g = UGraph()
92+
g.add_vertex([0])
93+
with self.assertRaises(ValueError):
94+
g.plot(block=None)
95+
96+
def test_plot_empty_graph(self):
97+
with self.assertRaises(ValueError):
98+
DGraph().plot(block=None)
99+
100+
def test_highlight_edge(self):
101+
self.g.plot(block=None)
102+
self.g.highlight_edge(self.edge)
103+
104+
def test_highlight_removed_edge(self):
105+
self.g.plot(block=None)
106+
self.g.remove_edge(self.edge)
107+
with self.assertRaises(ValueError):
108+
self.g.highlight_edge(self.edge)
109+
110+
111+
if __name__ == "__main__":
112+
unittest.main()

0 commit comments

Comments
 (0)