Skip to content

Commit 36fdbc8

Browse files
authored
Merge pull request #37 from petercorke/refactor/adjacent-canonical
refactor: adjacent() is the canonical name; neighbours/neighbors are aliases
2 parents f34c61e + 53e0bad commit 36fdbc8

3 files changed

Lines changed: 161 additions & 78 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 53 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1238,7 +1238,7 @@ def plot(
12381238
ax.text(vertex.x, vertex.y, f" {vertex.name}", **textopt)
12391239
if colorcomponents:
12401240
ax.plot(vertex.x, vertex.y, color=color[c, :], **vopt)
1241-
for v in vertex.neighbours():
1241+
for v in vertex.adjacent():
12421242
ax.plot(
12431243
[vertex.x, v.x],
12441244
[vertex.y, v.y],
@@ -1247,7 +1247,7 @@ def plot(
12471247
)
12481248
else:
12491249
ax.plot(vertex.x, vertex.y, **vopt)
1250-
for v in vertex.neighbours():
1250+
for v in vertex.adjacent():
12511251
ax.plot([vertex.x, v.x], [vertex.y, v.y], **eopt)
12521252
else:
12531253
# 3D or higher plotting, just do (x, y, z)
@@ -1267,7 +1267,7 @@ def plot(
12671267
vertex.z,
12681268
**{**dict(color=color[c, :]), **vopt},
12691269
)
1270-
for v in vertex.neighbours():
1270+
for v in vertex.adjacent():
12711271
ax.plot(
12721272
[vertex.x, v.x],
12731273
[vertex.y, v.y],
@@ -1276,7 +1276,7 @@ def plot(
12761276
)
12771277
else:
12781278
ax.plot(vertex.x, vertex.y, vertex.z, **vopt)
1279-
for v in vertex.neighbours():
1279+
for v in vertex.adjacent():
12801280
ax.plot(
12811281
[vertex.x, v.x],
12821282
[vertex.y, v.y],
@@ -1669,7 +1669,7 @@ def iscyclic(self) -> bool:
16691669
repeatedly remove vertices with no remaining incoming edges. If every
16701670
vertex can eventually be removed, the graph is a DAG (acyclic); if
16711671
some are never freed, they form a cycle. This is O(V+E), using
1672-
vertices' outgoing edges via :meth:`BaseVertex.neighbours` the same
1672+
vertices' outgoing edges via :meth:`BaseVertex.adjacent` the same
16731673
way :meth:`path_BFS` and friends do.
16741674
16751675
.. note:: A self-loop is a cycle of length one, so it makes either kind
@@ -1713,7 +1713,7 @@ def iscyclic(self) -> bool:
17131713
while frontier:
17141714
vertex = frontier.pop()
17151715
removed += 1
1716-
for n in vertex.neighbours():
1716+
for n in vertex.adjacent():
17171717
indegree[n] -= 1
17181718
if indegree[n] == 0:
17191719
frontier.append(n)
@@ -1950,7 +1950,7 @@ def adjacency(self) -> NDArray:
19501950

19511951
A = np.zeros((self.n, self.n))
19521952
for vertex in self:
1953-
for n in vertex.neighbours():
1953+
for n in vertex.adjacent():
19541954
A[vdict[vertex], vdict[n]] += 1
19551955
return A
19561956

@@ -2185,7 +2185,7 @@ def path_BFS(
21852185
print(" expand", x.name)
21862186

21872187
# expand the vertex
2188-
for n in x.neighbours():
2188+
for n in x.adjacent():
21892189
if n is x:
21902190
continue # self-loop, never part of a shortest path
21912191
if n is G:
@@ -2526,7 +2526,7 @@ def _graphcolor(self) -> None:
25262526
while len(q) > 0:
25272527
v = q.pop() # expand v
25282528
v.label = label
2529-
for n in v.neighbours():
2529+
for n in v.adjacent():
25302530
if n.label is None:
25312531
q.append(n)
25322532
lastlabel = label
@@ -2580,7 +2580,7 @@ def _graphcolor(self) -> int | None:
25802580
for v in self:
25812581
if v.label is None:
25822582
# no label, try to inherit one from a neighbour
2583-
for n in v.neighbours():
2583+
for n in v.adjacent():
25842584
if n.label is not None:
25852585
# neighbour has a label
25862586
v.label = n.label
@@ -2595,7 +2595,7 @@ def _graphcolor(self) -> int | None:
25952595
assert label is not None
25962596

25972597
# now look for clashes
2598-
for n in v.neighbours():
2598+
for n in v.adjacent():
25992599
if n.label is None:
26002600
# neighbour has no label, give it this one
26012601
n.label = label
@@ -3029,17 +3029,28 @@ def copy(self, cls: type[_BaseGraph] | None = None) -> BaseVertex:
30293029
else:
30303030
return self.__class__(coord=self.coord, name=self.name)
30313031

3032-
def neighbours(self) -> list[BaseVertex]:
3032+
def adjacent(self) -> list[BaseVertex]:
30333033
"""
3034-
Neighbours of a vertex
3034+
Vertices adjacent to this vertex
3035+
3036+
:return: the vertices at the far end of this vertex's edges
3037+
:rtype: list of BaseVertex subclass
30353038
3036-
``v.neighbours()`` is a list of neighbours of this vertex.
3039+
``v.adjacent()`` is a list of the vertices that this vertex is joined
3040+
to by an edge. "Adjacent" is the graph-theory term, and it is the
3041+
relation that :meth:`_BaseGraph.adjacency` tabulates: row ``i`` of the
3042+
adjacency matrix is non-zero exactly at the columns of the vertices
3043+
returned by ``g[i].adjacent()``.
30373044
3038-
.. note:: For a directed graph the neighbours are those on edges leaving this vertex
3045+
.. note::
30393046
3040-
.. note:: There is one entry per edge, so a neighbour joined by ``k``
3041-
parallel edges appears ``k`` times. In an undirected graph a
3042-
self-loop lists the vertex itself twice, once for each end.
3047+
- For a directed graph these are the vertices at the head of the
3048+
edges leaving this vertex, the *successors*.
3049+
- There is one entry per edge, so a vertex joined by ``k`` parallel
3050+
edges appears ``k`` times. In an undirected graph a self-loop
3051+
lists the vertex itself twice, once for each end.
3052+
- ``neighbours`` and ``neighbors`` are aliases, the same method
3053+
under the British and American spellings, and are not deprecated.
30433054
30443055
.. runblock:: pycon
30453056
@@ -3050,60 +3061,31 @@ def neighbours(self) -> list[BaseVertex]:
30503061
>>> v3 = g.add_vertex(coord=[2,2], name='v3')
30513062
>>> g.add_edge(v1, v2)
30523063
>>> g.add_edge(v1, v3)
3053-
>>> print(v1.neighbours())
3064+
>>> print(v1.adjacent())
30543065
3055-
:seealso: :meth:`neighbors` :meth:`incidences`
3066+
:seealso: :meth:`isadjacent` :meth:`incidences` :meth:`edges`
3067+
:meth:`_BaseGraph.adjacency`
30563068
"""
30573069
return [e.next(self) for e in self._edgelist]
30583070

3059-
def neighbors(self) -> list[BaseVertex]:
3060-
"""
3061-
Neighbors of a vertex
3062-
3063-
``v.neighbors()`` is a list of neighbors of this vertex.
3064-
3065-
.. note:: For a directed graph the neighbours are those on edges leaving this vertex
3066-
3067-
.. runblock:: pycon
3068-
3069-
>>> from pgraph import UGraph
3070-
>>> g = UGraph()
3071-
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
3072-
>>> v2 = g.add_vertex(coord=[1,1], name='v2')
3073-
>>> g.add_edge(v1, v2)
3074-
>>> print(v1.neighbors())
3071+
#: alias of :meth:`adjacent`
3072+
neighbours = adjacent
3073+
#: alias of :meth:`adjacent`
3074+
neighbors = adjacent
30753075

3076-
:seealso: :meth:`neighbours`
3076+
def isadjacent(self, vertex: BaseVertex) -> bool:
30773077
"""
3078-
return [e.next(self) for e in self._edgelist]
3079-
3080-
def adjacent(self) -> list[BaseVertex]:
3081-
"""
3082-
Neighbours of a vertex (deprecated)
3083-
3084-
:return: a list of neighbours of this vertex
3085-
:rtype: list of BaseVertex subclass
3086-
3087-
.. deprecated:: use :meth:`neighbours` instead
3088-
"""
3089-
warnings.warn(
3090-
"adjacent() is deprecated, use neighbours() instead",
3091-
DeprecationWarning,
3092-
stacklevel=2,
3093-
)
3094-
return self.neighbours()
3095-
3096-
def isneighbour(self, vertex: BaseVertex) -> bool:
3097-
"""
3098-
Test if vertex is a neigbour
3078+
Test if a vertex is adjacent to this vertex
30993079
31003080
:param vertex: vertex reference
31013081
:type vertex: BaseVertex subclass
3102-
:return: true if a neighbour
3082+
:return: true if ``vertex`` is adjacent
31033083
:rtype: bool
31043084
3105-
For a directed graph this is true only if the edge is from ``self`` to
3106-
``vertex``.
3085+
For a directed graph this is true only if there is an edge from
3086+
``self`` to ``vertex``.
3087+
3088+
``isneighbour`` and ``isneighbor`` are aliases.
31073089
31083090
.. runblock:: pycon
31093091
@@ -3113,19 +3095,24 @@ def isneighbour(self, vertex: BaseVertex) -> bool:
31133095
>>> v2 = g.add_vertex(coord=[1,1], name='v2')
31143096
>>> v3 = g.add_vertex(coord=[2,2], name='v3')
31153097
>>> g.add_edge(v1, v2)
3116-
>>> print(v1.isneighbour(v2))
3117-
>>> print(v1.isneighbour(v3))
3098+
>>> print(v1.isadjacent(v2))
3099+
>>> print(v1.isadjacent(v3))
31183100
3119-
:seealso: :meth:`neighbours`
3101+
:seealso: :meth:`adjacent`
31203102
"""
31213103
return vertex in [e.next(self) for e in self._edgelist]
31223104

3105+
#: alias of :meth:`isadjacent`
3106+
isneighbour = isadjacent
3107+
#: alias of :meth:`isadjacent`
3108+
isneighbor = isadjacent
3109+
31233110
def incidences(self) -> list[tuple[BaseVertex, Edge]]:
31243111
"""
31253112
Neighbours and edges of a vertex
31263113
31273114
``v.incidences()`` is a generator that returns a list of incidences,
3128-
tuples of (vertex, edge) for all neighbours of the vertex ``v``.
3115+
tuples of (vertex, edge) for all vertices adjacent to the vertex ``v``.
31293116
31303117
.. note:: For a directed graph the edges are those leaving this vertex
31313118
@@ -3138,7 +3125,7 @@ def incidences(self) -> list[tuple[BaseVertex, Edge]]:
31383125
>>> g.add_edge(v1, v2)
31393126
>>> print(v1.incidences())
31403127
3141-
:seealso: :meth:`neighbours` :meth:`edges`
3128+
:seealso: :meth:`adjacent` :meth:`edges`
31423129
"""
31433130
return [(e.next(self), e) for e in self._edgelist]
31443131

‎tests/test_adjacent.py‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
"""
2+
``adjacent()`` is the canonical name for the vertices at the far end of a
3+
vertex's edges, because "adjacent" is the graph-theory term and has one
4+
spelling. ``neighbours`` and ``neighbors`` (and ``isneighbour`` /
5+
``isneighbor``) remain as silent aliases: they are the same function, not a
6+
second implementation, and they do not warn.
7+
"""
8+
9+
import unittest
10+
import warnings
11+
12+
from pgraph import DGraph, UGraph, DVertex, UVertex
13+
from pgraph.PGraph import BaseVertex
14+
15+
16+
class TestAliases(unittest.TestCase):
17+
def test_aliases_are_the_same_function(self):
18+
for cls in (BaseVertex, UVertex, DVertex):
19+
with self.subTest(cls=cls.__name__):
20+
self.assertIs(cls.neighbours, cls.adjacent)
21+
self.assertIs(cls.neighbors, cls.adjacent)
22+
self.assertIs(cls.isneighbour, cls.isadjacent)
23+
self.assertIs(cls.isneighbor, cls.isadjacent)
24+
25+
def test_no_warnings(self):
26+
g = UGraph()
27+
a, b = g.add_vertex(name="a"), g.add_vertex(name="b")
28+
a.connect(b)
29+
with warnings.catch_warnings():
30+
warnings.simplefilter("error") # any warning is an error
31+
for name in ("adjacent", "neighbours", "neighbors"):
32+
self.assertEqual(getattr(a, name)(), [b])
33+
for name in ("isadjacent", "isneighbour", "isneighbor"):
34+
self.assertTrue(getattr(a, name)(b))
35+
36+
def test_docstring_names_the_aliases(self):
37+
doc = BaseVertex.adjacent.__doc__
38+
for name in ("neighbours", "neighbors"):
39+
self.assertIn(name, doc)
40+
41+
42+
class _Adjacent:
43+
Graph: type
44+
45+
def setUp(self):
46+
self.g = self.Graph()
47+
self.a = self.g.add_vertex([0, 0], name="a")
48+
self.b = self.g.add_vertex([1, 0], name="b")
49+
self.c = self.g.add_vertex([2, 0], name="c")
50+
51+
def test_simple(self):
52+
self.a.connect(self.b)
53+
self.assertEqual(self.a.adjacent(), [self.b])
54+
self.assertTrue(self.a.isadjacent(self.b))
55+
self.assertFalse(self.a.isadjacent(self.c))
56+
57+
def test_returns_a_new_list(self):
58+
self.a.connect(self.b)
59+
r = self.a.adjacent()
60+
r.clear()
61+
self.assertEqual(self.a.adjacent(), [self.b])
62+
63+
def test_parallel_edges_listed_once_per_edge(self):
64+
for _ in range(3):
65+
self.a.connect(self.b)
66+
self.assertEqual(self.a.adjacent(), [self.b, self.b, self.b])
67+
68+
def test_matches_a_row_of_the_adjacency_matrix(self):
69+
# the point of the name: row i of adjacency() is the vertices adjacent
70+
# to vertex i, with multiplicity
71+
self.a.connect(self.b)
72+
self.a.connect(self.b)
73+
self.a.connect(self.c)
74+
A = self.g.adjacency()
75+
for i, v in enumerate(self.g):
76+
counts = {w: v.adjacent().count(w) for w in self.g}
77+
for j, w in enumerate(self.g):
78+
self.assertEqual(A[i, j], counts[w], (v.name, w.name))
79+
80+
81+
class TestUGraphAdjacent(_Adjacent, unittest.TestCase):
82+
Graph = UGraph
83+
84+
def test_both_ends(self):
85+
self.a.connect(self.b)
86+
self.assertEqual(self.b.adjacent(), [self.a])
87+
self.assertTrue(self.b.isadjacent(self.a))
88+
89+
def test_self_loop_listed_twice(self):
90+
self.a.connect(self.a)
91+
self.assertEqual(self.a.adjacent(), [self.a, self.a])
92+
93+
94+
class TestDGraphAdjacent(_Adjacent, unittest.TestCase):
95+
Graph = DGraph
96+
97+
def test_outgoing_only(self):
98+
self.a.connect(self.b)
99+
self.assertEqual(self.b.adjacent(), [])
100+
self.assertFalse(self.b.isadjacent(self.a))
101+
102+
def test_self_loop_listed_once(self):
103+
self.a.connect(self.a)
104+
self.assertEqual(self.a.adjacent(), [self.a])
105+
106+
107+
if __name__ == "__main__":
108+
unittest.main()

‎tests/test_graph.py‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -153,18 +153,6 @@ def test_neighbours(self):
153153
self.assertFalse(v1.isneighbour(v3))
154154
self.assertFalse(v3.isneighbour(v1))
155155

156-
def test_adjacent_deprecated(self):
157-
# adjacent() must still work (same result as neighbours()) but
158-
# emit a DeprecationWarning, not a hard failure
159-
g = UGraph()
160-
v1 = g.add_vertex(name='v1')
161-
v2 = g.add_vertex(name='v2')
162-
v1.connect(v2)
163-
164-
with self.assertWarns(DeprecationWarning):
165-
n = v1.adjacent()
166-
self.assertEqual(n, v1.neighbours())
167-
168156
def test_getitem(self):
169157
g = UGraph()
170158
v1 = g.add_vertex(name='v1')

0 commit comments

Comments
 (0)