@@ -1310,6 +1310,7 @@ def remove_vertex(self, vertex: Vertex) -> None:
13101310 self ._vertexlist .remove (vertex )
13111311 del self ._vertexdict [vertex .name ]
13121312 vertex ._graph = None # it is not in any graph now
1313+ vertex ._label = None # and so not in a component
13131314 self ._connectivitychange = True
13141315
13151316 def remove (self , x : Edge | Vertex ) -> None :
@@ -1398,19 +1399,52 @@ def ne(self) -> int:
13981399 """
13991400 return len (self ._edges )
14001401
1401- def _graphcolor (self ) -> int | None :
1402+ def _graphcolor (self ) -> None :
14021403 """
1403- Color the graph (subclass method)
1404+ Label the components of the graph (private method)
14041405
1405- Concrete graph coloring algorithm, provided by :meth:`UGraph._graphcolor`
1406- and :meth:`DGraph._graphcolor`.
1406+ Assigns every vertex a ``label``, the number of its component, from 0
1407+ in the order of the first vertex of each component, and sets the
1408+ number of components. Components are *weakly* connected: the
1409+ direction of an edge is ignored, so a vertex is in the component of
1410+ every vertex that it has a path to or from.
14071411
1408- :raises NotImplementedError: not provided by this graph kind
1412+ This is a single pass over the vertices and edges, O(V + E), and is
1413+ only done again when the graph has changed since, which every
1414+ operation that adds or removes a vertex or edge records in the graph's
1415+ ``_connectivitychange``.
1416+
1417+ :seealso: :meth:`nc` :meth:`component`
14091418 """
1410- raise NotImplementedError (
1411- f"{ type (self ).__name__ } does not define how to color the graph; "
1412- "subclass UGraph or DGraph"
1413- )
1419+ if not self ._connectivitychange :
1420+ return
1421+
1422+ for vertex in self :
1423+ vertex ._label = None
1424+ vertex ._connectivitychange = False
1425+
1426+ count = 0
1427+ for start in self :
1428+ if start ._label is not None :
1429+ continue
1430+ start ._label = count
1431+ frontier = [start ]
1432+ while frontier :
1433+ v = frontier .pop ()
1434+ # an edge may be followed against its direction, so the
1435+ # vertices that lead to this one count as well as those it
1436+ # leads to; in an undirected graph they are the same
1437+ around = v .adjacent ()
1438+ if self .directed :
1439+ around = around + v .predecessors ()
1440+ for w in around :
1441+ if w ._label is None :
1442+ w ._label = count
1443+ frontier .append (w )
1444+ count += 1
1445+
1446+ self ._ncomponents = count
1447+ self ._connectivitychange = False
14141448
14151449 @property
14161450 def nc (self ) -> int :
@@ -1422,6 +1456,16 @@ def nc(self) -> int:
14221456
14231457 Number of components in the graph. Components are labeled from 0 to ``g.nc-1``.
14241458
1459+ For a directed graph the components are *weakly* connected: the
1460+ direction of the edges is ignored, so two vertices are in the same
1461+ component if there is a path between them that may run against the
1462+ arrows. A graph with no vertices has no components.
1463+
1464+ .. versionchanged:: 1.0
1465+ Does not hang. For many directed graphs, the smallest being the
1466+ 4-cycle, the algorithm of 0.6.5 never finished, which also stopped
1467+ :meth:`component`, :meth:`samecomponent` and :meth:`plot`.
1468+
14251469 .. runblock:: pycon
14261470
14271471 >>> from pgraph import UGraph
@@ -1439,10 +1483,7 @@ def nc(self) -> int:
14391483
14401484 :seealso: :meth:`component` :meth:`samecomponent`
14411485 """
1442- n = self ._graphcolor ()
1443- if n is not None :
1444- self ._ncomponents = n
1445-
1486+ self ._graphcolor ()
14461487 return self ._ncomponents
14471488
14481489 def _metricfunc (self , metric : Callable [[NDArray ], float ] | str ) -> Callable [[NDArray ], float ]:
@@ -2955,10 +2996,11 @@ def samecomponent(self, v1: Vertex, v2: Vertex) -> bool:
29552996 :return: true if vertices belong to same graph component
29562997 :rtype: bool
29572998
2958- Test whether vertices belong to the same component. For a:
2959-
2960- - directed graph this implies a path between them
2961- - undirected graph there is not necessarily a path between them
2999+ Test whether vertices belong to the same component. A component is a
3000+ set of vertices that are connected by a path of edges, ignoring their
3001+ direction, so for a directed graph this does not mean that there is a
3002+ path from one to the other: ``a -> c <- b`` is one component, but there
3003+ is no path from ``a`` to ``b``.
29623004
29633005 .. runblock:: pycon
29643006
@@ -3402,50 +3444,6 @@ def _endpoints_match(self, edge: Edge, v1: Vertex, v2: Vertex) -> bool:
34023444 """
34033445 return (edge .v1 is v1 and edge .v2 is v2 ) or (edge .v1 is v2 and edge .v2 is v1 )
34043446
3405- def _graphcolor (self ) -> None :
3406- """
3407- Color the graph
3408-
3409- Performs a depth-first labeling operation, assigning the ``label``
3410- attribute of every vertex with a sequential integer starting from 0.
3411-
3412- This method checks the ``_connectivitychange`` attribute of all vertices
3413- and if any are True it will perform the coloring operation. This flag
3414- is set True by any operation that adds or removes a vertex or edge.
3415-
3416- :seealso: :meth:`nc`
3417- """
3418- if self ._connectivitychange or any ([n ._connectivitychange for n in self ]):
3419-
3420- # color the graph
3421-
3422- # clear all the labels
3423- for vertex in self :
3424- vertex ._label = None
3425- vertex ._connectivitychange = False
3426-
3427- lastlabel : int | None = None
3428- for label in range (self .n ):
3429- assignment = False
3430- for v in self :
3431- # find first vertex with no label
3432- if v .label is None :
3433- # do BFS
3434- q = [v ] # initialize frontier
3435- while len (q ) > 0 :
3436- v = q .pop () # expand v
3437- v ._label = label
3438- for n in v .adjacent ():
3439- if n .label is None :
3440- q .append (n )
3441- lastlabel = label
3442- assignment = True
3443- break
3444- if not assignment :
3445- break
3446-
3447- self ._ncomponents = 0 if lastlabel is None else lastlabel + 1
3448-
34493447
34503448class DGraph (Graph ):
34513449 """
@@ -3491,79 +3489,6 @@ def _incoming(self, vertex: Vertex) -> list[Edge]:
34913489 """The edges that end at the vertex"""
34923490 return vertex ._inlist
34933491
3494- def _graphcolor (self ) -> int | None :
3495- """
3496- Color the graph
3497-
3498- Performs a depth-first labeling operation, assigning the ``label``
3499- attribute of every vertex with a sequential integer starting from 0.
3500-
3501- This method checks the ``_connectivitychange`` attribute of all vertices
3502- and if any are True it will perform the coloring operation. This flag
3503- is set True by any operation that adds or removes a vertex or edge.
3504-
3505- :seealso: :meth:`nc`
3506- """
3507- if self ._connectivitychange or any ([n ._connectivitychange for n in self ]):
3508-
3509- # color the graph
3510-
3511- # clear all the labels
3512- for vertex in self :
3513- vertex ._label = None
3514- vertex ._connectivitychange = False
3515-
3516- # initial labeling pass
3517- merge : dict [int , int ] = {}
3518- nextlabel = 1
3519- for v in self :
3520- if v .label is None :
3521- # no label, try to inherit one from a neighbour
3522- for n in v .adjacent ():
3523- if n .label is not None :
3524- # neighbour has a label
3525- v ._label = n .label
3526- break
3527-
3528- if v .label is None :
3529- # still not labeled, assign a new label
3530- v ._label = nextlabel
3531- nextlabel += 1
3532-
3533- label = v .label
3534- assert label is not None
3535-
3536- # now look for clashes
3537- for n in v .adjacent ():
3538- if n .label is None :
3539- # neighbour has no label, give it this one
3540- n ._label = label
3541- elif label != n .label :
3542- # label clash, note it for merging
3543- assert n .label is not None
3544- merge [n .label ] = label
3545-
3546- # merge labels and find unique labels
3547- unique : set [int ] = set ()
3548- for v in self :
3549- vlabel = v .label
3550- assert vlabel is not None
3551- while vlabel in merge :
3552- vlabel = merge [vlabel ]
3553- v ._label = vlabel
3554- unique .add (vlabel )
3555-
3556- final = {u : i for i , u in enumerate (unique )}
3557- for v in self :
3558- vlabel = v .label
3559- assert vlabel is not None
3560- v ._label = final [vlabel ]
3561-
3562- return len (unique )
3563- else :
3564- # no coloring performed
3565- return None
3566-
35673492
35683493# ========================================================================== #
35693494
@@ -4691,21 +4616,25 @@ def label(self) -> int | None:
46914616 """
46924617 Number of the graph component that contains the vertex
46934618
4694- :return: component number, counted from 0, or None if the components
4695- have not been found yet
4619+ :return: component number, counted from 0, or None if the vertex is
4620+ not in a graph
46964621 :rtype: int or None
46974622
4698- Assigned by the graph when its components are found, which happens when
4699- :attr:`Graph.nc`, :meth:`Graph.component` or
4700- :meth:`Graph.samecomponent` is used after the graph has changed.
4701- It is read-only.
4623+ Assigned by the graph, which finds its components when this is read
4624+ after the graph has changed, as it does for :attr:`Graph.nc`,
4625+ :meth:`Graph.component` and :meth:`Graph.samecomponent`. The numbering
4626+ is by the first vertex of each component, in the order the vertices
4627+ were added. It is read-only.
47024628
47034629 .. versionchanged:: 1.0
47044630 Read-only. It was a plain attribute, but it is computed from the
4705- graph's structure and meaningless to assign.
4631+ graph's structure and meaningless to assign. Reading it finds the
4632+ components; in 0.6.5 it was ``None`` until something else had.
47064633
47074634 :seealso: :attr:`Graph.nc` :meth:`Graph.component`
47084635 """
4636+ if self ._graph is not None :
4637+ self ._graph ._graphcolor ()
47094638 return self ._label
47104639
47114640 @property
0 commit comments