Skip to content

Commit 5acb105

Browse files
authored
Merge pull request #52 from petercorke/fix/dgraph-components-hang
fix: DGraph.nc no longer loops forever; one components algorithm
2 parents 6bff60e + aaf3e2e commit 5acb105

3 files changed

Lines changed: 304 additions & 142 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 70 additions & 141 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,6 +1218,7 @@ def remove_vertex(self, vertex: Vertex) -> None:
12181218
self._vertexlist.remove(vertex)
12191219
del self._vertexdict[vertex.name]
12201220
vertex._graph = None # it is not in any graph now
1221+
vertex._label = None # and so not in a component
12211222
self._connectivitychange = True
12221223

12231224
def remove(self, x: Edge | Vertex) -> None:
@@ -1306,19 +1307,52 @@ def ne(self) -> int:
13061307
"""
13071308
return len(self._edges)
13081309

1309-
def _graphcolor(self) -> int | None:
1310+
def _graphcolor(self) -> None:
13101311
"""
1311-
Color the graph (subclass method)
1312+
Label the components of the graph (private method)
13121313
1313-
Concrete graph coloring algorithm, provided by :meth:`UGraph._graphcolor`
1314-
and :meth:`DGraph._graphcolor`.
1314+
Assigns every vertex a ``label``, the number of its component, from 0
1315+
in the order of the first vertex of each component, and sets the
1316+
number of components. Components are *weakly* connected: the
1317+
direction of an edge is ignored, so a vertex is in the component of
1318+
every vertex that it has a path to or from.
13151319
1316-
:raises NotImplementedError: not provided by this graph kind
1320+
This is a single pass over the vertices and edges, O(V + E), and is
1321+
only done again when the graph has changed since, which every
1322+
operation that adds or removes a vertex or edge records in the graph's
1323+
``_connectivitychange``.
1324+
1325+
:seealso: :meth:`nc` :meth:`component`
13171326
"""
1318-
raise NotImplementedError(
1319-
f"{type(self).__name__} does not define how to color the graph; "
1320-
"subclass UGraph or DGraph"
1321-
)
1327+
if not self._connectivitychange:
1328+
return
1329+
1330+
for vertex in self:
1331+
vertex._label = None
1332+
vertex._connectivitychange = False
1333+
1334+
count = 0
1335+
for start in self:
1336+
if start._label is not None:
1337+
continue
1338+
start._label = count
1339+
frontier = [start]
1340+
while frontier:
1341+
v = frontier.pop()
1342+
# an edge may be followed against its direction, so the
1343+
# vertices that lead to this one count as well as those it
1344+
# leads to; in an undirected graph they are the same
1345+
around = v.adjacent()
1346+
if self.directed:
1347+
around = around + v.predecessors()
1348+
for w in around:
1349+
if w._label is None:
1350+
w._label = count
1351+
frontier.append(w)
1352+
count += 1
1353+
1354+
self._ncomponents = count
1355+
self._connectivitychange = False
13221356

13231357
@property
13241358
def nc(self) -> int:
@@ -1330,6 +1364,16 @@ def nc(self) -> int:
13301364
13311365
Number of components in the graph. Components are labeled from 0 to ``g.nc-1``.
13321366
1367+
For a directed graph the components are *weakly* connected: the
1368+
direction of the edges is ignored, so two vertices are in the same
1369+
component if there is a path between them that may run against the
1370+
arrows. A graph with no vertices has no components.
1371+
1372+
.. versionchanged:: 1.0
1373+
Does not hang. For many directed graphs, the smallest being the
1374+
4-cycle, the algorithm of 0.6.5 never finished, which also stopped
1375+
:meth:`component`, :meth:`samecomponent` and :meth:`plot`.
1376+
13331377
.. runblock:: pycon
13341378
13351379
>>> from pgraph import UGraph
@@ -1347,10 +1391,7 @@ def nc(self) -> int:
13471391
13481392
:seealso: :meth:`component` :meth:`samecomponent`
13491393
"""
1350-
n = self._graphcolor()
1351-
if n is not None:
1352-
self._ncomponents = n
1353-
1394+
self._graphcolor()
13541395
return self._ncomponents
13551396

13561397
def _metricfunc(self, metric: Callable[[NDArray], float] | str) -> Callable[[NDArray], float]:
@@ -2677,10 +2718,11 @@ def samecomponent(self, v1: Vertex, v2: Vertex) -> bool:
26772718
:return: true if vertices belong to same graph component
26782719
:rtype: bool
26792720
2680-
Test whether vertices belong to the same component. For a:
2681-
2682-
- directed graph this implies a path between them
2683-
- undirected graph there is not necessarily a path between them
2721+
Test whether vertices belong to the same component. A component is a
2722+
set of vertices that are connected by a path of edges, ignoring their
2723+
direction, so for a directed graph this does not mean that there is a
2724+
path from one to the other: ``a -> c <- b`` is one component, but there
2725+
is no path from ``a`` to ``b``.
26842726
26852727
.. runblock:: pycon
26862728
@@ -3124,50 +3166,6 @@ def _endpoints_match(self, edge: Edge, v1: Vertex, v2: Vertex) -> bool:
31243166
"""
31253167
return (edge.v1 is v1 and edge.v2 is v2) or (edge.v1 is v2 and edge.v2 is v1)
31263168

3127-
def _graphcolor(self) -> None:
3128-
"""
3129-
Color the graph
3130-
3131-
Performs a depth-first labeling operation, assigning the ``label``
3132-
attribute of every vertex with a sequential integer starting from 0.
3133-
3134-
This method checks the ``_connectivitychange`` attribute of all vertices
3135-
and if any are True it will perform the coloring operation. This flag
3136-
is set True by any operation that adds or removes a vertex or edge.
3137-
3138-
:seealso: :meth:`nc`
3139-
"""
3140-
if self._connectivitychange or any([n._connectivitychange for n in self]):
3141-
3142-
# color the graph
3143-
3144-
# clear all the labels
3145-
for vertex in self:
3146-
vertex._label = None
3147-
vertex._connectivitychange = False
3148-
3149-
lastlabel: int | None = None
3150-
for label in range(self.n):
3151-
assignment = False
3152-
for v in self:
3153-
# find first vertex with no label
3154-
if v.label is None:
3155-
# do BFS
3156-
q = [v] # initialize frontier
3157-
while len(q) > 0:
3158-
v = q.pop() # expand v
3159-
v._label = label
3160-
for n in v.adjacent():
3161-
if n.label is None:
3162-
q.append(n)
3163-
lastlabel = label
3164-
assignment = True
3165-
break
3166-
if not assignment:
3167-
break
3168-
3169-
self._ncomponents = 0 if lastlabel is None else lastlabel + 1
3170-
31713169

31723170
class DGraph(Graph):
31733171
"""
@@ -3213,79 +3211,6 @@ def _incoming(self, vertex: Vertex) -> list[Edge]:
32133211
"""The edges that end at the vertex"""
32143212
return vertex._inlist
32153213

3216-
def _graphcolor(self) -> int | None:
3217-
"""
3218-
Color the graph
3219-
3220-
Performs a depth-first labeling operation, assigning the ``label``
3221-
attribute of every vertex with a sequential integer starting from 0.
3222-
3223-
This method checks the ``_connectivitychange`` attribute of all vertices
3224-
and if any are True it will perform the coloring operation. This flag
3225-
is set True by any operation that adds or removes a vertex or edge.
3226-
3227-
:seealso: :meth:`nc`
3228-
"""
3229-
if self._connectivitychange or any([n._connectivitychange for n in self]):
3230-
3231-
# color the graph
3232-
3233-
# clear all the labels
3234-
for vertex in self:
3235-
vertex._label = None
3236-
vertex._connectivitychange = False
3237-
3238-
# initial labeling pass
3239-
merge: dict[int, int] = {}
3240-
nextlabel = 1
3241-
for v in self:
3242-
if v.label is None:
3243-
# no label, try to inherit one from a neighbour
3244-
for n in v.adjacent():
3245-
if n.label is not None:
3246-
# neighbour has a label
3247-
v._label = n.label
3248-
break
3249-
3250-
if v.label is None:
3251-
# still not labeled, assign a new label
3252-
v._label = nextlabel
3253-
nextlabel += 1
3254-
3255-
label = v.label
3256-
assert label is not None
3257-
3258-
# now look for clashes
3259-
for n in v.adjacent():
3260-
if n.label is None:
3261-
# neighbour has no label, give it this one
3262-
n._label = label
3263-
elif label != n.label:
3264-
# label clash, note it for merging
3265-
assert n.label is not None
3266-
merge[n.label] = label
3267-
3268-
# merge labels and find unique labels
3269-
unique: set[int] = set()
3270-
for v in self:
3271-
vlabel = v.label
3272-
assert vlabel is not None
3273-
while vlabel in merge:
3274-
vlabel = merge[vlabel]
3275-
v._label = vlabel
3276-
unique.add(vlabel)
3277-
3278-
final = {u: i for i, u in enumerate(unique)}
3279-
for v in self:
3280-
vlabel = v.label
3281-
assert vlabel is not None
3282-
v._label = final[vlabel]
3283-
3284-
return len(unique)
3285-
else:
3286-
# no coloring performed
3287-
return None
3288-
32893214

32903215
# ========================================================================== #
32913216

@@ -4413,21 +4338,25 @@ def label(self) -> int | None:
44134338
"""
44144339
Number of the graph component that contains the vertex
44154340
4416-
:return: component number, counted from 0, or None if the components
4417-
have not been found yet
4341+
:return: component number, counted from 0, or None if the vertex is
4342+
not in a graph
44184343
:rtype: int or None
44194344
4420-
Assigned by the graph when its components are found, which happens when
4421-
:attr:`Graph.nc`, :meth:`Graph.component` or
4422-
:meth:`Graph.samecomponent` is used after the graph has changed.
4423-
It is read-only.
4345+
Assigned by the graph, which finds its components when this is read
4346+
after the graph has changed, as it does for :attr:`Graph.nc`,
4347+
:meth:`Graph.component` and :meth:`Graph.samecomponent`. The numbering
4348+
is by the first vertex of each component, in the order the vertices
4349+
were added. It is read-only.
44244350
44254351
.. versionchanged:: 1.0
44264352
Read-only. It was a plain attribute, but it is computed from the
4427-
graph's structure and meaningless to assign.
4353+
graph's structure and meaningless to assign. Reading it finds the
4354+
components; in 0.6.5 it was ``None`` until something else had.
44284355
44294356
:seealso: :attr:`Graph.nc` :meth:`Graph.component`
44304357
"""
4358+
if self._graph is not None:
4359+
self._graph._graphcolor()
44314360
return self._label
44324361

44334362
@property

0 commit comments

Comments
 (0)