Skip to content

Commit 8ac3fc7

Browse files
petercorkeclaude
andcommitted
feat: graph.validate() reports inconsistencies between a graph's records
A graph keeps the same facts in several places: its set of edges, each vertex's outgoing (and, if directed, incoming) edge lists, each edge's two vertices, each vertex's pointer back to its graph, and the name table. validate() returns a list of the ways they disagree, empty when consistent. It does not change the graph, costs O(V+E), reports every problem rather than the first, and does not raise on corruption, including stray objects in the containers. For tests, debugging, and code that reaches into the internals; a graph built and edited through the public methods is always valid. 27 deliberate corruptions, one per kind of record, are each detected and named; random edit sequences stay valid. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent b588fbe commit 8ac3fc7

2 files changed

Lines changed: 419 additions & 0 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,190 @@ def edge_class(self) -> type[Edge]:
306306
"""
307307
return self._edge_class
308308

309+
def validate(self) -> list[str]:
310+
"""
311+
Check that the graph's records agree with each other
312+
313+
:return: a description of each inconsistency found, empty if the graph
314+
is consistent
315+
:rtype: list of str
316+
317+
A graph keeps the same facts in several places: its set of edges, each
318+
vertex's list of outgoing edges (and, for a directed graph, of incoming
319+
ones), each edge's two vertices, each vertex's pointer back to its
320+
graph, and the table of vertex names. The library keeps them in step,
321+
so a graph built and edited through the public methods is always
322+
valid. This is a check for tests, for debugging, and for code that
323+
reaches into the internals.
324+
325+
It does not change the graph, and takes time proportional to the
326+
number of vertices plus edges. It reports every inconsistency, not
327+
only the first.
328+
329+
The checks are:
330+
331+
- the vertex list holds only vertices, once each, and the edge set
332+
holds only edges
333+
- every edge in the graph has two vertices, both in this graph, and is
334+
an instance of :attr:`edge_class`
335+
- every vertex points back at this graph, is an instance of
336+
:attr:`vertex_class`, is in the name table under its own name, and
337+
has a coordinate of the required length if ``dim`` was given
338+
- every entry of the name table is a vertex of this graph and is
339+
filed under its own name
340+
- each edge is in the right vertex lists, the right number of times:
341+
both ends for an undirected edge (twice at one vertex for a
342+
self-loop), the source's outgoing and the target's incoming list for
343+
a directed edge
344+
- no vertex list holds an edge that is not in the graph
345+
346+
.. runblock:: pycon
347+
348+
>>> from pgraph import UGraph
349+
>>> g = UGraph()
350+
>>> v1 = g.add_vertex(name='v1')
351+
>>> v2 = g.add_vertex(name='v2')
352+
>>> g.add_edge(v1, v2)
353+
>>> print(g.validate())
354+
355+
:seealso: :meth:`remove_edge` :meth:`remove_vertex`
356+
"""
357+
from collections import Counter
358+
359+
problems: list[str] = []
360+
directed = isinstance(self, DGraph)
361+
362+
# ---- the containers themselves must hold the right kind of thing; a
363+
# stray object is reported and set aside so the checks below can run
364+
vertices: list[BaseVertex] = []
365+
for entry in self._vertexlist:
366+
if isinstance(entry, BaseVertex):
367+
vertices.append(entry)
368+
else:
369+
problems.append(f"the vertex list holds {entry!r}, which is not a vertex")
370+
graph_edges: list[Edge] = []
371+
for member in self._edgelist:
372+
if isinstance(member, Edge):
373+
graph_edges.append(member)
374+
else:
375+
problems.append(f"the edge set holds {member!r}, which is not an edge")
376+
377+
# ---- vertices
378+
members = {id(v) for v in vertices}
379+
for vid, n in Counter(id(v) for v in vertices).items():
380+
if n > 1:
381+
v = next(x for x in vertices if id(x) == vid)
382+
problems.append(f"vertex {v.name!r} is listed {n} times in the vertex list")
383+
for key, v in self._vertexdict.items():
384+
if not isinstance(v, BaseVertex) or id(v) not in members:
385+
problems.append(
386+
f"name table entry {key!r} refers to a vertex that is not in the graph"
387+
)
388+
elif v.name != key:
389+
problems.append(
390+
f"name table entry {key!r} refers to vertex {v.name!r}, "
391+
"which has a different name"
392+
)
393+
for v in vertices:
394+
if v._graph is not self:
395+
problems.append(f"vertex {v.name!r} does not point back at this graph")
396+
if v.name is None or self._vertexdict.get(v.name) is not v:
397+
problems.append(
398+
f"vertex {v.name!r} is not in the name table under its own name"
399+
)
400+
if not isinstance(v, self._vertex_class):
401+
problems.append(
402+
f"vertex {v.name!r} is a {type(v).__name__}, not a "
403+
f"{self._vertex_class.__name__}"
404+
)
405+
if (
406+
self._dim is not None
407+
and v.coord is not None
408+
and len(v.coord) != self._dim
409+
):
410+
problems.append(
411+
f"vertex {v.name!r} has a coordinate of length "
412+
f"{len(v.coord)} but the graph requires dim={self._dim}"
413+
)
414+
if not directed and v._inlist:
415+
problems.append(
416+
f"vertex {v.name!r} has {len(v._inlist)} incoming edges "
417+
"recorded, but an undirected vertex does not use that list"
418+
)
419+
420+
# ---- edges, and what each vertex list should then contain
421+
expected_out: Counter[tuple[int, int]] = Counter()
422+
expected_in: Counter[tuple[int, int]] = Counter()
423+
edges: dict[int, Edge] = {}
424+
in_graph = {id(e) for e in graph_edges}
425+
for e in graph_edges:
426+
edges[id(e)] = e
427+
if e.v1 is None or e.v2 is None:
428+
problems.append(f"edge {e!r} is in the graph but has no vertices")
429+
continue
430+
for end in (e.v1, e.v2):
431+
if id(end) not in members:
432+
problems.append(
433+
f"edge {e!r} joins vertex {end.name!r}, which is not in this graph"
434+
)
435+
if not isinstance(e, self._edge_class):
436+
problems.append(
437+
f"edge {e!r} is a {type(e).__name__}, not a {self._edge_class.__name__}"
438+
)
439+
expected_out[(id(e.v1), id(e))] += 1
440+
if directed:
441+
expected_in[(id(e.v2), id(e))] += 1
442+
else:
443+
expected_out[(id(e.v2), id(e))] += 1
444+
445+
actual_out: Counter[tuple[int, int]] = Counter()
446+
actual_in: Counter[tuple[int, int]] = Counter()
447+
owner = {id(v): v for v in vertices}
448+
for v in vertices:
449+
for listname, held, counter in (
450+
("outgoing" if directed else "edge", v._edgelist, actual_out),
451+
("incoming", v._inlist, actual_in),
452+
):
453+
for e in held:
454+
if not isinstance(e, Edge):
455+
problems.append(
456+
f"vertex {v.name!r} holds {e!r} in its {listname} list, "
457+
"which is not an edge"
458+
)
459+
continue
460+
counter[(id(v), id(e))] += 1
461+
edges.setdefault(id(e), e)
462+
463+
def report(expected: Counter, actual: Counter, listname: str) -> None:
464+
for key in expected.keys() | actual.keys():
465+
vid, eid = key
466+
want, have = expected[key], actual[key]
467+
if want == have:
468+
continue
469+
v, e = owner.get(vid), edges[eid]
470+
vname = v.name if v is not None else "?"
471+
if eid not in in_graph:
472+
problems.append(
473+
f"vertex {vname!r} holds edge {e!r} in its {listname} "
474+
"list, but that edge is not in the graph"
475+
)
476+
elif have < want:
477+
problems.append(
478+
f"edge {e!r} is missing from the {listname} list of "
479+
f"vertex {vname!r} (found {have}, expected {want})"
480+
)
481+
else:
482+
problems.append(
483+
f"edge {e!r} appears {have} times in the {listname} list "
484+
f"of vertex {vname!r}, expected {want}"
485+
)
486+
487+
report(expected_out, actual_out, "outgoing" if directed else "edge")
488+
if directed:
489+
report(expected_in, actual_in, "incoming")
490+
491+
return problems
492+
309493
def copy(self) -> BaseGraph:
310494
"""
311495
Deepcopy of graph

0 commit comments

Comments
 (0)