Skip to content

Commit e68d477

Browse files
authored
Merge pull request #40 from petercorke/feat/directed-in-edges
feat: directed vertices record incoming edges; degree is in plus out; validate(); BaseGraph
2 parents 9ac0001 + 8cab999 commit e68d477

10 files changed

Lines changed: 1358 additions & 140 deletions

‎src/pgraph/PGraph.py‎

Lines changed: 561 additions & 113 deletions
Large diffs are not rendered by default.

‎src/pgraph/__init__.py‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,19 @@
1-
from pgraph.PGraph import UGraph, DGraph, UVertex, DVertex, Edge
1+
from pgraph.PGraph import (
2+
BaseGraph,
3+
BaseVertex,
4+
UGraph,
5+
DGraph,
6+
UVertex,
7+
DVertex,
8+
Edge,
9+
)
10+
11+
__all__ = [
12+
"BaseGraph",
13+
"BaseVertex",
14+
"UGraph",
15+
"DGraph",
16+
"UVertex",
17+
"DVertex",
18+
"Edge",
19+
]

‎src/pgraph/exporters.py‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Export a graph as text (GraphViz DOT, Mermaid, GraphML, ELK JSON) or as a
33
rendered image (via the GraphViz command line tools).
44
5-
This module is reached through :meth:`pgraph.PGraph._BaseGraph.export`, which
5+
This module is reached through :meth:`pgraph.PGraph.BaseGraph.export`, which
66
dispatches on the format name or the file extension. Each text exporter is a
77
plain function ``f(graph, **options) -> str``, registered with
88
:func:`register_exporter`, so a user can add a format without touching the
@@ -27,7 +27,7 @@ def gexf(graph, *, version="1.3") -> str:
2727
from typing import IO, TYPE_CHECKING, Any, Callable
2828

2929
if TYPE_CHECKING:
30-
from .PGraph import BaseVertex, Edge, _BaseGraph
30+
from .PGraph import BaseVertex, Edge, BaseGraph
3131

3232
TextExporter = Callable[..., str]
3333

@@ -75,6 +75,23 @@ def decorator(func: TextExporter) -> TextExporter:
7575
return decorator
7676

7777

78+
def get_exporter(name: str) -> TextExporter:
79+
"""
80+
Look up a text exporter by format name
81+
82+
:param name: format name, eg. ``"dot"``
83+
:return: the function ``f(graph, **options) -> str``
84+
:raises ValueError: no text exporter has that name; the message lists those
85+
that do
86+
"""
87+
try:
88+
return _TEXT[name]
89+
except KeyError:
90+
raise ValueError(
91+
f"unknown export format {name!r}, expected one of {formats()}"
92+
) from None
93+
94+
7895
def formats() -> list[str]:
7996
"""
8097
Names of all supported export formats
@@ -114,20 +131,20 @@ def format_from_filename(filename: str | os.PathLike | IO | None) -> str | None:
114131
# helpers shared by the exporters
115132

116133

117-
def _is_directed(graph: _BaseGraph) -> bool:
134+
def _is_directed(graph: BaseGraph) -> bool:
118135
from .PGraph import DGraph # not at module level: PGraph imports this module
119136

120137
return isinstance(graph, DGraph)
121138

122139

123-
def _ordered_edges(graph: _BaseGraph) -> list[tuple[Edge, BaseVertex, BaseVertex]]:
140+
def _ordered_edges(graph: BaseGraph) -> list[tuple[Edge, BaseVertex, BaseVertex]]:
124141
"""
125142
Edges in a reproducible order
126143
127144
``graph.edges()`` is a set, so its order changes from run to run and the
128145
exported text would not be stable (useless for diffs and golden files).
129-
Instead walk the vertices in creation order and each vertex's own edge
130-
list, keeping the first sight of every edge. Identity is by object, not by
146+
Instead walk the vertices in creation order and each vertex's own
147+
outgoing edges, keeping the first sight of every edge. Identity is by object, not by
131148
endpoints, so parallel edges are all kept, and an undirected edge (held by
132149
both ends, twice for a self-loop) is listed once.
133150
@@ -136,15 +153,15 @@ def _ordered_edges(graph: _BaseGraph) -> list[tuple[Edge, BaseVertex, BaseVertex
136153
seen: set[int] = set()
137154
edges: list[tuple[Edge, BaseVertex, BaseVertex]] = []
138155
for vertex in graph:
139-
for e in vertex._edgelist:
156+
for e in vertex.out_edges():
140157
if id(e) in seen or e.v1 is None or e.v2 is None:
141158
continue
142159
seen.add(id(e))
143160
edges.append((e, e.v1, e.v2))
144161
return edges
145162

146163

147-
def _component_colors(graph: _BaseGraph) -> dict[BaseVertex, str]:
164+
def _component_colors(graph: BaseGraph) -> dict[BaseVertex, str]:
148165
"""
149166
Map each vertex to a ``#rrggbb`` colour for its component, as plot() does
150167
"""
@@ -194,7 +211,7 @@ def _dot_quote(text: str) -> str:
194211

195212
@register_exporter("dot", ".dot", ".gv")
196213
def dot(
197-
graph: _BaseGraph,
214+
graph: BaseGraph,
198215
*,
199216
direction: str | None = None,
200217
colorcomponents: bool = False,
@@ -243,7 +260,7 @@ def dot(
243260

244261
@register_exporter("mermaid", ".mmd", ".mermaid")
245262
def mermaid(
246-
graph: _BaseGraph,
263+
graph: BaseGraph,
247264
*,
248265
direction: str = "TB",
249266
colorcomponents: bool = False,
@@ -292,7 +309,7 @@ def mermaid(
292309

293310

294311
@register_exporter("graphml", ".graphml")
295-
def graphml(graph: _BaseGraph) -> str:
312+
def graphml(graph: BaseGraph) -> str:
296313
"""
297314
GraphML XML text
298315
@@ -357,7 +374,7 @@ def key(key_id: str, domain: str, name: str, type_: str) -> str:
357374

358375
@register_exporter("elk", ".elk.json", ".elk")
359376
def elk(
360-
graph: _BaseGraph,
377+
graph: BaseGraph,
361378
*,
362379
size: tuple[float, float] = (60, 40),
363380
layout_options: dict[str, str] | None = None,
@@ -433,7 +450,7 @@ def elk(
433450

434451

435452
def render(
436-
graph: _BaseGraph,
453+
graph: BaseGraph,
437454
fmt: str,
438455
*,
439456
engine: str | None = None,

‎tests/test_add_vertex_names.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""
2+
A graph's vertices have unique names (the name is the key ``g[name]`` looks
3+
them up by), and a vertex belongs to at most one graph. ``add_vertex`` used to
4+
overwrite the earlier vertex's table entry on a clash, and the default
5+
``#N`` names could clash after a removal; it now refuses, and chooses a default
6+
name that is free.
7+
"""
8+
9+
import unittest
10+
11+
from pgraph import DGraph, UGraph, UVertex
12+
13+
14+
class _AddVertex:
15+
Graph: type
16+
Vertex: type
17+
18+
def setUp(self):
19+
self.g = self.Graph()
20+
21+
def snapshot(self, g):
22+
return (g.n, sorted(g._vertexdict), [v.name for v in g])
23+
24+
def test_duplicate_name_is_refused(self):
25+
a = self.g.add_vertex(name="a")
26+
before = self.snapshot(self.g)
27+
with self.assertRaises(ValueError) as cm:
28+
self.g.add_vertex(name="a")
29+
self.assertIn("'a'", str(cm.exception))
30+
self.assertEqual(self.snapshot(self.g), before)
31+
self.assertIs(self.g["a"], a)
32+
self.assertEqual(self.g.validate(), [])
33+
34+
def test_duplicate_through_a_vertex_instance(self):
35+
self.g.add_vertex(name="a")
36+
clash = self.Vertex([1, 1], name="a")
37+
with self.assertRaises(ValueError):
38+
self.g.add_vertex(clash)
39+
self.assertIsNone(clash._graph) # untouched: not half added
40+
self.assertEqual(self.g.n, 1)
41+
42+
def test_name_argument_overriding_the_instance_name_is_checked_too(self):
43+
self.g.add_vertex(name="taken")
44+
v = self.Vertex([0, 0], name="free")
45+
with self.assertRaises(ValueError):
46+
self.g.add_vertex(v, name="taken")
47+
self.assertEqual(v.name, "free") # a refused add does not rename it
48+
49+
def test_default_names_are_unique_after_removals(self):
50+
vs = [self.g.add_vertex() for _ in range(4)] # #0 .. #3
51+
self.g.remove_vertex(vs[0])
52+
self.g.remove_vertex(vs[2])
53+
more = [self.g.add_vertex() for _ in range(3)]
54+
names = [v.name for v in self.g]
55+
self.assertEqual(len(names), len(set(names)))
56+
self.assertEqual(self.g.n, 5)
57+
self.assertEqual(self.g.validate(), [])
58+
for v in more:
59+
self.assertIs(self.g[v.name], v)
60+
61+
def test_default_name_skips_one_given_explicitly(self):
62+
self.g.add_vertex(name="#1")
63+
a = self.g.add_vertex()
64+
b = self.g.add_vertex()
65+
self.assertEqual(len({"#1", a.name, b.name}), 3)
66+
self.assertEqual(self.g.validate(), [])
67+
68+
def test_default_names_still_count_from_zero(self):
69+
self.assertEqual([self.g.add_vertex().name for _ in range(3)], ["#0", "#1", "#2"])
70+
71+
def test_a_vertex_in_this_graph_cannot_be_added_again(self):
72+
a = self.g.add_vertex(name="a")
73+
with self.assertRaises(ValueError):
74+
self.g.add_vertex(a)
75+
self.assertEqual(self.g.n, 1)
76+
self.assertEqual(self.g.validate(), [])
77+
78+
def test_a_vertex_in_another_graph_cannot_be_added(self):
79+
other = self.Graph()
80+
v = other.add_vertex(name="v")
81+
with self.assertRaises(ValueError):
82+
self.g.add_vertex(v)
83+
self.assertIs(v._graph, other) # still where it was
84+
self.assertEqual(other.validate(), [])
85+
self.assertEqual(self.g.n, 0)
86+
87+
def test_a_removed_vertex_can_be_added_again_or_elsewhere(self):
88+
a = self.g.add_vertex(name="a")
89+
self.g.remove_vertex(a)
90+
self.assertIs(self.g.add_vertex(a), a)
91+
self.g.remove_vertex(a)
92+
other = self.Graph()
93+
self.assertIs(other.add_vertex(a), a)
94+
self.assertEqual(other.validate(), [])
95+
96+
def test_wrong_dimension_changes_nothing(self):
97+
g = self.Graph(dim=3)
98+
v = self.Vertex([1, 2], name="short")
99+
with self.assertRaises(ValueError):
100+
g.add_vertex(v)
101+
self.assertEqual(g.n, 0)
102+
self.assertIsNone(v._graph)
103+
104+
105+
class TestUGraph(_AddVertex, unittest.TestCase):
106+
Graph, Vertex = UGraph, UVertex
107+
108+
109+
class TestDGraph(_AddVertex, unittest.TestCase):
110+
from pgraph import DVertex as Vertex
111+
112+
Graph = DGraph
113+
114+
115+
if __name__ == "__main__":
116+
unittest.main()

0 commit comments

Comments
 (0)