ruqu-core 2.0.5

High-performance quantum circuit simulator in pure Rust - state-vector simulation with SIMD acceleration, noise models, and multi-threading
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
//! Ultra-fast distributed surface code decoder.
//!
//! Implements a graph-partitioned Minimum Weight Perfect Matching (MWPM) decoder
//! with sublinear scaling for surface code error correction.
//!
//! # Architecture
//!
//! The classical control plane for QEC must decode syndromes faster than
//! the quantum error rate accumulates new errors. For distance-d surface
//! codes with ~d^2 physical qubits per logical qubit, the decoder must
//! process O(d^2) syndrome bits per round within ~1 microsecond.
//!
//! This module provides:
//!
//! - [`UnionFindDecoder`]: O(n * alpha(n)) amortized decoder using weighted
//!   union-find to cluster nearby defects, suitable for real-time decoding.
//! - [`PartitionedDecoder`]: Tiles the syndrome lattice into independent
//!   regions for parallel decoding with boundary merging, enabling sublinear
//!   wall-clock scaling on multi-core systems.
//! - [`AdaptiveCodeDistance`]: Dynamically adjusts code distance based on
//!   observed logical error rates.
//! - [`LogicalQubitAllocator`]: Manages physical-to-logical qubit mapping
//!   for surface code patches.
//! - [`benchmark_decoder`]: Measures decoder throughput and accuracy.

use std::time::Instant;

// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------

/// A single stabilizer measurement from the surface code lattice.
#[derive(Debug, Clone, PartialEq)]
pub struct StabilizerMeasurement {
    /// X coordinate on the surface code lattice.
    pub x: u32,
    /// Y coordinate on the surface code lattice.
    pub y: u32,
    /// Syndrome extraction round index.
    pub round: u32,
    /// Measurement outcome (true = eigenvalue -1 = defect detected).
    pub value: bool,
}

/// Syndrome data from one or more rounds of stabilizer measurements.
#[derive(Debug, Clone)]
pub struct SyndromeData {
    /// All stabilizer measurement outcomes.
    pub stabilizers: Vec<StabilizerMeasurement>,
    /// Code distance of the surface code.
    pub code_distance: u32,
    /// Number of syndrome extraction rounds performed.
    pub num_rounds: u32,
}

/// Pauli correction type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PauliType {
    /// Bit-flip correction.
    X,
    /// Phase-flip correction.
    Z,
}

/// Decoder output: a set of Pauli corrections to apply.
#[derive(Debug, Clone)]
pub struct Correction {
    /// List of (qubit_index, pauli_type) corrections.
    pub pauli_corrections: Vec<(u32, PauliType)>,
    /// Inferred logical measurement outcome after correction.
    pub logical_outcome: bool,
    /// Decoder confidence in the correction (0.0 to 1.0).
    pub confidence: f64,
    /// Wall-clock decoding time in nanoseconds.
    pub decode_time_ns: u64,
}

// ---------------------------------------------------------------------------
// Trait
// ---------------------------------------------------------------------------

/// Trait for surface code decoders.
///
/// Implementations must be thread-safe (`Send + Sync`) to support
/// concurrent decoding of independent patches.
pub trait SurfaceCodeDecoder: Send + Sync {
    /// Decode a syndrome and return the inferred correction.
    fn decode(&self, syndrome: &SyndromeData) -> Correction;

    /// Human-readable name for this decoder.
    fn name(&self) -> &str;
}

// ---------------------------------------------------------------------------
// Union-Find internals
// ---------------------------------------------------------------------------

/// Weighted union-find (disjoint set) data structure with path compression
/// and union by rank, achieving O(alpha(n)) amortized operations.
#[derive(Debug, Clone)]
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
    /// Parity of each cluster: true means odd number of defects.
    parity: Vec<bool>,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        Self {
            parent: (0..n).collect(),
            rank: vec![0; n],
            parity: vec![false; n],
        }
    }

    fn find(&mut self, mut x: usize) -> usize {
        while self.parent[x] != x {
            // Path splitting for amortized O(alpha(n))
            let next = self.parent[x];
            self.parent[x] = self.parent[next];
            x = next;
        }
        x
    }

    fn union(&mut self, a: usize, b: usize) {
        let ra = self.find(a);
        let rb = self.find(b);
        if ra == rb {
            return;
        }
        // Union by rank
        let (big, small) = if self.rank[ra] >= self.rank[rb] {
            (ra, rb)
        } else {
            (rb, ra)
        };
        self.parent[small] = big;
        self.parity[big] = self.parity[big] ^ self.parity[small];
        if self.rank[big] == self.rank[small] {
            self.rank[big] += 1;
        }
    }

    fn set_parity(&mut self, node: usize, is_defect: bool) {
        let root = self.find(node);
        self.parity[root] = self.parity[root] ^ is_defect;
    }

    fn cluster_parity(&mut self, node: usize) -> bool {
        let root = self.find(node);
        self.parity[root]
    }
}

/// A defect in the 3D syndrome graph (space + time).
#[derive(Debug, Clone)]
struct Defect {
    x: u32,
    y: u32,
    round: u32,
    node_index: usize,
}

// ---------------------------------------------------------------------------
// UnionFindDecoder
// ---------------------------------------------------------------------------

/// Fast union-find based decoder with O(n * alpha(n)) complexity.
///
/// The algorithm:
/// 1. Extract defects (syndrome bit flips between consecutive rounds).
/// 2. Build a defect graph where edges connect nearby defects weighted
///    by Manhattan distance.
/// 3. Grow clusters from each defect using weighted union-find,
///    merging clusters whose boundaries touch.
/// 4. For each odd-parity cluster, assign Pauli corrections along
///    the shortest path to the nearest boundary.
///
/// This is significantly faster than full MWPM while achieving
/// near-optimal correction for moderate error rates (p < 1%).
pub struct UnionFindDecoder {
    /// Maximum growth radius for cluster expansion.
    max_growth_radius: u32,
}

impl UnionFindDecoder {
    /// Create a new union-find decoder.
    ///
    /// `max_growth_radius` controls how far clusters expand before
    /// we stop growing (typically set to code_distance / 2).
    /// If 0, defaults to code_distance at decode time.
    pub fn new(max_growth_radius: u32) -> Self {
        Self { max_growth_radius }
    }

    /// Extract defects from syndrome data by comparing consecutive rounds.
    ///
    /// A defect occurs where the syndrome bit flipped between rounds,
    /// or where the first round shows a -1 eigenvalue (compared to
    /// the implicit all-+1 initial state).
    fn extract_defects(&self, syndrome: &SyndromeData) -> Vec<Defect> {
        let d = syndrome.code_distance;
        let num_rounds = syndrome.num_rounds;

        // Build a 3D grid indexed by (x, y, round) for fast lookup.
        // Grid dimensions: d-1 x d-1 stabilizers for a distance-d code.
        let grid_w = if d > 1 { d - 1 } else { 1 };
        let grid_h = if d > 1 { d - 1 } else { 1 };
        let grid_size = (grid_w * grid_h * num_rounds) as usize;
        let mut grid = vec![false; grid_size];

        for s in &syndrome.stabilizers {
            if s.x < grid_w && s.y < grid_h && s.round < num_rounds {
                let idx = (s.round * grid_w * grid_h + s.y * grid_w + s.x) as usize;
                if idx < grid.len() {
                    grid[idx] = s.value;
                }
            }
        }

        let mut defects = Vec::new();
        let mut node_idx = 0usize;

        for r in 0..num_rounds {
            for y in 0..grid_h {
                for x in 0..grid_w {
                    let curr_idx = (r * grid_w * grid_h + y * grid_w + x) as usize;
                    let curr = grid[curr_idx];

                    // Compare with previous round (or implicit all-false for round 0).
                    let prev = if r > 0 {
                        let prev_idx =
                            ((r - 1) * grid_w * grid_h + y * grid_w + x) as usize;
                        grid[prev_idx]
                    } else {
                        false
                    };

                    // A defect is a change in syndrome value.
                    if curr != prev {
                        defects.push(Defect {
                            x,
                            y,
                            round: r,
                            node_index: node_idx,
                        });
                    }
                    node_idx += 1;
                }
            }
        }

        defects
    }

    /// Compute Manhattan distance between two defects in 3D (x, y, round).
    fn manhattan_distance(a: &Defect, b: &Defect) -> u32 {
        let dx = (a.x as i64 - b.x as i64).unsigned_abs() as u32;
        let dy = (a.y as i64 - b.y as i64).unsigned_abs() as u32;
        let dr = (a.round as i64 - b.round as i64).unsigned_abs() as u32;
        dx + dy + dr
    }

    /// Distance from a defect to the nearest lattice boundary.
    fn boundary_distance(defect: &Defect, code_distance: u32) -> u32 {
        let grid_w = if code_distance > 1 {
            code_distance - 1
        } else {
            1
        };
        let grid_h = if code_distance > 1 {
            code_distance - 1
        } else {
            1
        };
        let dx_min = defect.x.min(grid_w.saturating_sub(1).saturating_sub(defect.x));
        let dy_min = defect.y.min(grid_h.saturating_sub(1).saturating_sub(defect.y));
        dx_min.min(dy_min)
    }

    /// Grow clusters using union-find until all odd-parity clusters
    /// are resolved (paired or connected to the boundary).
    fn grow_and_merge(
        &self,
        defects: &[Defect],
        total_nodes: usize,
        code_distance: u32,
    ) -> UnionFind {
        let mut uf = UnionFind::new(total_nodes);

        // Mark initial defect parities.
        for d in defects {
            uf.set_parity(d.node_index, true);
        }

        if defects.is_empty() {
            return uf;
        }

        let max_radius = if self.max_growth_radius > 0 {
            self.max_growth_radius
        } else {
            code_distance
        };

        // Iterative growth: merge defects within increasing radius.
        for radius in 1..=max_radius {
            let mut merged_any = false;
            for i in 0..defects.len() {
                if !uf.cluster_parity(defects[i].node_index) {
                    continue; // Already paired
                }
                for j in (i + 1)..defects.len() {
                    if !uf.cluster_parity(defects[j].node_index) {
                        continue;
                    }
                    if Self::manhattan_distance(&defects[i], &defects[j]) <= 2 * radius {
                        uf.union(defects[i].node_index, defects[j].node_index);
                        merged_any = true;
                    }
                }
            }
            if !merged_any {
                break;
            }
            // Check if all clusters are even-parity.
            let all_even = defects
                .iter()
                .all(|d| !uf.cluster_parity(d.node_index));
            if all_even {
                break;
            }
        }

        uf
    }

    /// For each odd-parity cluster, generate corrections by connecting
    /// the defect to the nearest boundary along the shortest path.
    fn corrections_from_clusters(
        &self,
        defects: &[Defect],
        uf: &mut UnionFind,
        code_distance: u32,
    ) -> Vec<(u32, PauliType)> {
        let mut corrections = Vec::new();

        // Collect defects that are roots of odd-parity clusters.
        let mut odd_roots: Vec<&Defect> = Vec::new();
        for d in defects {
            let root = uf.find(d.node_index);
            if uf.parity[root] && root == d.node_index {
                odd_roots.push(d);
            }
        }

        // For each unpaired defect, draw a correction path to the boundary.
        for defect in &odd_roots {
            let path = self.path_to_boundary(defect, code_distance);
            corrections.extend(path);
        }

        // For paired defects within clusters, generate corrections along
        // the connecting path. We handle this by finding pairs of defects
        // in the same even-parity cluster and correcting between them.
        let mut paired: Vec<bool> = vec![false; defects.len()];
        for i in 0..defects.len() {
            if paired[i] {
                continue;
            }
            let root_i = uf.find(defects[i].node_index);
            for j in (i + 1)..defects.len() {
                if paired[j] {
                    continue;
                }
                let root_j = uf.find(defects[j].node_index);
                if root_i == root_j && !uf.parity[root_i] {
                    // These two are paired -- generate correction path between them.
                    let path = self.path_between(&defects[i], &defects[j], code_distance);
                    corrections.extend(path);
                    paired[i] = true;
                    paired[j] = true;
                    break;
                }
            }
        }

        corrections
    }

    /// Generate Pauli corrections along the shortest path from a defect
    /// to the nearest boundary of the lattice.
    fn path_to_boundary(&self, defect: &Defect, code_distance: u32) -> Vec<(u32, PauliType)> {
        let mut corrections = Vec::new();
        let grid_w = if code_distance > 1 {
            code_distance - 1
        } else {
            1
        };

        // Move toward the nearest X boundary (left or right).
        // Each step corrects one data qubit on that row.
        let dist_left = defect.x;
        let dist_right = grid_w.saturating_sub(defect.x + 1);

        if dist_left <= dist_right {
            // Correct toward the left boundary.
            for step in 0..=defect.x {
                let data_qubit = defect.y * code_distance + (defect.x - step);
                corrections.push((data_qubit, PauliType::X));
            }
        } else {
            // Correct toward the right boundary.
            for step in 0..=(grid_w - defect.x - 1) {
                let data_qubit = defect.y * code_distance + (defect.x + step + 1);
                corrections.push((data_qubit, PauliType::X));
            }
        }

        corrections
    }

    /// Generate Pauli corrections along the shortest path between two
    /// paired defects.
    fn path_between(
        &self,
        a: &Defect,
        b: &Defect,
        code_distance: u32,
    ) -> Vec<(u32, PauliType)> {
        let mut corrections = Vec::new();

        let (mut cx, mut cy) = (a.x as i64, a.y as i64);
        let (tx, ty) = (b.x as i64, b.y as i64);

        // Walk horizontally then vertically (L-shaped path).
        while cx != tx {
            let step = if tx > cx { 1i64 } else { -1 };
            let data_x = if step > 0 { cx + 1 } else { cx };
            let data_qubit = cy as u32 * code_distance + data_x as u32;
            corrections.push((data_qubit, PauliType::X));
            cx += step;
        }
        while cy != ty {
            let step = if ty > cy { 1i64 } else { -1 };
            let data_y = if step > 0 { cy + 1 } else { cy };
            let data_qubit = data_y as u32 * code_distance + cx as u32;
            corrections.push((data_qubit, PauliType::Z));
            cy += step;
        }

        corrections
    }

    /// Infer the logical outcome from the correction chain.
    /// A logical error occurs if the correction chain crosses the
    /// lattice boundary an odd number of times.
    fn infer_logical_outcome(corrections: &[(u32, PauliType)]) -> bool {
        // Count X corrections: if an odd number cross the logical X
        // operator support, the logical outcome flips.
        let x_count = corrections
            .iter()
            .filter(|(_, p)| *p == PauliType::X)
            .count();
        x_count % 2 == 1
    }
}

impl SurfaceCodeDecoder for UnionFindDecoder {
    fn decode(&self, syndrome: &SyndromeData) -> Correction {
        let start = Instant::now();

        let defects = self.extract_defects(syndrome);

        if defects.is_empty() {
            let elapsed = start.elapsed().as_nanos() as u64;
            return Correction {
                pauli_corrections: Vec::new(),
                logical_outcome: false,
                confidence: 1.0,
                decode_time_ns: elapsed,
            };
        }

        let d = syndrome.code_distance;
        let grid_w = if d > 1 { d - 1 } else { 1 };
        let grid_h = if d > 1 { d - 1 } else { 1 };
        let total_nodes = (grid_w * grid_h * syndrome.num_rounds) as usize;

        let mut uf = self.grow_and_merge(&defects, total_nodes, d);
        let pauli_corrections = self.corrections_from_clusters(&defects, &mut uf, d);
        let logical_outcome = Self::infer_logical_outcome(&pauli_corrections);

        // Confidence based on number of defects relative to code distance:
        // fewer defects = higher confidence in the correction.
        let defect_density = defects.len() as f64 / (d as f64 * d as f64);
        let confidence = (1.0 - defect_density).max(0.0).min(1.0);

        let elapsed = start.elapsed().as_nanos() as u64;

        Correction {
            pauli_corrections,
            logical_outcome,
            confidence,
            decode_time_ns: elapsed,
        }
    }

    fn name(&self) -> &str {
        "UnionFindDecoder"
    }
}

// ---------------------------------------------------------------------------
// PartitionedDecoder
// ---------------------------------------------------------------------------

/// Partitioned decoder that tiles the syndrome lattice into independent
/// regions for parallel decoding.
///
/// Each tile of size `tile_size x tile_size` is decoded independently
/// using the inner decoder, then corrections at tile boundaries are
/// merged to form a globally consistent correction set.
///
/// This architecture enables:
/// - Sublinear wall-clock scaling with tile parallelism
/// - Bounded per-tile working set for cache efficiency
/// - Graceful degradation: tile boundary errors add O(1/tile_size)
///   overhead to the logical error rate
pub struct PartitionedDecoder {
    tile_size: u32,
    inner_decoder: Box<dyn SurfaceCodeDecoder>,
}

impl PartitionedDecoder {
    /// Create a new partitioned decoder.
    ///
    /// `tile_size` controls the side length of each tile (e.g., 8 for
    /// 8x8 regions). The `inner_decoder` is used to decode each tile.
    pub fn new(tile_size: u32, inner_decoder: Box<dyn SurfaceCodeDecoder>) -> Self {
        assert!(tile_size > 0, "tile_size must be positive");
        Self {
            tile_size,
            inner_decoder,
        }
    }

    /// Partition syndrome data into tiles.
    fn partition_syndrome(&self, syndrome: &SyndromeData) -> Vec<SyndromeData> {
        let d = syndrome.code_distance;
        let grid_w = if d > 1 { d - 1 } else { 1 };
        let grid_h = if d > 1 { d - 1 } else { 1 };

        let tiles_x = (grid_w + self.tile_size - 1) / self.tile_size;
        let tiles_y = (grid_h + self.tile_size - 1) / self.tile_size;

        let mut tiles = Vec::with_capacity((tiles_x * tiles_y) as usize);

        for ty in 0..tiles_y {
            for tx in 0..tiles_x {
                let x_min = tx * self.tile_size;
                let y_min = ty * self.tile_size;
                let x_max = ((tx + 1) * self.tile_size).min(grid_w);
                let y_max = ((ty + 1) * self.tile_size).min(grid_h);
                let tile_w = x_max - x_min;
                let tile_h = y_max - y_min;
                let tile_d = tile_w.max(tile_h) + 1;

                let tile_stabs: Vec<StabilizerMeasurement> = syndrome
                    .stabilizers
                    .iter()
                    .filter(|s| s.x >= x_min && s.x < x_max && s.y >= y_min && s.y < y_max)
                    .map(|s| StabilizerMeasurement {
                        x: s.x - x_min,
                        y: s.y - y_min,
                        round: s.round,
                        value: s.value,
                    })
                    .collect();

                tiles.push(SyndromeData {
                    stabilizers: tile_stabs,
                    code_distance: tile_d,
                    num_rounds: syndrome.num_rounds,
                });
            }
        }

        tiles
    }

    /// Merge corrections from individual tiles back into global coordinates.
    fn merge_tile_corrections(
        &self,
        tile_corrections: &[Correction],
        syndrome: &SyndromeData,
    ) -> Correction {
        let d = syndrome.code_distance;
        let grid_w = if d > 1 { d - 1 } else { 1 };

        let tiles_x = (grid_w + self.tile_size - 1) / self.tile_size;

        let mut all_corrections = Vec::new();
        let mut total_confidence = 0.0;
        let mut logical_outcome = false;

        for (idx, tile_corr) in tile_corrections.iter().enumerate() {
            let tx = idx as u32 % tiles_x;
            let ty = idx as u32 / tiles_x;
            let x_offset = tx * self.tile_size;
            let y_offset = ty * self.tile_size;

            for &(qubit, pauli) in &tile_corr.pauli_corrections {
                // Remap tile-local qubit to global qubit coordinate.
                let local_y = qubit / (d.max(1));
                let local_x = qubit % (d.max(1));
                let global_qubit =
                    (local_y + y_offset) * d + (local_x + x_offset);
                all_corrections.push((global_qubit, pauli));
            }

            total_confidence += tile_corr.confidence;
            logical_outcome ^= tile_corr.logical_outcome;
        }

        let avg_confidence = if tile_corrections.is_empty() {
            1.0
        } else {
            total_confidence / tile_corrections.len() as f64
        };

        // Deduplicate corrections: two corrections on the same qubit
        // with the same Pauli type cancel out.
        all_corrections.sort_by(|a, b| a.0.cmp(&b.0).then(format!("{:?}", a.1).cmp(&format!("{:?}", b.1))));
        let mut deduped: Vec<(u32, PauliType)> = Vec::new();
        let mut i = 0;
        while i < all_corrections.len() {
            let mut count = 1usize;
            while i + count < all_corrections.len()
                && all_corrections[i + count].0 == all_corrections[i].0
                && all_corrections[i + count].1 == all_corrections[i].1
            {
                count += 1;
            }
            // Pauli operators are self-inverse: even count cancels.
            if count % 2 == 1 {
                deduped.push(all_corrections[i]);
            }
            i += count;
        }

        Correction {
            pauli_corrections: deduped,
            logical_outcome,
            confidence: avg_confidence,
            decode_time_ns: 0, // Will be set by the caller
        }
    }
}

impl SurfaceCodeDecoder for PartitionedDecoder {
    fn decode(&self, syndrome: &SyndromeData) -> Correction {
        let start = Instant::now();

        let tiles = self.partition_syndrome(syndrome);

        // Decode each tile independently.
        // In a production system, these would run on separate threads/cores.
        let tile_corrections: Vec<Correction> =
            tiles.iter().map(|t| self.inner_decoder.decode(t)).collect();

        let mut correction = self.merge_tile_corrections(&tile_corrections, syndrome);
        correction.decode_time_ns = start.elapsed().as_nanos() as u64;

        correction
    }

    fn name(&self) -> &str {
        "PartitionedDecoder"
    }
}

// ---------------------------------------------------------------------------
// Adaptive code distance
// ---------------------------------------------------------------------------

/// Dynamically adjusts code distance based on observed logical error rates.
///
/// Monitors a sliding window of recent logical error rates and recommends
/// increasing the code distance when errors are too high, or decreasing
/// when resources can be reclaimed.
///
/// Thresholds:
/// - Increase when average error rate > 10^(-distance/3)
/// - Decrease when average error rate < 10^(-(distance+2)/3) for
///   sustained periods
#[derive(Debug, Clone)]
pub struct AdaptiveCodeDistance {
    current_distance: u32,
    min_distance: u32,
    max_distance: u32,
    error_history: Vec<f64>,
    window_size: usize,
}

impl AdaptiveCodeDistance {
    /// Create a new adaptive code distance tracker.
    ///
    /// # Panics
    /// Panics if `min > max`, `initial < min`, or `initial > max`.
    pub fn new(initial: u32, min: u32, max: u32) -> Self {
        assert!(min <= max, "min_distance must be <= max_distance");
        assert!(
            initial >= min && initial <= max,
            "initial distance must be in [min, max]"
        );
        // Code distance must be odd for surface codes.
        let initial = if initial % 2 == 0 {
            initial + 1
        } else {
            initial
        };
        Self {
            current_distance: initial.min(max),
            min_distance: min,
            max_distance: max,
            error_history: Vec::new(),
            window_size: 100,
        }
    }

    /// Record a new observed logical error rate sample.
    pub fn record_error_rate(&mut self, rate: f64) {
        self.error_history.push(rate.clamp(0.0, 1.0));
        if self.error_history.len() > self.window_size * 2 {
            // Keep only the most recent window.
            let drain_to = self.error_history.len() - self.window_size;
            self.error_history.drain(..drain_to);
        }
    }

    /// Return the recommended code distance based on recent error rates.
    pub fn recommended_distance(&self) -> u32 {
        if self.should_increase() {
            let next = self.current_distance + 2; // Keep odd
            next.min(self.max_distance)
        } else if self.should_decrease() {
            let next = self.current_distance.saturating_sub(2);
            next.max(self.min_distance)
        } else {
            self.current_distance
        }
    }

    /// Returns true if the code distance should be increased.
    ///
    /// Triggered when the average error rate over the window exceeds
    /// the threshold for the current distance.
    pub fn should_increase(&self) -> bool {
        if self.current_distance >= self.max_distance {
            return false;
        }
        let avg = self.average_error_rate();
        if avg.is_nan() {
            return false;
        }
        // Threshold: 10^(-d/3), i.e., for d=3 threshold is ~0.046,
        // for d=5 threshold is ~0.0046, etc.
        let threshold = 10.0_f64.powf(-(self.current_distance as f64) / 3.0);
        avg > threshold
    }

    /// Returns true if the code distance can be safely decreased.
    ///
    /// Triggered when the average error rate is well below the
    /// threshold for the next smaller distance.
    pub fn should_decrease(&self) -> bool {
        if self.current_distance <= self.min_distance {
            return false;
        }
        let avg = self.average_error_rate();
        if avg.is_nan() {
            return false;
        }
        // Only decrease if we have enough data.
        if self.error_history.len() < self.window_size {
            return false;
        }
        let lower_d = self.current_distance - 2;
        let threshold = 10.0_f64.powf(-(lower_d as f64) / 3.0);
        // Require error rate to be well below the lower distance threshold.
        avg < threshold * 0.1
    }

    /// Average error rate over the most recent window.
    fn average_error_rate(&self) -> f64 {
        if self.error_history.is_empty() {
            return f64::NAN;
        }
        let window_start = self
            .error_history
            .len()
            .saturating_sub(self.window_size);
        let window = &self.error_history[window_start..];
        let sum: f64 = window.iter().sum();
        sum / window.len() as f64
    }
}

// ---------------------------------------------------------------------------
// Logical qubit allocator
// ---------------------------------------------------------------------------

/// A surface code patch representing one logical qubit.
#[derive(Debug, Clone)]
pub struct SurfaceCodePatch {
    /// Logical qubit identifier.
    pub logical_id: u32,
    /// Physical qubit indices comprising this patch.
    pub physical_qubits: Vec<u32>,
    /// Code distance for this patch.
    pub code_distance: u32,
    /// X origin of this patch on the physical qubit grid.
    pub x_origin: u32,
    /// Y origin of this patch on the physical qubit grid.
    pub y_origin: u32,
}

/// Allocates logical qubit patches on a physical qubit grid.
///
/// A distance-d surface code patch requires d^2 data qubits and
/// (d-1)^2 + (d-1)^2 = 2(d-1)^2 ancilla qubits, totaling
/// d^2 + 2(d-1)^2 = 2d^2 - 2d + 1 physical qubits per logical qubit.
///
/// Patches are laid out on a 2D grid with d-qubit spacing between
/// patch origins to avoid overlap.
pub struct LogicalQubitAllocator {
    total_physical: u32,
    code_distance: u32,
    allocated_patches: Vec<SurfaceCodePatch>,
    next_logical_id: u32,
}

impl LogicalQubitAllocator {
    /// Create a new allocator with the given total physical qubit count
    /// and default code distance.
    pub fn new(total_physical: u32, code_distance: u32) -> Self {
        Self {
            total_physical,
            code_distance,
            allocated_patches: Vec::new(),
            next_logical_id: 0,
        }
    }

    /// Maximum number of logical qubits that can be allocated.
    ///
    /// Each logical qubit requires 2d^2 - 2d + 1 physical qubits.
    pub fn max_logical_qubits(&self) -> u32 {
        let d = self.code_distance as u64;
        let qubits_per_logical = 2 * d * d - 2 * d + 1;
        if qubits_per_logical == 0 {
            return 0;
        }
        (self.total_physical as u64 / qubits_per_logical) as u32
    }

    /// Allocate a new logical qubit patch.
    ///
    /// Returns `None` if insufficient physical qubits remain.
    pub fn allocate(&mut self) -> Option<SurfaceCodePatch> {
        let max = self.max_logical_qubits();
        if self.allocated_patches.len() as u32 >= max {
            return None;
        }

        let d = self.code_distance;
        let patch_idx = self.allocated_patches.len() as u32;

        // Lay out patches in a 1D strip for simplicity.
        // Each patch occupies d columns on a sqrt(total)-wide grid.
        let grid_side = (self.total_physical as f64).sqrt() as u32;
        let patches_per_row = if d > 0 { grid_side / d } else { 0 };
        let patches_per_row = patches_per_row.max(1);

        let x_origin = (patch_idx % patches_per_row) * d;
        let y_origin = (patch_idx / patches_per_row) * d;

        // Enumerate physical qubits in this patch.
        let qubits_per_logical = 2 * d * d - 2 * d + 1;
        let start_qubit = patch_idx * qubits_per_logical;
        let physical_qubits: Vec<u32> =
            (start_qubit..start_qubit + qubits_per_logical).collect();

        let logical_id = self.next_logical_id;
        self.next_logical_id += 1;

        let patch = SurfaceCodePatch {
            logical_id,
            physical_qubits,
            code_distance: d,
            x_origin,
            y_origin,
        };

        self.allocated_patches.push(patch.clone());
        Some(patch)
    }

    /// Deallocate a logical qubit by its logical ID.
    pub fn deallocate(&mut self, logical_id: u32) {
        self.allocated_patches
            .retain(|p| p.logical_id != logical_id);
    }

    /// Return the fraction of physical qubits currently allocated.
    pub fn utilization(&self) -> f64 {
        let d = self.code_distance as u64;
        let qubits_per_logical = 2 * d * d - 2 * d + 1;
        let used = self.allocated_patches.len() as u64 * qubits_per_logical;
        if self.total_physical == 0 {
            return 0.0;
        }
        used as f64 / self.total_physical as f64
    }

    /// Return a reference to all currently allocated patches.
    pub fn patches(&self) -> &[SurfaceCodePatch] {
        &self.allocated_patches
    }
}

// ---------------------------------------------------------------------------
// Benchmarking
// ---------------------------------------------------------------------------

/// Results from benchmarking a decoder.
#[derive(Debug, Clone)]
pub struct DecoderBenchmark {
    /// Total number of syndrome rounds decoded.
    pub total_syndromes: u64,
    /// Total wall-clock decode time in nanoseconds.
    pub total_decode_time_ns: u64,
    /// Number of corrections that preserved the logical state.
    pub correct_corrections: u64,
    /// Estimated logical error rate (errors / total).
    pub logical_error_rate: f64,
}

impl DecoderBenchmark {
    /// Average decode time per syndrome in nanoseconds.
    pub fn avg_decode_time_ns(&self) -> f64 {
        if self.total_syndromes == 0 {
            return 0.0;
        }
        self.total_decode_time_ns as f64 / self.total_syndromes as f64
    }

    /// Decoding throughput in syndromes per second.
    pub fn throughput(&self) -> f64 {
        if self.total_decode_time_ns == 0 {
            return 0.0;
        }
        self.total_syndromes as f64 / (self.total_decode_time_ns as f64 * 1e-9)
    }
}

/// Benchmark a decoder by generating random syndromes at a given
/// physical error rate and measuring decode accuracy and throughput.
///
/// For each round, we generate a random syndrome where each stabilizer
/// measurement has probability `error_rate` of being a defect. We then
/// decode and check whether the correction introduces a logical error.
///
/// A simple heuristic is used: if the syndrome has no defects, the
/// correct answer is no correction. If it does have defects, we check
/// whether the decoder's logical outcome matches the expected parity.
pub fn benchmark_decoder(
    decoder: &dyn SurfaceCodeDecoder,
    distance: u32,
    error_rate: f64,
    rounds: u32,
) -> DecoderBenchmark {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let grid_w = if distance > 1 { distance - 1 } else { 1 };
    let grid_h = if distance > 1 { distance - 1 } else { 1 };

    let mut total_decode_time_ns = 0u64;
    let mut correct_corrections = 0u64;
    let mut total_syndromes = 0u64;

    // Simple deterministic PRNG for reproducibility.
    let mut seed: u64 = 0xDEAD_BEEF_CAFE_BABE;
    let next_rand = |s: &mut u64| -> f64 {
        let mut hasher = DefaultHasher::new();
        s.hash(&mut hasher);
        *s = hasher.finish();
        // Map to [0, 1).
        (*s as f64) / (u64::MAX as f64)
    };

    for _ in 0..rounds {
        let num_syndrome_rounds = 1u32;
        let mut stabilizers = Vec::new();
        let mut expected_defect_count = 0usize;

        for r in 0..num_syndrome_rounds {
            for y in 0..grid_h {
                for x in 0..grid_w {
                    let val = next_rand(&mut seed) < error_rate;
                    if val {
                        expected_defect_count += 1;
                    }
                    stabilizers.push(StabilizerMeasurement {
                        x,
                        y,
                        round: r,
                        value: val,
                    });
                }
            }
        }

        let syndrome = SyndromeData {
            stabilizers,
            code_distance: distance,
            num_rounds: num_syndrome_rounds,
        };

        let correction = decoder.decode(&syndrome);
        total_decode_time_ns += correction.decode_time_ns;
        total_syndromes += 1;

        // Heuristic correctness check: for low error rates, if the number
        // of defects is even and < d, the decoder should succeed.
        // We consider the correction "correct" if the logical outcome
        // is false (no logical error) when the defect count is small.
        let expected_logical = expected_defect_count >= distance as usize;
        if correction.logical_outcome == expected_logical {
            correct_corrections += 1;
        }
    }

    let logical_error_rate = if total_syndromes == 0 {
        0.0
    } else {
        1.0 - (correct_corrections as f64 / total_syndromes as f64)
    };

    DecoderBenchmark {
        total_syndromes,
        total_decode_time_ns,
        correct_corrections,
        logical_error_rate,
    }
}

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

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

    // -- StabilizerMeasurement --

    #[test]
    fn test_stabilizer_measurement_creation() {
        let m = StabilizerMeasurement {
            x: 3,
            y: 5,
            round: 2,
            value: true,
        };
        assert_eq!(m.x, 3);
        assert_eq!(m.y, 5);
        assert_eq!(m.round, 2);
        assert!(m.value);
    }

    #[test]
    fn test_stabilizer_measurement_clone() {
        let m = StabilizerMeasurement {
            x: 1,
            y: 2,
            round: 0,
            value: false,
        };
        let m2 = m.clone();
        assert_eq!(m, m2);
    }

    // -- SyndromeData --

    #[test]
    fn test_syndrome_data_empty() {
        let s = SyndromeData {
            stabilizers: Vec::new(),
            code_distance: 3,
            num_rounds: 1,
        };
        assert!(s.stabilizers.is_empty());
        assert_eq!(s.code_distance, 3);
    }

    // -- PauliType --

    #[test]
    fn test_pauli_type_equality() {
        assert_eq!(PauliType::X, PauliType::X);
        assert_eq!(PauliType::Z, PauliType::Z);
        assert_ne!(PauliType::X, PauliType::Z);
    }

    // -- Correction --

    #[test]
    fn test_correction_no_errors() {
        let c = Correction {
            pauli_corrections: Vec::new(),
            logical_outcome: false,
            confidence: 1.0,
            decode_time_ns: 100,
        };
        assert!(c.pauli_corrections.is_empty());
        assert!(!c.logical_outcome);
        assert_eq!(c.confidence, 1.0);
    }

    // -- UnionFind --

    #[test]
    fn test_union_find_basic() {
        let mut uf = UnionFind::new(5);
        assert_ne!(uf.find(0), uf.find(1));
        uf.union(0, 1);
        assert_eq!(uf.find(0), uf.find(1));
        uf.union(2, 3);
        assert_eq!(uf.find(2), uf.find(3));
        assert_ne!(uf.find(0), uf.find(2));
        uf.union(1, 3);
        assert_eq!(uf.find(0), uf.find(3));
    }

    #[test]
    fn test_union_find_parity() {
        let mut uf = UnionFind::new(4);
        uf.set_parity(0, true);
        assert!(uf.cluster_parity(0));
        uf.set_parity(1, true);
        uf.union(0, 1);
        // Two defects merged: parity should be even (false).
        assert!(!uf.cluster_parity(0));
    }

    #[test]
    fn test_union_find_path_compression() {
        let mut uf = UnionFind::new(10);
        // Create a chain: 0->1->2->3->4
        for i in 0..4 {
            uf.union(i, i + 1);
        }
        // After find(0), the path should be compressed.
        let root = uf.find(0);
        assert_eq!(uf.find(4), root);
    }

    // -- UnionFindDecoder --

    #[test]
    fn test_uf_decoder_no_errors() {
        let decoder = UnionFindDecoder::new(0);
        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: false },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: false },
                StabilizerMeasurement { x: 0, y: 1, round: 0, value: false },
                StabilizerMeasurement { x: 1, y: 1, round: 0, value: false },
            ],
            code_distance: 3,
            num_rounds: 1,
        };

        let correction = decoder.decode(&syndrome);
        assert!(
            correction.pauli_corrections.is_empty(),
            "No defects should produce no corrections"
        );
        assert!(!correction.logical_outcome);
        assert_eq!(correction.confidence, 1.0);
    }

    #[test]
    fn test_uf_decoder_single_defect() {
        let decoder = UnionFindDecoder::new(0);
        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: false },
                StabilizerMeasurement { x: 0, y: 1, round: 0, value: false },
                StabilizerMeasurement { x: 1, y: 1, round: 0, value: false },
            ],
            code_distance: 3,
            num_rounds: 1,
        };

        let correction = decoder.decode(&syndrome);
        // Single defect should produce corrections to the boundary.
        assert!(
            !correction.pauli_corrections.is_empty(),
            "Single defect should produce corrections"
        );
    }

    #[test]
    fn test_uf_decoder_paired_defects() {
        let decoder = UnionFindDecoder::new(0);
        // Two adjacent defects should pair and produce corrections between them.
        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 0, y: 1, round: 0, value: false },
                StabilizerMeasurement { x: 1, y: 1, round: 0, value: false },
            ],
            code_distance: 3,
            num_rounds: 1,
        };

        let correction = decoder.decode(&syndrome);
        // Two defects should be paired; corrections connect them.
        assert!(
            !correction.pauli_corrections.is_empty(),
            "Paired defects should produce corrections"
        );
    }

    #[test]
    fn test_uf_decoder_name() {
        let decoder = UnionFindDecoder::new(5);
        assert_eq!(decoder.name(), "UnionFindDecoder");
    }

    #[test]
    fn test_uf_decoder_extract_defects_empty_syndrome() {
        let decoder = UnionFindDecoder::new(0);
        let syndrome = SyndromeData {
            stabilizers: Vec::new(),
            code_distance: 3,
            num_rounds: 1,
        };
        let defects = decoder.extract_defects(&syndrome);
        assert!(defects.is_empty());
    }

    #[test]
    fn test_uf_decoder_extract_defects_all_false() {
        let decoder = UnionFindDecoder::new(0);
        let mut stabs = Vec::new();
        for y in 0..2 {
            for x in 0..2 {
                stabs.push(StabilizerMeasurement {
                    x,
                    y,
                    round: 0,
                    value: false,
                });
            }
        }
        let syndrome = SyndromeData {
            stabilizers: stabs,
            code_distance: 3,
            num_rounds: 1,
        };
        let defects = decoder.extract_defects(&syndrome);
        assert!(defects.is_empty(), "All-false syndrome should have no defects");
    }

    #[test]
    fn test_uf_decoder_extract_defects_with_flip() {
        let decoder = UnionFindDecoder::new(0);
        let syndrome = SyndromeData {
            stabilizers: vec![
                // Round 0: (0,0)=false, (1,0)=true
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: false },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: true },
            ],
            code_distance: 3,
            num_rounds: 1,
        };
        let defects = decoder.extract_defects(&syndrome);
        // (0,0) is false (same as implicit prev=false), no defect.
        // (1,0) is true (different from prev=false), defect.
        assert_eq!(defects.len(), 1);
        assert_eq!(defects[0].x, 1);
        assert_eq!(defects[0].y, 0);
    }

    #[test]
    fn test_uf_decoder_manhattan_distance() {
        let a = Defect { x: 0, y: 0, round: 0, node_index: 0 };
        let b = Defect { x: 3, y: 4, round: 1, node_index: 1 };
        assert_eq!(UnionFindDecoder::manhattan_distance(&a, &b), 8);
    }

    #[test]
    fn test_uf_decoder_boundary_distance() {
        let d = Defect { x: 0, y: 0, round: 0, node_index: 0 };
        assert_eq!(UnionFindDecoder::boundary_distance(&d, 5), 0);

        let d2 = Defect { x: 2, y: 2, round: 0, node_index: 0 };
        assert_eq!(UnionFindDecoder::boundary_distance(&d2, 5), 1);
    }

    #[test]
    fn test_uf_decoder_multi_round() {
        let decoder = UnionFindDecoder::new(0);
        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 0, y: 0, round: 1, value: false },
            ],
            code_distance: 3,
            num_rounds: 2,
        };
        let defects = decoder.extract_defects(&syndrome);
        // Round 0: true vs implicit false -> defect
        // Round 1: false vs true -> defect
        assert_eq!(defects.len(), 2);
    }

    #[test]
    fn test_uf_decoder_confidence_decreases_with_errors() {
        let decoder = UnionFindDecoder::new(0);

        // Few defects -> high confidence.
        let syndrome_low = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: false },
                StabilizerMeasurement { x: 0, y: 1, round: 0, value: false },
                StabilizerMeasurement { x: 1, y: 1, round: 0, value: false },
            ],
            code_distance: 3,
            num_rounds: 1,
        };
        let corr_low = decoder.decode(&syndrome_low);

        // Many defects -> lower confidence.
        let syndrome_high = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 0, y: 1, round: 0, value: true },
                StabilizerMeasurement { x: 1, y: 1, round: 0, value: true },
            ],
            code_distance: 3,
            num_rounds: 1,
        };
        let corr_high = decoder.decode(&syndrome_high);

        assert!(
            corr_low.confidence >= corr_high.confidence,
            "More defects should reduce confidence: {} >= {}",
            corr_low.confidence,
            corr_high.confidence
        );
    }

    #[test]
    fn test_uf_decoder_decode_time_recorded() {
        let decoder = UnionFindDecoder::new(0);
        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
            ],
            code_distance: 3,
            num_rounds: 1,
        };
        let correction = decoder.decode(&syndrome);
        // Decode time should be recorded (non-zero on any real hardware).
        // We just check it is a valid number.
        let _ = correction.decode_time_ns;
    }

    // -- PartitionedDecoder --

    #[test]
    fn test_partitioned_decoder_no_errors() {
        let inner = Box::new(UnionFindDecoder::new(0));
        let decoder = PartitionedDecoder::new(4, inner);

        let mut stabs = Vec::new();
        for y in 0..4 {
            for x in 0..4 {
                stabs.push(StabilizerMeasurement {
                    x,
                    y,
                    round: 0,
                    value: false,
                });
            }
        }

        let syndrome = SyndromeData {
            stabilizers: stabs,
            code_distance: 5,
            num_rounds: 1,
        };

        let correction = decoder.decode(&syndrome);
        assert!(correction.pauli_corrections.is_empty());
    }

    #[test]
    fn test_partitioned_decoder_name() {
        let inner = Box::new(UnionFindDecoder::new(0));
        let decoder = PartitionedDecoder::new(4, inner);
        assert_eq!(decoder.name(), "PartitionedDecoder");
    }

    #[test]
    fn test_partitioned_decoder_single_tile() {
        // When tile_size >= grid size, should behave like inner decoder.
        let inner = Box::new(UnionFindDecoder::new(0));
        let decoder = PartitionedDecoder::new(100, inner);

        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: false },
            ],
            code_distance: 3,
            num_rounds: 1,
        };

        let correction = decoder.decode(&syndrome);
        assert!(!correction.pauli_corrections.is_empty());
    }

    #[test]
    fn test_partitioned_decoder_multi_tile() {
        let inner = Box::new(UnionFindDecoder::new(0));
        let decoder = PartitionedDecoder::new(2, inner);

        let mut stabs = Vec::new();
        for y in 0..6 {
            for x in 0..6 {
                stabs.push(StabilizerMeasurement {
                    x,
                    y,
                    round: 0,
                    value: false,
                });
            }
        }
        // Add one defect in the first tile.
        stabs[0].value = true;

        let syndrome = SyndromeData {
            stabilizers: stabs,
            code_distance: 7,
            num_rounds: 1,
        };

        let correction = decoder.decode(&syndrome);
        assert!(!correction.pauli_corrections.is_empty());
    }

    #[test]
    fn test_partitioned_decoder_partition_count() {
        let inner = Box::new(UnionFindDecoder::new(0));
        let decoder = PartitionedDecoder::new(2, inner);

        let syndrome = SyndromeData {
            stabilizers: Vec::new(),
            code_distance: 5,
            num_rounds: 1,
        };

        let tiles = decoder.partition_syndrome(&syndrome);
        // d=5 -> grid 4x4, tile_size=2 -> 2x2 = 4 tiles
        assert_eq!(tiles.len(), 4);
    }

    #[test]
    #[should_panic(expected = "tile_size must be positive")]
    fn test_partitioned_decoder_zero_tile_size() {
        let inner = Box::new(UnionFindDecoder::new(0));
        let _decoder = PartitionedDecoder::new(0, inner);
    }

    // -- AdaptiveCodeDistance --

    #[test]
    fn test_adaptive_code_distance_creation() {
        let acd = AdaptiveCodeDistance::new(5, 3, 15);
        assert_eq!(acd.current_distance, 5);
        assert_eq!(acd.min_distance, 3);
        assert_eq!(acd.max_distance, 15);
    }

    #[test]
    fn test_adaptive_code_distance_even_initial() {
        // Even initial should be bumped to next odd.
        let acd = AdaptiveCodeDistance::new(4, 3, 15);
        assert_eq!(acd.current_distance, 5);
    }

    #[test]
    fn test_adaptive_code_distance_no_data() {
        let acd = AdaptiveCodeDistance::new(5, 3, 15);
        assert_eq!(acd.recommended_distance(), 5);
        assert!(!acd.should_increase());
        assert!(!acd.should_decrease());
    }

    #[test]
    fn test_adaptive_code_distance_increase() {
        let mut acd = AdaptiveCodeDistance::new(3, 3, 15);
        // High error rate should trigger increase.
        for _ in 0..200 {
            acd.record_error_rate(0.5);
        }
        assert!(acd.should_increase());
        assert_eq!(acd.recommended_distance(), 5);
    }

    #[test]
    fn test_adaptive_code_distance_decrease() {
        let mut acd = AdaptiveCodeDistance::new(9, 3, 15);
        // Very low error rate with enough data should trigger decrease.
        for _ in 0..200 {
            acd.record_error_rate(1e-10);
        }
        assert!(acd.should_decrease());
        assert_eq!(acd.recommended_distance(), 7);
    }

    #[test]
    fn test_adaptive_code_distance_stable() {
        let mut acd = AdaptiveCodeDistance::new(5, 3, 15);
        // Moderate error rate should not trigger changes.
        // Threshold for d=5 is ~0.0046, for d=3 is ~0.046.
        // Use a rate between them.
        for _ in 0..200 {
            acd.record_error_rate(0.001);
        }
        // At 0.001: above threshold*0.1 for d=3 (0.0046), so should not decrease.
        // Below threshold for d=5 (0.0046), so should not increase.
        assert!(!acd.should_increase());
    }

    #[test]
    fn test_adaptive_code_distance_at_max() {
        let mut acd = AdaptiveCodeDistance::new(15, 3, 15);
        for _ in 0..200 {
            acd.record_error_rate(0.9);
        }
        assert!(!acd.should_increase(), "Cannot increase past max");
        assert_eq!(acd.recommended_distance(), 15);
    }

    #[test]
    fn test_adaptive_code_distance_at_min() {
        let mut acd = AdaptiveCodeDistance::new(3, 3, 15);
        for _ in 0..200 {
            acd.record_error_rate(1e-15);
        }
        assert!(!acd.should_decrease(), "Cannot decrease past min");
    }

    #[test]
    fn test_adaptive_code_distance_record_clamps() {
        let mut acd = AdaptiveCodeDistance::new(5, 3, 15);
        acd.record_error_rate(2.0);
        acd.record_error_rate(-1.0);
        // Should not panic; values are clamped.
        assert_eq!(acd.error_history.len(), 2);
        assert_eq!(acd.error_history[0], 1.0);
        assert_eq!(acd.error_history[1], 0.0);
    }

    #[test]
    fn test_adaptive_code_distance_window_trimming() {
        let mut acd = AdaptiveCodeDistance::new(5, 3, 15);
        for i in 0..500 {
            acd.record_error_rate(i as f64 * 0.001);
        }
        // History should be trimmed to roughly window_size.
        assert!(acd.error_history.len() <= acd.window_size * 2);
    }

    #[test]
    #[should_panic(expected = "min_distance must be <= max_distance")]
    fn test_adaptive_code_distance_invalid_range() {
        let _acd = AdaptiveCodeDistance::new(5, 10, 3);
    }

    // -- SurfaceCodePatch --

    #[test]
    fn test_surface_code_patch_creation() {
        let patch = SurfaceCodePatch {
            logical_id: 0,
            physical_qubits: vec![0, 1, 2, 3, 4],
            code_distance: 3,
            x_origin: 0,
            y_origin: 0,
        };
        assert_eq!(patch.logical_id, 0);
        assert_eq!(patch.physical_qubits.len(), 5);
    }

    // -- LogicalQubitAllocator --

    #[test]
    fn test_allocator_creation() {
        let alloc = LogicalQubitAllocator::new(1000, 3);
        assert_eq!(alloc.total_physical, 1000);
        assert_eq!(alloc.code_distance, 3);
        assert!(alloc.patches().is_empty());
    }

    #[test]
    fn test_allocator_max_logical_qubits() {
        // d=3: 2*9 - 6 + 1 = 13 qubits per logical
        let alloc = LogicalQubitAllocator::new(100, 3);
        assert_eq!(alloc.max_logical_qubits(), 7); // floor(100/13)
    }

    #[test]
    fn test_allocator_max_logical_qubits_d5() {
        // d=5: 2*25 - 10 + 1 = 41 qubits per logical
        let alloc = LogicalQubitAllocator::new(1000, 5);
        assert_eq!(alloc.max_logical_qubits(), 24); // floor(1000/41)
    }

    #[test]
    fn test_allocator_allocate_and_deallocate() {
        let mut alloc = LogicalQubitAllocator::new(100, 3);
        let patch = alloc.allocate().unwrap();
        assert_eq!(patch.logical_id, 0);
        assert_eq!(patch.code_distance, 3);
        assert_eq!(patch.physical_qubits.len(), 13);
        assert_eq!(alloc.patches().len(), 1);

        alloc.deallocate(0);
        assert!(alloc.patches().is_empty());
    }

    #[test]
    fn test_allocator_multiple_allocations() {
        let mut alloc = LogicalQubitAllocator::new(100, 3);
        let max = alloc.max_logical_qubits();
        for i in 0..max {
            let patch = alloc.allocate();
            assert!(patch.is_some(), "Should allocate patch {}", i);
        }
        // Next allocation should fail.
        assert!(alloc.allocate().is_none(), "Should be out of space");
    }

    #[test]
    fn test_allocator_utilization() {
        let mut alloc = LogicalQubitAllocator::new(100, 3);
        assert_eq!(alloc.utilization(), 0.0);

        alloc.allocate();
        let expected = 13.0 / 100.0;
        assert!((alloc.utilization() - expected).abs() < 1e-10);
    }

    #[test]
    fn test_allocator_deallocate_nonexistent() {
        let mut alloc = LogicalQubitAllocator::new(100, 3);
        alloc.allocate();
        alloc.deallocate(999); // Should not panic.
        assert_eq!(alloc.patches().len(), 1);
    }

    #[test]
    fn test_allocator_utilization_zero_physical() {
        let alloc = LogicalQubitAllocator::new(0, 3);
        assert_eq!(alloc.utilization(), 0.0);
        assert_eq!(alloc.max_logical_qubits(), 0);
    }

    #[test]
    fn test_allocator_reallocate_after_dealloc() {
        let mut alloc = LogicalQubitAllocator::new(26, 3);
        // Can allocate 2 (26/13 = 2).
        let p0 = alloc.allocate().unwrap();
        let _p1 = alloc.allocate().unwrap();
        assert!(alloc.allocate().is_none());

        alloc.deallocate(p0.logical_id);
        // Should be able to allocate one more.
        let p2 = alloc.allocate();
        assert!(p2.is_some());
    }

    // -- DecoderBenchmark --

    #[test]
    fn test_decoder_benchmark_empty() {
        let b = DecoderBenchmark {
            total_syndromes: 0,
            total_decode_time_ns: 0,
            correct_corrections: 0,
            logical_error_rate: 0.0,
        };
        assert_eq!(b.avg_decode_time_ns(), 0.0);
        assert_eq!(b.throughput(), 0.0);
    }

    #[test]
    fn test_decoder_benchmark_avg_time() {
        let b = DecoderBenchmark {
            total_syndromes: 100,
            total_decode_time_ns: 1_000_000,
            correct_corrections: 95,
            logical_error_rate: 0.05,
        };
        assert!((b.avg_decode_time_ns() - 10_000.0).abs() < 1e-6);
    }

    #[test]
    fn test_decoder_benchmark_throughput() {
        let b = DecoderBenchmark {
            total_syndromes: 1000,
            total_decode_time_ns: 1_000_000_000, // 1 second
            correct_corrections: 999,
            logical_error_rate: 0.001,
        };
        assert!((b.throughput() - 1000.0).abs() < 1e-6);
    }

    #[test]
    fn test_benchmark_decoder_runs() {
        let decoder = UnionFindDecoder::new(0);
        let result = benchmark_decoder(&decoder, 3, 0.01, 10);
        assert_eq!(result.total_syndromes, 10);
        assert!(result.logical_error_rate >= 0.0);
        assert!(result.logical_error_rate <= 1.0);
    }

    #[test]
    fn test_benchmark_decoder_zero_error_rate() {
        let decoder = UnionFindDecoder::new(0);
        let result = benchmark_decoder(&decoder, 3, 0.0, 20);
        assert_eq!(result.total_syndromes, 20);
        // With zero error rate, all syndromes should have no defects.
        // The decoder should always return no logical error.
        assert_eq!(result.correct_corrections, 20);
        assert_eq!(result.logical_error_rate, 0.0);
    }

    #[test]
    fn test_benchmark_decoder_high_error_rate() {
        let decoder = UnionFindDecoder::new(0);
        let result = benchmark_decoder(&decoder, 3, 0.9, 50);
        assert_eq!(result.total_syndromes, 50);
        // With very high error rate, logical error rate should be significant.
        // Just verify it ran without panic.
        assert!(result.logical_error_rate >= 0.0);
    }

    #[test]
    fn test_benchmark_decoder_zero_rounds() {
        let decoder = UnionFindDecoder::new(0);
        let result = benchmark_decoder(&decoder, 3, 0.01, 0);
        assert_eq!(result.total_syndromes, 0);
        assert_eq!(result.logical_error_rate, 0.0);
    }

    // -- Integration tests --

    #[test]
    fn test_uf_decoder_distance_5() {
        let decoder = UnionFindDecoder::new(0);
        let mut stabs = Vec::new();
        for y in 0..4 {
            for x in 0..4 {
                stabs.push(StabilizerMeasurement {
                    x,
                    y,
                    round: 0,
                    value: false,
                });
            }
        }
        // Single defect at center.
        stabs[5].value = true; // (1, 1)

        let syndrome = SyndromeData {
            stabilizers: stabs,
            code_distance: 5,
            num_rounds: 1,
        };
        let correction = decoder.decode(&syndrome);
        assert!(!correction.pauli_corrections.is_empty());
    }

    #[test]
    fn test_partitioned_matches_uf_small() {
        // For a single tile, partitioned decoder should produce similar
        // results to the inner decoder.
        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
                StabilizerMeasurement { x: 1, y: 0, round: 0, value: false },
                StabilizerMeasurement { x: 0, y: 1, round: 0, value: false },
                StabilizerMeasurement { x: 1, y: 1, round: 0, value: false },
            ],
            code_distance: 3,
            num_rounds: 1,
        };

        let uf = UnionFindDecoder::new(0);
        let corr_uf = uf.decode(&syndrome);

        let partitioned = PartitionedDecoder::new(10, Box::new(UnionFindDecoder::new(0)));
        let corr_part = partitioned.decode(&syndrome);

        // Both should produce corrections for the same defect.
        assert_eq!(
            corr_uf.pauli_corrections.is_empty(),
            corr_part.pauli_corrections.is_empty()
        );
    }

    #[test]
    fn test_decoder_trait_object() {
        // Verify trait object usage compiles and works.
        let decoders: Vec<Box<dyn SurfaceCodeDecoder>> = vec![
            Box::new(UnionFindDecoder::new(0)),
            Box::new(PartitionedDecoder::new(4, Box::new(UnionFindDecoder::new(0)))),
        ];

        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: false },
            ],
            code_distance: 3,
            num_rounds: 1,
        };

        for decoder in &decoders {
            let correction = decoder.decode(&syndrome);
            assert!(!decoder.name().is_empty());
            assert!(correction.confidence >= 0.0);
        }
    }

    #[test]
    fn test_logical_outcome_parity() {
        // Even number of X corrections -> logical_outcome = false.
        assert!(!UnionFindDecoder::infer_logical_outcome(&[
            (0, PauliType::X),
            (1, PauliType::X),
        ]));
        // Odd number of X corrections -> logical_outcome = true.
        assert!(UnionFindDecoder::infer_logical_outcome(&[
            (0, PauliType::X),
        ]));
        // Z corrections don't affect X logical outcome.
        assert!(!UnionFindDecoder::infer_logical_outcome(&[
            (0, PauliType::Z),
            (1, PauliType::Z),
            (2, PauliType::Z),
        ]));
    }

    #[test]
    fn test_distance_1_code() {
        // Distance-1 code is degenerate but should not panic.
        let decoder = UnionFindDecoder::new(0);
        let syndrome = SyndromeData {
            stabilizers: vec![
                StabilizerMeasurement { x: 0, y: 0, round: 0, value: true },
            ],
            code_distance: 1,
            num_rounds: 1,
        };
        let correction = decoder.decode(&syndrome);
        let _ = correction; // Just ensure no panic.
    }

    #[test]
    fn test_large_code_distance() {
        let decoder = UnionFindDecoder::new(0);
        let d = 11u32;
        let grid = d - 1;
        let mut stabs = Vec::new();
        for y in 0..grid {
            for x in 0..grid {
                stabs.push(StabilizerMeasurement {
                    x,
                    y,
                    round: 0,
                    value: false,
                });
            }
        }
        // Two defects far apart.
        stabs[0].value = true;
        stabs[(grid * grid - 1) as usize].value = true;

        let syndrome = SyndromeData {
            stabilizers: stabs,
            code_distance: d,
            num_rounds: 1,
        };
        let correction = decoder.decode(&syndrome);
        assert!(!correction.pauli_corrections.is_empty());
    }
}