Skip to content

Commit 1df4d4c

Browse files
petercorkeclaude
andcommitted
test: Adjacency() turns a non-zero diagonal into self-loops
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent a17d3cc commit 1df4d4c

1 file changed

Lines changed: 86 additions & 0 deletions

File tree

‎tests/test_adjacency_loops.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
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, 3) # 0--1, 1--2, 1--1
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, 2)
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+
self.assertEqual(g.adjacency()[1, 1], self.loop_adjacency)
53+
54+
def test_other_validation_unchanged(self):
55+
with self.assertRaises(ValueError):
56+
self.Graph.Adjacency(np.zeros((2, 3)))
57+
with self.assertRaises(ValueError):
58+
self.Graph.Adjacency(np.zeros((2, 2)), names=["a"])
59+
with self.assertRaises(ValueError):
60+
self.Graph.Adjacency(np.zeros((2, 2)), coords=np.zeros((3, 2)))
61+
62+
63+
class TestUGraphAdjacencyLoops(_AdjacencyLoops, unittest.TestCase):
64+
Graph = UGraph
65+
loop_adjacency = 2 # an undirected loop has two ends
66+
67+
def test_lower_triangle_still_ignored(self):
68+
# documented: only the upper triangle (and now the diagonal) is read
69+
A = np.array([[0, 0], [5, 0]])
70+
g = UGraph.Adjacency(A)
71+
self.assertEqual(g.ne, 0)
72+
73+
74+
class TestDGraphAdjacencyLoops(_AdjacencyLoops, unittest.TestCase):
75+
Graph = DGraph
76+
loop_adjacency = 1
77+
78+
def test_directed_uses_whole_matrix(self):
79+
A = np.array([[0, 0], [5, 0]])
80+
g = DGraph.Adjacency(A)
81+
self.assertEqual(g.ne, 1)
82+
self.assertEqual(g[1].neighbours(), [g[0]])
83+
84+
85+
if __name__ == "__main__":
86+
unittest.main()

0 commit comments

Comments
 (0)