aboutsummaryrefslogtreecommitdiff
path: root/.venv/lib/python3.12/site-packages/networkx/algorithms/tests/test_distance_measures.py
blob: 0b3840fd23e0bca32d708a276d4b3e328b9dc82d (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
import math
from random import Random

import pytest

import networkx as nx
from networkx import convert_node_labels_to_integers as cnlti
from networkx.algorithms.distance_measures import _extrema_bounding


def test__extrema_bounding_invalid_compute_kwarg():
    G = nx.path_graph(3)
    with pytest.raises(ValueError, match="compute must be one of"):
        _extrema_bounding(G, compute="spam")


class TestDistance:
    def setup_method(self):
        G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
        self.G = G

    def test_eccentricity(self):
        assert nx.eccentricity(self.G, 1) == 6
        e = nx.eccentricity(self.G)
        assert e[1] == 6

        sp = dict(nx.shortest_path_length(self.G))
        e = nx.eccentricity(self.G, sp=sp)
        assert e[1] == 6

        e = nx.eccentricity(self.G, v=1)
        assert e == 6

        # This behavior changed in version 1.8 (ticket #739)
        e = nx.eccentricity(self.G, v=[1, 1])
        assert e[1] == 6
        e = nx.eccentricity(self.G, v=[1, 2])
        assert e[1] == 6

        # test against graph with one node
        G = nx.path_graph(1)
        e = nx.eccentricity(G)
        assert e[0] == 0
        e = nx.eccentricity(G, v=0)
        assert e == 0
        pytest.raises(nx.NetworkXError, nx.eccentricity, G, 1)

        # test against empty graph
        G = nx.empty_graph()
        e = nx.eccentricity(G)
        assert e == {}

    def test_diameter(self):
        assert nx.diameter(self.G) == 6

    def test_harmonic_diameter(self):
        assert abs(nx.harmonic_diameter(self.G) - 2.0477815699658715) < 1e-12

    def test_harmonic_diameter_empty(self):
        assert math.isnan(nx.harmonic_diameter(nx.empty_graph()))

    def test_harmonic_diameter_single_node(self):
        assert math.isnan(nx.harmonic_diameter(nx.empty_graph(1)))

    def test_harmonic_diameter_discrete(self):
        assert math.isinf(nx.harmonic_diameter(nx.empty_graph(3)))

    def test_harmonic_diameter_not_strongly_connected(self):
        DG = nx.DiGraph()
        DG.add_edge(0, 1)
        assert nx.harmonic_diameter(DG) == 2

    def test_radius(self):
        assert nx.radius(self.G) == 4

    def test_periphery(self):
        assert set(nx.periphery(self.G)) == {1, 4, 13, 16}

    def test_center(self):
        assert set(nx.center(self.G)) == {6, 7, 10, 11}

    def test_bound_diameter(self):
        assert nx.diameter(self.G, usebounds=True) == 6

    def test_bound_radius(self):
        assert nx.radius(self.G, usebounds=True) == 4

    def test_bound_periphery(self):
        result = {1, 4, 13, 16}
        assert set(nx.periphery(self.G, usebounds=True)) == result

    def test_bound_center(self):
        result = {6, 7, 10, 11}
        assert set(nx.center(self.G, usebounds=True)) == result

    def test_radius_exception(self):
        G = nx.Graph()
        G.add_edge(1, 2)
        G.add_edge(3, 4)
        pytest.raises(nx.NetworkXError, nx.diameter, G)

    def test_eccentricity_infinite(self):
        with pytest.raises(nx.NetworkXError):
            G = nx.Graph([(1, 2), (3, 4)])
            e = nx.eccentricity(G)

    def test_eccentricity_undirected_not_connected(self):
        with pytest.raises(nx.NetworkXError):
            G = nx.Graph([(1, 2), (3, 4)])
            e = nx.eccentricity(G, sp=1)

    def test_eccentricity_directed_weakly_connected(self):
        with pytest.raises(nx.NetworkXError):
            DG = nx.DiGraph([(1, 2), (1, 3)])
            nx.eccentricity(DG)


class TestWeightedDistance:
    def setup_method(self):
        G = nx.Graph()
        G.add_edge(0, 1, weight=0.6, cost=0.6, high_cost=6)
        G.add_edge(0, 2, weight=0.2, cost=0.2, high_cost=2)
        G.add_edge(2, 3, weight=0.1, cost=0.1, high_cost=1)
        G.add_edge(2, 4, weight=0.7, cost=0.7, high_cost=7)
        G.add_edge(2, 5, weight=0.9, cost=0.9, high_cost=9)
        G.add_edge(1, 5, weight=0.3, cost=0.3, high_cost=3)
        self.G = G
        self.weight_fn = lambda v, u, e: 2

    def test_eccentricity_weight_None(self):
        assert nx.eccentricity(self.G, 1, weight=None) == 3
        e = nx.eccentricity(self.G, weight=None)
        assert e[1] == 3

        e = nx.eccentricity(self.G, v=1, weight=None)
        assert e == 3

        # This behavior changed in version 1.8 (ticket #739)
        e = nx.eccentricity(self.G, v=[1, 1], weight=None)
        assert e[1] == 3
        e = nx.eccentricity(self.G, v=[1, 2], weight=None)
        assert e[1] == 3

    def test_eccentricity_weight_attr(self):
        assert nx.eccentricity(self.G, 1, weight="weight") == 1.5
        e = nx.eccentricity(self.G, weight="weight")
        assert (
            e
            == nx.eccentricity(self.G, weight="cost")
            != nx.eccentricity(self.G, weight="high_cost")
        )
        assert e[1] == 1.5

        e = nx.eccentricity(self.G, v=1, weight="weight")
        assert e == 1.5

        # This behavior changed in version 1.8 (ticket #739)
        e = nx.eccentricity(self.G, v=[1, 1], weight="weight")
        assert e[1] == 1.5
        e = nx.eccentricity(self.G, v=[1, 2], weight="weight")
        assert e[1] == 1.5

    def test_eccentricity_weight_fn(self):
        assert nx.eccentricity(self.G, 1, weight=self.weight_fn) == 6
        e = nx.eccentricity(self.G, weight=self.weight_fn)
        assert e[1] == 6

        e = nx.eccentricity(self.G, v=1, weight=self.weight_fn)
        assert e == 6

        # This behavior changed in version 1.8 (ticket #739)
        e = nx.eccentricity(self.G, v=[1, 1], weight=self.weight_fn)
        assert e[1] == 6
        e = nx.eccentricity(self.G, v=[1, 2], weight=self.weight_fn)
        assert e[1] == 6

    def test_diameter_weight_None(self):
        assert nx.diameter(self.G, weight=None) == 3

    def test_diameter_weight_attr(self):
        assert (
            nx.diameter(self.G, weight="weight")
            == nx.diameter(self.G, weight="cost")
            == 1.6
            != nx.diameter(self.G, weight="high_cost")
        )

    def test_diameter_weight_fn(self):
        assert nx.diameter(self.G, weight=self.weight_fn) == 6

    def test_radius_weight_None(self):
        assert pytest.approx(nx.radius(self.G, weight=None)) == 2

    def test_radius_weight_attr(self):
        assert (
            pytest.approx(nx.radius(self.G, weight="weight"))
            == pytest.approx(nx.radius(self.G, weight="cost"))
            == 0.9
            != nx.radius(self.G, weight="high_cost")
        )

    def test_radius_weight_fn(self):
        assert nx.radius(self.G, weight=self.weight_fn) == 4

    def test_periphery_weight_None(self):
        for v in set(nx.periphery(self.G, weight=None)):
            assert nx.eccentricity(self.G, v, weight=None) == nx.diameter(
                self.G, weight=None
            )

    def test_periphery_weight_attr(self):
        periphery = set(nx.periphery(self.G, weight="weight"))
        assert (
            periphery
            == set(nx.periphery(self.G, weight="cost"))
            == set(nx.periphery(self.G, weight="high_cost"))
        )
        for v in periphery:
            assert (
                nx.eccentricity(self.G, v, weight="high_cost")
                != nx.eccentricity(self.G, v, weight="weight")
                == nx.eccentricity(self.G, v, weight="cost")
                == nx.diameter(self.G, weight="weight")
                == nx.diameter(self.G, weight="cost")
                != nx.diameter(self.G, weight="high_cost")
            )
            assert nx.eccentricity(self.G, v, weight="high_cost") == nx.diameter(
                self.G, weight="high_cost"
            )

    def test_periphery_weight_fn(self):
        for v in set(nx.periphery(self.G, weight=self.weight_fn)):
            assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.diameter(
                self.G, weight=self.weight_fn
            )

    def test_center_weight_None(self):
        for v in set(nx.center(self.G, weight=None)):
            assert pytest.approx(nx.eccentricity(self.G, v, weight=None)) == nx.radius(
                self.G, weight=None
            )

    def test_center_weight_attr(self):
        center = set(nx.center(self.G, weight="weight"))
        assert (
            center
            == set(nx.center(self.G, weight="cost"))
            != set(nx.center(self.G, weight="high_cost"))
        )
        for v in center:
            assert (
                nx.eccentricity(self.G, v, weight="high_cost")
                != pytest.approx(nx.eccentricity(self.G, v, weight="weight"))
                == pytest.approx(nx.eccentricity(self.G, v, weight="cost"))
                == nx.radius(self.G, weight="weight")
                == nx.radius(self.G, weight="cost")
                != nx.radius(self.G, weight="high_cost")
            )
            assert nx.eccentricity(self.G, v, weight="high_cost") == nx.radius(
                self.G, weight="high_cost"
            )

    def test_center_weight_fn(self):
        for v in set(nx.center(self.G, weight=self.weight_fn)):
            assert nx.eccentricity(self.G, v, weight=self.weight_fn) == nx.radius(
                self.G, weight=self.weight_fn
            )

    def test_bound_diameter_weight_None(self):
        assert nx.diameter(self.G, usebounds=True, weight=None) == 3

    def test_bound_diameter_weight_attr(self):
        assert (
            nx.diameter(self.G, usebounds=True, weight="high_cost")
            != nx.diameter(self.G, usebounds=True, weight="weight")
            == nx.diameter(self.G, usebounds=True, weight="cost")
            == 1.6
            != nx.diameter(self.G, usebounds=True, weight="high_cost")
        )
        assert nx.diameter(self.G, usebounds=True, weight="high_cost") == nx.diameter(
            self.G, usebounds=True, weight="high_cost"
        )

    def test_bound_diameter_weight_fn(self):
        assert nx.diameter(self.G, usebounds=True, weight=self.weight_fn) == 6

    def test_bound_radius_weight_None(self):
        assert pytest.approx(nx.radius(self.G, usebounds=True, weight=None)) == 2

    def test_bound_radius_weight_attr(self):
        assert (
            nx.radius(self.G, usebounds=True, weight="high_cost")
            != pytest.approx(nx.radius(self.G, usebounds=True, weight="weight"))
            == pytest.approx(nx.radius(self.G, usebounds=True, weight="cost"))
            == 0.9
            != nx.radius(self.G, usebounds=True, weight="high_cost")
        )
        assert nx.radius(self.G, usebounds=True, weight="high_cost") == nx.radius(
            self.G, usebounds=True, weight="high_cost"
        )

    def test_bound_radius_weight_fn(self):
        assert nx.radius(self.G, usebounds=True, weight=self.weight_fn) == 4

    def test_bound_periphery_weight_None(self):
        result = {1, 3, 4}
        assert set(nx.periphery(self.G, usebounds=True, weight=None)) == result

    def test_bound_periphery_weight_attr(self):
        result = {4, 5}
        assert (
            set(nx.periphery(self.G, usebounds=True, weight="weight"))
            == set(nx.periphery(self.G, usebounds=True, weight="cost"))
            == result
        )

    def test_bound_periphery_weight_fn(self):
        result = {1, 3, 4}
        assert (
            set(nx.periphery(self.G, usebounds=True, weight=self.weight_fn)) == result
        )

    def test_bound_center_weight_None(self):
        result = {0, 2, 5}
        assert set(nx.center(self.G, usebounds=True, weight=None)) == result

    def test_bound_center_weight_attr(self):
        result = {0}
        assert (
            set(nx.center(self.G, usebounds=True, weight="weight"))
            == set(nx.center(self.G, usebounds=True, weight="cost"))
            == result
        )

    def test_bound_center_weight_fn(self):
        result = {0, 2, 5}
        assert set(nx.center(self.G, usebounds=True, weight=self.weight_fn)) == result


class TestResistanceDistance:
    @classmethod
    def setup_class(cls):
        global np
        np = pytest.importorskip("numpy")
        sp = pytest.importorskip("scipy")

    def setup_method(self):
        G = nx.Graph()
        G.add_edge(1, 2, weight=2)
        G.add_edge(2, 3, weight=4)
        G.add_edge(3, 4, weight=1)
        G.add_edge(1, 4, weight=3)
        self.G = G

    def test_resistance_distance_directed_graph(self):
        G = nx.DiGraph()
        with pytest.raises(nx.NetworkXNotImplemented):
            nx.resistance_distance(G)

    def test_resistance_distance_empty(self):
        G = nx.Graph()
        with pytest.raises(nx.NetworkXError):
            nx.resistance_distance(G)

    def test_resistance_distance_not_connected(self):
        with pytest.raises(nx.NetworkXError):
            self.G.add_node(5)
            nx.resistance_distance(self.G, 1, 5)

    def test_resistance_distance_nodeA_not_in_graph(self):
        with pytest.raises(nx.NetworkXError):
            nx.resistance_distance(self.G, 9, 1)

    def test_resistance_distance_nodeB_not_in_graph(self):
        with pytest.raises(nx.NetworkXError):
            nx.resistance_distance(self.G, 1, 9)

    def test_resistance_distance(self):
        rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
        test_data = 1 / (1 / (2 + 4) + 1 / (1 + 3))
        assert round(rd, 5) == round(test_data, 5)

    def test_resistance_distance_noinv(self):
        rd = nx.resistance_distance(self.G, 1, 3, "weight", False)
        test_data = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1 + 1 / 3))
        assert round(rd, 5) == round(test_data, 5)

    def test_resistance_distance_no_weight(self):
        rd = nx.resistance_distance(self.G, 1, 3)
        assert round(rd, 5) == 1

    def test_resistance_distance_neg_weight(self):
        self.G[2][3]["weight"] = -4
        rd = nx.resistance_distance(self.G, 1, 3, "weight", True)
        test_data = 1 / (1 / (2 + -4) + 1 / (1 + 3))
        assert round(rd, 5) == round(test_data, 5)

    def test_multigraph(self):
        G = nx.MultiGraph()
        G.add_edge(1, 2, weight=2)
        G.add_edge(2, 3, weight=4)
        G.add_edge(3, 4, weight=1)
        G.add_edge(1, 4, weight=3)
        rd = nx.resistance_distance(G, 1, 3, "weight", True)
        assert np.isclose(rd, 1 / (1 / (2 + 4) + 1 / (1 + 3)))

    def test_resistance_distance_div0(self):
        with pytest.raises(ZeroDivisionError):
            self.G[1][2]["weight"] = 0
            nx.resistance_distance(self.G, 1, 3, "weight")

    def test_resistance_distance_same_node(self):
        assert nx.resistance_distance(self.G, 1, 1) == 0

    def test_resistance_distance_only_nodeA(self):
        rd = nx.resistance_distance(self.G, nodeA=1)
        test_data = {}
        test_data[1] = 0
        test_data[2] = 0.75
        test_data[3] = 1
        test_data[4] = 0.75
        assert type(rd) == dict
        assert sorted(rd.keys()) == sorted(test_data.keys())
        for key in rd:
            assert np.isclose(rd[key], test_data[key])

    def test_resistance_distance_only_nodeB(self):
        rd = nx.resistance_distance(self.G, nodeB=1)
        test_data = {}
        test_data[1] = 0
        test_data[2] = 0.75
        test_data[3] = 1
        test_data[4] = 0.75
        assert type(rd) == dict
        assert sorted(rd.keys()) == sorted(test_data.keys())
        for key in rd:
            assert np.isclose(rd[key], test_data[key])

    def test_resistance_distance_all(self):
        rd = nx.resistance_distance(self.G)
        assert type(rd) == dict
        assert round(rd[1][3], 5) == 1


class TestEffectiveGraphResistance:
    @classmethod
    def setup_class(cls):
        global np
        np = pytest.importorskip("numpy")
        sp = pytest.importorskip("scipy")

    def setup_method(self):
        G = nx.Graph()
        G.add_edge(1, 2, weight=2)
        G.add_edge(1, 3, weight=1)
        G.add_edge(2, 3, weight=4)
        self.G = G

    def test_effective_graph_resistance_directed_graph(self):
        G = nx.DiGraph()
        with pytest.raises(nx.NetworkXNotImplemented):
            nx.effective_graph_resistance(G)

    def test_effective_graph_resistance_empty(self):
        G = nx.Graph()
        with pytest.raises(nx.NetworkXError):
            nx.effective_graph_resistance(G)

    def test_effective_graph_resistance_not_connected(self):
        G = nx.Graph([(1, 2), (3, 4)])
        RG = nx.effective_graph_resistance(G)
        assert np.isinf(RG)

    def test_effective_graph_resistance(self):
        RG = nx.effective_graph_resistance(self.G, "weight", True)
        rd12 = 1 / (1 / (1 + 4) + 1 / 2)
        rd13 = 1 / (1 / (1 + 2) + 1 / 4)
        rd23 = 1 / (1 / (2 + 4) + 1 / 1)
        assert np.isclose(RG, rd12 + rd13 + rd23)

    def test_effective_graph_resistance_noinv(self):
        RG = nx.effective_graph_resistance(self.G, "weight", False)
        rd12 = 1 / (1 / (1 / 1 + 1 / 4) + 1 / (1 / 2))
        rd13 = 1 / (1 / (1 / 1 + 1 / 2) + 1 / (1 / 4))
        rd23 = 1 / (1 / (1 / 2 + 1 / 4) + 1 / (1 / 1))
        assert np.isclose(RG, rd12 + rd13 + rd23)

    def test_effective_graph_resistance_no_weight(self):
        RG = nx.effective_graph_resistance(self.G)
        assert np.isclose(RG, 2)

    def test_effective_graph_resistance_neg_weight(self):
        self.G[2][3]["weight"] = -4
        RG = nx.effective_graph_resistance(self.G, "weight", True)
        rd12 = 1 / (1 / (1 + -4) + 1 / 2)
        rd13 = 1 / (1 / (1 + 2) + 1 / (-4))
        rd23 = 1 / (1 / (2 + -4) + 1 / 1)
        assert np.isclose(RG, rd12 + rd13 + rd23)

    def test_effective_graph_resistance_multigraph(self):
        G = nx.MultiGraph()
        G.add_edge(1, 2, weight=2)
        G.add_edge(1, 3, weight=1)
        G.add_edge(2, 3, weight=1)
        G.add_edge(2, 3, weight=3)
        RG = nx.effective_graph_resistance(G, "weight", True)
        edge23 = 1 / (1 / 1 + 1 / 3)
        rd12 = 1 / (1 / (1 + edge23) + 1 / 2)
        rd13 = 1 / (1 / (1 + 2) + 1 / edge23)
        rd23 = 1 / (1 / (2 + edge23) + 1 / 1)
        assert np.isclose(RG, rd12 + rd13 + rd23)

    def test_effective_graph_resistance_div0(self):
        with pytest.raises(ZeroDivisionError):
            self.G[1][2]["weight"] = 0
            nx.effective_graph_resistance(self.G, "weight")

    def test_effective_graph_resistance_complete_graph(self):
        N = 10
        G = nx.complete_graph(N)
        RG = nx.effective_graph_resistance(G)
        assert np.isclose(RG, N - 1)

    def test_effective_graph_resistance_path_graph(self):
        N = 10
        G = nx.path_graph(N)
        RG = nx.effective_graph_resistance(G)
        assert np.isclose(RG, (N - 1) * N * (N + 1) // 6)


class TestBarycenter:
    """Test :func:`networkx.algorithms.distance_measures.barycenter`."""

    def barycenter_as_subgraph(self, g, **kwargs):
        """Return the subgraph induced on the barycenter of g"""
        b = nx.barycenter(g, **kwargs)
        assert isinstance(b, list)
        assert set(b) <= set(g)
        return g.subgraph(b)

    def test_must_be_connected(self):
        pytest.raises(nx.NetworkXNoPath, nx.barycenter, nx.empty_graph(5))

    def test_sp_kwarg(self):
        # Complete graph K_5. Normally it works...
        K_5 = nx.complete_graph(5)
        sp = dict(nx.shortest_path_length(K_5))
        assert nx.barycenter(K_5, sp=sp) == list(K_5)

        # ...but not with the weight argument
        for u, v, data in K_5.edges.data():
            data["weight"] = 1
        pytest.raises(ValueError, nx.barycenter, K_5, sp=sp, weight="weight")

        # ...and a corrupted sp can make it seem like K_5 is disconnected
        del sp[0][1]
        pytest.raises(nx.NetworkXNoPath, nx.barycenter, K_5, sp=sp)

    def test_trees(self):
        """The barycenter of a tree is a single vertex or an edge.

        See [West01]_, p. 78.
        """
        prng = Random(0xDEADBEEF)
        for i in range(50):
            RT = nx.random_labeled_tree(prng.randint(1, 75), seed=prng)
            b = self.barycenter_as_subgraph(RT)
            if len(b) == 2:
                assert b.size() == 1
            else:
                assert len(b) == 1
                assert b.size() == 0

    def test_this_one_specific_tree(self):
        """Test the tree pictured at the bottom of [West01]_, p. 78."""
        g = nx.Graph(
            {
                "a": ["b"],
                "b": ["a", "x"],
                "x": ["b", "y"],
                "y": ["x", "z"],
                "z": ["y", 0, 1, 2, 3, 4],
                0: ["z"],
                1: ["z"],
                2: ["z"],
                3: ["z"],
                4: ["z"],
            }
        )
        b = self.barycenter_as_subgraph(g, attr="barycentricity")
        assert list(b) == ["z"]
        assert not b.edges
        expected_barycentricity = {
            0: 23,
            1: 23,
            2: 23,
            3: 23,
            4: 23,
            "a": 35,
            "b": 27,
            "x": 21,
            "y": 17,
            "z": 15,
        }
        for node, barycentricity in expected_barycentricity.items():
            assert g.nodes[node]["barycentricity"] == barycentricity

        # Doubling weights should do nothing but double the barycentricities
        for edge in g.edges:
            g.edges[edge]["weight"] = 2
        b = self.barycenter_as_subgraph(g, weight="weight", attr="barycentricity2")
        assert list(b) == ["z"]
        assert not b.edges
        for node, barycentricity in expected_barycentricity.items():
            assert g.nodes[node]["barycentricity2"] == barycentricity * 2


class TestKemenyConstant:
    @classmethod
    def setup_class(cls):
        global np
        np = pytest.importorskip("numpy")
        sp = pytest.importorskip("scipy")

    def setup_method(self):
        G = nx.Graph()
        w12 = 2
        w13 = 3
        w23 = 4
        G.add_edge(1, 2, weight=w12)
        G.add_edge(1, 3, weight=w13)
        G.add_edge(2, 3, weight=w23)
        self.G = G

    def test_kemeny_constant_directed(self):
        G = nx.DiGraph()
        G.add_edge(1, 2)
        G.add_edge(1, 3)
        G.add_edge(2, 3)
        with pytest.raises(nx.NetworkXNotImplemented):
            nx.kemeny_constant(G)

    def test_kemeny_constant_not_connected(self):
        self.G.add_node(5)
        with pytest.raises(nx.NetworkXError):
            nx.kemeny_constant(self.G)

    def test_kemeny_constant_no_nodes(self):
        G = nx.Graph()
        with pytest.raises(nx.NetworkXError):
            nx.kemeny_constant(G)

    def test_kemeny_constant_negative_weight(self):
        G = nx.Graph()
        w12 = 2
        w13 = 3
        w23 = -10
        G.add_edge(1, 2, weight=w12)
        G.add_edge(1, 3, weight=w13)
        G.add_edge(2, 3, weight=w23)
        with pytest.raises(nx.NetworkXError):
            nx.kemeny_constant(G, weight="weight")

    def test_kemeny_constant(self):
        K = nx.kemeny_constant(self.G, weight="weight")
        w12 = 2
        w13 = 3
        w23 = 4
        test_data = (
            3
            / 2
            * (w12 + w13)
            * (w12 + w23)
            * (w13 + w23)
            / (
                w12**2 * (w13 + w23)
                + w13**2 * (w12 + w23)
                + w23**2 * (w12 + w13)
                + 3 * w12 * w13 * w23
            )
        )
        assert np.isclose(K, test_data)

    def test_kemeny_constant_no_weight(self):
        K = nx.kemeny_constant(self.G)
        assert np.isclose(K, 4 / 3)

    def test_kemeny_constant_multigraph(self):
        G = nx.MultiGraph()
        w12_1 = 2
        w12_2 = 1
        w13 = 3
        w23 = 4
        G.add_edge(1, 2, weight=w12_1)
        G.add_edge(1, 2, weight=w12_2)
        G.add_edge(1, 3, weight=w13)
        G.add_edge(2, 3, weight=w23)
        K = nx.kemeny_constant(G, weight="weight")
        w12 = w12_1 + w12_2
        test_data = (
            3
            / 2
            * (w12 + w13)
            * (w12 + w23)
            * (w13 + w23)
            / (
                w12**2 * (w13 + w23)
                + w13**2 * (w12 + w23)
                + w23**2 * (w12 + w13)
                + 3 * w12 * w13 * w23
            )
        )
        assert np.isclose(K, test_data)

    def test_kemeny_constant_weight0(self):
        G = nx.Graph()
        w12 = 0
        w13 = 3
        w23 = 4
        G.add_edge(1, 2, weight=w12)
        G.add_edge(1, 3, weight=w13)
        G.add_edge(2, 3, weight=w23)
        K = nx.kemeny_constant(G, weight="weight")
        test_data = (
            3
            / 2
            * (w12 + w13)
            * (w12 + w23)
            * (w13 + w23)
            / (
                w12**2 * (w13 + w23)
                + w13**2 * (w12 + w23)
                + w23**2 * (w12 + w13)
                + 3 * w12 * w13 * w23
            )
        )
        assert np.isclose(K, test_data)

    def test_kemeny_constant_selfloop(self):
        G = nx.Graph()
        w11 = 1
        w12 = 2
        w13 = 3
        w23 = 4
        G.add_edge(1, 1, weight=w11)
        G.add_edge(1, 2, weight=w12)
        G.add_edge(1, 3, weight=w13)
        G.add_edge(2, 3, weight=w23)
        K = nx.kemeny_constant(G, weight="weight")
        test_data = (
            (2 * w11 + 3 * w12 + 3 * w13)
            * (w12 + w23)
            * (w13 + w23)
            / (
                (w12 * w13 + w12 * w23 + w13 * w23)
                * (w11 + 2 * w12 + 2 * w13 + 2 * w23)
            )
        )
        assert np.isclose(K, test_data)

    def test_kemeny_constant_complete_bipartite_graph(self):
        # Theorem 1 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
        n1 = 5
        n2 = 4
        G = nx.complete_bipartite_graph(n1, n2)
        K = nx.kemeny_constant(G)
        assert np.isclose(K, n1 + n2 - 3 / 2)

    def test_kemeny_constant_path_graph(self):
        # Theorem 2 in https://www.sciencedirect.com/science/article/pii/S0166218X20302912
        n = 10
        G = nx.path_graph(n)
        K = nx.kemeny_constant(G)
        assert np.isclose(K, n**2 / 3 - 2 * n / 3 + 1 / 2)