Skip to content

Commit a5df2c8

Browse files
petercorkeclaude
andcommitted
feat: UGraph/DGraph take vertex_class and edge_class
A graph now owns the policy of which vertex and edge classes it builds, so user subclasses no longer have to be constructed by hand and passed in: g = UGraph(vertex_class=MyVertex, edge_class=MyEdge) g.add_vertex([0, 0]) # MyVertex g.add_edge(v1, v2) # MyEdge add_vertex() and connect(edge=) enforce the configured classes; the Dict() and Adjacency() factories forward constructor arguments; copy() preserves them. Defaults are unchanged (UVertex/DVertex and Edge). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 941624c commit a5df2c8

2 files changed

Lines changed: 97 additions & 19 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 96 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ def __init__(
2929
heuristic: Callable[[NDArray], float] | str | None = None,
3030
verbose: bool = False,
3131
dim: int | None = None,
32+
vertex_class: type[BaseVertex] | None = None,
33+
edge_class: type[Edge] | None = None,
3234
):
3335
"""
3436
Abstract base class for graphs
@@ -44,15 +46,53 @@ def __init__(
4446
None (unconstrained -- vertices may have coordinates of any
4547
length, or none at all)
4648
:type dim: int, optional
49+
:param vertex_class: class of the vertices this graph creates, defaults
50+
to ``UVertex`` for a :class:`UGraph` and ``DVertex`` for a
51+
:class:`DGraph`
52+
:type vertex_class: subclass of ``UVertex`` or ``DVertex``, optional
53+
:param edge_class: class of the edges this graph creates, defaults to
54+
:class:`Edge`
55+
:type edge_class: subclass of ``Edge``, optional
4756
:raises ValueError: ``dim`` is given but is not a positive integer
57+
:raises TypeError: ``vertex_class`` is not a subclass of this graph's
58+
own vertex kind, or ``edge_class`` is not a subclass of ``Edge``
4859
4960
This is the common base class of :class:`UGraph` and :class:`DGraph`
5061
and should not be instantiated directly.
5162
63+
``vertex_class`` and ``edge_class`` let user subclasses be built by the
64+
graph, so they never need to be constructed by hand::
65+
66+
g = UGraph(vertex_class=MyVertex, edge_class=MyEdge)
67+
v = g.add_vertex([0, 0]) # a MyVertex
68+
e = g.add_edge(v, w) # a MyEdge
69+
70+
The classes are called as ``vertex_class(coord, name=name)`` and
71+
``edge_class(v1, v2, cost=cost, data=data)``, so a subclass that
72+
overrides ``__init__`` must accept and pass on those arguments.
73+
A graph given a ``vertex_class`` only accepts vertices of that class
74+
in :meth:`add_vertex`, and one given an ``edge_class`` only accepts
75+
edges of that class.
76+
5277
:seealso: :class:`UGraph` :class:`DGraph` :meth:`add_vertex`
78+
:meth:`add_edge` :attr:`vertex_class` :attr:`edge_class`
5379
"""
5480
if dim is not None and dim <= 0:
5581
raise ValueError(f"dim must be a positive integer, got {dim!r}")
82+
kind = type(self)._vertex_cls
83+
if vertex_class is None:
84+
vertex_class = kind
85+
elif not (isinstance(vertex_class, type) and issubclass(vertex_class, kind)):
86+
raise TypeError(
87+
f"vertex_class must be a subclass of {kind.__name__} for a "
88+
f"{type(self).__name__}, got {vertex_class!r}"
89+
)
90+
if edge_class is None:
91+
edge_class = Edge
92+
elif not (isinstance(edge_class, type) and issubclass(edge_class, Edge)):
93+
raise TypeError(f"edge_class must be a subclass of Edge, got {edge_class!r}")
94+
self._vertex_class: type[BaseVertex] = vertex_class
95+
self._edge_class: type[Edge] = edge_class
5696
# we use a list and a dict, the list respects the order of adding
5797
self._vertexlist: list[BaseVertex] = []
5898
self._vertexdict: dict[str, BaseVertex] = {}
@@ -100,13 +140,15 @@ def __repr__(self) -> str:
100140
return str(self)
101141

102142
@classmethod
103-
def Dict(cls, d: dict, reverse: bool = False) -> _BaseGraph:
143+
def Dict(cls, d: dict, reverse: bool = False, **kwargs: Any) -> _BaseGraph:
104144
"""
105145
Create graph from parent/child dictionary
106146
107147
:param d: dictionary that maps from ``BaseVertex`` subclass to ``BaseVertex`` subclass
108148
:type d: dict
109149
:param reverse: reverse link direction, defaults to False
150+
:param kwargs: optional arguments passed to the graph constructor, for
151+
example ``vertex_class`` or ``edge_class``
110152
:return: graph
111153
:rtype: UGraph or DGraph
112154
@@ -127,7 +169,7 @@ def Dict(cls, d: dict, reverse: bool = False) -> _BaseGraph:
127169
:seealso: :meth:`Adjacency`
128170
"""
129171

130-
g = cls()
172+
g = cls(**kwargs)
131173

132174
for vertex, parent in d.items():
133175
if isinstance(vertex, str):
@@ -162,6 +204,7 @@ def Adjacency(
162204
A: NDArray,
163205
coords: NDArray | None = None,
164206
names: list[str] | None = None,
207+
**kwargs: Any,
165208
) -> _BaseGraph:
166209
"""
167210
Create graph from adjacency matrix
@@ -172,6 +215,8 @@ def Adjacency(
172215
:type coords: ndarray(N,M), optional
173216
:param names: names of vertices, defaults to None
174217
:type names: list(N) of str, optional
218+
:param kwargs: optional arguments passed to the graph constructor, for
219+
example ``vertex_class`` or ``edge_class``
175220
:return: graph
176221
:rtype: UGraph or DGraph
177222
@@ -199,7 +244,7 @@ def Adjacency(
199244
if coords is not None and coords.shape[0] != A.shape[0]:
200245
raise ValueError("coords must have same number of rows as adjacency matrix")
201246

202-
g = cls()
247+
g = cls(**kwargs)
203248

204249
name = None
205250
coord = None
@@ -227,6 +272,30 @@ def Adjacency(
227272

228273
return g
229274

275+
@property
276+
def vertex_class(self) -> type[BaseVertex]:
277+
"""
278+
Class of the vertices this graph creates
279+
280+
:return: vertex class
281+
:rtype: subclass of ``UVertex`` or ``DVertex``
282+
283+
:seealso: :meth:`add_vertex` :attr:`edge_class`
284+
"""
285+
return self._vertex_class
286+
287+
@property
288+
def edge_class(self) -> type[Edge]:
289+
"""
290+
Class of the edges this graph creates
291+
292+
:return: edge class
293+
:rtype: subclass of ``Edge``
294+
295+
:seealso: :meth:`add_edge` :attr:`vertex_class`
296+
"""
297+
return self._edge_class
298+
230299
def copy(self) -> _BaseGraph:
231300
"""
232301
Deepcopy of graph
@@ -257,26 +326,29 @@ def add_vertex(
257326
:type coord: array-like or BaseVertex subclass, optional
258327
:param name: name of vertex, defaults to "#i"
259328
:type name: str, optional
260-
:raises TypeError: ``coord`` is a ``BaseVertex`` of the wrong kind
329+
:raises TypeError: ``coord`` is a ``BaseVertex`` that is not an
330+
instance of this graph's :attr:`vertex_class`
261331
:raises ValueError: the graph was constructed with ``dim``, and
262332
``coord`` is given but its length doesn't match
263333
:return: the added vertex
264334
:rtype: BaseVertex subclass
265335
266336
- ``g.add_vertex()`` creates a new vertex with optional ``coord`` and
267337
``name``.
268-
- ``g.add_vertex(v)`` takes an instance or subclass of this graph's
269-
own vertex kind and adds it to the graph.
338+
- ``g.add_vertex(v)`` takes an instance of this graph's
339+
:attr:`vertex_class` (by default any ``UVertex`` for a
340+
:class:`UGraph`, any ``DVertex`` for a :class:`DGraph`) and adds it
341+
to the graph.
270342
271343
If the vertex has no name and ``name`` is None give it a default name
272344
``#N`` where ``N`` is a consecutive integer.
273345
274346
The vertex is placed into a dictionary with a key equal to its name.
275347
276348
This single implementation, shared by :class:`UGraph` and
277-
:class:`DGraph`, is parameterized by each subclass's
278-
:attr:`_vertex_cls` rather than duplicated per subclass -- see
279-
:doc:`policy` for why that matters.
349+
:class:`DGraph`, is parameterized by the graph's :attr:`vertex_class`
350+
rather than duplicated per subclass -- see :doc:`policy` for why that
351+
matters.
280352
281353
.. runblock:: pycon
282354
@@ -301,15 +373,15 @@ def add_vertex(
301373
302374
:seealso: :meth:`vertex_copy`
303375
"""
304-
if isinstance(coord, self._vertex_cls):
376+
if isinstance(coord, self._vertex_class):
305377
vertex = coord
306378
elif isinstance(coord, BaseVertex):
307379
raise TypeError(
308-
f"expecting {self._vertex_cls.__name__} or coordinate data, "
380+
f"expecting {self._vertex_class.__name__} or coordinate data, "
309381
f"got {type(coord).__name__}"
310382
)
311383
else:
312-
vertex = self._vertex_cls(coord, name=name)
384+
vertex = self._vertex_class(coord, name=name)
313385

314386
if (
315387
self._dim is not None
@@ -2759,9 +2831,10 @@ def connect(
27592831
27602832
:param dest: The vertex to connect to
27612833
:type dest: ``BaseVertex`` subclass
2762-
:param edge: Use this as the edge object, otherwise a new ``Edge``
2763-
object is created from the vertices being connected,
2764-
and the ``cost`` and ``edge`` parameters, defaults to None
2834+
:param edge: Use this as the edge object, otherwise a new object of the
2835+
graph's :attr:`_BaseGraph.edge_class` is created from the
2836+
vertices being connected, and the ``cost`` and ``data``
2837+
parameters, defaults to None
27652838
:type edge: ``Edge`` subclass, optional
27662839
:param cost: the cost to traverse this edge, defaults to None
27672840
:type cost: float, optional
@@ -2771,6 +2844,8 @@ def connect(
27712844
:raises ValueError: either vertex has not been added to a graph, the
27722845
vertices belong to different graphs, or ``edge`` already connects
27732846
other vertices
2847+
:raises TypeError: ``edge`` is not an instance of the graph's
2848+
:attr:`_BaseGraph.edge_class`
27742849
:return: the edge connecting the vertices
27752850
:rtype: Edge
27762851
@@ -2808,10 +2883,15 @@ def connect(
28082883
elif self._graph is not dest._graph:
28092884
raise ValueError("vertices must belong to the same graph")
28102885
elif isinstance(edge, Edge):
2886+
if not isinstance(edge, self._graph._edge_class):
2887+
raise TypeError(
2888+
f"expecting an edge of class {self._graph._edge_class.__name__}, "
2889+
f"got {type(edge).__name__}"
2890+
)
28112891
e = edge
28122892
self._bind_edge(e, dest)
28132893
else:
2814-
e = Edge(self, dest, cost=cost, data=data)
2894+
e = self._graph._edge_class(self, dest, cost=cost, data=data)
28152895

28162896
self._graph._edgelist.add(e)
28172897
self._graph._connectivitychange = True

‎tests/test_graph_classes.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,6 @@ class _Classes:
2626
OtherVertex: type # the wrong kind for this graph
2727

2828
def setUp(self):
29-
outer = self
30-
3129
class MyVertex(self.Vertex):
3230
def __init__(self, *args, **kwargs):
3331
super().__init__(*args, **kwargs)
@@ -105,7 +103,7 @@ def test_default_graph_still_accepts_subclasses(self):
105103
g = self.Graph()
106104
self.assertIsInstance(g.add_vertex(self.MyVertex([0, 0])), self.MyVertex)
107105
a, b = g[0], g.add_vertex([1, 1])
108-
self.assertIsInstance(g.add_edge(MyEdge(a, b)), MyEdge)
106+
self.assertIsInstance(a.connect(b, edge=MyEdge(a, b)), MyEdge)
109107

110108
def test_bad_vertex_class(self):
111109
for bad in (self.OtherVertex, int, "UVertex", self.Vertex([0, 0]), Edge):

0 commit comments

Comments
 (0)