oxgraph-algo 0.3.2

Substrate-agnostic graph algorithms over oxgraph-topology traits.
Documentation
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
//! `PageRank` algorithms over `OxGraph` capability views.
//!
//! The module provides ordinary directed graph `PageRank` and directed
//! hypergraph incidence/bipartite `PageRank`. Property layers are not read here;
//! callers select named layers into topology weight capability views before
//! invoking weighted variants.
// kani-skip: PageRank uses unbounded caller-supplied iteration counts and floating-point
// convergence; deterministic unit tests and Criterion benches cover this slice.
#![cfg_attr(
    not(test),
    expect(
        clippy::missing_docs_in_private_items,
        reason = "PageRank helper functions are private implementation details behind documented public API tiers"
    )
)]

#[cfg(feature = "alloc")]
use alloc::{vec, vec::Vec};
#[cfg(feature = "alloc")]
use core::marker::PhantomData;
use core::{
    error::Error,
    fmt,
    ops::{Add, AddAssign, Div, Mul, Sub},
};

use oxgraph_graph::ForwardGraph;
use oxgraph_hyper::{DirectedHyperedgeIncidences, DirectedVertexHyperedges};
use oxgraph_topology::{
    ElementId, ElementIndex, IncidenceElement, IncidenceIndex, IncidenceWeight, RelationId,
    RelationIndex, RelationWeight,
};

/// Rank scalar accepted by `OxGraph` `PageRank` entry points.
///
/// The trait is owned by `OxGraph` so topology weights do not inherit arithmetic
/// semantics and public algorithms do not expose a broad numeric dependency.
/// Implementations define the numeric operations `PageRank` needs for rank state,
/// damping, tolerance, personalization, and converted weights.
///
/// # Scalar laws
///
/// Implementations must use ordinary finite numeric ordering and arithmetic:
/// `ZERO` is the additive identity, `ONE` is the multiplicative identity,
/// division by a positive count is finite for supported topology sizes, and
/// `abs(a - b)` is non-negative and finite whenever `a` and `b` are finite.
pub trait PageRankScalar:
    Copy
    + fmt::Debug
    + PartialOrd
    + Add<Output = Self>
    + Sub<Output = Self>
    + Mul<Output = Self>
    + Div<Output = Self>
    + AddAssign
    + 'static
{
    /// Additive identity.
    const ZERO: Self;
    /// Multiplicative identity.
    const ONE: Self;
    /// Positive infinity sentinel used before the first iteration delta.
    const INFINITY: Self;

    /// Converts a row degree or visible-state count into this scalar.
    fn from_usize(value: usize) -> Self;

    /// Converts a Rust float literal/default into this scalar.
    fn from_f64(value: f64) -> Self;

    /// Absolute value.
    #[must_use]
    fn abs(self) -> Self;

    /// Returns whether this value is finite.
    fn is_finite(self) -> bool;
}

impl PageRankScalar for f64 {
    const ZERO: Self = 0.0;
    const ONE: Self = 1.0;
    #[expect(
        clippy::use_self,
        reason = "primitive inherent infinity constant is clearer here"
    )]
    const INFINITY: Self = f64::INFINITY;

    #[expect(
        clippy::cast_precision_loss,
        reason = "PageRank degree conversion is a documented scalar-boundary conversion"
    )]
    fn from_usize(value: usize) -> Self {
        value as Self
    }

    fn from_f64(value: f64) -> Self {
        value
    }

    fn abs(self) -> Self {
        self.abs()
    }

    fn is_finite(self) -> bool {
        self.is_finite()
    }
}

impl PageRankScalar for f32 {
    const ZERO: Self = 0.0;
    const ONE: Self = 1.0;
    #[expect(
        clippy::use_self,
        reason = "primitive inherent infinity constant is clearer here"
    )]
    const INFINITY: Self = f32::INFINITY;

    #[expect(
        clippy::cast_precision_loss,
        reason = "PageRank degree conversion is a documented scalar-boundary conversion"
    )]
    fn from_usize(value: usize) -> Self {
        value as Self
    }

    #[expect(
        clippy::cast_possible_truncation,
        reason = "f32 PageRank callers explicitly select f32 rank/config output"
    )]
    fn from_f64(value: f64) -> Self {
        value as Self
    }

    fn abs(self) -> Self {
        self.abs()
    }

    fn is_finite(self) -> bool {
        self.is_finite()
    }
}

/// Explicit conversion from a topology weight into a `PageRank` rank scalar.
///
/// Implementations are deliberately limited to documented primitive conversions;
/// downstream topology weights stay semantic-free and algorithms opt into the
/// numeric interpretation at this boundary.
pub trait IntoPageRankScalar<S: PageRankScalar> {
    /// Converts `self` into rank scalar `S`.
    fn into_pagerank_scalar(self) -> S;
}

impl<S: PageRankScalar> IntoPageRankScalar<S> for S {
    fn into_pagerank_scalar(self) -> S {
        self
    }
}

/// Implements lossless primitive conversions into a `PageRank` scalar.
macro_rules! impl_weight_into_pagerank_scalar_from {
    ($target:ty; $($type:ty),* $(,)?) => {
        $(
            impl IntoPageRankScalar<$target> for $type {
                fn into_pagerank_scalar(self) -> $target { <$target>::from(self) }
            }
        )*
    };
}

/// Implements explicitly lossy primitive conversions into a `PageRank` scalar.
macro_rules! impl_weight_into_pagerank_scalar_cast {
    ($target:ty; $($type:ty),* $(,)?) => {
        $(
            impl IntoPageRankScalar<$target> for $type {
                #[expect(
                    clippy::cast_precision_loss,
                    reason = "PageRank primitive weight conversions are explicit algorithm-boundary numeric interpretations"
                )]
                fn into_pagerank_scalar(self) -> $target { self as $target }
            }
        )*
    };
}

impl_weight_into_pagerank_scalar_from!(f64; u8, u16, u32, i8, i16, i32, f32);
impl_weight_into_pagerank_scalar_cast!(f64; u64, usize, i64, isize);
impl_weight_into_pagerank_scalar_from!(f32; u8, u16, i8, i16);
impl_weight_into_pagerank_scalar_cast!(f32; u32, u64, usize, i32, i64, isize);

impl IntoPageRankScalar<f32> for f64 {
    #[expect(
        clippy::cast_possible_truncation,
        reason = "f32 PageRank callers explicitly select f32 rank and configuration output"
    )]
    fn into_pagerank_scalar(self) -> f32 {
        self as f32
    }
}

/// Per-element outgoing rank-distribution rule used by graph `PageRank`.
///
/// Implementations decide how an element's current `rank` is split across its
/// outgoing visible neighbors and how much of it (if any) flows to the
/// dangling reservoir. Built-in [`Uniform`] divides equally over visible
/// out-degree; built-in [`Weighted`] divides proportionally to relation
/// weights. User crates can implement this trait for custom rules — for
/// example, attenuated decay, top-k filtering, or caller-supplied
/// per-element shares — without forking the kernel.
///
/// # Contract
///
/// On success, `distribute_outgoing` writes per-target shares into `next`
/// (visible-masked) and returns the dangling contribution. The sum of `next`
/// increments plus the returned dangling contribution must equal `rank` when
/// at least one visible target exists; when no visible targets exist, the
/// implementation must return `rank` and write nothing. Failures are surfaced
/// as [`PageRankError`].
///
/// # Performance
///
/// `perf: unspecified`; built-in implementations document their per-element
/// cost. Most do `O(degree)` work per element with one or two passes over
/// the outgoing-edge iterator.
pub trait OutgoingDistribution<G, S>
where
    G: ForwardGraph + ElementIndex,
    S: PageRankScalar,
{
    /// Distributes `rank` from `element` to its outgoing visible neighbors.
    ///
    /// # Errors
    ///
    /// Returns [`PageRankError`] when a topology index is invalid, when a
    /// caller-supplied weight is invalid, or when an arithmetic boundary is
    /// crossed.
    ///
    /// # Performance
    ///
    /// `perf: unspecified`; implementations document their cost.
    #[expect(
        clippy::too_many_arguments,
        reason = "distribution kernel needs graph, element, rank, output buffer, and visibility mask explicitly"
    )]
    fn distribute_outgoing(
        &self,
        graph: &G,
        element: G::ElementId,
        rank: S,
        next: &mut [S],
        visible: &[u8],
    ) -> Result<S, PageRankError<S>>;
}

/// Distributes outgoing rank uniformly across visible out-degree.
///
/// Built-in [`OutgoingDistribution`] implementation matching the unweighted
/// `PageRank` semantics. Two passes over the outgoing-edge iterator: one to
/// count visible degree, one to write the share `rank / degree`.
///
/// # Performance
///
/// Each call is `O(degree)`.
#[derive(Clone, Copy, Debug, Default)]
pub struct Uniform;

impl<G, S> OutgoingDistribution<G, S> for Uniform
where
    G: ForwardGraph + ElementIndex,
    S: PageRankScalar,
{
    fn distribute_outgoing(
        &self,
        graph: &G,
        element: G::ElementId,
        rank: S,
        next: &mut [S],
        visible: &[u8],
    ) -> Result<S, PageRankError<S>> {
        let mut degree = 0_usize;
        for edge in graph.outgoing_edges(element) {
            let target = graph.target(edge);
            let target_index = checked_element_index(graph, target)?;
            if is_visible(visible, target_index) {
                degree += 1;
            }
        }
        if degree == 0 {
            return Ok(rank);
        }
        let share = rank / S::from_usize(degree);
        for edge in graph.outgoing_edges(element) {
            let target = graph.target(edge);
            let target_index = checked_element_index(graph, target)?;
            if is_visible(visible, target_index) {
                next[target_index] += share;
            }
        }
        Ok(S::ZERO)
    }
}

/// Distributes outgoing rank proportionally to caller-supplied weights.
///
/// Built-in [`OutgoingDistribution`] implementation matching the weighted
/// `PageRank` semantics. Holds a borrowed [`RelationWeight`] adapter and uses
/// two passes over the outgoing-edge iterator: one to compute the visible
/// outgoing-weight total, one to write per-edge shares `rank * weight /
/// total`. Dangling rows (zero or non-positive total) flow the entire `rank`
/// to the dangling reservoir.
///
/// # Performance
///
/// Each call is `O(degree)`.
#[derive(Clone, Copy, Debug)]
pub struct Weighted<'w, W> {
    /// Borrowed relation-weight adapter.
    weights: &'w W,
}

impl<'w, W> Weighted<'w, W> {
    /// Constructs a [`Weighted`] distribution borrowing `weights`.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn new(weights: &'w W) -> Self {
        Self { weights }
    }
}

impl<G, W, S> OutgoingDistribution<G, S> for Weighted<'_, W>
where
    G: ForwardGraph + ElementIndex + RelationIndex,
    W: RelationWeight<ElementId = G::ElementId, RelationId = G::RelationId>,
    W::Weight: IntoPageRankScalar<S>,
    S: PageRankScalar,
{
    fn distribute_outgoing(
        &self,
        graph: &G,
        element: G::ElementId,
        rank: S,
        next: &mut [S],
        visible: &[u8],
    ) -> Result<S, PageRankError<S>> {
        let total = outgoing_weight_total(graph, self.weights, element, visible)?;
        if total <= S::ZERO {
            return Ok(rank);
        }
        for edge in graph.outgoing_edges(element) {
            let target = graph.target(edge);
            let target_index = checked_element_index(graph, target)?;
            if is_visible(visible, target_index) {
                let weight = checked_relation_weight(graph, self.weights, edge)?;
                next[target_index] += rank * (weight / total);
            }
        }
        Ok(S::ZERO)
    }
}

/// Bipartite outgoing rank-distribution rule used by hypergraph `PageRank`.
///
/// Implementations decide how an element's current `rank` is split across its
/// outgoing visible relations, and how a relation's current `rank` is split
/// across its visible target elements. Built-in [`Uniform`] divides each leg
/// evenly over the visible out-degree; built-in [`HyperWeighted`] divides
/// element-to-relation by [`RelationWeight`] values and relation-to-element by
/// [`IncidenceWeight`] values. User crates can implement this trait for custom
/// bipartite policies — e.g. attenuated decay, top-k filtering, or
/// caller-supplied per-state shares — without forking the kernel.
///
/// # Contract
///
/// On success, both methods write per-target shares into the appropriate next
/// buffer (visible-masked) and return the dangling contribution for the
/// source state. The sum of `next_*` increments plus the returned dangling
/// contribution must equal `rank` when at least one visible target exists;
/// when no visible target exists, the implementation must return `rank` and
/// write nothing. Failures are surfaced as [`PageRankError`].
///
/// # Performance
///
/// `perf: unspecified`; built-in implementations document their per-state
/// cost. Most do `O(degree)` work per state with one or two passes over the
/// outgoing-incidence iterator.
pub trait HypergraphOutgoingDistribution<H, S>
where
    H: DirectedVertexHyperedges
        + DirectedHyperedgeIncidences
        + IncidenceElement
        + ElementIndex
        + RelationIndex,
    S: PageRankScalar,
{
    /// Distributes `rank` from `element` to its outgoing visible relations.
    ///
    /// # Errors
    ///
    /// Returns [`PageRankError`] when a topology index is invalid, when a
    /// caller-supplied weight is invalid, or when an arithmetic boundary is
    /// crossed.
    ///
    /// # Performance
    ///
    /// `perf: unspecified`; implementations document their cost.
    #[expect(
        clippy::too_many_arguments,
        reason = "distribution kernel needs hypergraph, element, rank, output buffer, and visibility mask explicitly"
    )]
    fn distribute_from_element(
        &self,
        hypergraph: &H,
        element: H::ElementId,
        rank: S,
        next_relations: &mut [S],
        visible_relations: &[u8],
    ) -> Result<S, PageRankError<S>>;

    /// Distributes `rank` from `relation` to its visible target elements.
    ///
    /// # Errors
    ///
    /// Returns [`PageRankError`] when a topology index is invalid, when a
    /// caller-supplied weight is invalid, or when an arithmetic boundary is
    /// crossed.
    ///
    /// # Performance
    ///
    /// `perf: unspecified`; implementations document their cost.
    #[expect(
        clippy::too_many_arguments,
        reason = "distribution kernel needs hypergraph, relation, rank, output buffer, and visibility mask explicitly"
    )]
    fn distribute_from_relation(
        &self,
        hypergraph: &H,
        relation: H::RelationId,
        rank: S,
        next_elements: &mut [S],
        visible_elements: &[u8],
    ) -> Result<S, PageRankError<S>>;
}

impl<H, S> HypergraphOutgoingDistribution<H, S> for Uniform
where
    H: DirectedVertexHyperedges
        + DirectedHyperedgeIncidences
        + IncidenceElement
        + ElementIndex
        + RelationIndex,
    S: PageRankScalar,
{
    fn distribute_from_element(
        &self,
        hypergraph: &H,
        element: H::ElementId,
        rank: S,
        next_relations: &mut [S],
        visible_relations: &[u8],
    ) -> Result<S, PageRankError<S>> {
        let mut degree = 0_usize;
        for relation in hypergraph.outgoing_hyperedges(element) {
            let relation_index = checked_relation_index_for(hypergraph, relation)?;
            if is_visible(visible_relations, relation_index) {
                degree += 1;
            }
        }
        if degree == 0 {
            return Ok(rank);
        }
        let share = rank / S::from_usize(degree);
        for relation in hypergraph.outgoing_hyperedges(element) {
            let relation_index = checked_relation_index_for(hypergraph, relation)?;
            if is_visible(visible_relations, relation_index) {
                next_relations[relation_index] += share;
            }
        }
        Ok(S::ZERO)
    }

    fn distribute_from_relation(
        &self,
        hypergraph: &H,
        relation: H::RelationId,
        rank: S,
        next_elements: &mut [S],
        visible_elements: &[u8],
    ) -> Result<S, PageRankError<S>> {
        let mut degree = 0_usize;
        for incidence in hypergraph.target_incidences(relation) {
            let target = hypergraph.incidence_element(incidence);
            let target_index = checked_element_index(hypergraph, target)?;
            if is_visible(visible_elements, target_index) {
                degree += 1;
            }
        }
        if degree == 0 {
            return Ok(rank);
        }
        let share = rank / S::from_usize(degree);
        for incidence in hypergraph.target_incidences(relation) {
            let target = hypergraph.incidence_element(incidence);
            let target_index = checked_element_index(hypergraph, target)?;
            if is_visible(visible_elements, target_index) {
                next_elements[target_index] += share;
            }
        }
        Ok(S::ZERO)
    }
}

/// Distributes bipartite outgoing rank proportionally to caller-supplied
/// weights.
///
/// Built-in [`HypergraphOutgoingDistribution`] implementation matching the
/// weighted incidence/bipartite `PageRank` semantics. Holds borrowed
/// [`RelationWeight`] and [`IncidenceWeight`] adapters: element-to-relation
/// distribution uses relation weights, and relation-to-element distribution
/// uses target-incidence weights. Source-incidence weights are intentionally
/// not used by the default policy. Dangling rows (zero or non-positive total)
/// flow the entire `rank` to the dangling reservoir.
///
/// # Performance
///
/// Each call is `O(degree)` for the source state's visible neighborhood.
#[derive(Clone, Copy, Debug)]
pub struct HyperWeighted<'rw, 'iw, RW, IW> {
    /// Borrowed relation-weight adapter driving element → relation transitions.
    relation_weights: &'rw RW,
    /// Borrowed incidence-weight adapter driving relation → element transitions.
    incidence_weights: &'iw IW,
}

impl<'rw, 'iw, RW, IW> HyperWeighted<'rw, 'iw, RW, IW> {
    /// Constructs a [`HyperWeighted`] distribution borrowing the relation and
    /// incidence weight adapters.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn new(relation_weights: &'rw RW, incidence_weights: &'iw IW) -> Self {
        Self {
            relation_weights,
            incidence_weights,
        }
    }
}

impl<H, RW, IW, S> HypergraphOutgoingDistribution<H, S> for HyperWeighted<'_, '_, RW, IW>
where
    H: DirectedVertexHyperedges
        + DirectedHyperedgeIncidences
        + IncidenceElement
        + ElementIndex
        + RelationIndex
        + IncidenceIndex,
    RW: RelationWeight<ElementId = H::ElementId, RelationId = H::RelationId>,
    RW::Weight: IntoPageRankScalar<S>,
    IW: IncidenceWeight<
            ElementId = H::ElementId,
            RelationId = H::RelationId,
            IncidenceId = H::IncidenceId,
        >,
    IW::Weight: IntoPageRankScalar<S>,
    S: PageRankScalar,
{
    fn distribute_from_element(
        &self,
        hypergraph: &H,
        element: H::ElementId,
        rank: S,
        next_relations: &mut [S],
        visible_relations: &[u8],
    ) -> Result<S, PageRankError<S>> {
        let total = hyper_outgoing_relation_weight(
            hypergraph,
            self.relation_weights,
            element,
            visible_relations,
        )?;
        if total <= S::ZERO {
            return Ok(rank);
        }
        for relation in hypergraph.outgoing_hyperedges(element) {
            let relation_index = checked_relation_index_for(hypergraph, relation)?;
            if !is_visible(visible_relations, relation_index) {
                continue;
            }
            let weight = checked_relation_weight(hypergraph, self.relation_weights, relation)?;
            next_relations[relation_index] += rank * (weight / total);
        }
        Ok(S::ZERO)
    }

    fn distribute_from_relation(
        &self,
        hypergraph: &H,
        relation: H::RelationId,
        rank: S,
        next_elements: &mut [S],
        visible_elements: &[u8],
    ) -> Result<S, PageRankError<S>> {
        let total = hyper_target_incidence_weight(
            hypergraph,
            self.incidence_weights,
            relation,
            visible_elements,
        )?;
        if total <= S::ZERO {
            return Ok(rank);
        }
        for incidence in hypergraph.target_incidences(relation) {
            let target = hypergraph.incidence_element(incidence);
            let target_index = checked_element_index(hypergraph, target)?;
            if !is_visible(visible_elements, target_index) {
                continue;
            }
            let weight = checked_incidence_weight(hypergraph, self.incidence_weights, incidence)?;
            next_elements[target_index] += rank * (weight / total);
        }
        Ok(S::ZERO)
    }
}

/// `PageRank` configuration shared by graph and hypergraph policies.
///
/// # Performance
///
/// Copying and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct PageRankConfig<S> {
    /// Damping factor, usually `0.85`.
    pub damping: S,
    /// L1 convergence tolerance.
    pub tolerance: S,
    /// Maximum power-iteration count.
    pub max_iterations: usize,
}

impl<S> PageRankConfig<S> {
    /// Constructs a `PageRank` configuration.
    ///
    /// Validation is performed by the `PageRank` entry point so callers can build
    /// configs before deciding which algorithm variant to invoke.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn new(damping: S, tolerance: S, max_iterations: usize) -> Self {
        Self {
            damping,
            tolerance,
            max_iterations,
        }
    }
}

/// Successful `PageRank` convergence report.
///
/// # Performance
///
/// Copying and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct PageRankReport<S> {
    /// Number of iterations executed.
    pub iterations: usize,
    /// Final L1 rank delta.
    pub delta: S,
}

/// `PageRank` input, numeric, scratch, and convergence errors.
///
/// # Performance
///
/// Formatting is `O(message length)`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum PageRankError<S> {
    /// `PageRank` is undefined for an empty visible state set.
    EmptyState,
    /// Damping must be finite and in `[0, 1]`.
    InvalidDamping {
        /// Invalid damping value.
        damping: S,
    },
    /// Tolerance must be finite and non-negative.
    InvalidTolerance {
        /// Invalid tolerance value.
        tolerance: S,
    },
    /// At least one iteration is required.
    InvalidMaxIterations,
    /// Output rank storage was shorter than the topology index bound.
    OutputTooShort {
        /// Required length.
        required: usize,
        /// Actual length.
        actual: usize,
    },
    /// Scratch storage was shorter than the required bound.
    ScratchTooShort {
        /// Scratch slice name.
        name: &'static str,
        /// Required length.
        required: usize,
        /// Actual length.
        actual: usize,
    },
    /// Personalization storage was shorter than the topology index bound.
    PersonalizationTooShort {
        /// Required length.
        required: usize,
        /// Actual length.
        actual: usize,
    },
    /// A personalization entry was negative or non-finite.
    InvalidPersonalization {
        /// Invalid index.
        index: usize,
        /// Invalid value.
        value: S,
    },
    /// Personalization sum was zero over visible states.
    ZeroPersonalization,
    /// A topology element mapped outside the advertised element bound.
    ElementIndexOutOfBounds {
        /// Invalid index.
        index: usize,
        /// Advertised bound.
        bound: usize,
    },
    /// A visible element was provided more than once.
    DuplicateElement {
        /// Duplicate dense element index.
        index: usize,
    },
    /// A visible relation was provided more than once.
    DuplicateRelation {
        /// Duplicate dense relation index.
        index: usize,
    },
    /// A topology relation mapped outside the advertised relation bound.
    RelationIndexOutOfBounds {
        /// Invalid index.
        index: usize,
        /// Advertised bound.
        bound: usize,
    },
    /// A topology incidence mapped outside the advertised incidence bound.
    IncidenceIndexOutOfBounds {
        /// Invalid index.
        index: usize,
        /// Advertised bound.
        bound: usize,
    },
    /// A relation weight was negative or non-finite.
    InvalidRelationWeight {
        /// Dense relation index.
        index: usize,
        /// Invalid value.
        value: S,
    },
    /// An incidence weight was negative or non-finite.
    InvalidIncidenceWeight {
        /// Dense incidence index.
        index: usize,
        /// Invalid value.
        value: S,
    },
    /// Power iteration reached the maximum iteration count before convergence.
    NonConverged {
        /// Iterations executed.
        iterations: usize,
        /// Final L1 delta.
        delta: S,
    },
}

impl<S: fmt::Debug> fmt::Display for PageRankError<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyState => formatter.write_str("pagerank state set is empty"),
            Self::InvalidDamping { damping } => {
                write!(formatter, "invalid pagerank damping {damping:?}")
            }
            Self::InvalidTolerance { tolerance } => {
                write!(formatter, "invalid pagerank tolerance {tolerance:?}")
            }
            Self::InvalidMaxIterations => {
                formatter.write_str("pagerank max_iterations must be positive")
            }
            Self::OutputTooShort { required, actual } => write!(
                formatter,
                "pagerank output too short: required {required}, got {actual}"
            ),
            Self::ScratchTooShort {
                name,
                required,
                actual,
            } => write!(
                formatter,
                "pagerank scratch '{name}' too short: required {required}, got {actual}"
            ),
            Self::PersonalizationTooShort { required, actual } => write!(
                formatter,
                "pagerank personalization too short: required {required}, got {actual}"
            ),
            Self::InvalidPersonalization { index, value } => write!(
                formatter,
                "invalid pagerank personalization at {index}: {value:?}"
            ),
            Self::ZeroPersonalization => {
                formatter.write_str("pagerank personalization sum is zero")
            }
            Self::ElementIndexOutOfBounds { index, bound } => {
                write!(formatter, "element index {index} is outside bound {bound}")
            }
            Self::DuplicateElement { index } => {
                write!(formatter, "duplicate pagerank element index {index}")
            }
            Self::DuplicateRelation { index } => {
                write!(formatter, "duplicate pagerank relation index {index}")
            }
            Self::RelationIndexOutOfBounds { index, bound } => {
                write!(formatter, "relation index {index} is outside bound {bound}")
            }
            Self::IncidenceIndexOutOfBounds { index, bound } => {
                write!(
                    formatter,
                    "incidence index {index} is outside bound {bound}"
                )
            }
            Self::InvalidRelationWeight { index, value } => {
                write!(formatter, "invalid relation weight at {index}: {value:?}")
            }
            Self::InvalidIncidenceWeight { index, value } => {
                write!(formatter, "invalid incidence weight at {index}: {value:?}")
            }
            Self::NonConverged { iterations, delta } => write!(
                formatter,
                "pagerank did not converge after {iterations} iterations; delta {delta:?}"
            ),
        }
    }
}

impl<S: fmt::Debug> Error for PageRankError<S> {}

/// Borrowed scratch storage for ordinary graph `PageRank`.
///
/// # Performance
///
/// Construction is `O(1)`. The slices must be at least `graph.element_bound()`
/// long for the graph passed to a scratch API.
#[derive(Debug)]
#[must_use]
pub struct PageRankScratch<'scratch, S> {
    /// Teleport/personalization scratch by element index.
    teleport: &'scratch mut [S],
    /// Next-rank scratch by element index.
    next: &'scratch mut [S],
    /// Visible element bitset by element index.
    visible_elements: &'scratch mut [u8],
}

impl<'scratch, S> PageRankScratch<'scratch, S> {
    /// Constructs borrowed graph `PageRank` scratch from caller-owned slices.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    pub const fn new(
        teleport: &'scratch mut [S],
        next: &'scratch mut [S],
        visible_elements: &'scratch mut [u8],
    ) -> Self {
        Self {
            teleport,
            next,
            visible_elements,
        }
    }

    /// Returns current teleport scratch capacity.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn teleport_capacity(&self) -> usize {
        self.teleport.len()
    }

    /// Returns current next-rank scratch capacity.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn next_capacity(&self) -> usize {
        self.next.len()
    }

    /// Returns current visible-element scratch capacity.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn visible_element_capacity(&self) -> usize {
        self.visible_elements.len()
    }
}

/// Borrowed scratch storage for incidence/bipartite hypergraph `PageRank`.
///
/// # Performance
///
/// Construction is `O(1)`. `teleport` must cover `element_bound + relation_bound`,
/// while `next_elements` and `next_relations` cover their respective bounds.
#[derive(Debug)]
#[must_use]
pub struct HypergraphPageRankScratch<'scratch, S> {
    /// Teleport/personalization scratch by combined element+relation state index.
    teleport: &'scratch mut [S],
    /// Next element ranks by element index.
    next_elements: &'scratch mut [S],
    /// Next relation ranks by relation index.
    next_relations: &'scratch mut [S],
    /// Visible element bitset by element index.
    visible_elements: &'scratch mut [u8],
    /// Visible relation bitset by relation index.
    visible_relations: &'scratch mut [u8],
}

impl<'scratch, S> HypergraphPageRankScratch<'scratch, S> {
    /// Constructs borrowed hypergraph `PageRank` scratch from caller-owned slices.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    pub const fn new(
        teleport: &'scratch mut [S],
        next_elements: &'scratch mut [S],
        next_relations: &'scratch mut [S],
        visible_elements: &'scratch mut [u8],
        visible_relations: &'scratch mut [u8],
    ) -> Self {
        Self {
            teleport,
            next_elements,
            next_relations,
            visible_elements,
            visible_relations,
        }
    }

    /// Returns current teleport scratch capacity.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn teleport_capacity(&self) -> usize {
        self.teleport.len()
    }
}

/// Owned reusable workspace for ordinary graph `PageRank`.
///
/// The `G` parameter brands the workspace to a view type, mirroring
/// [`crate::BfsWorkspace`]. The scalar `S` fixes the rank/storage scalar.
///
/// # Performance
///
/// Memory usage is `O(b)` for the largest element bound used with the workspace.
#[cfg(feature = "alloc")]
#[derive(Clone, Debug)]
pub struct PageRankWorkspace<G, S> {
    /// Teleport/personalization scratch.
    teleport: Vec<S>,
    /// Next-rank scratch.
    next: Vec<S>,
    /// Visible element bitset.
    visible_elements: Vec<u8>,
    /// Brands workspace storage to a topology view type without owning the view.
    _graph: PhantomData<fn() -> G>,
}

#[cfg(feature = "alloc")]
impl<G, S: PageRankScalar> Default for PageRankWorkspace<G, S> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "alloc")]
impl<G, S: PageRankScalar> PageRankWorkspace<G, S> {
    /// Creates an empty reusable `PageRank` workspace.
    ///
    /// # Performance
    ///
    /// This function is `O(1)` and performs no allocation.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            teleport: Vec::new(),
            next: Vec::new(),
            visible_elements: Vec::new(),
            _graph: PhantomData,
        }
    }

    /// Creates a workspace sized for `graph.element_bound()`.
    ///
    /// # Performance
    ///
    /// Allocates and initializes `O(graph.element_bound())` storage.
    #[must_use]
    pub fn for_graph(graph: &G) -> Self
    where
        G: ElementIndex,
    {
        Self::with_element_bound(graph.element_bound())
    }

    /// Creates a workspace with capacity for `element_bound` element states.
    ///
    /// # Performance
    ///
    /// Allocates and initializes `O(element_bound)` storage.
    #[must_use]
    pub fn with_element_bound(element_bound: usize) -> Self {
        Self {
            teleport: vec![S::ZERO; element_bound],
            next: vec![S::ZERO; element_bound],
            visible_elements: vec![0; element_bound],
            _graph: PhantomData,
        }
    }

    /// Returns the element-bound capacity currently available without growth.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn element_bound_capacity(&self) -> usize {
        self.teleport.len()
    }

    /// Ensures workspace storage covers `element_bound`.
    fn ensure_element_bound(&mut self, element_bound: usize) {
        if self.teleport.len() < element_bound {
            self.teleport.resize(element_bound, S::ZERO);
        }
        if self.next.len() < element_bound {
            self.next.resize(element_bound, S::ZERO);
        }
        if self.visible_elements.len() < element_bound {
            self.visible_elements.resize(element_bound, 0);
        }
    }

    /// Borrows this workspace as scratch.
    fn as_scratch(&mut self) -> PageRankScratch<'_, S> {
        PageRankScratch::new(
            &mut self.teleport,
            &mut self.next,
            &mut self.visible_elements,
        )
    }
}

/// Owned reusable workspace for incidence/bipartite hypergraph `PageRank`.
///
/// # Performance
///
/// Memory usage is `O(e + r)` for the largest element and relation bounds used.
#[cfg(feature = "alloc")]
#[derive(Clone, Debug)]
pub struct HypergraphPageRankWorkspace<H, S> {
    /// Combined element+relation teleport/personalization scratch.
    teleport: Vec<S>,
    /// Next element ranks.
    next_elements: Vec<S>,
    /// Next relation ranks.
    next_relations: Vec<S>,
    /// Visible element bitset.
    visible_elements: Vec<u8>,
    /// Visible relation bitset.
    visible_relations: Vec<u8>,
    /// Brands workspace storage to a hypergraph view type without owning the view.
    _hypergraph: PhantomData<fn() -> H>,
}

#[cfg(feature = "alloc")]
impl<H, S: PageRankScalar> Default for HypergraphPageRankWorkspace<H, S> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "alloc")]
impl<H, S: PageRankScalar> HypergraphPageRankWorkspace<H, S> {
    /// Creates an empty reusable hypergraph `PageRank` workspace.
    ///
    /// # Performance
    ///
    /// This function is `O(1)` and performs no allocation.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            teleport: Vec::new(),
            next_elements: Vec::new(),
            next_relations: Vec::new(),
            visible_elements: Vec::new(),
            visible_relations: Vec::new(),
            _hypergraph: PhantomData,
        }
    }

    /// Creates a workspace sized for a hypergraph's element/relation bounds.
    ///
    /// # Performance
    ///
    /// Allocates and initializes `O(element_bound + relation_bound)` storage.
    #[must_use]
    pub fn for_hypergraph(hypergraph: &H) -> Self
    where
        H: ElementIndex + RelationIndex,
    {
        Self::with_bounds(hypergraph.element_bound(), hypergraph.relation_bound())
    }

    /// Creates a workspace with capacity for element and relation bounds.
    ///
    /// # Performance
    ///
    /// Allocates and initializes `O(element_bound + relation_bound)` storage.
    #[must_use]
    pub fn with_bounds(element_bound: usize, relation_bound: usize) -> Self {
        let state_bound = element_bound.saturating_add(relation_bound);
        Self {
            teleport: vec![S::ZERO; state_bound],
            next_elements: vec![S::ZERO; element_bound],
            next_relations: vec![S::ZERO; relation_bound],
            visible_elements: vec![0; element_bound],
            visible_relations: vec![0; relation_bound],
            _hypergraph: PhantomData,
        }
    }

    /// Returns current element-rank capacity.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn element_bound_capacity(&self) -> usize {
        self.next_elements.len()
    }

    /// Returns current relation-rank capacity.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn relation_bound_capacity(&self) -> usize {
        self.next_relations.len()
    }

    /// Ensures workspace storage covers the requested bounds.
    fn ensure_bounds(&mut self, element_bound: usize, relation_bound: usize, state_bound: usize) {
        if self.teleport.len() < state_bound {
            self.teleport.resize(state_bound, S::ZERO);
        }
        if self.next_elements.len() < element_bound {
            self.next_elements.resize(element_bound, S::ZERO);
        }
        if self.next_relations.len() < relation_bound {
            self.next_relations.resize(relation_bound, S::ZERO);
        }
        if self.visible_elements.len() < element_bound {
            self.visible_elements.resize(element_bound, 0);
        }
        if self.visible_relations.len() < relation_bound {
            self.visible_relations.resize(relation_bound, 0);
        }
    }

    /// Borrows this workspace as hypergraph scratch.
    fn as_scratch(&mut self) -> HypergraphPageRankScratch<'_, S> {
        HypergraphPageRankScratch::new(
            &mut self.teleport,
            &mut self.next_elements,
            &mut self.next_relations,
            &mut self.visible_elements,
            &mut self.visible_relations,
        )
    }
}

/// Computes ordinary directed graph `PageRank` with the supplied outgoing
/// distribution policy, allocating temporary scratch.
///
/// `distribution` selects the per-edge rank-transfer rule:
/// [`Uniform`] reproduces the textbook unweighted `PageRank` (every parallel
/// outgoing edge carries a unit transition weight), while [`Weighted`]
/// reads a caller-supplied edge weight. Any [`OutgoingDistribution`] impl
/// is accepted. `elements` defines the visible state iteration order.
///
/// # Errors
///
/// Returns [`PageRankError`] for invalid configuration, personalization,
/// topology indexes, output length, scratch length, or non-convergence.
///
/// # Performance
///
/// Each iteration is `O(n + m · cost(D))` for `n` visible elements, `m`
/// outgoing edge entries yielded from those elements, and `cost(D)` the
/// per-edge cost of [`OutgoingDistribution::distribute_outgoing`]
/// (`O(1)` for the built-in [`Uniform`] and [`Weighted`] impls).
/// Scratch allocation is `O(b)` where `b` is `graph.element_bound()`.
#[cfg(feature = "alloc")]
#[expect(
    clippy::too_many_arguments,
    reason = "PageRank entry point keeps graph, distribution, elements, config, personalization, and output explicit"
)]
pub fn pagerank_graph<G, D, I, S>(
    graph: &G,
    distribution: &D,
    elements: I,
    config: PageRankConfig<S>,
    personalization: Option<&[S]>,
    ranks: &mut [S],
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    G: ForwardGraph + ElementIndex,
    D: OutgoingDistribution<G, S>,
    I: Clone + IntoIterator<Item = ElementId<G>>,
    S: PageRankScalar,
{
    let bound = graph.element_bound();
    let mut teleport = vec![S::ZERO; bound];
    let mut next = vec![S::ZERO; bound];
    let mut visible_elements = vec![0; bound];
    pagerank_graph_with_scratch(
        graph,
        distribution,
        elements,
        config,
        personalization,
        ranks,
        PageRankScratch::new(&mut teleport, &mut next, &mut visible_elements),
    )
}

/// Computes graph `PageRank` under the supplied outgoing distribution
/// policy with caller-provided borrowed scratch.
///
/// See [`pagerank_graph`] for the role of `distribution`.
///
/// # Errors
///
/// Returns [`PageRankError`] for invalid configuration, personalization,
/// topology indexes, output length, scratch length, or non-convergence.
///
/// # Performance
///
/// Performs no heap allocation after caller scratch has been provided. Each
/// iteration is `O(n + m · cost(D))`.
#[expect(
    clippy::too_many_arguments,
    clippy::needless_pass_by_value,
    reason = "PageRank scratch API consumes a scratch handle and keeps policy inputs explicit"
)]
pub fn pagerank_graph_with_scratch<G, D, I, S>(
    graph: &G,
    distribution: &D,
    elements: I,
    config: PageRankConfig<S>,
    personalization: Option<&[S]>,
    ranks: &mut [S],
    scratch: PageRankScratch<'_, S>,
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    G: ForwardGraph + ElementIndex,
    D: OutgoingDistribution<G, S>,
    I: Clone + IntoIterator<Item = ElementId<G>>,
    S: PageRankScalar,
{
    validate_config(config)?;
    let bound = graph.element_bound();
    ensure_output_len(ranks.len(), bound)?;
    ensure_scratch_len("teleport", scratch.teleport.len(), bound)?;
    ensure_scratch_len("next", scratch.next.len(), bound)?;
    ensure_scratch_len("visible_elements", scratch.visible_elements.len(), bound)?;
    build_personalization_into(
        elements.clone(),
        bound,
        personalization,
        |element| graph.element_index(element),
        scratch.teleport,
        scratch.visible_elements,
    )?;
    initialize_ranks(elements.clone(), graph, scratch.teleport, ranks)?;
    iterate_graph(
        graph,
        distribution,
        elements,
        config,
        scratch.teleport,
        scratch.visible_elements,
        ranks,
        scratch.next,
    )
}

/// Computes graph `PageRank` under the supplied outgoing distribution
/// policy with a reusable owned workspace.
///
/// See [`pagerank_graph`] for the role of `distribution`.
///
/// # Errors
///
/// Returns [`PageRankError`] for invalid configuration, personalization,
/// topology indexes, output length, or non-convergence.
///
/// # Performance
///
/// Grows workspace storage to `graph.element_bound()` if needed, then performs no
/// additional heap allocation. Each iteration is `O(n + m · cost(D))`.
#[cfg(feature = "alloc")]
#[expect(
    clippy::too_many_arguments,
    reason = "PageRank workspace API keeps policy and reusable storage inputs explicit"
)]
pub fn pagerank_graph_with_workspace<G, D, I, S>(
    graph: &G,
    distribution: &D,
    elements: I,
    config: PageRankConfig<S>,
    personalization: Option<&[S]>,
    ranks: &mut [S],
    workspace: &mut PageRankWorkspace<G, S>,
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    G: ForwardGraph + ElementIndex,
    D: OutgoingDistribution<G, S>,
    I: Clone + IntoIterator<Item = ElementId<G>>,
    S: PageRankScalar,
{
    workspace.ensure_element_bound(graph.element_bound());
    pagerank_graph_with_scratch(
        graph,
        distribution,
        elements,
        config,
        personalization,
        ranks,
        workspace.as_scratch(),
    )
}

/// Computes directed hypergraph incidence/bipartite `PageRank` under the
/// supplied bipartite outgoing distribution policy, allocating temporary
/// scratch.
///
/// `distribution` selects the per-state rank-transfer rule:
/// [`Uniform`] divides each leg uniformly over visible out-degree, while
/// [`HyperWeighted`] reads caller-supplied relation and target-incidence
/// weights. Any [`HypergraphOutgoingDistribution`] impl is accepted.
/// `elements` and `relations` define the visible state iteration order
/// across the bipartite element + relation state space.
///
/// # Errors
///
/// Returns [`PageRankError`] for invalid configuration, personalization,
/// topology indexes, invalid weights, output length, scratch length, or
/// non-convergence.
///
/// # Performance
///
/// Each iteration is `O(e + r + p · cost(D))` for `e` visible elements, `r`
/// visible relations, `p` traversed source/target participant entries, and
/// `cost(D)` the per-entry cost of
/// [`HypergraphOutgoingDistribution::distribute_from_element`] and
/// [`HypergraphOutgoingDistribution::distribute_from_relation`] (`O(1)` for
/// the built-in [`Uniform`] and [`HyperWeighted`] impls). Scratch allocation
/// is `O(e + r)`.
#[cfg(feature = "alloc")]
#[expect(
    clippy::too_many_arguments,
    reason = "hypergraph PageRank entry point keeps hypergraph, distribution, state families, and output explicit"
)]
pub fn pagerank_hypergraph<H, D, IE, IR, S>(
    hypergraph: &H,
    distribution: &D,
    elements: IE,
    relations: IR,
    config: PageRankConfig<S>,
    personalization: Option<&[S]>,
    element_ranks: &mut [S],
    relation_ranks: &mut [S],
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    H: DirectedVertexHyperedges
        + DirectedHyperedgeIncidences
        + IncidenceElement
        + ElementIndex
        + RelationIndex,
    D: HypergraphOutgoingDistribution<H, S>,
    IE: Clone + IntoIterator<Item = ElementId<H>>,
    IR: Clone + IntoIterator<Item = RelationId<H>>,
    S: PageRankScalar,
{
    let e_bound = hypergraph.element_bound();
    let r_bound = hypergraph.relation_bound();
    let state_bound =
        checked_state_bound::<S>(e_bound, r_bound, element_ranks.len(), relation_ranks.len())?;
    let mut teleport = vec![S::ZERO; state_bound];
    let mut next_elements = vec![S::ZERO; e_bound];
    let mut next_relations = vec![S::ZERO; r_bound];
    let mut visible_elements = vec![0; e_bound];
    let mut visible_relations = vec![0; r_bound];
    pagerank_hypergraph_with_scratch(
        hypergraph,
        distribution,
        elements,
        relations,
        config,
        personalization,
        element_ranks,
        relation_ranks,
        HypergraphPageRankScratch::new(
            &mut teleport,
            &mut next_elements,
            &mut next_relations,
            &mut visible_elements,
            &mut visible_relations,
        ),
    )
}

/// Computes hypergraph `PageRank` under the supplied outgoing distribution
/// policy with caller-provided borrowed scratch.
///
/// See [`pagerank_hypergraph`] for the role of `distribution`.
///
/// # Errors
///
/// Returns [`PageRankError`] for invalid configuration, personalization,
/// topology indexes, invalid weights, output length, scratch length, or
/// non-convergence.
///
/// # Performance
///
/// Performs no heap allocation after caller scratch has been provided. Each
/// iteration is `O(e + r + p · cost(D))`.
#[expect(
    clippy::too_many_arguments,
    reason = "hypergraph PageRank scratch entry point keeps policy and storage inputs explicit"
)]
#[expect(
    clippy::needless_pass_by_value,
    reason = "hypergraph PageRank scratch API consumes a scratch handle and keeps policy inputs explicit"
)]
pub fn pagerank_hypergraph_with_scratch<H, D, IE, IR, S>(
    hypergraph: &H,
    distribution: &D,
    elements: IE,
    relations: IR,
    config: PageRankConfig<S>,
    personalization: Option<&[S]>,
    element_ranks: &mut [S],
    relation_ranks: &mut [S],
    scratch: HypergraphPageRankScratch<'_, S>,
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    H: DirectedVertexHyperedges
        + DirectedHyperedgeIncidences
        + IncidenceElement
        + ElementIndex
        + RelationIndex,
    D: HypergraphOutgoingDistribution<H, S>,
    IE: Clone + IntoIterator<Item = ElementId<H>>,
    IR: Clone + IntoIterator<Item = RelationId<H>>,
    S: PageRankScalar,
{
    validate_config(config)?;
    let e_bound = hypergraph.element_bound();
    let r_bound = hypergraph.relation_bound();
    let state_bound =
        checked_state_bound::<S>(e_bound, r_bound, element_ranks.len(), relation_ranks.len())?;
    ensure_scratch_len("teleport", scratch.teleport.len(), state_bound)?;
    ensure_scratch_len("next_elements", scratch.next_elements.len(), e_bound)?;
    ensure_scratch_len("next_relations", scratch.next_relations.len(), r_bound)?;
    ensure_scratch_len("visible_elements", scratch.visible_elements.len(), e_bound)?;
    ensure_scratch_len(
        "visible_relations",
        scratch.visible_relations.len(),
        r_bound,
    )?;
    build_hyper_personalization_into(
        hypergraph,
        elements.clone(),
        relations.clone(),
        state_bound,
        personalization,
        scratch.teleport,
        scratch.visible_elements,
        scratch.visible_relations,
    )?;
    initialize_hyper_ranks(
        hypergraph,
        elements.clone(),
        relations.clone(),
        scratch.teleport,
        element_ranks,
        relation_ranks,
    )?;
    iterate_hypergraph(
        hypergraph,
        distribution,
        elements,
        relations,
        config,
        scratch.teleport,
        scratch.visible_elements,
        scratch.visible_relations,
        element_ranks,
        relation_ranks,
        scratch.next_elements,
        scratch.next_relations,
    )
}

/// Computes hypergraph `PageRank` under the supplied outgoing distribution
/// policy with a reusable owned workspace.
///
/// See [`pagerank_hypergraph`] for the role of `distribution`.
///
/// # Errors
///
/// Returns [`PageRankError`] for invalid configuration, personalization,
/// topology indexes, invalid weights, output length, or non-convergence.
///
/// # Performance
///
/// Grows workspace storage to the visible bounds if needed, then performs no
/// additional heap allocation. Each iteration is `O(e + r + p · cost(D))`.
#[cfg(feature = "alloc")]
#[expect(
    clippy::too_many_arguments,
    reason = "hypergraph PageRank workspace entry point keeps policy and storage inputs explicit"
)]
pub fn pagerank_hypergraph_with_workspace<H, D, IE, IR, S>(
    hypergraph: &H,
    distribution: &D,
    elements: IE,
    relations: IR,
    config: PageRankConfig<S>,
    personalization: Option<&[S]>,
    element_ranks: &mut [S],
    relation_ranks: &mut [S],
    workspace: &mut HypergraphPageRankWorkspace<H, S>,
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    H: DirectedVertexHyperedges
        + DirectedHyperedgeIncidences
        + IncidenceElement
        + ElementIndex
        + RelationIndex,
    D: HypergraphOutgoingDistribution<H, S>,
    IE: Clone + IntoIterator<Item = ElementId<H>>,
    IR: Clone + IntoIterator<Item = RelationId<H>>,
    S: PageRankScalar,
{
    let e_bound = hypergraph.element_bound();
    let r_bound = hypergraph.relation_bound();
    let state_bound =
        checked_state_bound::<S>(e_bound, r_bound, element_ranks.len(), relation_ranks.len())?;
    workspace.ensure_bounds(e_bound, r_bound, state_bound);
    pagerank_hypergraph_with_scratch(
        hypergraph,
        distribution,
        elements,
        relations,
        config,
        personalization,
        element_ranks,
        relation_ranks,
        workspace.as_scratch(),
    )
}

fn validate_config<S: PageRankScalar>(config: PageRankConfig<S>) -> Result<(), PageRankError<S>> {
    if !config.damping.is_finite() || config.damping < S::ZERO || config.damping > S::ONE {
        return Err(PageRankError::InvalidDamping {
            damping: config.damping,
        });
    }
    if !config.tolerance.is_finite() || config.tolerance < S::ZERO {
        return Err(PageRankError::InvalidTolerance {
            tolerance: config.tolerance,
        });
    }
    if config.max_iterations == 0 {
        return Err(PageRankError::InvalidMaxIterations);
    }
    Ok(())
}

const fn ensure_output_len<S>(actual: usize, required: usize) -> Result<(), PageRankError<S>> {
    if actual < required {
        Err(PageRankError::OutputTooShort { required, actual })
    } else {
        Ok(())
    }
}

const fn ensure_scratch_len<S>(
    name: &'static str,
    actual: usize,
    required: usize,
) -> Result<(), PageRankError<S>> {
    if actual < required {
        Err(PageRankError::ScratchTooShort {
            name,
            required,
            actual,
        })
    } else {
        Ok(())
    }
}

fn checked_state_bound<S>(
    e_bound: usize,
    r_bound: usize,
    element_output_len: usize,
    relation_output_len: usize,
) -> Result<usize, PageRankError<S>> {
    ensure_output_len(element_output_len, e_bound)?;
    ensure_output_len(relation_output_len, r_bound)?;
    e_bound
        .checked_add(r_bound)
        .ok_or_else(|| PageRankError::OutputTooShort {
            required: usize::MAX,
            actual: element_output_len.saturating_add(relation_output_len),
        })
}

fn clear<S: PageRankScalar>(values: &mut [S], len: usize) {
    for value in &mut values[..len] {
        *value = S::ZERO;
    }
}

fn clear_u8(values: &mut [u8], len: usize) {
    for value in &mut values[..len] {
        *value = 0;
    }
}

fn mark_visible_element<S>(visible: &mut [u8], index: usize) -> Result<(), PageRankError<S>> {
    if visible[index] != 0 {
        return Err(PageRankError::DuplicateElement { index });
    }
    visible[index] = 1;
    Ok(())
}

fn mark_visible_relation<S>(visible: &mut [u8], index: usize) -> Result<(), PageRankError<S>> {
    if visible[index] != 0 {
        return Err(PageRankError::DuplicateRelation { index });
    }
    visible[index] = 1;
    Ok(())
}

// `visible` slices are sized to the view's element/relation bound and every
// index is derived from `element_index`/`relation_index`, so direct indexing is
// in range — matching `mark_visible_element`/`mark_visible_relation`, which also
// index directly. This keeps a single "exactly-sized bitset" contract.
fn is_visible(visible: &[u8], index: usize) -> bool {
    visible[index] != 0
}

#[expect(
    clippy::too_many_arguments,
    reason = "personalization normalization keeps topology family bounds and caller buffers explicit"
)]
fn build_personalization_into<I, F, S>(
    elements: I,
    bound: usize,
    personalization: Option<&[S]>,
    index_of: F,
    out: &mut [S],
    visible: &mut [u8],
) -> Result<(), PageRankError<S>>
where
    I: IntoIterator,
    F: Fn(I::Item) -> usize,
    S: PageRankScalar,
{
    clear(out, bound);
    clear_u8(visible, bound);
    let mut count = 0_usize;
    let mut sum = S::ZERO;
    if let Some(input) = personalization {
        if input.len() < bound {
            return Err(PageRankError::PersonalizationTooShort {
                required: bound,
                actual: input.len(),
            });
        }
        for element in elements {
            let index = index_of(element);
            check_index(index, bound)?;
            mark_visible_element(visible, index)?;
            let value = input[index];
            check_personalization_value(index, value)?;
            out[index] = value;
            sum += value;
            count += 1;
        }
    } else {
        for element in elements {
            let index = index_of(element);
            check_index(index, bound)?;
            mark_visible_element(visible, index)?;
            out[index] = S::ONE;
            sum += S::ONE;
            count += 1;
        }
    }
    normalize_personalization(out, count, sum)
}

/// Personalization source used by [`PageRank`](crate) initialization.
///
/// Drives the per-visible-state initialization: either copy from a
/// caller-supplied vector ([`Self::FromInput`]) or fill every visible state
/// with `S::ONE` ([`Self::Uniform`]).
///
/// # Performance
///
/// `value_at` is `O(1)`. The fill methods walk visible elements and (for
/// hypergraphs) visible relations exactly once.
enum PersonalizationSource<'a, S> {
    /// Initialize every visible state slot to `S::ONE`.
    Uniform,
    /// Copy the value at the matching state index from the supplied slice.
    /// The slice must already be range-checked against the caller's state
    /// bound; [`Self::value_at`] only validates each value.
    FromInput(&'a [S]),
}

impl<S> PersonalizationSource<'_, S>
where
    S: PageRankScalar,
{
    /// Returns the value to place at `state_index`.
    ///
    /// `FromInput` reads `input[state_index]` and rejects non-finite or
    /// negative entries via [`PageRankError::InvalidPersonalization`].
    /// `Uniform` returns `S::ONE` unconditionally.
    ///
    /// # Performance
    ///
    /// `O(1)`.
    fn value_at(&self, state_index: usize) -> Result<S, PageRankError<S>> {
        match *self {
            Self::Uniform => Ok(S::ONE),
            Self::FromInput(input) => {
                let value = input[state_index];
                check_personalization_value(state_index, value)?;
                Ok(value)
            }
        }
    }

    /// Fills the hypergraph teleport vector at visible-element and
    /// visible-relation states.
    ///
    /// Returns `(count, sum)` for the normalization step. `state_bound` is
    /// the total length of `out` (`element_bound + relation_bound`); it is
    /// used to bounds-check `FromInput` slices before iteration.
    ///
    /// # Errors
    ///
    /// [`PageRankError::PersonalizationTooShort`] when a `FromInput` slice is
    /// shorter than `state_bound`;
    /// [`PageRankError::ElementIndexOutOfBounds`] /
    /// [`PageRankError::RelationIndexOutOfBounds`] when a visible element or
    /// relation maps outside its bound; [`PageRankError::DuplicateElement`] /
    /// [`PageRankError::DuplicateRelation`] when a state is marked visible
    /// twice; and [`PageRankError::InvalidPersonalization`] for a negative
    /// personalization entry.
    ///
    /// # Performance
    ///
    /// `O(|elements| + |relations|)` plus the index/visibility check cost
    /// per state slot.
    #[expect(
        clippy::too_many_arguments,
        reason = "method threads separate element/relation iterables, scratch slices, and the state bound; bundling them obscures the borrow shape that callers explicitly construct"
    )]
    fn fill_hypergraph<H, IE, IR>(
        &self,
        hypergraph: &H,
        elements: IE,
        relations: IR,
        state_bound: usize,
        out: &mut [S],
        visible_elements: &mut [u8],
        visible_relations: &mut [u8],
    ) -> Result<(usize, S), PageRankError<S>>
    where
        H: ElementIndex + RelationIndex,
        IE: IntoIterator<Item = ElementId<H>>,
        IR: IntoIterator<Item = RelationId<H>>,
    {
        if let Self::FromInput(input) = *self
            && input.len() < state_bound
        {
            return Err(PageRankError::PersonalizationTooShort {
                required: state_bound,
                actual: input.len(),
            });
        }
        let e_bound = hypergraph.element_bound();
        let r_bound = hypergraph.relation_bound();
        let mut count = 0_usize;
        let mut sum = S::ZERO;
        for element in elements {
            let index = hypergraph.element_index(element);
            check_index(index, e_bound)?;
            mark_visible_element(visible_elements, index)?;
            let value = self.value_at(index)?;
            out[index] = value;
            sum += value;
            count += 1;
        }
        for relation in relations {
            let index = hypergraph.relation_index(relation);
            check_relation_index(index, r_bound)?;
            mark_visible_relation(visible_relations, index)?;
            let state = e_bound + index;
            let value = self.value_at(state)?;
            out[state] = value;
            sum += value;
            count += 1;
        }
        Ok((count, sum))
    }
}

#[expect(
    clippy::too_many_arguments,
    reason = "helper threads separate element/relation state and caller scratch explicitly"
)]
fn build_hyper_personalization_into<H, IE, IR, S>(
    hypergraph: &H,
    elements: IE,
    relations: IR,
    state_bound: usize,
    personalization: Option<&[S]>,
    out: &mut [S],
    visible_elements: &mut [u8],
    visible_relations: &mut [u8],
) -> Result<(), PageRankError<S>>
where
    H: ElementIndex + RelationIndex,
    IE: IntoIterator<Item = ElementId<H>>,
    IR: IntoIterator<Item = RelationId<H>>,
    S: PageRankScalar,
{
    clear(out, state_bound);
    clear_u8(visible_elements, hypergraph.element_bound());
    clear_u8(visible_relations, hypergraph.relation_bound());
    let source = personalization.map_or(
        PersonalizationSource::Uniform,
        PersonalizationSource::FromInput,
    );
    let (count, sum) = source.fill_hypergraph(
        hypergraph,
        elements,
        relations,
        state_bound,
        out,
        visible_elements,
        visible_relations,
    )?;
    normalize_personalization(out, count, sum)
}

fn normalize_personalization<S: PageRankScalar>(
    out: &mut [S],
    count: usize,
    sum: S,
) -> Result<(), PageRankError<S>> {
    if count == 0 {
        return Err(PageRankError::EmptyState);
    }
    if sum <= S::ZERO {
        return Err(PageRankError::ZeroPersonalization);
    }
    for value in out {
        *value = *value / sum;
    }
    Ok(())
}

fn check_personalization_value<S: PageRankScalar>(
    index: usize,
    value: S,
) -> Result<(), PageRankError<S>> {
    if !value.is_finite() || value < S::ZERO {
        Err(PageRankError::InvalidPersonalization { index, value })
    } else {
        Ok(())
    }
}

fn initialize_ranks<G, I, S>(
    elements: I,
    graph: &G,
    teleport: &[S],
    ranks: &mut [S],
) -> Result<(), PageRankError<S>>
where
    G: ElementIndex,
    I: IntoIterator<Item = ElementId<G>>,
    S: PageRankScalar,
{
    clear(ranks, graph.element_bound());
    for element in elements {
        let index = graph.element_index(element);
        check_index(index, graph.element_bound())?;
        ranks[index] = teleport[index];
    }
    Ok(())
}

#[expect(
    clippy::too_many_arguments,
    reason = "initialization writes separate element and relation rank slices"
)]
fn initialize_hyper_ranks<H, IE, IR, S>(
    hypergraph: &H,
    elements: IE,
    relations: IR,
    teleport: &[S],
    element_ranks: &mut [S],
    relation_ranks: &mut [S],
) -> Result<(), PageRankError<S>>
where
    H: ElementIndex + RelationIndex,
    IE: IntoIterator<Item = ElementId<H>>,
    IR: IntoIterator<Item = RelationId<H>>,
    S: PageRankScalar,
{
    clear(element_ranks, hypergraph.element_bound());
    clear(relation_ranks, hypergraph.relation_bound());
    for element in elements {
        let index = hypergraph.element_index(element);
        check_index(index, hypergraph.element_bound())?;
        element_ranks[index] = teleport[index];
    }
    for relation in relations {
        let index = hypergraph.relation_index(relation);
        check_relation_index(index, hypergraph.relation_bound())?;
        relation_ranks[index] = teleport[hypergraph.element_bound() + index];
    }
    Ok(())
}

#[expect(
    clippy::too_many_arguments,
    reason = "graph iteration helper keeps distribution, scratch, and policy inputs explicit"
)]
#[expect(
    clippy::needless_pass_by_value,
    reason = "iteration helpers own cloneable iterator values and clone them each power iteration"
)]
fn iterate_graph<G, D, I, S>(
    graph: &G,
    distribution: &D,
    elements: I,
    config: PageRankConfig<S>,
    teleport: &[S],
    visible: &[u8],
    ranks: &mut [S],
    next: &mut [S],
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    G: ForwardGraph + ElementIndex,
    D: OutgoingDistribution<G, S>,
    I: Clone + IntoIterator<Item = ElementId<G>>,
    S: PageRankScalar,
{
    let mut last_delta = S::INFINITY;
    for iteration in 1..=config.max_iterations {
        clear(next, graph.element_bound());
        let mut dangling = S::ZERO;
        for element in elements.clone() {
            let index = checked_element_index(graph, element)?;
            let rank = ranks[index];
            dangling += distribution.distribute_outgoing(graph, element, rank, next, visible)?;
        }
        let delta = apply_graph_teleport(
            graph,
            elements.clone(),
            config,
            teleport,
            dangling,
            ranks,
            next,
        )?;
        last_delta = delta;
        if delta <= config.tolerance {
            return Ok(PageRankReport {
                iterations: iteration,
                delta,
            });
        }
    }
    Err(PageRankError::NonConverged {
        iterations: config.max_iterations,
        delta: last_delta,
    })
}

#[expect(
    clippy::too_many_arguments,
    reason = "hypergraph iteration helper keeps distribution, state families, scratch, and policy inputs explicit"
)]
#[expect(
    clippy::needless_pass_by_value,
    reason = "iteration helpers own cloneable iterator values and clone them each power iteration"
)]
fn iterate_hypergraph<H, D, IE, IR, S>(
    hypergraph: &H,
    distribution: &D,
    elements: IE,
    relations: IR,
    config: PageRankConfig<S>,
    teleport: &[S],
    visible_elements: &[u8],
    visible_relations: &[u8],
    element_ranks: &mut [S],
    relation_ranks: &mut [S],
    next_elements: &mut [S],
    next_relations: &mut [S],
) -> Result<PageRankReport<S>, PageRankError<S>>
where
    H: DirectedVertexHyperedges
        + DirectedHyperedgeIncidences
        + IncidenceElement
        + ElementIndex
        + RelationIndex,
    D: HypergraphOutgoingDistribution<H, S>,
    IE: Clone + IntoIterator<Item = ElementId<H>>,
    IR: Clone + IntoIterator<Item = RelationId<H>>,
    S: PageRankScalar,
{
    let mut last_delta = S::INFINITY;
    for iteration in 1..=config.max_iterations {
        clear(next_elements, hypergraph.element_bound());
        clear(next_relations, hypergraph.relation_bound());
        let mut dangling = S::ZERO;
        for element in elements.clone() {
            let index = checked_element_index(hypergraph, element)?;
            let rank = element_ranks[index];
            dangling += distribution.distribute_from_element(
                hypergraph,
                element,
                rank,
                next_relations,
                visible_relations,
            )?;
        }
        for relation in relations.clone() {
            let index = checked_relation_index_for(hypergraph, relation)?;
            let rank = relation_ranks[index];
            dangling += distribution.distribute_from_relation(
                hypergraph,
                relation,
                rank,
                next_elements,
                visible_elements,
            )?;
        }
        let delta = apply_hyper_teleport(
            hypergraph,
            elements.clone(),
            relations.clone(),
            config,
            teleport,
            dangling,
            element_ranks,
            relation_ranks,
            next_elements,
            next_relations,
        )?;
        last_delta = delta;
        if delta <= config.tolerance {
            return Ok(PageRankReport {
                iterations: iteration,
                delta,
            });
        }
    }
    Err(PageRankError::NonConverged {
        iterations: config.max_iterations,
        delta: last_delta,
    })
}

fn checked_element_index<G: ElementIndex, S>(
    graph: &G,
    element: ElementId<G>,
) -> Result<usize, PageRankError<S>> {
    let index = graph.element_index(element);
    check_index(index, graph.element_bound())?;
    Ok(index)
}

const fn check_index<S>(index: usize, bound: usize) -> Result<(), PageRankError<S>> {
    if index < bound {
        Ok(())
    } else {
        Err(PageRankError::ElementIndexOutOfBounds { index, bound })
    }
}

const fn check_relation_index<S>(index: usize, bound: usize) -> Result<(), PageRankError<S>> {
    if index < bound {
        Ok(())
    } else {
        Err(PageRankError::RelationIndexOutOfBounds { index, bound })
    }
}

fn checked_relation_weight<G, W, S>(
    graph: &G,
    weights: &W,
    relation: RelationId<G>,
) -> Result<S, PageRankError<S>>
where
    G: RelationIndex,
    W: RelationWeight<ElementId = G::ElementId, RelationId = G::RelationId>,
    W::Weight: IntoPageRankScalar<S>,
    S: PageRankScalar,
{
    let index = graph.relation_index(relation);
    check_relation_index(index, graph.relation_bound())?;
    let value = weights.relation_weight(relation).into_pagerank_scalar();
    if !value.is_finite() || value < S::ZERO {
        Err(PageRankError::InvalidRelationWeight { index, value })
    } else {
        Ok(value)
    }
}

fn checked_incidence_weight<H, W, S>(
    hypergraph: &H,
    weights: &W,
    incidence: H::IncidenceId,
) -> Result<S, PageRankError<S>>
where
    H: IncidenceIndex,
    W: IncidenceWeight<
            ElementId = H::ElementId,
            RelationId = H::RelationId,
            IncidenceId = H::IncidenceId,
        >,
    W::Weight: IntoPageRankScalar<S>,
    S: PageRankScalar,
{
    let index = hypergraph.incidence_index(incidence);
    let bound = hypergraph.incidence_bound();
    if index >= bound {
        return Err(PageRankError::IncidenceIndexOutOfBounds { index, bound });
    }
    let value = weights.incidence_weight(incidence).into_pagerank_scalar();
    if !value.is_finite() || value < S::ZERO {
        Err(PageRankError::InvalidIncidenceWeight { index, value })
    } else {
        Ok(value)
    }
}

fn outgoing_weight_total<G, W, S>(
    graph: &G,
    weights: &W,
    element: ElementId<G>,
    visible: &[u8],
) -> Result<S, PageRankError<S>>
where
    G: ForwardGraph + ElementIndex + RelationIndex,
    W: RelationWeight<ElementId = G::ElementId, RelationId = G::RelationId>,
    W::Weight: IntoPageRankScalar<S>,
    S: PageRankScalar,
{
    let mut total = S::ZERO;
    for edge in graph.outgoing_edges(element) {
        let target = graph.target(edge);
        let target_index = checked_element_index(graph, target)?;
        if is_visible(visible, target_index) {
            total += checked_relation_weight(graph, weights, edge)?;
        }
    }
    Ok(total)
}

/// Computes the teleport-blended rank for one state and its absolute delta.
///
/// Shared by the graph and both hypergraph state legs so the convergence
/// formula `damping * accumulated + teleport_scale * teleport` lives in exactly
/// one place. Returns `(new_value, |new_value - previous|)`; the caller writes
/// `new_value` into the rank slice (the `next`/accumulator slice is cleared at
/// the top of the following iteration, so it is intentionally not written back).
///
/// # Performance
///
/// This function is `O(1)`.
fn teleport_update<S: PageRankScalar>(
    damping: S,
    teleport_scale: S,
    accumulated: S,
    teleport: S,
    previous: S,
) -> (S, S) {
    let value = (damping * accumulated) + (teleport_scale * teleport);
    let delta = (value - previous).abs();
    (value, delta)
}

#[expect(
    clippy::too_many_arguments,
    reason = "teleport helper updates caller-provided rank and scratch slices"
)]
fn apply_graph_teleport<G, I, S>(
    graph: &G,
    elements: I,
    config: PageRankConfig<S>,
    teleport: &[S],
    dangling: S,
    ranks: &mut [S],
    next: &[S],
) -> Result<S, PageRankError<S>>
where
    G: ElementIndex,
    I: IntoIterator<Item = ElementId<G>>,
    S: PageRankScalar,
{
    let mut delta = S::ZERO;
    let teleport_scale = (S::ONE - config.damping) + (config.damping * dangling);
    for element in elements {
        let index = checked_element_index(graph, element)?;
        let (value, state_delta) = teleport_update(
            config.damping,
            teleport_scale,
            next[index],
            teleport[index],
            ranks[index],
        );
        delta += state_delta;
        ranks[index] = value;
    }
    Ok(delta)
}

fn checked_relation_index_for<H: RelationIndex, S>(
    hypergraph: &H,
    relation: RelationId<H>,
) -> Result<usize, PageRankError<S>> {
    let index = hypergraph.relation_index(relation);
    check_relation_index(index, hypergraph.relation_bound())?;
    Ok(index)
}

fn hyper_outgoing_relation_weight<H, W, S>(
    hypergraph: &H,
    weights: &W,
    element: ElementId<H>,
    visible_relations: &[u8],
) -> Result<S, PageRankError<S>>
where
    H: DirectedVertexHyperedges + RelationIndex,
    W: RelationWeight<ElementId = H::ElementId, RelationId = H::RelationId>,
    W::Weight: IntoPageRankScalar<S>,
    S: PageRankScalar,
{
    let mut total = S::ZERO;
    for relation in hypergraph.outgoing_hyperedges(element) {
        let relation_index = checked_relation_index_for(hypergraph, relation)?;
        if is_visible(visible_relations, relation_index) {
            total += checked_relation_weight(hypergraph, weights, relation)?;
        }
    }
    Ok(total)
}

fn hyper_target_incidence_weight<H, W, S>(
    hypergraph: &H,
    weights: &W,
    relation: RelationId<H>,
    visible_elements: &[u8],
) -> Result<S, PageRankError<S>>
where
    H: DirectedHyperedgeIncidences + IncidenceElement + ElementIndex + IncidenceIndex,
    W: IncidenceWeight<
            ElementId = H::ElementId,
            RelationId = H::RelationId,
            IncidenceId = H::IncidenceId,
        >,
    W::Weight: IntoPageRankScalar<S>,
    S: PageRankScalar,
{
    let mut total = S::ZERO;
    for incidence in hypergraph.target_incidences(relation) {
        let target = hypergraph.incidence_element(incidence);
        let target_index = checked_element_index(hypergraph, target)?;
        if is_visible(visible_elements, target_index) {
            total += checked_incidence_weight(hypergraph, weights, incidence)?;
        }
    }
    Ok(total)
}

#[expect(
    clippy::too_many_arguments,
    reason = "hypergraph teleport updates separate element and relation slices"
)]
fn apply_hyper_teleport<H, IE, IR, S>(
    hypergraph: &H,
    elements: IE,
    relations: IR,
    config: PageRankConfig<S>,
    teleport: &[S],
    dangling: S,
    element_ranks: &mut [S],
    relation_ranks: &mut [S],
    next_elements: &[S],
    next_relations: &[S],
) -> Result<S, PageRankError<S>>
where
    H: ElementIndex + RelationIndex,
    IE: IntoIterator<Item = ElementId<H>>,
    IR: IntoIterator<Item = RelationId<H>>,
    S: PageRankScalar,
{
    let mut delta = S::ZERO;
    let e_bound = hypergraph.element_bound();
    let teleport_scale = (S::ONE - config.damping) + (config.damping * dangling);
    for element in elements {
        let index = checked_element_index(hypergraph, element)?;
        let (value, state_delta) = teleport_update(
            config.damping,
            teleport_scale,
            next_elements[index],
            teleport[index],
            element_ranks[index],
        );
        delta += state_delta;
        element_ranks[index] = value;
    }
    for relation in relations {
        let index = checked_relation_index_for(hypergraph, relation)?;
        let state = e_bound + index;
        let (value, state_delta) = teleport_update(
            config.damping,
            teleport_scale,
            next_relations[index],
            teleport[state],
            relation_ranks[index],
        );
        delta += state_delta;
        relation_ranks[index] = value;
    }
    Ok(delta)
}