Skip to content

Commit 7c68cab

Browse files
authored
Merge pull request #32 from petercorke/fix/adjacency-diagonal-loops
fix: Adjacency() makes self-loops from the diagonal for both graph kinds
2 parents 3b203d9 + 96ba4d6 commit 7c68cab

2 files changed

Lines changed: 101 additions & 13 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -219,9 +219,8 @@ def Adjacency(
219219
:type names: list(N) of str, optional
220220
:param kwargs: optional arguments passed to the graph constructor, for
221221
example ``vertex_class`` or ``edge_class``
222-
:raises ValueError: ``A`` is not square, the length of ``names`` or
223-
the number of rows of ``coords`` does not match ``A``, or ``A``
224-
has a non-zero diagonal element and the graph is a ``DGraph``
222+
:raises ValueError: ``A`` is not square, or the length of ``names`` or
223+
the number of rows of ``coords`` does not match ``A``
225224
:raises TypeError: ``vertex_class`` or ``edge_class`` is not a
226225
suitable class, see :meth:`_BaseGraph.__init__`
227226
:return: graph
@@ -230,12 +229,14 @@ def Adjacency(
230229
Create a directed or undirected graph where non-zero elements ``A[i,j]``
231230
correspond to edges from vertex ``i`` to vertex ``j``.
232231
232+
A non-zero diagonal element ``A[i,i]`` is a self-loop on vertex ``i``,
233+
for both kinds of graph.
234+
233235
.. warning:: For undirected graph ``A`` should be symmetric but this
234-
is not checked. Only the strictly upper triangular part is used,
235-
so the diagonal is ignored and no self-loops are created. A
236-
directed graph rejects a non-zero diagonal with ``ValueError``.
237-
Edge counts greater than one are not turned into parallel edges;
238-
a non-zero element is a single edge with that element as its cost.
236+
is not checked. Only the upper triangular part, including the
237+
diagonal, is used. Elements are costs, not edge counts: a non-zero
238+
element is a single edge with that element as its cost, so
239+
parallel edges cannot be created this way.
239240
240241
.. runblock:: pycon
241242
@@ -267,18 +268,16 @@ def Adjacency(
267268
g.add_vertex(name=name, coord=coord)
268269

269270
if isinstance(g, UGraph):
270-
# undirected graph
271+
# undirected graph: upper triangle including the diagonal
271272
for i in range(A.shape[0]):
272-
for j in range(i + 1, A.shape[1]):
273+
for j in range(i, A.shape[1]):
273274
if A[i, j] > 0:
274275
g[i].connect(g[j], cost=A[i, j])
275276
else:
276-
# directed graph
277+
# directed graph: whole matrix, a diagonal element is a self-loop
277278
for i in range(A.shape[0]):
278279
for j in range(A.shape[1]):
279280
if A[i, j] > 0:
280-
if i == j:
281-
raise ValueError("loops in graph not supported")
282281
g[i].connect(g[j], cost=A[i, j])
283282

284283
return g

‎tests/test_adjacency_loops.py‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
"""
2+
A non-zero diagonal element of the matrix given to ``Adjacency()`` is a
3+
self-loop, for undirected and directed graphs alike. The package permits
4+
self-loops everywhere else (``connect``, ``add_edge``), so the factory must
5+
not be the one place that silently drops, or refuses, them.
6+
"""
7+
8+
import unittest
9+
10+
import numpy as np
11+
12+
from pgraph import DGraph, UGraph
13+
14+
15+
class _AdjacencyLoops:
16+
Graph: type
17+
18+
def setUp(self):
19+
# 0 1 2
20+
self.A = np.array(
21+
[
22+
[0, 1, 0], # 0 -- 1
23+
[1, 4, 1], # 1 has a self-loop of cost 4, and -- 2
24+
[0, 1, 0],
25+
]
26+
)
27+
28+
def loops(self, g):
29+
return [e for e in g.edges() if e.v1 is e.v2]
30+
31+
def test_diagonal_makes_a_self_loop(self):
32+
g = self.Graph.Adjacency(self.A)
33+
34+
self.assertEqual(g.n, 3)
35+
self.assertEqual(g.ne, self.ne_with_loop)
36+
loops = self.loops(g)
37+
self.assertEqual(len(loops), 1)
38+
self.assertIs(loops[0].v1, g[1])
39+
self.assertEqual(loops[0].cost, 4)
40+
41+
def test_no_diagonal_no_loop(self):
42+
A = self.A.copy()
43+
A[1, 1] = 0
44+
g = self.Graph.Adjacency(A)
45+
self.assertEqual(self.loops(g), [])
46+
self.assertEqual(g.ne, self.ne_without_loop)
47+
48+
def test_loop_is_a_real_edge(self):
49+
g = self.Graph.Adjacency(self.A)
50+
self.assertTrue(g.iscyclic())
51+
self.assertEqual(g.distance()[1, 1], 4)
52+
53+
def test_other_validation_unchanged(self):
54+
with self.assertRaises(ValueError):
55+
self.Graph.Adjacency(np.zeros((2, 3)))
56+
with self.assertRaises(ValueError):
57+
self.Graph.Adjacency(np.zeros((2, 2)), names=["a"])
58+
with self.assertRaises(ValueError):
59+
self.Graph.Adjacency(np.zeros((2, 2)), coords=np.zeros((3, 2)))
60+
61+
62+
class TestUGraphAdjacencyLoops(_AdjacencyLoops, unittest.TestCase):
63+
Graph = UGraph
64+
# the symmetric matrix is read once, upper triangle: 0--1, 1--2 and 1--1
65+
ne_with_loop = 3
66+
ne_without_loop = 2
67+
68+
def test_lower_triangle_still_ignored(self):
69+
# documented: only the upper triangle (and now the diagonal) is read
70+
A = np.array([[0, 0], [5, 0]])
71+
g = UGraph.Adjacency(A)
72+
self.assertEqual(g.ne, 0)
73+
74+
75+
class TestDGraphAdjacencyLoops(_AdjacencyLoops, unittest.TestCase):
76+
Graph = DGraph
77+
# the whole matrix is read: 0->1, 1->0, 1->2, 2->1 and 1->1
78+
ne_with_loop = 5
79+
ne_without_loop = 4
80+
81+
def test_directed_uses_whole_matrix(self):
82+
A = np.array([[0, 0], [5, 0]])
83+
g = DGraph.Adjacency(A)
84+
self.assertEqual(g.ne, 1)
85+
self.assertEqual(g[1].neighbours(), [g[0]])
86+
87+
88+
if __name__ == "__main__":
89+
unittest.main()

0 commit comments

Comments
 (0)