topological-coherence 0.3.1

Toroidal topology primitives for LLM coherence research — Tonnetz geometry, spectral gap, attention masks, Karmonic spectral filter (v7: inference-time bias null, training-time valid)
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
//! # Topological Coherence
//!
//! Rust implementation of topological constraints for coherent inference.
//! Based on: "Topological Constraints for Coherent Language Models" (Cormier, 2026)
//!
//! ## Theory
//!
//! Hallucination is a geometry problem: unconstrained latent dynamics permit
//! arbitrary drift through latent space. Topological constraints (specifically
//! toroidal manifolds with constant spectral gap) bound this drift.
//!
//! ## Hierarchy
//!
//! ```text
//! mHC (Birkhoff) ⊂ ERLHS (Hamiltonian) ⊂ Karmonic (Toroidal + Spectral)
//! ```
//!
//! ## Key Results (from validation experiment)
//!
//! | Condition | Drift Rate | Interpretation |
//! |-----------|------------|----------------|
//! | Toroidal  | 0.006      | 40% lower than baseline |
//! | Random    | 0.167      | 28x worse (proves topology matters) |
//!
//! ## Usage
//!
//! ```rust,ignore
//! use topological_coherence::{Tonnetz, ToroidalMask};
//!
//! // Create 12x12 Tonnetz (standard musical topology)
//! let tonnetz = Tonnetz::<12>::new();
//!
//! // Distance on torus
//! let d = tonnetz.distance((0, 0), (5, 7));
//!
//! // Attention mask with locality radius 2
//! let mask = ToroidalMask::new(64, 2.0, 1.0);
//! ```

#![cfg_attr(not(feature = "std"), no_std)]

use libm::{expf, cosf, fabsf};

// Substrate SCALE codec support
#[cfg(feature = "substrate")]
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
#[cfg(feature = "substrate")]
use scale_info::TypeInfo;

// =============================================================================
// Implementation Status
// =============================================================================
//
// Phase 1: Core Topology — COMPLETE
//   Tonnetz struct, toroidal distance, attention masks, spectral gap, property tests
//
// Phase 2: Mask Variants — COMPLETE
//   Hard cutoff, soft exponential, hybrid, Sinkhorn-Knopp projection
//
// Phase 3: Integration Points — COMPLETE
//   Substrate SCALE codec types, CoherenceConfig, CoherenceResult, ToroidalPosition
//
// Phase 4: Advanced Features — COMPLETE
//   Learned toroidal projection, adjacency loss, multi-scale Tonnetz, 3D torus (T^3),
//   sparse CSR mask format
//
// Phase 5: Grounding Projector — COMPLETE
//   Orthogonal evidence projection G = A(AᵀA)⁻¹Aᵀ, hallucination scoring,
//   vector decomposition into grounded and hallucinated components
//
// References:
//   Paper: https://github.com/Paraxiom/topological-coherence
//   ERLHS: DOI 10.5281/zenodo.17928909
//   Karmonic: DOI 10.5281/zenodo.17928991
//
// =============================================================================

/// Mask type variants for different use cases.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "substrate", derive(Encode, Decode, MaxEncodedLen, TypeInfo))]
pub enum MaskType {
    /// Hard cutoff: M(i,j) = 1 if d <= r, else 0
    HardCutoff,
    /// Soft exponential: M(i,j) = exp(-α * d)
    SoftExponential,
    /// Hybrid: 1 if d <= r, else exp(-α * (d - r))
    Hybrid,
}

/// Tonnetz topology on a 2D torus of size N x N.
///
/// The Tonnetz is a toroidal lattice where:
/// - Horizontal edges connect by perfect fifths
/// - Vertical edges connect by major thirds
/// - Diagonal edges connect by minor thirds
///
/// We use it as a constructive existence proof of a low-genus manifold
/// with constant spectral gap λ₁ = Θ(1) for fixed N.
#[derive(Debug, Clone, Copy)]
pub struct Tonnetz<const N: usize>;

impl<const N: usize> Tonnetz<N> {
    /// Create a new Tonnetz topology.
    pub const fn new() -> Self {
        Self
    }

    /// Grid size (N x N torus).
    pub const fn size(&self) -> usize {
        N
    }

    /// Total number of positions on the torus.
    pub const fn total_positions(&self) -> usize {
        N * N
    }

    /// Convert linear index to 2D torus coordinates.
    #[inline]
    pub const fn to_coords(index: usize) -> (usize, usize) {
        (index / N, index % N)
    }

    /// Convert 2D torus coordinates to linear index.
    #[inline]
    pub const fn to_index(row: usize, col: usize) -> usize {
        (row % N) * N + (col % N)
    }

    /// Toroidal distance between two positions.
    ///
    /// Uses L1 (Manhattan) distance with wraparound:
    /// d_T(a, b) = min(|a.0 - b.0|, N - |a.0 - b.0|) + min(|a.1 - b.1|, N - |a.1 - b.1|)
    #[inline]
    pub fn distance(a: (usize, usize), b: (usize, usize)) -> usize {
        let dx = a.0.abs_diff(b.0);
        let dy = a.1.abs_diff(b.1);

        let dx_wrap = if dx > N / 2 { N - dx } else { dx };
        let dy_wrap = if dy > N / 2 { N - dy } else { dy };

        dx_wrap + dy_wrap
    }

    /// Distance between two linear indices.
    #[inline]
    pub fn distance_linear(i: usize, j: usize) -> usize {
        Self::distance(Self::to_coords(i), Self::to_coords(j))
    }

    /// First non-trivial eigenvalue of the torus Laplacian (spectral gap).
    ///
    /// For a d-dimensional torus T^d_N:
    /// λ₁ = 2 - 2cos(2π/N) = Θ(1) for fixed N
    ///
    /// This is the key property: spectral gap remains constant regardless
    /// of how we scale the embedding dimension.
    pub fn spectral_gap() -> f32 {
        let pi = core::f32::consts::PI;
        2.0 - 2.0 * cosf(2.0 * pi / N as f32)
    }

    /// Spectral gap decay rate for non-resonant modes.
    ///
    /// Non-resonant modes decay as e^(-λ₁ * t).
    pub fn decay_rate(t: f32) -> f32 {
        expf(-Self::spectral_gap() * t)
    }
}

impl<const N: usize> Default for Tonnetz<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Toroidal attention mask generator.
///
/// Creates masks according to Eq. 17 from the paper:
/// ```text
/// M_Tonnetz(i, j) = 1                        if d_Tonnetz(i, j) ≤ r
///                   exp(-α · d_Tonnetz(i,j)) otherwise
/// ```
#[derive(Debug, Clone)]
pub struct ToroidalMask {
    /// Sequence length
    pub seq_len: usize,
    /// Locality radius (hard cutoff)
    pub radius: f32,
    /// Decay rate for soft falloff
    pub alpha: f32,
    /// Grid size for Tonnetz mapping
    pub grid_size: usize,
    /// Mask type variant
    pub mask_type: MaskType,
}

impl ToroidalMask {
    /// Create a new toroidal mask configuration (hybrid by default).
    pub fn new(seq_len: usize, radius: f32, alpha: f32) -> Self {
        Self::with_grid(seq_len, radius, alpha, 12)
    }

    /// Create with custom grid size.
    pub fn with_grid(seq_len: usize, radius: f32, alpha: f32, grid_size: usize) -> Self {
        Self {
            seq_len,
            radius,
            alpha,
            grid_size,
            mask_type: MaskType::Hybrid,
        }
    }

    /// Create hard cutoff mask: M(i,j) = 1 if d <= r, else 0
    pub fn hard_cutoff(seq_len: usize, radius: f32, grid_size: usize) -> Self {
        Self {
            seq_len,
            radius,
            alpha: 0.0,
            grid_size,
            mask_type: MaskType::HardCutoff,
        }
    }

    /// Create soft exponential mask: M(i,j) = exp(-α * d)
    pub fn soft_exponential(seq_len: usize, alpha: f32, grid_size: usize) -> Self {
        Self {
            seq_len,
            radius: 0.0,
            alpha,
            grid_size,
            mask_type: MaskType::SoftExponential,
        }
    }

    /// Compute toroidal distance between two sequence positions.
    fn toroidal_distance(&self, i: usize, j: usize) -> f32 {
        let n = self.grid_size;
        let pos_i = (i % n, (i / n) % n);
        let pos_j = (j % n, (j / n) % n);

        let dx = pos_i.0.abs_diff(pos_j.0);
        let dy = pos_i.1.abs_diff(pos_j.1);

        let dx_wrap = if dx > n / 2 { n - dx } else { dx };
        let dy_wrap = if dy > n / 2 { n - dy } else { dy };
        (dx_wrap + dy_wrap) as f32
    }

    /// Compute mask value for position pair (i, j).
    pub fn value(&self, i: usize, j: usize) -> f32 {
        let dist = self.toroidal_distance(i, j);

        match self.mask_type {
            MaskType::HardCutoff => {
                if dist <= self.radius { 1.0 } else { 0.0 }
            }
            MaskType::SoftExponential => {
                expf(-self.alpha * dist)
            }
            MaskType::Hybrid => {
                if dist <= self.radius {
                    1.0
                } else {
                    expf(-self.alpha * (dist - self.radius))
                }
            }
        }
    }

    /// Generate full mask matrix.
    #[cfg(feature = "std")]
    pub fn generate(&self) -> Vec<Vec<f32>> {
        (0..self.seq_len)
            .map(|i| (0..self.seq_len).map(|j| self.value(i, j)).collect())
            .collect()
    }

    /// Generate and apply Sinkhorn-Knopp to make doubly-stochastic.
    #[cfg(feature = "std")]
    pub fn generate_doubly_stochastic(&self, iterations: usize) -> Vec<Vec<f32>> {
        let mask = self.generate();
        sinkhorn_knopp(mask, iterations)
    }
}

/// Sinkhorn-Knopp algorithm: project matrix to doubly-stochastic.
///
/// Alternately normalizes rows and columns until convergence.
/// A doubly-stochastic matrix has all rows and columns sum to 1.
///
/// This is used for mHC-style constraints (Birkhoff polytope projection).
#[cfg(feature = "std")]
pub fn sinkhorn_knopp(mut matrix: Vec<Vec<f32>>, iterations: usize) -> Vec<Vec<f32>> {
    let n = matrix.len();
    if n == 0 {
        return matrix;
    }

    for _ in 0..iterations {
        // Normalize rows
        for row in &mut matrix {
            let row_sum: f32 = row.iter().sum();
            if row_sum > 1e-10 {
                for val in row.iter_mut() {
                    *val /= row_sum;
                }
            }
        }

        // Normalize columns
        for j in 0..n {
            let col_sum: f32 = matrix.iter().map(|row| row[j]).sum();
            if col_sum > 1e-10 {
                for row in &mut matrix {
                    row[j] /= col_sum;
                }
            }
        }
    }

    matrix
}

/// Check if matrix is approximately doubly-stochastic.
#[cfg(feature = "std")]
pub fn is_doubly_stochastic(matrix: &[Vec<f32>], tolerance: f32) -> bool {
    let n = matrix.len();
    if n == 0 {
        return true;
    }

    // Check row sums
    for row in matrix {
        let sum: f32 = row.iter().sum();
        if fabsf(sum - 1.0) > tolerance {
            return false;
        }
    }

    // Check column sums
    for j in 0..n {
        let sum: f32 = (0..n).map(|i| matrix[i][j]).sum();
        if fabsf(sum - 1.0) > tolerance {
            return false;
        }
    }

    true
}

/// Drift measurement utilities.
///
/// Drift rate = fraction of transitions where d_Tonnetz(pred, target) > threshold.
pub struct DriftMeter {
    /// Distance threshold for "drift" classification
    pub threshold: usize,
    /// Number of transitions measured
    pub count: usize,
    /// Number of drifts detected
    pub drifts: usize,
}

impl DriftMeter {
    /// Create a new drift meter with given threshold.
    pub fn new(threshold: usize) -> Self {
        Self {
            threshold,
            count: 0,
            drifts: 0,
        }
    }

    /// Record a transition from predicted to target position.
    pub fn record<const N: usize>(&mut self, pred: usize, target: usize) {
        let dist = Tonnetz::<N>::distance_linear(pred, target);
        self.count += 1;
        if dist > self.threshold {
            self.drifts += 1;
        }
    }

    /// Current drift rate (0.0 to 1.0).
    pub fn rate(&self) -> f32 {
        if self.count == 0 {
            0.0
        } else {
            self.drifts as f32 / self.count as f32
        }
    }

    /// Reset measurements.
    pub fn reset(&mut self) {
        self.count = 0;
        self.drifts = 0;
    }
}

// =============================================================================
// Substrate Integration Types
// =============================================================================

/// Position on the Tonnetz torus (for on-chain storage).
///
/// Stores coordinates as u8 to minimize storage cost.
/// Supports grids up to 255x255.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "substrate", derive(Encode, Decode, MaxEncodedLen, TypeInfo))]
pub struct ToroidalPosition {
    /// Row coordinate (0..N)
    pub row: u8,
    /// Column coordinate (0..N)
    pub col: u8,
}

impl ToroidalPosition {
    /// Create a new position.
    pub const fn new(row: u8, col: u8) -> Self {
        Self { row, col }
    }

    /// Convert to tuple.
    pub const fn as_tuple(&self) -> (usize, usize) {
        (self.row as usize, self.col as usize)
    }

    /// Distance to another position on an NxN torus.
    pub fn distance_to<const N: usize>(&self, other: &Self) -> usize {
        Tonnetz::<N>::distance(self.as_tuple(), other.as_tuple())
    }
}

/// Configuration for coherence validation (for pallet storage).
///
/// Defines the parameters for topological coherence checking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "substrate", derive(Encode, Decode, MaxEncodedLen, TypeInfo))]
pub struct CoherenceConfig {
    /// Grid size for Tonnetz topology
    pub grid_size: u8,
    /// Locality radius (scaled by 100 for fixed-point)
    pub radius_scaled: u16,
    /// Decay rate alpha (scaled by 100 for fixed-point)
    pub alpha_scaled: u16,
    /// Drift threshold for coherence violation
    pub drift_threshold: u8,
    /// Mask type to use
    pub mask_type: MaskType,
}

impl Default for CoherenceConfig {
    fn default() -> Self {
        Self {
            grid_size: 12,
            radius_scaled: 200,  // 2.0
            alpha_scaled: 100,   // 1.0
            drift_threshold: 2,
            mask_type: MaskType::Hybrid,
        }
    }
}

impl CoherenceConfig {
    /// Create a new configuration.
    pub const fn new(
        grid_size: u8,
        radius: f32,
        alpha: f32,
        drift_threshold: u8,
        mask_type: MaskType,
    ) -> Self {
        Self {
            grid_size,
            radius_scaled: (radius * 100.0) as u16,
            alpha_scaled: (alpha * 100.0) as u16,
            drift_threshold,
            mask_type,
        }
    }

    /// Get radius as f32.
    pub fn radius(&self) -> f32 {
        self.radius_scaled as f32 / 100.0
    }

    /// Get alpha as f32.
    pub fn alpha(&self) -> f32 {
        self.alpha_scaled as f32 / 100.0
    }

    /// Create a ToroidalMask from this config.
    pub fn to_mask(&self, seq_len: usize) -> ToroidalMask {
        ToroidalMask {
            seq_len,
            radius: self.radius(),
            alpha: self.alpha(),
            grid_size: self.grid_size as usize,
            mask_type: self.mask_type,
        }
    }
}

/// Result of coherence validation (for on-chain reporting).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "substrate", derive(Encode, Decode, MaxEncodedLen, TypeInfo))]
pub struct CoherenceResult {
    /// Number of transitions checked
    pub transitions: u32,
    /// Number of drift violations
    pub violations: u32,
    /// Whether coherence is within bounds
    pub is_coherent: bool,
}

impl CoherenceResult {
    /// Create from drift meter measurements.
    pub fn from_meter(meter: &DriftMeter, max_rate: f32) -> Self {
        let rate = meter.rate();
        Self {
            transitions: meter.count as u32,
            violations: meter.drifts as u32,
            is_coherent: rate <= max_rate,
        }
    }

    /// Drift rate (0.0 to 1.0).
    pub fn drift_rate(&self) -> f32 {
        if self.transitions == 0 {
            0.0
        } else {
            self.violations as f32 / self.transitions as f32
        }
    }
}

// =============================================================================
// Phase 4: Advanced Features
// =============================================================================

/// 3D Torus topology (T^3).
///
/// Higher-dimensional torus for richer semantic spaces.
/// Distance is L1 with wraparound in all three dimensions.
#[derive(Debug, Clone, Copy)]
pub struct Torus3D<const N: usize>;

impl<const N: usize> Torus3D<N> {
    /// Create a new 3D torus topology.
    pub const fn new() -> Self {
        Self
    }

    /// Total number of positions.
    pub const fn total_positions() -> usize {
        N * N * N
    }

    /// Convert linear index to 3D coordinates.
    #[inline]
    pub const fn to_coords(index: usize) -> (usize, usize, usize) {
        let z = index / (N * N);
        let rem = index % (N * N);
        let y = rem / N;
        let x = rem % N;
        (x, y, z)
    }

    /// Convert 3D coordinates to linear index.
    #[inline]
    pub const fn to_index(x: usize, y: usize, z: usize) -> usize {
        (z % N) * N * N + (y % N) * N + (x % N)
    }

    /// 3D toroidal distance (L1 with wraparound).
    #[inline]
    pub fn distance(a: (usize, usize, usize), b: (usize, usize, usize)) -> usize {
        let dx = a.0.abs_diff(b.0);
        let dy = a.1.abs_diff(b.1);
        let dz = a.2.abs_diff(b.2);

        let dx_wrap = if dx > N / 2 { N - dx } else { dx };
        let dy_wrap = if dy > N / 2 { N - dy } else { dy };
        let dz_wrap = if dz > N / 2 { N - dz } else { dz };

        dx_wrap + dy_wrap + dz_wrap
    }

    /// Spectral gap for 3D torus.
    pub fn spectral_gap() -> f32 {
        // For T^3, gap is same as T^2 for fixed N
        let pi = core::f32::consts::PI;
        2.0 - 2.0 * cosf(2.0 * pi / N as f32)
    }
}

impl<const N: usize> Default for Torus3D<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Multi-scale Tonnetz configuration.
///
/// Combines multiple grid sizes for hierarchical coherence.
#[derive(Debug, Clone)]
pub struct MultiScaleTonnetz {
    /// Grid sizes (e.g., [6, 12, 24])
    pub scales: [usize; 3],
    /// Weights for each scale
    pub weights: [f32; 3],
}

impl Default for MultiScaleTonnetz {
    fn default() -> Self {
        Self {
            scales: [6, 12, 24],
            weights: [0.5, 0.3, 0.2],
        }
    }
}

impl MultiScaleTonnetz {
    /// Create with custom scales and weights.
    pub fn new(scales: [usize; 3], weights: [f32; 3]) -> Self {
        Self { scales, weights }
    }

    /// Weighted multi-scale distance.
    pub fn distance(&self, a: (usize, usize), b: (usize, usize)) -> f32 {
        let mut total = 0.0;
        for (i, &scale) in self.scales.iter().enumerate() {
            let d = Self::distance_at_scale(a, b, scale) as f32;
            total += self.weights[i] * d;
        }
        total
    }

    fn distance_at_scale(a: (usize, usize), b: (usize, usize), n: usize) -> usize {
        // Map positions to scale
        let a_scaled = (a.0 % n, a.1 % n);
        let b_scaled = (b.0 % n, b.1 % n);

        let dx = a_scaled.0.abs_diff(b_scaled.0);
        let dy = a_scaled.1.abs_diff(b_scaled.1);

        let dx_wrap = if dx > n / 2 { n - dx } else { dx };
        let dy_wrap = if dy > n / 2 { n - dy } else { dy };

        dx_wrap + dy_wrap
    }
}

/// Learned toroidal projection parameters.
///
/// Implements φ_θ(e) = (σ(W₁e) mod 1, σ(W₂e) mod 1)
/// where σ is sigmoid and e is an embedding vector.
///
/// Note: Only available with `std` feature due to Vec usage.
#[cfg(feature = "std")]
#[derive(Debug, Clone)]
pub struct LearnedProjection {
    /// Input dimension
    pub input_dim: usize,
    /// Grid size for output
    pub grid_size: usize,
    /// Weight matrix W1 (flattened, grid_size elements)
    pub w1: Vec<f32>,
    /// Weight matrix W2 (flattened, grid_size elements)
    pub w2: Vec<f32>,
}

#[cfg(feature = "std")]
impl LearnedProjection {
    /// Create a new projection with random initialization.
    pub fn new(input_dim: usize, grid_size: usize) -> Self {
        // Initialize with small random values (placeholder - use proper RNG in practice)
        let scale = 1.0 / (input_dim as f32).sqrt();
        let w1 = (0..input_dim).map(|i| ((i * 7) % 100) as f32 * scale / 100.0 - scale / 2.0).collect();
        let w2 = (0..input_dim).map(|i| ((i * 13) % 100) as f32 * scale / 100.0 - scale / 2.0).collect();
        Self { input_dim, grid_size, w1, w2 }
    }

    /// Sigmoid function.
    fn sigmoid(x: f32) -> f32 {
        1.0 / (1.0 + expf(-x))
    }

    /// Project embedding to torus position.
    ///
    /// φ_θ(e) = (σ(W₁·e) mod 1, σ(W₂·e) mod 1) * grid_size
    pub fn project(&self, embedding: &[f32]) -> (usize, usize) {
        assert_eq!(embedding.len(), self.input_dim);

        // Compute W1 · e
        let dot1: f32 = self.w1.iter().zip(embedding.iter()).map(|(w, e)| w * e).sum();
        let x = Self::sigmoid(dot1);

        // Compute W2 · e
        let dot2: f32 = self.w2.iter().zip(embedding.iter()).map(|(w, e)| w * e).sum();
        let y = Self::sigmoid(dot2);

        // Map to grid
        let row = ((x * self.grid_size as f32) as usize) % self.grid_size;
        let col = ((y * self.grid_size as f32) as usize) % self.grid_size;

        (row, col)
    }
}

/// Adjacency loss computation.
///
/// L_topo = E[(a,b)~co-occur][d_T(φ(a), φ(b))] - λ · E[(a,c)~random][d_T(φ(a), φ(c))]
///
/// Co-occurring pairs should be close; random pairs should be far.
#[derive(Debug, Clone)]
pub struct AdjacencyLoss<const N: usize> {
    /// Regularization weight for negative samples
    pub lambda: f32,
    /// Accumulated positive pair distances
    positive_sum: f32,
    positive_count: usize,
    /// Accumulated negative pair distances
    negative_sum: f32,
    negative_count: usize,
}

impl<const N: usize> AdjacencyLoss<N> {
    /// Create a new adjacency loss tracker.
    pub fn new(lambda: f32) -> Self {
        Self {
            lambda,
            positive_sum: 0.0,
            positive_count: 0,
            negative_sum: 0.0,
            negative_count: 0,
        }
    }

    /// Record a positive (co-occurring) pair.
    pub fn record_positive(&mut self, a: (usize, usize), b: (usize, usize)) {
        let d = Tonnetz::<N>::distance(a, b) as f32;
        self.positive_sum += d;
        self.positive_count += 1;
    }

    /// Record a negative (random) pair.
    pub fn record_negative(&mut self, a: (usize, usize), c: (usize, usize)) {
        let d = Tonnetz::<N>::distance(a, c) as f32;
        self.negative_sum += d;
        self.negative_count += 1;
    }

    /// Compute the loss.
    ///
    /// Lower is better: positive pairs close, negative pairs far.
    pub fn loss(&self) -> f32 {
        let pos_mean = if self.positive_count > 0 {
            self.positive_sum / self.positive_count as f32
        } else {
            0.0
        };

        let neg_mean = if self.negative_count > 0 {
            self.negative_sum / self.negative_count as f32
        } else {
            0.0
        };

        pos_mean - self.lambda * neg_mean
    }

    /// Reset accumulators.
    pub fn reset(&mut self) {
        self.positive_sum = 0.0;
        self.positive_count = 0;
        self.negative_sum = 0.0;
        self.negative_count = 0;
    }
}

/// Sparse mask in CSR (Compressed Sparse Row) format.
///
/// Efficient storage for sparse attention masks.
#[cfg(feature = "std")]
#[derive(Debug, Clone)]
pub struct SparseMask {
    /// Number of rows/columns
    pub size: usize,
    /// Row pointers (size + 1 elements)
    pub row_ptr: Vec<usize>,
    /// Column indices
    pub col_idx: Vec<usize>,
    /// Non-zero values
    pub values: Vec<f32>,
}

#[cfg(feature = "std")]
impl SparseMask {
    /// Create from dense mask, keeping values above threshold.
    pub fn from_dense(dense: &[Vec<f32>], threshold: f32) -> Self {
        let size = dense.len();
        let mut row_ptr = vec![0];
        let mut col_idx = Vec::new();
        let mut values = Vec::new();

        for row in dense {
            for (j, &val) in row.iter().enumerate() {
                if val > threshold {
                    col_idx.push(j);
                    values.push(val);
                }
            }
            row_ptr.push(col_idx.len());
        }

        Self { size, row_ptr, col_idx, values }
    }

    /// Create from ToroidalMask with threshold.
    pub fn from_toroidal(mask: &ToroidalMask, threshold: f32) -> Self {
        let dense = mask.generate();
        Self::from_dense(&dense, threshold)
    }

    /// Number of non-zero elements.
    pub fn nnz(&self) -> usize {
        self.values.len()
    }

    /// Sparsity ratio (1.0 = fully sparse, 0.0 = fully dense).
    pub fn sparsity(&self) -> f32 {
        let total = self.size * self.size;
        if total == 0 {
            0.0
        } else {
            1.0 - (self.nnz() as f32 / total as f32)
        }
    }

    /// Get value at (i, j), or 0 if not stored.
    pub fn get(&self, i: usize, j: usize) -> f32 {
        if i >= self.size {
            return 0.0;
        }

        let start = self.row_ptr[i];
        let end = self.row_ptr[i + 1];

        for k in start..end {
            if self.col_idx[k] == j {
                return self.values[k];
            }
        }

        0.0
    }

    /// Memory usage in bytes (approximate).
    pub fn memory_bytes(&self) -> usize {
        self.row_ptr.len() * 8 + self.col_idx.len() * 8 + self.values.len() * 4
    }
}

// =============================================================================
// Phase 5: Grounding Projector — Orthogonal Evidence Projection
// =============================================================================
//
// Implements G = A(AᵀA)⁻¹Aᵀ where:
//   A = evidence embedding matrix (m evidence vectors of dim n)
//   G = orthogonal projector onto col(A)
//
// For any LLM output vector x:
//   x_grounded    = G·x   (component supported by evidence)
//   x_hallucinated = (I - G)·x  (component orthogonal to evidence)
//
// Hallucination magnitude = ‖(I - G)·x‖ / ‖x‖
//
// Patent pending — Paraxiom Technologies Inc.

/// Orthogonal grounding projector G = A(AᵀA)⁻¹Aᵀ.
///
/// Projects LLM output vectors onto the subspace spanned by evidence embeddings.
/// The residual (I - G)x is the hallucination component.
#[cfg(feature = "std")]
#[derive(Debug, Clone)]
pub struct GroundingProjector {
    /// Dimension of embedding space
    dim: usize,
    /// Number of evidence vectors
    rank: usize,
    /// Precomputed projection matrix G (dim × dim, row-major)
    matrix: Vec<f32>,
}

#[cfg(feature = "std")]
impl GroundingProjector {
    /// Build a grounding projector from evidence embeddings.
    ///
    /// `evidence` is a slice of embedding vectors, each of length `dim`.
    /// Returns `None` if evidence is empty or AᵀA is singular.
    pub fn from_evidence(evidence: &[&[f32]], dim: usize) -> Option<Self> {
        let m = evidence.len();
        if m == 0 || dim == 0 {
            return None;
        }

        // Validate all evidence vectors have correct dimension
        for v in evidence {
            if v.len() != dim {
                return None;
            }
        }

        // Compute AᵀA (m × m)
        let mut ata = vec![0.0f32; m * m];
        for i in 0..m {
            for j in i..m {
                let dot: f32 = evidence[i]
                    .iter()
                    .zip(evidence[j].iter())
                    .map(|(a, b)| a * b)
                    .sum();
                ata[i * m + j] = dot;
                ata[j * m + i] = dot;
            }
        }

        // Invert AᵀA via Gauss-Jordan elimination
        let ata_inv = invert_matrix(&ata, m)?;

        // Compute G = A(AᵀA)⁻¹Aᵀ  (dim × dim)
        //
        // First: B = (AᵀA)⁻¹Aᵀ  (m × dim)
        // Then:  G = A · B       (dim × dim)
        //
        // A is dim × m (columns are evidence vectors)
        // Aᵀ is m × dim

        // B = (AᵀA)⁻¹ · Aᵀ  →  B[i][k] = Σ_j ata_inv[i][j] * A[k][j]
        //                                 = Σ_j ata_inv[i][j] * evidence[j][k]
        let mut b = vec![0.0f32; m * dim];
        for i in 0..m {
            for k in 0..dim {
                let mut sum = 0.0f32;
                for j in 0..m {
                    sum += ata_inv[i * m + j] * evidence[j][k];
                }
                b[i * dim + k] = sum;
            }
        }

        // G = A · B  →  G[p][q] = Σ_i A[p][i] * B[i][q]
        //                        = Σ_i evidence[i][p] * B[i][q]
        let mut g = vec![0.0f32; dim * dim];
        for p in 0..dim {
            for q in 0..dim {
                let mut sum = 0.0f32;
                for i in 0..m {
                    sum += evidence[i][p] * b[i * dim + q];
                }
                g[p * dim + q] = sum;
            }
        }

        Some(Self {
            dim,
            rank: m,
            matrix: g,
        })
    }

    /// Project vector onto evidence subspace (grounded component).
    ///
    /// Returns G·x — the part of x supported by evidence.
    pub fn project_grounded(&self, x: &[f32]) -> Vec<f32> {
        assert_eq!(x.len(), self.dim);
        let mut result = vec![0.0f32; self.dim];
        for i in 0..self.dim {
            let mut sum = 0.0f32;
            for j in 0..self.dim {
                sum += self.matrix[i * self.dim + j] * x[j];
            }
            result[i] = sum;
        }
        result
    }

    /// Project vector onto hallucination subspace.
    ///
    /// Returns (I - G)·x — the part of x not supported by evidence.
    pub fn project_hallucinated(&self, x: &[f32]) -> Vec<f32> {
        let grounded = self.project_grounded(x);
        x.iter()
            .zip(grounded.iter())
            .map(|(xi, gi)| xi - gi)
            .collect()
    }

    /// Compute hallucination score for a vector.
    ///
    /// Returns ‖(I - G)·x‖ / ‖x‖ ∈ [0, 1].
    /// 0 = fully grounded, 1 = fully hallucinated.
    pub fn hallucination_score(&self, x: &[f32]) -> f32 {
        let x_norm_sq: f32 = x.iter().map(|v| v * v).sum();
        if x_norm_sq < 1e-12 {
            return 0.0;
        }

        let hallucinated = self.project_hallucinated(x);
        let h_norm_sq: f32 = hallucinated.iter().map(|v| v * v).sum();

        libm::sqrtf(h_norm_sq / x_norm_sq)
    }

    /// Decompose a vector into grounded and hallucinated components with scores.
    pub fn decompose(&self, x: &[f32]) -> GroundingDecomposition {
        let grounded = self.project_grounded(x);
        let hallucinated: Vec<f32> = x
            .iter()
            .zip(grounded.iter())
            .map(|(xi, gi)| xi - gi)
            .collect();

        let x_norm = libm::sqrtf(x.iter().map(|v| v * v).sum());
        let g_norm = libm::sqrtf(grounded.iter().map(|v| v * v).sum());
        let h_norm = libm::sqrtf(hallucinated.iter().map(|v| v * v).sum());

        GroundingDecomposition {
            grounded,
            hallucinated,
            grounding_ratio: if x_norm > 1e-12 { g_norm / x_norm } else { 0.0 },
            hallucination_ratio: if x_norm > 1e-12 { h_norm / x_norm } else { 0.0 },
        }
    }

    /// Dimension of the embedding space.
    pub fn dim(&self) -> usize {
        self.dim
    }

    /// Rank of the evidence subspace.
    pub fn rank(&self) -> usize {
        self.rank
    }

    /// Verify G² ≈ G (idempotent — defining property of projection).
    pub fn verify_idempotent(&self, tolerance: f32) -> bool {
        // Compute G² and check ‖G² - G‖_max < tolerance
        for i in 0..self.dim {
            for j in 0..self.dim {
                let mut g2_ij = 0.0f32;
                for k in 0..self.dim {
                    g2_ij += self.matrix[i * self.dim + k] * self.matrix[k * self.dim + j];
                }
                if fabsf(g2_ij - self.matrix[i * self.dim + j]) > tolerance {
                    return false;
                }
            }
        }
        true
    }

    /// Verify Gᵀ = G (symmetric — orthogonal projection).
    pub fn verify_symmetric(&self, tolerance: f32) -> bool {
        for i in 0..self.dim {
            for j in (i + 1)..self.dim {
                if fabsf(
                    self.matrix[i * self.dim + j] - self.matrix[j * self.dim + i],
                ) > tolerance
                {
                    return false;
                }
            }
        }
        true
    }
}

/// Result of decomposing a vector into grounded and hallucinated components.
#[cfg(feature = "std")]
#[derive(Debug, Clone)]
pub struct GroundingDecomposition {
    /// Component supported by evidence (G·x)
    pub grounded: Vec<f32>,
    /// Component orthogonal to evidence ((I-G)·x)
    pub hallucinated: Vec<f32>,
    /// ‖G·x‖ / ‖x‖  — fraction of signal grounded in evidence
    pub grounding_ratio: f32,
    /// ‖(I-G)·x‖ / ‖x‖  — fraction of signal that is hallucination
    pub hallucination_ratio: f32,
}

/// Invert a square matrix using Gauss-Jordan elimination.
/// Returns None if matrix is singular (det ≈ 0).
#[cfg(feature = "std")]
fn invert_matrix(mat: &[f32], n: usize) -> Option<Vec<f32>> {
    // Augmented matrix [A | I]
    let mut aug = vec![0.0f32; n * 2 * n];
    for i in 0..n {
        for j in 0..n {
            aug[i * 2 * n + j] = mat[i * n + j];
        }
        aug[i * 2 * n + n + i] = 1.0;
    }

    for col in 0..n {
        // Partial pivoting
        let mut max_val = fabsf(aug[col * 2 * n + col]);
        let mut max_row = col;
        for row in (col + 1)..n {
            let val = fabsf(aug[row * 2 * n + col]);
            if val > max_val {
                max_val = val;
                max_row = row;
            }
        }

        if max_val < 1e-10 {
            return None; // Singular
        }

        // Swap rows
        if max_row != col {
            for k in 0..(2 * n) {
                let tmp = aug[col * 2 * n + k];
                aug[col * 2 * n + k] = aug[max_row * 2 * n + k];
                aug[max_row * 2 * n + k] = tmp;
            }
        }

        // Scale pivot row
        let pivot = aug[col * 2 * n + col];
        for k in 0..(2 * n) {
            aug[col * 2 * n + k] /= pivot;
        }

        // Eliminate column
        for row in 0..n {
            if row == col {
                continue;
            }
            let factor = aug[row * 2 * n + col];
            for k in 0..(2 * n) {
                aug[row * 2 * n + k] -= factor * aug[col * 2 * n + k];
            }
        }
    }

    // Extract inverse
    let mut inv = vec![0.0f32; n * n];
    for i in 0..n {
        for j in 0..n {
            inv[i * n + j] = aug[i * 2 * n + n + j];
        }
    }

    Some(inv)
}

// =============================================================================
// Phase 6: Karmonic Spectral Filter — Training-Time Regularization
// =============================================================================
//
// Implements the Karmonic spectral filter from Theorem 12.1:
//   Low-frequency toroidal modes (global coherence) are PRESERVED;
//   high-frequency modes (noise) are ATTENUATED toward uniformity.
//
// The filter weight for Fourier mode n on an N-cycle graph:
//   λ_n = 2 - 2·cos(2πn/N)     (nth eigenvalue of cycle Laplacian)
//   w(n) = (λ_n - λ_1) / (λ_max - λ_1)
//
// Mode 1: w ≈ 0.000 → preserve (class discrimination)
// Mode 2: w ≈ 0.196 → mild regularization
// Mode 3: w ≈ 0.464 → moderate
// Mode 4+: w > 0.73 → strong (enforce torus coverage)
//
// This is the TRAINING-TIME primitive that works (+1.3pp MC1, +4.4pp MC2),
// unlike inference-time logit bias which was shown null (March 2026).
//
// Reference: Karmonic LLM (DOI: 10.5281/zenodo.18746144)

/// Karmonic spectral filter for training-time regularization.
///
/// Computes mode-dependent weights from the cycle graph Laplacian eigenvalues.
/// Low-frequency modes (semantically meaningful) get low weight (preserved);
/// high-frequency modes (noise) get high weight (regularized toward uniformity).
///
/// # Example
///
/// ```rust
/// use topological_coherence::KarmonicFilter;
///
/// let filter = KarmonicFilter::new(12, 6);
/// assert_eq!(filter.n_modes(), 6);
///
/// // Mode 1 has zero weight (preserved)
/// assert!(filter.weight(0) < 0.001);
///
/// // Higher modes have increasing weight
/// assert!(filter.weight(1) < filter.weight(2));
/// assert!(filter.weight(2) < filter.weight(3));
///
/// // Compute regularization loss for a batch of embeddings
/// // Expected dim = 2 * torus_dim * n_modes = 2 * 1 * 6 = 12
/// let embeddings = vec![
///     vec![1.0, 0.0, 0.5, 0.5, -0.3, 0.2, 0.1, -0.1, 0.4, 0.3, -0.2, 0.1],
///     vec![0.0, 1.0, 0.4, 0.6, -0.1, 0.3, 0.2, -0.2, 0.3, 0.4, -0.1, 0.2],
///     vec![0.5, 0.5, 0.3, 0.7, -0.2, 0.1, 0.3, -0.3, 0.2, 0.5, -0.3, 0.3],
/// ];
/// let loss = filter.uniformity_loss(&embeddings, 1, 2.0);
/// // Loss is finite and non-negative for well-formed input
/// ```
#[derive(Debug, Clone)]
pub struct KarmonicFilter {
    /// Grid size N for the cycle graph
    grid_size: usize,
    /// Number of Fourier modes
    n_modes: usize,
    /// Precomputed eigenvalues λ_n = 2 - 2·cos(2πn/N)
    eigenvalues: Vec<f32>,
    /// Normalized weights w(n) ∈ [0, 1]
    weights: Vec<f32>,
}

impl KarmonicFilter {
    /// Create a new Karmonic filter.
    ///
    /// # Arguments
    /// * `grid_size` - Torus grid size N (typically 12)
    /// * `n_modes` - Number of Fourier modes (typically 6)
    pub fn new(grid_size: usize, n_modes: usize) -> Self {
        assert!(grid_size >= 2, "grid_size must be >= 2");
        assert!(n_modes >= 1, "n_modes must be >= 1");

        // Clamp to Nyquist limit: eigenvalues of cycle graph C_N are symmetric
        // around N/2, so modes beyond N/2 are redundant (same eigenvalues mirrored).
        let n_modes = core::cmp::min(n_modes, grid_size / 2);
        let n_modes = core::cmp::max(n_modes, 1); // ensure at least 1 mode

        let pi = core::f32::consts::PI;

        let eigenvalues: Vec<f32> = (1..=n_modes)
            .map(|n| 2.0 - 2.0 * cosf(2.0 * pi * n as f32 / grid_size as f32))
            .collect();

        let lam_1 = eigenvalues[0];
        let lam_max = eigenvalues.iter().copied().fold(f32::NEG_INFINITY, f32::max);

        let weights = if (lam_max - lam_1).abs() < 1e-10 {
            vec![0.0; n_modes]
        } else {
            eigenvalues
                .iter()
                .map(|&lam| (lam - lam_1) / (lam_max - lam_1))
                .collect()
        };

        Self {
            grid_size,
            n_modes,
            eigenvalues,
            weights,
        }
    }

    /// Number of Fourier modes.
    pub fn n_modes(&self) -> usize {
        self.n_modes
    }

    /// Grid size.
    pub fn grid_size(&self) -> usize {
        self.grid_size
    }

    /// Get the eigenvalue for mode `idx` (0-indexed).
    pub fn eigenvalue(&self, idx: usize) -> f32 {
        self.eigenvalues[idx]
    }

    /// Get the normalized weight for mode `idx` (0-indexed).
    ///
    /// Returns 0.0 for mode 0 (preserve), approaching 1.0 for high modes (regularize).
    pub fn weight(&self, idx: usize) -> f32 {
        self.weights[idx]
    }

    /// Get all weights as a slice.
    pub fn weights(&self) -> &[f32] {
        &self.weights
    }

    /// Get all eigenvalues as a slice.
    pub fn eigenvalues(&self) -> &[f32] {
        &self.eigenvalues
    }

    /// Compute mode-weighted uniformity loss for a batch of Fourier embeddings.
    ///
    /// This is the core Karmonic regularization term to add to a training loss.
    ///
    /// # Arguments
    /// * `fourier_embeddings` - Batch of Fourier coordinates, each of length `2 * torus_dim * n_modes`
    ///   grouped by mode: `[mode_1_all_circles | mode_2_all_circles | ...]`
    /// * `torus_dim` - Number of torus circles (k), typically 2
    /// * `temperature` - Wang-Isola uniformity temperature (typically 2.0)
    ///
    /// # Returns
    /// Weighted uniformity loss (scalar). Lower = more uniform on high-freq modes.
    #[cfg(feature = "std")]
    pub fn uniformity_loss(
        &self,
        fourier_embeddings: &[Vec<f32>],
        torus_dim: usize,
        temperature: f32,
    ) -> f32 {
        let batch_size = fourier_embeddings.len();
        if batch_size < 2 {
            return 0.0;
        }

        let expected_dim = 2 * torus_dim * self.n_modes;
        let slice_size = 2 * torus_dim; // 2k dims per mode

        let mut total = 0.0f32;

        for n in 0..self.n_modes {
            let start = slice_size * n;
            let end = start + slice_size;

            // Compute pairwise squared distances for this mode
            let mut log_sum_total = 0.0f32;

            for i in 0..batch_size {
                assert!(
                    fourier_embeddings[i].len() >= expected_dim,
                    "embedding dim {} < expected {}", fourier_embeddings[i].len(), expected_dim
                );

                let mut neg_dists: Vec<f32> = Vec::with_capacity(batch_size - 1);

                for j in 0..batch_size {
                    if i == j {
                        continue;
                    }

                    // Squared L2 distance for this mode slice
                    let sq_dist: f32 = (start..end)
                        .map(|d| {
                            let diff = fourier_embeddings[i][d] - fourier_embeddings[j][d];
                            diff * diff
                        })
                        .sum();

                    neg_dists.push(-temperature * sq_dist);
                }

                // log-sum-exp for numerical stability
                let max_val = neg_dists.iter().copied().fold(f32::NEG_INFINITY, f32::max);
                let lse: f32 = max_val
                    + neg_dists
                        .iter()
                        .map(|&x| expf(x - max_val))
                        .sum::<f32>()
                        .ln();

                let log_b_minus_1 = ((batch_size - 1) as f32).ln();
                log_sum_total += lse - log_b_minus_1;
            }

            let unif_n = log_sum_total / batch_size as f32;
            total += self.weights[n] * unif_n;
        }

        total
    }

    /// Compute circular spread loss (decorrelation across torus dimensions).
    ///
    /// Penalizes correlation between angles on different circles,
    /// encouraging independent coverage of each torus dimension.
    ///
    /// # Arguments
    /// * `angles` - Batch of raw angles in `[0, 2π)`, each of length `torus_dim`
    ///
    /// # Returns
    /// Mean squared circular correlation across all circle pairs.
    #[cfg(feature = "std")]
    pub fn spread_loss(&self, angles: &[Vec<f32>]) -> f32 {
        if angles.is_empty() || angles[0].len() < 2 {
            return 0.0;
        }

        let batch_size = angles.len();
        let k = angles[0].len(); // torus_dim

        let mut total_corr = 0.0f32;
        let mut n_pairs = 0;

        for i in 0..k {
            for j in (i + 1)..k {
                // Mean angle (circular mean)
                let sin_mean_i: f32 = angles.iter().map(|a| libm::sinf(a[i])).sum::<f32>() / batch_size as f32;
                let cos_mean_i: f32 = angles.iter().map(|a| cosf(a[i])).sum::<f32>() / batch_size as f32;
                let mu_i = libm::atan2f(sin_mean_i, cos_mean_i);

                let sin_mean_j: f32 = angles.iter().map(|a| libm::sinf(a[j])).sum::<f32>() / batch_size as f32;
                let cos_mean_j: f32 = angles.iter().map(|a| cosf(a[j])).sum::<f32>() / batch_size as f32;
                let mu_j = libm::atan2f(sin_mean_j, cos_mean_j);

                // Circular correlation
                let mut num = 0.0f32;
                let mut den_i = 0.0f32;
                let mut den_j = 0.0f32;

                for a in angles.iter() {
                    let s_i = libm::sinf(a[i] - mu_i);
                    let s_j = libm::sinf(a[j] - mu_j);
                    num += s_i * s_j;
                    den_i += s_i * s_i;
                    den_j += s_j * s_j;
                }

                num /= batch_size as f32;
                den_i /= batch_size as f32;
                den_j /= batch_size as f32;

                let den = libm::sqrtf(den_i * den_j + 1e-8);
                let corr = num / den;
                total_corr += corr * corr;
                n_pairs += 1;
            }
        }

        if n_pairs > 0 {
            total_corr / n_pairs as f32
        } else {
            0.0
        }
    }
}

/// Fourier torus projection: map angles to Fourier coordinates.
///
/// For each angle θ and mode n, computes (cos(nθ), sin(nθ)).
/// Output grouped by mode: `[mode_1 | mode_2 | ... | mode_m]`.
///
/// # Arguments
/// * `angles` - Raw angles in `[0, 2π)` of length `torus_dim`
/// * `n_modes` - Number of Fourier modes
///
/// # Returns
/// Fourier embedding of length `2 * torus_dim * n_modes`
pub fn fourier_expand(angles: &[f32], n_modes: usize) -> Vec<f32> {
    let k = angles.len();
    let mut result = Vec::with_capacity(2 * k * n_modes);

    for n in 1..=n_modes {
        for &theta in angles {
            let n_theta = n as f32 * theta;
            result.push(cosf(n_theta));
            result.push(libm::sinf(n_theta));
        }
    }

    result
}

/// Angles to torus position: quantize continuous angles to grid coordinates.
///
/// # Arguments
/// * `angles` - Raw angles in `[0, 2π)` of length `torus_dim`
/// * `grid_size` - Grid size N
///
/// # Returns
/// Grid coordinates (one per angle)
pub fn angles_to_grid(angles: &[f32], grid_size: usize) -> Vec<usize> {
    let pi = core::f32::consts::PI;
    angles
        .iter()
        .map(|&theta| {
            let normalized = theta / (2.0 * pi); // [0, 1)
            let coord = (normalized * grid_size as f32) as usize;
            coord % grid_size
        })
        .collect()
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // -------------------------------------------------------------------------
    // Basic Distance Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_tonnetz_distance_self() {
        let d = Tonnetz::<12>::distance((5, 5), (5, 5));
        assert_eq!(d, 0);
    }

    #[test]
    fn test_tonnetz_distance_adjacent() {
        let d = Tonnetz::<12>::distance((0, 0), (0, 1));
        assert_eq!(d, 1);
    }

    #[test]
    fn test_tonnetz_distance_wraparound() {
        // On a 12x12 torus, (0,0) to (0,11) should wrap to distance 1
        let d = Tonnetz::<12>::distance((0, 0), (0, 11));
        assert_eq!(d, 1);
    }

    #[test]
    fn test_tonnetz_distance_diagonal_wrap() {
        // (0,0) to (11,11) wraps both dimensions
        let d = Tonnetz::<12>::distance((0, 0), (11, 11));
        assert_eq!(d, 2); // 1 + 1 after wrapping
    }

    // -------------------------------------------------------------------------
    // Property Tests: Metric Space Axioms
    // -------------------------------------------------------------------------

    #[test]
    fn test_distance_symmetry() {
        // d(a, b) = d(b, a) for all points
        for i in 0..12 {
            for j in 0..12 {
                for k in 0..12 {
                    for l in 0..12 {
                        let d1 = Tonnetz::<12>::distance((i, j), (k, l));
                        let d2 = Tonnetz::<12>::distance((k, l), (i, j));
                        assert_eq!(d1, d2, "Symmetry violated at ({},{}) <-> ({},{})", i, j, k, l);
                    }
                }
            }
        }
    }

    #[test]
    fn test_distance_identity() {
        // d(a, a) = 0 for all points
        for i in 0..12 {
            for j in 0..12 {
                let d = Tonnetz::<12>::distance((i, j), (i, j));
                assert_eq!(d, 0, "Identity violated at ({},{})", i, j);
            }
        }
    }

    #[test]
    fn test_triangle_inequality() {
        // d(a, c) <= d(a, b) + d(b, c) for all points
        // Test a sample of points (full test is O(n^6))
        let points = [(0, 0), (3, 5), (7, 2), (11, 11), (6, 6), (1, 10)];
        for &a in &points {
            for &b in &points {
                for &c in &points {
                    let d_ac = Tonnetz::<12>::distance(a, c);
                    let d_ab = Tonnetz::<12>::distance(a, b);
                    let d_bc = Tonnetz::<12>::distance(b, c);
                    assert!(
                        d_ac <= d_ab + d_bc,
                        "Triangle inequality violated: d({:?},{:?})={} > d({:?},{:?})={} + d({:?},{:?})={}",
                        a, c, d_ac, a, b, d_ab, b, c, d_bc
                    );
                }
            }
        }
    }

    #[test]
    fn test_distance_non_negative() {
        // d(a, b) >= 0 for all points
        for i in 0..12 {
            for j in 0..12 {
                for k in 0..12 {
                    for l in 0..12 {
                        let d = Tonnetz::<12>::distance((i, j), (k, l));
                        // usize is always >= 0, but verify the computation doesn't overflow
                        assert!(d <= 12, "Distance too large at ({},{}) <-> ({},{}): {}", i, j, k, l, d);
                    }
                }
            }
        }
    }

    #[test]
    fn test_max_distance_bounded() {
        // On a 12x12 torus, max L1 distance is 6+6=12 (half grid in each dim)
        let mut max_dist = 0;
        for i in 0..12 {
            for j in 0..12 {
                let d = Tonnetz::<12>::distance((0, 0), (i, j));
                if d > max_dist {
                    max_dist = d;
                }
            }
        }
        assert_eq!(max_dist, 12, "Max distance should be 12 (6+6)");
    }

    // -------------------------------------------------------------------------
    // Spectral Gap Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_spectral_gap_positive() {
        let gap = Tonnetz::<12>::spectral_gap();
        assert!(gap > 0.0);
        assert!(gap < 1.0); // For N=12, gap ≈ 0.268
    }

    #[test]
    fn test_spectral_gap_scales_with_n() {
        // Smaller N -> larger gap (more connected)
        let gap_6 = Tonnetz::<6>::spectral_gap();
        let gap_12 = Tonnetz::<12>::spectral_gap();
        let gap_24 = Tonnetz::<24>::spectral_gap();
        assert!(gap_6 > gap_12, "Gap should decrease with N");
        assert!(gap_12 > gap_24, "Gap should decrease with N");
    }

    // -------------------------------------------------------------------------
    // Mask Type Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_toroidal_mask_self() {
        let mask = ToroidalMask::new(64, 2.0, 1.0);
        assert_eq!(mask.value(0, 0), 1.0);
    }

    #[test]
    fn test_toroidal_mask_decay() {
        let mask = ToroidalMask::new(64, 1.0, 1.0);
        let v_near = mask.value(0, 1);
        let v_far = mask.value(0, 5);
        assert!(v_near >= v_far);
    }

    #[test]
    fn test_hard_cutoff_mask() {
        let mask = ToroidalMask::hard_cutoff(64, 2.0, 12);
        // Within radius -> 1.0
        assert_eq!(mask.value(0, 0), 1.0);
        assert_eq!(mask.value(0, 1), 1.0);
        // Outside radius -> 0.0
        assert_eq!(mask.value(0, 36), 0.0); // distance 6
    }

    #[test]
    fn test_soft_exponential_mask() {
        let mask = ToroidalMask::soft_exponential(64, 1.0, 12);
        // Self -> exp(0) = 1.0
        assert!((mask.value(0, 0) - 1.0).abs() < 1e-6);
        // Distance 1 -> exp(-1) ≈ 0.368
        let v1 = mask.value(0, 1);
        assert!((v1 - 0.368).abs() < 0.01);
    }

    #[test]
    fn test_hybrid_mask() {
        let mask = ToroidalMask::new(64, 2.0, 1.0);
        // Within radius -> 1.0
        assert_eq!(mask.value(0, 0), 1.0);
        assert_eq!(mask.value(0, 1), 1.0);
        // Just outside radius -> exp(-α*(d-r)) = exp(-1*(3-2)) = exp(-1)
        // Need to find a point at distance 3
    }

    // -------------------------------------------------------------------------
    // Sinkhorn-Knopp Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_sinkhorn_knopp_doubly_stochastic() {
        let mask = ToroidalMask::new(16, 2.0, 0.5);
        let ds = mask.generate_doubly_stochastic(50);
        assert!(
            is_doubly_stochastic(&ds, 0.01),
            "Sinkhorn-Knopp should produce doubly-stochastic matrix"
        );
    }

    #[test]
    fn test_sinkhorn_preserves_structure() {
        // After Sinkhorn-Knopp, nearby positions should still have higher values
        let mask = ToroidalMask::new(16, 2.0, 0.5);
        let ds = mask.generate_doubly_stochastic(50);
        // Diagonal (self-attention) should be relatively high
        let diag_avg: f32 = (0..16).map(|i| ds[i][i]).sum::<f32>() / 16.0;
        let total_avg: f32 = ds.iter().flat_map(|r| r.iter()).sum::<f32>() / 256.0;
        assert!(
            diag_avg > total_avg,
            "Diagonal should be above average after Sinkhorn"
        );
    }

    // -------------------------------------------------------------------------
    // Drift Meter Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_drift_meter() {
        let mut meter = DriftMeter::new(2);
        meter.record::<12>(0, 1);  // distance 1, not drift
        meter.record::<12>(0, 6);  // distance 6, drift
        meter.record::<12>(0, 0);  // distance 0, not drift

        assert_eq!(meter.count, 3);
        assert_eq!(meter.drifts, 1);
        assert!((meter.rate() - 0.333).abs() < 0.01);
    }

    #[test]
    fn test_drift_meter_reset() {
        let mut meter = DriftMeter::new(2);
        meter.record::<12>(0, 6);
        meter.reset();
        assert_eq!(meter.count, 0);
        assert_eq!(meter.drifts, 0);
        assert_eq!(meter.rate(), 0.0);
    }

    // -------------------------------------------------------------------------
    // Coordinate Conversion Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_coord_conversion_roundtrip() {
        for idx in 0..144 {
            let coords = Tonnetz::<12>::to_coords(idx);
            let back = Tonnetz::<12>::to_index(coords.0, coords.1);
            assert_eq!(idx, back, "Roundtrip failed for index {}", idx);
        }
    }

    // -------------------------------------------------------------------------
    // Substrate Integration Type Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_toroidal_position() {
        let pos = ToroidalPosition::new(5, 7);
        assert_eq!(pos.as_tuple(), (5, 7));
    }

    #[test]
    fn test_toroidal_position_distance() {
        let a = ToroidalPosition::new(0, 0);
        let b = ToroidalPosition::new(5, 7);
        let dist = a.distance_to::<12>(&b);
        assert_eq!(dist, Tonnetz::<12>::distance((0, 0), (5, 7)));
    }

    #[test]
    fn test_coherence_config_default() {
        let config = CoherenceConfig::default();
        assert_eq!(config.grid_size, 12);
        assert!((config.radius() - 2.0).abs() < 0.01);
        assert!((config.alpha() - 1.0).abs() < 0.01);
        assert_eq!(config.drift_threshold, 2);
        assert_eq!(config.mask_type, MaskType::Hybrid);
    }

    #[test]
    fn test_coherence_config_to_mask() {
        let config = CoherenceConfig::default();
        let mask = config.to_mask(64);
        assert_eq!(mask.seq_len, 64);
        assert_eq!(mask.grid_size, 12);
        assert_eq!(mask.mask_type, MaskType::Hybrid);
    }

    #[test]
    fn test_coherence_result_from_meter() {
        let mut meter = DriftMeter::new(2);
        meter.record::<12>(0, 1);
        meter.record::<12>(0, 6);
        meter.record::<12>(0, 0);

        let result = CoherenceResult::from_meter(&meter, 0.5);
        assert_eq!(result.transitions, 3);
        assert_eq!(result.violations, 1);
        assert!(result.is_coherent); // 0.333 < 0.5

        let strict_result = CoherenceResult::from_meter(&meter, 0.1);
        assert!(!strict_result.is_coherent); // 0.333 > 0.1
    }

    #[test]
    fn test_coherence_result_drift_rate() {
        let result = CoherenceResult {
            transitions: 100,
            violations: 25,
            is_coherent: true,
        };
        assert!((result.drift_rate() - 0.25).abs() < 0.001);
    }

    // -------------------------------------------------------------------------
    // Phase 4: Advanced Feature Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_torus3d_distance_self() {
        let d = Torus3D::<8>::distance((0, 0, 0), (0, 0, 0));
        assert_eq!(d, 0);
    }

    #[test]
    fn test_torus3d_distance_adjacent() {
        let d = Torus3D::<8>::distance((0, 0, 0), (1, 0, 0));
        assert_eq!(d, 1);
    }

    #[test]
    fn test_torus3d_distance_wraparound() {
        // On 8x8x8 torus, (0,0,0) to (7,0,0) should wrap to distance 1
        let d = Torus3D::<8>::distance((0, 0, 0), (7, 0, 0));
        assert_eq!(d, 1);
    }

    #[test]
    fn test_torus3d_max_distance() {
        // Max distance on 8x8x8 torus is 4+4+4=12
        let d = Torus3D::<8>::distance((0, 0, 0), (4, 4, 4));
        assert_eq!(d, 12);
    }

    #[test]
    fn test_torus3d_coord_roundtrip() {
        for idx in 0..512 {
            let (x, y, z) = Torus3D::<8>::to_coords(idx);
            let back = Torus3D::<8>::to_index(x, y, z);
            assert_eq!(idx, back, "Roundtrip failed for index {}", idx);
        }
    }

    #[test]
    fn test_multi_scale_tonnetz_default() {
        let ms = MultiScaleTonnetz::default();
        assert_eq!(ms.scales, [6, 12, 24]);
    }

    #[test]
    fn test_multi_scale_distance_same_point() {
        let ms = MultiScaleTonnetz::default();
        let d = ms.distance((0, 0), (0, 0));
        assert_eq!(d, 0.0);
    }

    #[test]
    fn test_multi_scale_distance_weighted() {
        let ms = MultiScaleTonnetz::new([6, 12, 24], [1.0, 0.0, 0.0]);
        // Only use 6x6 scale
        let d = ms.distance((0, 0), (3, 3));
        // On 6x6 torus, (0,0) to (3,3) = 3+3 = 6
        assert_eq!(d, 6.0);
    }

    #[test]
    fn test_learned_projection() {
        let proj = LearnedProjection::new(4, 12);
        let embedding = vec![1.0, 0.5, -0.5, 0.2];
        let (row, col) = proj.project(&embedding);
        assert!(row < 12);
        assert!(col < 12);
    }

    #[test]
    fn test_adjacency_loss_positive_pairs() {
        let mut loss = AdjacencyLoss::<12>::new(0.5);
        loss.record_positive((0, 0), (1, 1)); // distance 2
        loss.record_positive((0, 0), (0, 1)); // distance 1
        // Mean positive distance = 1.5
        let l = loss.loss();
        assert!((l - 1.5).abs() < 0.001);
    }

    #[test]
    fn test_adjacency_loss_with_negatives() {
        let mut loss = AdjacencyLoss::<12>::new(0.5);
        loss.record_positive((0, 0), (1, 0)); // distance 1
        loss.record_negative((0, 0), (6, 6)); // distance 12
        // Loss = 1 - 0.5 * 12 = -5
        let l = loss.loss();
        assert!((l - (-5.0)).abs() < 0.001);
    }

    #[test]
    fn test_sparse_mask_from_toroidal() {
        let mask = ToroidalMask::hard_cutoff(16, 1.0, 4);
        let sparse = SparseMask::from_toroidal(&mask, 0.5);
        // Hard cutoff with radius 1 on 4x4 grid should have limited non-zeros
        assert!(sparse.nnz() < 16 * 16);
        assert!(sparse.sparsity() > 0.0);
    }

    #[test]
    fn test_sparse_mask_get() {
        let mask = ToroidalMask::hard_cutoff(16, 1.0, 4);
        let dense = mask.generate();
        let sparse = SparseMask::from_toroidal(&mask, 0.5);

        // Spot check some values
        for i in 0..16 {
            for j in 0..16 {
                let dense_val = dense[i][j];
                let sparse_val = sparse.get(i, j);
                if dense_val > 0.5 {
                    assert!((dense_val - sparse_val).abs() < 0.001);
                } else {
                    assert_eq!(sparse_val, 0.0);
                }
            }
        }
    }

    #[test]
    fn test_sparse_mask_memory() {
        let mask = ToroidalMask::soft_exponential(64, 2.0, 12);
        let sparse = SparseMask::from_toroidal(&mask, 0.1);
        let dense_bytes = 64 * 64 * 4; // f32 = 4 bytes
        let sparse_bytes = sparse.memory_bytes();
        // Sparse should use less memory if sufficiently sparse
        if sparse.sparsity() > 0.5 {
            assert!(sparse_bytes < dense_bytes);
        }
    }

    // -------------------------------------------------------------------------
    // Grounding Projector Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_grounding_projector_single_vector() {
        // Single evidence vector [1, 0, 0] — projects onto x-axis
        let e1: Vec<f32> = vec![1.0, 0.0, 0.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        // x = [3, 4, 5] → grounded = [3, 0, 0], hallucinated = [0, 4, 5]
        let x = vec![3.0, 4.0, 5.0];
        let g = proj.project_grounded(&x);
        assert!((g[0] - 3.0).abs() < 1e-5);
        assert!((g[1]).abs() < 1e-5);
        assert!((g[2]).abs() < 1e-5);
    }

    #[test]
    fn test_grounding_projector_two_vectors() {
        // Evidence spans xy-plane
        let e1: Vec<f32> = vec![1.0, 0.0, 0.0];
        let e2: Vec<f32> = vec![0.0, 1.0, 0.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice(), e2.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        // x = [3, 4, 5] → grounded = [3, 4, 0], hallucinated = [0, 0, 5]
        let x = vec![3.0, 4.0, 5.0];
        let g = proj.project_grounded(&x);
        let h = proj.project_hallucinated(&x);
        assert!((g[0] - 3.0).abs() < 1e-5);
        assert!((g[1] - 4.0).abs() < 1e-5);
        assert!((g[2]).abs() < 1e-5);
        assert!((h[0]).abs() < 1e-5);
        assert!((h[1]).abs() < 1e-5);
        assert!((h[2] - 5.0).abs() < 1e-5);
    }

    #[test]
    fn test_grounding_projector_idempotent() {
        // G² = G (projection property)
        let e1: Vec<f32> = vec![1.0, 1.0, 0.0, 0.0];
        let e2: Vec<f32> = vec![0.0, 0.0, 1.0, 1.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice(), e2.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 4).unwrap();

        assert!(proj.verify_idempotent(1e-5));
    }

    #[test]
    fn test_grounding_projector_symmetric() {
        // Gᵀ = G (orthogonal projection)
        let e1: Vec<f32> = vec![1.0, 2.0, 3.0];
        let e2: Vec<f32> = vec![4.0, 5.0, 6.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice(), e2.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        assert!(proj.verify_symmetric(1e-5));
    }

    #[test]
    fn test_grounding_fully_grounded() {
        // Vector in evidence subspace → score = 0
        let e1: Vec<f32> = vec![1.0, 0.0, 0.0];
        let e2: Vec<f32> = vec![0.0, 1.0, 0.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice(), e2.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        let x = vec![3.0, 4.0, 0.0]; // lies in xy-plane
        let score = proj.hallucination_score(&x);
        assert!(score < 1e-5, "Expected ~0, got {}", score);
    }

    #[test]
    fn test_grounding_fully_hallucinated() {
        // Vector orthogonal to evidence → score = 1
        let e1: Vec<f32> = vec![1.0, 0.0, 0.0];
        let e2: Vec<f32> = vec![0.0, 1.0, 0.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice(), e2.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        let x = vec![0.0, 0.0, 5.0]; // along z-axis
        let score = proj.hallucination_score(&x);
        assert!((score - 1.0).abs() < 1e-5, "Expected ~1, got {}", score);
    }

    #[test]
    fn test_grounding_partial() {
        // Vector partially in evidence subspace
        let e1: Vec<f32> = vec![1.0, 0.0, 0.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        let x = vec![1.0, 1.0, 0.0]; // half grounded
        let score = proj.hallucination_score(&x);
        // ‖hallucinated‖ = ‖[0,1,0]‖ = 1, ‖x‖ = √2 → score = 1/√2 ≈ 0.707
        assert!((score - 0.7071).abs() < 0.01, "Expected ~0.707, got {}", score);
    }

    #[test]
    fn test_grounding_decompose() {
        let e1: Vec<f32> = vec![1.0, 0.0, 0.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        let x = vec![3.0, 4.0, 0.0];
        let decomp = proj.decompose(&x);

        assert!((decomp.grounded[0] - 3.0).abs() < 1e-5);
        assert!((decomp.hallucinated[1] - 4.0).abs() < 1e-5);
        // Pythagorean: grounding² + hallucination² ≈ 1
        let sum_sq = decomp.grounding_ratio.powi(2) + decomp.hallucination_ratio.powi(2);
        assert!((sum_sq - 1.0).abs() < 1e-4, "Pythagorean check failed: {}", sum_sq);
    }

    #[test]
    fn test_grounding_empty_evidence() {
        let evidence: Vec<&[f32]> = vec![];
        let result = GroundingProjector::from_evidence(&evidence, 3);
        assert!(result.is_none());
    }

    #[test]
    fn test_grounding_non_orthogonal_evidence() {
        // Non-orthogonal evidence — (AᵀA)⁻¹ handles this
        let e1: Vec<f32> = vec![1.0, 1.0, 0.0];
        let e2: Vec<f32> = vec![1.0, 0.0, 0.0];
        let evidence: Vec<&[f32]> = vec![e1.as_slice(), e2.as_slice()];
        let proj = GroundingProjector::from_evidence(&evidence, 3).unwrap();

        // Still idempotent and symmetric
        assert!(proj.verify_idempotent(1e-4));
        assert!(proj.verify_symmetric(1e-4));

        // Rank should be 2 (spans xy-plane)
        assert_eq!(proj.rank(), 2);

        // z-axis should be fully hallucinated
        let z = vec![0.0, 0.0, 1.0];
        let score = proj.hallucination_score(&z);
        assert!((score - 1.0).abs() < 1e-4);
    }

    #[test]
    fn test_invert_matrix_2x2() {
        // [2, 1; 1, 1]⁻¹ = [1, -1; -1, 2]
        let m = vec![2.0, 1.0, 1.0, 1.0];
        let inv = invert_matrix(&m, 2).unwrap();
        assert!((inv[0] - 1.0).abs() < 1e-5);
        assert!((inv[1] - (-1.0)).abs() < 1e-5);
        assert!((inv[2] - (-1.0)).abs() < 1e-5);
        assert!((inv[3] - 2.0).abs() < 1e-5);
    }

    #[test]
    fn test_invert_singular_matrix() {
        // Singular matrix → None
        let m = vec![1.0, 2.0, 2.0, 4.0];
        assert!(invert_matrix(&m, 2).is_none());
    }

    // -------------------------------------------------------------------------
    // Karmonic Filter Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_karmonic_filter_creation() {
        let filter = KarmonicFilter::new(12, 6);
        assert_eq!(filter.n_modes(), 6);
        assert_eq!(filter.grid_size(), 12);
    }

    #[test]
    fn test_karmonic_mode1_preserved() {
        // Mode 1 should have weight ≈ 0 (preserved, not regularized)
        let filter = KarmonicFilter::new(12, 6);
        assert!(filter.weight(0) < 0.001, "Mode 1 weight should be ~0, got {}", filter.weight(0));
    }

    #[test]
    fn test_karmonic_weights_monotonic() {
        // Weights should increase with mode index
        let filter = KarmonicFilter::new(12, 6);
        for i in 1..filter.n_modes() {
            assert!(
                filter.weight(i) >= filter.weight(i - 1),
                "Weights not monotonic: w[{}]={} < w[{}]={}",
                i, filter.weight(i), i - 1, filter.weight(i - 1)
            );
        }
    }

    #[test]
    fn test_karmonic_highest_mode_is_one() {
        // Highest mode should have weight = 1.0 (maximum regularization)
        let filter = KarmonicFilter::new(12, 6);
        let last = filter.n_modes() - 1;
        assert!(
            (filter.weight(last) - 1.0).abs() < 0.001,
            "Last mode weight should be ~1.0, got {}",
            filter.weight(last)
        );
    }

    #[test]
    fn test_karmonic_eigenvalues_positive() {
        let filter = KarmonicFilter::new(12, 6);
        for (i, &lam) in filter.eigenvalues().iter().enumerate() {
            assert!(lam > 0.0, "Eigenvalue {} should be positive, got {}", i, lam);
        }
    }

    #[test]
    fn test_karmonic_eigenvalue_formula() {
        // λ_1 for N=12: 2 - 2·cos(2π/12) = 2 - 2·cos(π/6) = 2 - √3 ≈ 0.268
        let filter = KarmonicFilter::new(12, 6);
        let expected = 2.0 - 3.0_f32.sqrt();
        assert!(
            (filter.eigenvalue(0) - expected).abs() < 0.01,
            "λ₁ should be ~{}, got {}", expected, filter.eigenvalue(0)
        );
    }

    #[test]
    fn test_karmonic_spectral_gap_matches_tonnetz() {
        // Karmonic eigenvalue(0) should match Tonnetz spectral gap
        let filter = KarmonicFilter::new(12, 6);
        let tonnetz_gap = Tonnetz::<12>::spectral_gap();
        assert!(
            (filter.eigenvalue(0) - tonnetz_gap).abs() < 0.01,
            "Karmonic λ₁={} should match Tonnetz gap={}",
            filter.eigenvalue(0), tonnetz_gap
        );
    }

    #[test]
    fn test_karmonic_uniformity_loss_batch_too_small() {
        let filter = KarmonicFilter::new(12, 6);
        // Batch of 1 should return 0
        let embeddings = vec![vec![0.0; 24]]; // 2 * 2 * 6 = 24
        let loss = filter.uniformity_loss(&embeddings, 2, 2.0);
        assert_eq!(loss, 0.0);
    }

    #[test]
    fn test_karmonic_uniformity_loss_finite() {
        let filter = KarmonicFilter::new(12, 6);
        let embeddings = vec![
            vec![1.0, 0.0, 0.5, 0.5, -0.3, 0.2, 0.1, -0.1, 0.4, 0.3, -0.2, 0.1,
                 0.3, 0.1, 0.2, -0.4, 0.1, 0.5, -0.1, 0.2, 0.3, -0.3, 0.4, 0.1],
            vec![0.0, 1.0, 0.4, 0.6, -0.1, 0.3, 0.2, -0.2, 0.3, 0.4, -0.1, 0.2,
                 0.2, 0.3, 0.1, -0.3, 0.2, 0.4, -0.2, 0.3, 0.2, -0.2, 0.3, 0.2],
            vec![0.5, 0.5, 0.3, 0.7, -0.2, 0.1, 0.3, -0.3, 0.2, 0.5, -0.3, 0.3,
                 0.1, 0.2, 0.3, -0.2, 0.3, 0.3, -0.3, 0.1, 0.1, -0.1, 0.5, 0.3],
        ];
        let loss = filter.uniformity_loss(&embeddings, 2, 2.0);
        assert!(loss.is_finite(), "Loss should be finite, got {}", loss);
    }

    #[test]
    fn test_karmonic_identical_embeddings_low_loss() {
        // Identical embeddings → distances are 0 → uniformity is high (low loss)
        let filter = KarmonicFilter::new(12, 3);
        let emb = vec![0.5; 12]; // 2 * 2 * 3 = 12
        let embeddings = vec![emb.clone(), emb.clone(), emb.clone()];
        let loss = filter.uniformity_loss(&embeddings, 2, 2.0);
        assert!(loss.is_finite());
    }

    #[test]
    fn test_fourier_expand_dims() {
        let angles = vec![1.0, 2.0]; // 2 circles
        let embed = fourier_expand(&angles, 6);
        assert_eq!(embed.len(), 2 * 2 * 6); // 2k*m = 24
    }

    #[test]
    fn test_fourier_expand_mode1() {
        let angles = vec![0.0]; // single circle, angle=0
        let embed = fourier_expand(&angles, 3);
        // Mode 1: cos(0)=1, sin(0)=0
        assert!((embed[0] - 1.0).abs() < 1e-6);
        assert!(embed[1].abs() < 1e-6);
    }

    #[test]
    fn test_angles_to_grid() {
        let pi = core::f32::consts::PI;
        // angle = 0 → grid 0
        // angle = π → grid 6 (halfway on N=12)
        let coords = angles_to_grid(&[0.0, pi], 12);
        assert_eq!(coords[0], 0);
        assert_eq!(coords[1], 6);
    }

    #[test]
    fn test_spread_loss_uncorrelated() {
        let filter = KarmonicFilter::new(12, 6);
        // Generate angles that are roughly uncorrelated
        let angles = vec![
            vec![0.0, 3.14],
            vec![1.57, 0.5],
            vec![3.14, 1.57],
            vec![4.71, 4.0],
        ];
        let spread = filter.spread_loss(&angles);
        assert!(spread.is_finite());
        assert!(spread >= 0.0);
    }

    #[test]
    fn test_spread_loss_single_dim() {
        let filter = KarmonicFilter::new(12, 6);
        // Single dimension → no pairs → 0
        let angles = vec![vec![1.0], vec![2.0]];
        assert_eq!(filter.spread_loss(&angles), 0.0);
    }

    #[test]
    fn test_karmonic_different_grid_sizes() {
        // Filter should work with different grid sizes.
        // n_modes is clamped to grid_size/2 (Nyquist limit).
        for &n in &[4, 6, 8, 12, 24] {
            let filter = KarmonicFilter::new(n, 4);
            let actual_modes = filter.n_modes();
            assert!(actual_modes >= 1);
            assert!(actual_modes <= n / 2);
            // Lowest mode always has weight 0
            assert!(filter.weight(0) < 0.001);
            // Highest available mode always has weight 1
            assert!(
                (filter.weight(actual_modes - 1) - 1.0).abs() < 0.001,
                "grid_size={}, n_modes={}, highest weight={}",
                n, actual_modes, filter.weight(actual_modes - 1)
            );
        }
    }
}