Skip to content

Commit 4613e04

Browse files
petercorkeclaude
andcommitted
refactor: public names say what is API; label and name cannot corrupt a graph
label read-only. It is the component number, computed by the graph. name assigning to the name of a vertex that is in a graph updates the graph's name table, refuses a name already in use (ValueError) and refuses to clear it. It left the table stale before, so g[new] failed. exporters use the public API: out_edges() instead of a vertex's private _edgelist, and get_exporter(name) instead of the private table. docs BaseVertex no longer lists _edgelist as an attribute. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 8ac3fc7 commit 4613e04

3 files changed

Lines changed: 275 additions & 24 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 86 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1736,14 +1736,7 @@ def export(
17361736
filename.write(image.decode("utf-8"))
17371737
return None
17381738

1739-
try:
1740-
func = exporters._TEXT[format]
1741-
except KeyError:
1742-
raise ValueError(
1743-
f"unknown export format {format!r}, expected one of "
1744-
f"{exporters.formats()}"
1745-
) from None
1746-
text = func(self, **options)
1739+
text = exporters.get_exporter(format)(self, **options)
17471740

17481741
if filename is None:
17491742
return text
@@ -2712,7 +2705,7 @@ def _graphcolor(self) -> None:
27122705

27132706
# clear all the labels
27142707
for vertex in self:
2715-
vertex.label = None
2708+
vertex._label = None
27162709
vertex._connectivitychange = False
27172710

27182711
lastlabel: int | None = None
@@ -2725,7 +2718,7 @@ def _graphcolor(self) -> None:
27252718
q = [v] # initialize frontier
27262719
while len(q) > 0:
27272720
v = q.pop() # expand v
2728-
v.label = label
2721+
v._label = label
27292722
for n in v.adjacent():
27302723
if n.label is None:
27312724
q.append(n)
@@ -2771,7 +2764,7 @@ def _graphcolor(self) -> int | None:
27712764

27722765
# clear all the labels
27732766
for vertex in self:
2774-
vertex.label = None
2767+
vertex._label = None
27752768
vertex._connectivitychange = False
27762769

27772770
# initial labeling pass
@@ -2783,12 +2776,12 @@ def _graphcolor(self) -> int | None:
27832776
for n in v.adjacent():
27842777
if n.label is not None:
27852778
# neighbour has a label
2786-
v.label = n.label
2779+
v._label = n.label
27872780
break
27882781

27892782
if v.label is None:
27902783
# still not labeled, assign a new label
2791-
v.label = nextlabel
2784+
v._label = nextlabel
27922785
nextlabel += 1
27932786

27942787
label = v.label
@@ -2798,7 +2791,7 @@ def _graphcolor(self) -> int | None:
27982791
for n in v.adjacent():
27992792
if n.label is None:
28002793
# neighbour has no label, give it this one
2801-
n.label = label
2794+
n._label = label
28022795
elif label != n.label:
28032796
# label clash, note it for merging
28042797
assert n.label is not None
@@ -2811,14 +2804,14 @@ def _graphcolor(self) -> int | None:
28112804
assert vlabel is not None
28122805
while vlabel in merge:
28132806
vlabel = merge[vlabel]
2814-
v.label = vlabel
2807+
v._label = vlabel
28152808
unique.add(vlabel)
28162809

28172810
final = {u: i for i, u in enumerate(unique)}
28182811
for v in self:
28192812
vlabel = v.label
28202813
assert vlabel is not None
2821-
v.label = final[vlabel]
2814+
v._label = final[vlabel]
28222815

28232816
return len(unique)
28242817
else:
@@ -3184,11 +3177,15 @@ class BaseVertex:
31843177
Base class for vertices of directed and non-directed graphs.
31853178
31863179
Each vertex has:
3187-
- ``name``
3188-
- ``label`` an int indicating which graph component contains it
3189-
- ``_edgelist`` a list of edge objects that connect this vertex to others
3180+
- ``name`` which is its key in the graph, so renaming a vertex that is
3181+
in a graph updates the graph
3182+
- ``label`` an int indicating which graph component contains it,
3183+
read-only: the graph assigns it
31903184
- ``coord`` the coordinate in an embedded graph (optional)
31913185
3186+
and its edges are available from :meth:`edges`, :meth:`out_edges` and
3187+
:meth:`in_edges`.
3188+
31923189
:seealso: :class:`UVertex` :class:`DVertex` :class:`Edge`
31933190
"""
31943191

@@ -3217,8 +3214,8 @@ def __init__(self, coord: ArrayLike | None = None, name: str | None = None):
32173214
self.coord = None
32183215
else:
32193216
self.coord = np.r_[coord]
3220-
self.name = name
3221-
self.label: int | None = None
3217+
self._name = name
3218+
self._label: int | None = None
32223219
self._connectivitychange = True
32233220
self._edgelist = []
32243221
#: edges ending at this vertex. Only a directed vertex fills it: an
@@ -3845,6 +3842,74 @@ def _incident_edges(self) -> list[Edge]:
38453842
seen.setdefault(id(e), e)
38463843
return list(seen.values())
38473844

3845+
@property
3846+
def name(self) -> str | None:
3847+
"""
3848+
Name of the vertex
3849+
3850+
:return: the name
3851+
:rtype: str or None
3852+
3853+
The name is the vertex's key in its graph: ``g[name]`` and ``name in
3854+
g`` look it up. A vertex that is not in a graph can be given any name,
3855+
or none. For one that is in a graph:
3856+
3857+
- assigning a new name updates the graph's name table, so the vertex
3858+
is then found under the new name and not the old
3859+
- a name already used by another vertex in the graph raises
3860+
``ValueError`` and changes nothing
3861+
- the name cannot be cleared
3862+
3863+
.. versionchanged:: 1.0
3864+
Renaming a vertex in a graph used to leave the graph's name table
3865+
stale, so lookups by the new name failed.
3866+
3867+
:seealso: :meth:`BaseGraph.add_vertex`
3868+
"""
3869+
return self._name
3870+
3871+
@name.setter
3872+
def name(self, value: str | None) -> None:
3873+
graph = self._graph
3874+
old = self._name
3875+
if (
3876+
graph is not None
3877+
and old is not None
3878+
and graph._vertexdict.get(old) is self
3879+
):
3880+
if value is None:
3881+
raise ValueError("a vertex in a graph must have a name")
3882+
if value != old:
3883+
if value in graph._vertexdict:
3884+
raise ValueError(
3885+
f"the graph already has a vertex named {value!r}"
3886+
)
3887+
del graph._vertexdict[old]
3888+
graph._vertexdict[value] = self
3889+
self._name = value
3890+
3891+
@property
3892+
def label(self) -> int | None:
3893+
"""
3894+
Number of the graph component that contains the vertex
3895+
3896+
:return: component number, counted from 0, or None if the components
3897+
have not been found yet
3898+
:rtype: int or None
3899+
3900+
Assigned by the graph when its components are found, which happens when
3901+
:attr:`BaseGraph.nc`, :meth:`BaseGraph.component` or
3902+
:meth:`BaseGraph.samecomponent` is used after the graph has changed.
3903+
It is read-only.
3904+
3905+
.. versionchanged:: 1.0
3906+
Read-only. It was a plain attribute, but it is computed from the
3907+
graph's structure and meaningless to assign.
3908+
3909+
:seealso: :attr:`BaseGraph.nc` :meth:`BaseGraph.component`
3910+
"""
3911+
return self._label
3912+
38483913
@property
38493914
def x(self) -> float:
38503915
"""

‎src/pgraph/exporters.py‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -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
@@ -126,8 +143,8 @@ def _ordered_edges(graph: BaseGraph) -> list[tuple[Edge, BaseVertex, BaseVertex]
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,7 +153,7 @@ 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))

0 commit comments

Comments
 (0)