quantrs2-circuit 0.2.1

Quantum circuit representation and DSL for the QuantRS2 framework
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
//! Auto-generated module
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)

use crate::builder::Circuit;
use quantrs2_core::{
    buffer_pool::BufferPool,
    error::{QuantRS2Error, QuantRS2Result},
    gate::GateOp,
    qubit::QubitId,
};
pub use scirs2_core::Complex64;
use scirs2_core::{
    parallel_ops::{IndexedParallelIterator, ParallelIterator},
    simd_ops::*,
};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;

pub struct BLAS;
impl BLAS {
    /// Check whether two sparse matrices are approximately equal entry-wise within `tol`.
    /// For each entry present in either matrix the corresponding value in the other is
    /// treated as zero when absent, and the element-wise difference must satisfy |diff| ≤ tol.
    #[must_use]
    pub fn matrix_approx_equal(
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
        tol: f64,
    ) -> bool {
        if a.shape != b.shape {
            return false;
        }
        let mut b_map: HashMap<(usize, usize), Complex64> = HashMap::with_capacity(b.data.len());
        for &(r, c, v) in &b.data {
            b_map.insert((r, c), v);
        }
        for &(r, c, va) in &a.data {
            let vb = b_map.remove(&(r, c)).unwrap_or(Complex64::new(0.0, 0.0));
            if (va - vb).norm() > tol {
                return false;
            }
        }
        for (_, vb) in b_map {
            if vb.norm() > tol {
                return false;
            }
        }
        true
    }
    /// 2-norm condition number `σ_max / σ_min` from the singular values.
    /// Returns `f64::INFINITY` for a singular (or empty) matrix.
    #[must_use]
    pub fn condition_number(matrix: &SciRSSparseMatrix<Complex64>) -> f64 {
        let (dense, rows, cols) = densify(matrix);
        if rows == 0 || cols == 0 {
            return f64::INFINITY;
        }
        let sv = singular_values_dense(&dense, rows, cols);
        let smax = sv.first().copied().unwrap_or(0.0);
        let smin = sv.last().copied().unwrap_or(0.0);
        if smax == 0.0 || smin <= smax * 1e-15 {
            f64::INFINITY
        } else {
            smax / smin
        }
    }
    #[must_use]
    pub fn is_symmetric(matrix: &SciRSSparseMatrix<Complex64>, tol: f64) -> bool {
        if matrix.shape.0 != matrix.shape.1 {
            return false;
        }
        for (row, col, value) in &matrix.data {
            let transpose_entry = matrix
                .data
                .iter()
                .find(|(r, c, _)| *r == *col && *c == *row);
            match transpose_entry {
                Some((_, _, transpose_value)) => {
                    if (value - transpose_value).norm() > tol {
                        return false;
                    }
                }
                None => {
                    if value.norm() > tol {
                        return false;
                    }
                }
            }
        }
        true
    }
    #[must_use]
    pub fn is_hermitian(matrix: &SciRSSparseMatrix<Complex64>, tol: f64) -> bool {
        if matrix.shape.0 != matrix.shape.1 {
            return false;
        }
        for (row, col, value) in &matrix.data {
            let conj_transpose_entry = matrix
                .data
                .iter()
                .find(|(r, c, _)| *r == *col && *c == *row);
            match conj_transpose_entry {
                Some((_, _, conj_transpose_value)) => {
                    if (value - conj_transpose_value.conj()).norm() > tol {
                        return false;
                    }
                }
                None => {
                    if value.norm() > tol {
                        return false;
                    }
                }
            }
        }
        true
    }
    /// A matrix is positive definite iff it is Hermitian and every eigenvalue is
    /// strictly positive.
    #[must_use]
    pub fn is_positive_definite(matrix: &SciRSSparseMatrix<Complex64>) -> bool {
        if !Self::is_hermitian(matrix, 1e-12) {
            return false;
        }
        let (dense, rows, cols) = densify(matrix);
        if rows == 0 || rows != cols {
            return false;
        }
        hermitian_eigenvalues_dense(&dense, rows)
            .iter()
            .all(|&e| e > 1e-12)
    }
    /// Matrix norm computed from the actual entries.  Supported `norm_type`
    /// values: `"1"`/`"one"` (max column sum), `"inf"`/`"infinity"` (max row
    /// sum), `"max"` (largest magnitude entry), `"2"`/`"spectral"` (largest
    /// singular value); any other value yields the Frobenius norm.
    #[must_use]
    pub fn matrix_norm(matrix: &SciRSSparseMatrix<Complex64>, norm_type: &str) -> f64 {
        match norm_type {
            "1" | "one" | "L1" => {
                let mut col_sums: HashMap<usize, f64> = HashMap::new();
                for &(_, c, v) in &matrix.data {
                    *col_sums.entry(c).or_insert(0.0) += v.norm();
                }
                col_sums.values().copied().fold(0.0, f64::max)
            }
            "inf" | "infinity" | "Linf" => {
                let mut row_sums: HashMap<usize, f64> = HashMap::new();
                for &(r, _, v) in &matrix.data {
                    *row_sums.entry(r).or_insert(0.0) += v.norm();
                }
                row_sums.values().copied().fold(0.0, f64::max)
            }
            "max" => matrix
                .data
                .iter()
                .map(|(_, _, v)| v.norm())
                .fold(0.0, f64::max),
            "2" | "spectral" => {
                let (dense, rows, cols) = densify(matrix);
                singular_values_dense(&dense, rows, cols)
                    .first()
                    .copied()
                    .unwrap_or(0.0)
            }
            _ => matrix
                .data
                .iter()
                .map(|(_, _, v)| v.norm_sqr())
                .sum::<f64>()
                .sqrt(),
        }
    }
    /// Numerical rank: the number of singular values above `tol` (with a relative
    /// safety floor scaled by the largest singular value and machine epsilon).
    #[must_use]
    pub fn numerical_rank(matrix: &SciRSSparseMatrix<Complex64>, tol: f64) -> usize {
        let (dense, rows, cols) = densify(matrix);
        if rows == 0 || cols == 0 {
            return 0;
        }
        let sv = singular_values_dense(&dense, rows, cols);
        let smax = sv.first().copied().unwrap_or(0.0);
        let threshold = tol.max(smax * (rows.max(cols) as f64) * f64::EPSILON);
        sv.iter().filter(|&&s| s > threshold).count()
    }
    /// Spectral radius (largest eigenvalue magnitude, via power iteration) and the
    /// eigenvalue-magnitude spread `max|λ| − min|λ|` (min via inverse iteration).
    #[must_use]
    pub fn spectral_analysis(matrix: &SciRSSparseMatrix<Complex64>) -> SpectralAnalysis {
        let (dense, rows, cols) = densify(matrix);
        if rows == 0 || rows != cols {
            return SpectralAnalysis {
                spectral_radius: 0.0,
                eigenvalue_spread: 0.0,
            };
        }
        let radius = spectral_radius_dense(&dense, rows);
        let min_mag = min_eig_magnitude_dense(&dense, rows);
        SpectralAnalysis {
            spectral_radius: radius,
            eigenvalue_spread: (radius - min_mag).max(0.0),
        }
    }
    /// Average gate fidelity between two gates, `F_avg = (d·F_pro + 1)/(d + 1)`
    /// with process fidelity `F_pro = |Tr(A† B)|² / d²`.  Equals `1` for
    /// identical unitaries.
    #[must_use]
    pub fn gate_fidelity(
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
    ) -> f64 {
        let d = a.shape.0;
        if d == 0 || a.shape != b.shape {
            return 0.0;
        }
        let f_pro = frobenius_inner(a, b).norm_sqr() / (d as f64 * d as f64);
        let dd = d as f64;
        (dd * f_pro + 1.0) / (dd + 1.0)
    }
    /// Trace-norm distance `½‖A − B‖₁ = ½ Σ σ_i(A − B)` (half the sum of the
    /// singular values of the difference).  Zero for identical operands.
    #[must_use]
    pub fn trace_distance(
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
    ) -> f64 {
        if a.shape != b.shape {
            return f64::INFINITY;
        }
        let (da, rows, cols) = densify(a);
        let (db, _, _) = densify(b);
        let diff: Vec<Complex64> = da.iter().zip(db.iter()).map(|(x, y)| x - y).collect();
        0.5 * singular_values_dense(&diff, rows, cols).iter().sum::<f64>()
    }
    /// Diamond-norm distance between the unitary channels defined by `A` and `B`
    /// (exact for unitary operands), from the eigenvalues of `W = A† B`.
    #[must_use]
    pub fn diamond_distance(
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
    ) -> f64 {
        if a.shape != b.shape || a.shape.0 == 0 {
            return 0.0;
        }
        let n = a.shape.0;
        let (da, _, _) = densify(a);
        let (db, _, _) = densify(b);
        // W = A† B
        let mut w = vec![Complex64::new(0.0, 0.0); n * n];
        for i in 0..n {
            for j in 0..n {
                let mut acc = Complex64::new(0.0, 0.0);
                for k in 0..n {
                    acc += da[k * n + i].conj() * db[k * n + j];
                }
                w[i * n + j] = acc;
            }
        }
        hull_diamond_distance(&normal_eigenvalues_dense(&w, n))
    }
    /// Process (entanglement) fidelity `F_pro = |Tr(A† B)|² / d²`.  Equals `1` for
    /// identical unitaries.
    #[must_use]
    pub fn process_fidelity(
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
    ) -> f64 {
        let d = a.shape.0;
        if d == 0 || a.shape != b.shape {
            return 0.0;
        }
        frobenius_inner(a, b).norm_sqr() / (d as f64 * d as f64)
    }
    /// Leading-order coherent/incoherent split of the average-gate infidelity
    /// between actual `A` and ideal `B`.  From the eigenphases `{θ_k}` of the
    /// error unitary `W = B† A`, the coherent part scales with the squared mean
    /// phase `⟨θ⟩²` (a systematic over-rotation) and the incoherent part with the
    /// phase variance `Var(θ)`; both vanish when `A == B`.
    #[must_use]
    pub fn error_decomposition(
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
    ) -> ErrorDecomposition {
        let n = a.shape.0;
        if n == 0 || a.shape != b.shape {
            return ErrorDecomposition {
                coherent_component: 0.0,
                incoherent_component: 0.0,
            };
        }
        let (da, _, _) = densify(a);
        let (db, _, _) = densify(b);
        // W = B† A
        let mut w = vec![Complex64::new(0.0, 0.0); n * n];
        for i in 0..n {
            for j in 0..n {
                let mut acc = Complex64::new(0.0, 0.0);
                for k in 0..n {
                    acc += db[k * n + i].conj() * da[k * n + j];
                }
                w[i * n + j] = acc;
            }
        }
        let phases: Vec<f64> = normal_eigenvalues_dense(&w, n)
            .iter()
            .map(|z| z.arg())
            .collect();
        let d = n as f64;
        let mean = phases.iter().sum::<f64>() / d;
        let mean_sq = phases.iter().map(|p| p * p).sum::<f64>() / d;
        let var = (mean_sq - mean * mean).max(0.0);
        let pref = d / (d + 1.0);
        ErrorDecomposition {
            coherent_component: pref * mean * mean,
            incoherent_component: pref * var,
        }
    }
    pub const fn sparse_matvec(
        _matrix: &SciRSSparseMatrix<Complex64>,
        _vector: &VectorizedOps,
    ) -> QuantRS2Result<VectorizedOps> {
        Ok(VectorizedOps)
    }
    /// Matrix exponential `exp(scale · matrix)` via dense scaling-and-squaring.
    pub fn matrix_exp(
        matrix: &SciRSSparseMatrix<Complex64>,
        scale: f64,
    ) -> QuantRS2Result<SciRSSparseMatrix<Complex64>> {
        let (rows, cols) = matrix.shape;
        if rows != cols {
            return Err(QuantRS2Error::InvalidInput(
                "Matrix exponentiation requires a square matrix".to_string(),
            ));
        }
        let (dense, _, _) = densify(matrix);
        let expm = expm_dense(&dense, rows, scale);
        let mut result = SciRSSparseMatrix::new(rows, cols);
        for i in 0..rows {
            for j in 0..cols {
                let value = expm[i * cols + j];
                if value.norm() > 1e-15 {
                    result.insert(i, j, value);
                }
            }
        }
        Ok(result)
    }
}
pub struct SparsityPattern;
impl SparsityPattern {
    #[must_use]
    pub const fn analyze(_matrix: &SciRSSparseMatrix<Complex64>) -> Self {
        Self
    }
    #[must_use]
    pub const fn estimate_compression_ratio(&self) -> f64 {
        0.5
    }
    #[must_use]
    pub const fn bandwidth(&self) -> usize {
        10
    }
    #[must_use]
    pub const fn is_diagonal(&self) -> bool {
        false
    }
    #[must_use]
    pub const fn has_block_structure(&self) -> bool {
        false
    }
    #[must_use]
    pub const fn is_gpu_suitable(&self) -> bool {
        false
    }
    #[must_use]
    pub const fn is_simd_aligned(&self) -> bool {
        true
    }
    #[must_use]
    pub const fn sparsity(&self) -> f64 {
        0.1
    }
    #[must_use]
    pub const fn has_row_major_access(&self) -> bool {
        true
    }
    #[must_use]
    pub const fn analyze_access_patterns(&self) -> AccessPatterns {
        AccessPatterns
    }
}
pub struct VectorizedOps;
impl VectorizedOps {
    #[must_use]
    pub const fn from_slice(_slice: &[Complex64]) -> Self {
        Self
    }
    pub const fn copy_to_slice(&self, _slice: &mut [Complex64]) {}
}
pub struct ParallelMatrixOps;
impl ParallelMatrixOps {
    #[must_use]
    pub const fn kronecker_product(
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
    ) -> SciRSSparseMatrix<Complex64> {
        SciRSSparseMatrix::new(a.shape.0 * b.shape.0, a.shape.1 * b.shape.1)
    }
    pub fn batch_optimize(
        matrices: &[SparseMatrix],
        _simd_ops: &Arc<SimdOperations>,
        _buffer_pool: &Arc<quantrs2_core::buffer_pool::BufferPool<Complex64>>,
    ) -> Vec<SparseMatrix> {
        matrices.to_vec()
    }
}
/// Enhanced performance metrics for sparse matrix operations
#[derive(Debug, Clone)]
pub struct SparseMatrixMetrics {
    pub operation_time: std::time::Duration,
    pub memory_usage: usize,
    pub compression_ratio: f64,
    pub simd_utilization: f64,
    pub cache_hits: usize,
}
#[derive(Debug, Clone)]
pub struct SciRSSparseMatrix<T> {
    data: Vec<(usize, usize, T)>,
    shape: (usize, usize),
}
impl<T: Clone> SciRSSparseMatrix<T> {
    #[must_use]
    pub const fn new(rows: usize, cols: usize) -> Self {
        Self {
            data: Vec::new(),
            shape: (rows, cols),
        }
    }
    #[must_use]
    pub fn identity(size: usize) -> Self
    where
        T: From<f64> + Default,
    {
        let mut matrix = Self::new(size, size);
        for i in 0..size {
            matrix.data.push((i, i, T::from(1.0)));
        }
        matrix
    }
    pub fn insert(&mut self, row: usize, col: usize, value: T) {
        self.data.push((row, col, value));
    }
    #[must_use]
    pub fn nnz(&self) -> usize {
        self.data.len()
    }
    /// Read-only view of the stored `(row, col, value)` triplets (COO format).
    #[must_use]
    pub fn triplets(&self) -> &[(usize, usize, T)] {
        &self.data
    }
}
impl SciRSSparseMatrix<Complex64> {
    /// Sparse matrix multiplication using COO-format accumulation.
    /// Computes C = A * B where entries are accumulated by (row, col) key.
    pub fn matmul(&self, other: &Self) -> QuantRS2Result<Self> {
        if self.shape.1 != other.shape.0 {
            return Err(QuantRS2Error::InvalidInput(format!(
                "Matrix dimension mismatch: ({},{}) * ({},{})",
                self.shape.0, self.shape.1, other.shape.0, other.shape.1
            )));
        }
        let mut acc: HashMap<(usize, usize), Complex64> = HashMap::new();
        for &(i, k, a_ik) in &self.data {
            for &(k2, j, b_kj) in &other.data {
                if k == k2 {
                    *acc.entry((i, j)).or_insert(Complex64::new(0.0, 0.0)) += a_ik * b_kj;
                }
            }
        }
        let mut result = Self::new(self.shape.0, other.shape.1);
        result.data = acc
            .into_iter()
            .filter(|(_, v)| v.norm() > 1e-300)
            .map(|((r, c), v)| (r, c, v))
            .collect();
        Ok(result)
    }
    #[must_use]
    pub fn transpose_optimized(&self) -> Self {
        let mut result = Self::new(self.shape.1, self.shape.0);
        result.data = self.data.iter().map(|&(r, c, v)| (c, r, v)).collect();
        result
    }
    /// Conjugate transpose (Hermitian adjoint U†): swap indices and conjugate values.
    #[must_use]
    pub fn hermitian_conjugate(&self) -> Self {
        let mut result = Self::new(self.shape.1, self.shape.0);
        result.data = self
            .data
            .iter()
            .map(|&(r, c, v)| (c, r, v.conj()))
            .collect();
        result
    }
    #[must_use]
    pub fn convert_to_format(&self, _format: SciRSSparseFormat) -> Self {
        self.clone()
    }
    pub fn compress(&self, _level: CompressionLevel) -> QuantRS2Result<Self> {
        Ok(self.clone())
    }
    #[must_use]
    pub fn memory_footprint(&self) -> usize {
        self.data.len() * std::mem::size_of::<(usize, usize, Complex64)>()
    }
}
/// Circuit to sparse matrix converter
pub struct CircuitToSparseMatrix {
    gate_library: Arc<SparseGateLibrary>,
}
impl CircuitToSparseMatrix {
    /// Create a new converter
    #[must_use]
    pub fn new() -> Self {
        Self {
            gate_library: Arc::new(SparseGateLibrary::new()),
        }
    }
    /// Convert circuit to sparse matrix representation
    pub fn convert<const N: usize>(&self, circuit: &Circuit<N>) -> QuantRS2Result<SparseMatrix> {
        let matrix_size = 1usize << N;
        let mut result = SparseMatrix::identity(matrix_size);
        for gate in circuit.gates() {
            let gate_matrix = self.gate_to_sparse_matrix(gate.as_ref(), N)?;
            result = gate_matrix.matmul(&result)?;
        }
        Ok(result)
    }
    /// Convert single gate to sparse matrix
    fn gate_to_sparse_matrix(
        &self,
        gate: &dyn GateOp,
        total_qubits: usize,
    ) -> QuantRS2Result<SparseMatrix> {
        let gate_name = gate.name();
        let qubits = gate.qubits();
        match qubits.len() {
            1 => {
                let target_qubit = qubits[0].id() as usize;
                self.gate_library
                    .embed_single_qubit_gate(gate_name, target_qubit, total_qubits)
            }
            2 => {
                let control_qubit = qubits[0].id() as usize;
                let target_qubit = qubits[1].id() as usize;
                self.gate_library.embed_two_qubit_gate(
                    gate_name,
                    control_qubit,
                    target_qubit,
                    total_qubits,
                )
            }
            _ => Err(QuantRS2Error::InvalidInput(
                "Multi-qubit gates beyond 2 qubits not yet supported".to_string(),
            )),
        }
    }
    /// Get gate library
    #[must_use]
    pub fn gate_library(&self) -> &SparseGateLibrary {
        &self.gate_library
    }
}
/// Advanced sparse matrix optimization utilities with `SciRS2` integration
pub struct SparseOptimizer {
    simd_ops: Arc<SimdOperations>,
    buffer_pool: Arc<BufferPool<Complex64>>,
    optimization_cache: HashMap<String, SparseMatrix>,
}
impl SparseOptimizer {
    /// Create new optimizer with `SciRS2` acceleration
    #[must_use]
    pub fn new() -> Self {
        Self {
            simd_ops: Arc::new(SimdOperations::new()),
            buffer_pool: Arc::new(quantrs2_core::buffer_pool::BufferPool::new()),
            optimization_cache: HashMap::new(),
        }
    }
    /// Advanced sparse matrix optimization with `SciRS2`
    #[must_use]
    pub fn optimize_sparsity(&self, matrix: &SparseMatrix, threshold: f64) -> SparseMatrix {
        let start_time = Instant::now();
        let mut optimized = matrix.clone();
        optimized.inner = self.simd_ops.threshold_filter(&matrix.inner, threshold);
        let analysis = optimized.analyze_structure();
        if analysis.compression_potential > 0.5 {
            let _ = optimized.compress(CompressionLevel::High);
        }
        if analysis.recommended_format != optimized.format {
            optimized = optimized.to_format(analysis.recommended_format);
        }
        optimized.metrics.operation_time += start_time.elapsed();
        optimized
    }
    /// Advanced format optimization using `SciRS2` analysis
    #[must_use]
    pub fn find_optimal_format(&self, matrix: &SparseMatrix) -> SparseFormat {
        let analysis = matrix.analyze_structure();
        let pattern = SparsityPattern::analyze(&matrix.inner);
        let access_patterns = pattern.analyze_access_patterns();
        let performance_prediction = self.simd_ops.predict_format_performance(&pattern);
        if self.simd_ops.has_advanced_simd() && analysis.sparsity < 0.5 {
            return SparseFormat::SIMDAligned;
        }
        if matrix.shape.0 > 1000 && matrix.shape.1 > 1000 && self.simd_ops.has_gpu_support() {
            return SparseFormat::GPUOptimized;
        }
        performance_prediction.best_format
    }
    /// Comprehensive gate matrix analysis using `SciRS2`
    #[must_use]
    pub fn analyze_gate_properties(&self, matrix: &SparseMatrix) -> GateProperties {
        let start_time = Instant::now();
        let structure_analysis = matrix.analyze_structure();
        let spectral_analysis = BLAS::spectral_analysis(&matrix.inner);
        let matrix_norm = BLAS::matrix_norm(&matrix.inner, "frobenius");
        let numerical_rank = BLAS::numerical_rank(&matrix.inner, 1e-12);
        GateProperties {
            is_unitary: matrix.is_unitary(1e-12),
            is_hermitian: BLAS::is_hermitian(&matrix.inner, 1e-12),
            sparsity: structure_analysis.sparsity,
            condition_number: structure_analysis.condition_number,
            spectral_radius: spectral_analysis.spectral_radius,
            matrix_norm,
            numerical_rank,
            eigenvalue_spread: spectral_analysis.eigenvalue_spread,
            structure_analysis,
        }
    }
    /// Batch optimization for multiple matrices
    pub fn batch_optimize(&mut self, matrices: &[SparseMatrix]) -> Vec<SparseMatrix> {
        let start_time = Instant::now();
        let optimized =
            ParallelMatrixOps::batch_optimize(matrices, &self.simd_ops, &self.buffer_pool);
        println!(
            "Batch optimized {} matrices in {:?}",
            matrices.len(),
            start_time.elapsed()
        );
        optimized
    }
    /// Cache frequently used matrices for performance
    pub fn cache_matrix(&mut self, key: String, matrix: SparseMatrix) {
        self.optimization_cache.insert(key, matrix);
    }
    /// Retrieve cached matrix
    #[must_use]
    pub fn get_cached_matrix(&self, key: &str) -> Option<&SparseMatrix> {
        self.optimization_cache.get(key)
    }
    /// Clear optimization cache
    pub fn clear_cache(&mut self) {
        self.optimization_cache.clear();
    }
}
#[derive(Debug, Clone)]
pub struct SimdOperations;
impl SimdOperations {
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
    pub const fn sparse_matmul(
        &self,
        _a: &SciRSSparseMatrix<Complex64>,
        _b: &SciRSSparseMatrix<Complex64>,
    ) -> QuantRS2Result<SciRSSparseMatrix<Complex64>> {
        Ok(SciRSSparseMatrix::new(1, 1))
    }
    #[must_use]
    pub fn transpose_simd(
        &self,
        matrix: &SciRSSparseMatrix<Complex64>,
    ) -> SciRSSparseMatrix<Complex64> {
        matrix.clone()
    }
    #[must_use]
    pub fn hermitian_conjugate_simd(
        &self,
        matrix: &SciRSSparseMatrix<Complex64>,
    ) -> SciRSSparseMatrix<Complex64> {
        matrix.clone()
    }
    #[must_use]
    pub fn matrices_approx_equal(
        &self,
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
        tol: f64,
    ) -> bool {
        BLAS::matrix_approx_equal(a, b, tol)
    }
    /// Drop entries whose magnitude is below `threshold`.
    #[must_use]
    pub fn threshold_filter(
        &self,
        matrix: &SciRSSparseMatrix<Complex64>,
        threshold: f64,
    ) -> SciRSSparseMatrix<Complex64> {
        let mut result = SciRSSparseMatrix::new(matrix.shape.0, matrix.shape.1);
        for &(r, c, v) in &matrix.data {
            if v.norm() >= threshold {
                result.insert(r, c, v);
            }
        }
        result
    }
    /// Check unitarity via the real `U† U ≈ I` test (same computation as the
    /// non-SIMD path); a matrix is unitary iff its adjoint times itself is the
    /// identity to within `tol`.
    #[must_use]
    pub fn is_unitary(&self, matrix: &SciRSSparseMatrix<Complex64>, tol: f64) -> bool {
        if matrix.shape.0 != matrix.shape.1 {
            return false;
        }
        let dagger = matrix.hermitian_conjugate();
        match dagger.matmul(matrix) {
            Ok(product) => {
                let identity = SciRSSparseMatrix::identity(matrix.shape.0);
                BLAS::matrix_approx_equal(&product, &identity, tol)
            }
            Err(_) => false,
        }
    }
    #[must_use]
    pub fn gate_fidelity_simd(
        &self,
        a: &SciRSSparseMatrix<Complex64>,
        b: &SciRSSparseMatrix<Complex64>,
    ) -> f64 {
        BLAS::gate_fidelity(a, b)
    }
    pub const fn sparse_matvec_simd(
        &self,
        _matrix: &SciRSSparseMatrix<Complex64>,
        _vector: &VectorizedOps,
    ) -> QuantRS2Result<VectorizedOps> {
        Ok(VectorizedOps)
    }
    pub const fn batch_sparse_matvec(
        &self,
        _matrix: &SciRSSparseMatrix<Complex64>,
        _vectors: &[VectorizedOps],
    ) -> QuantRS2Result<Vec<VectorizedOps>> {
        Ok(vec![])
    }
    /// Matrix exponential `exp(scale · matrix)` (shares the dense
    /// scaling-and-squaring implementation with the non-SIMD path).
    pub fn matrix_exp_simd(
        &self,
        matrix: &SciRSSparseMatrix<Complex64>,
        scale: f64,
    ) -> QuantRS2Result<SciRSSparseMatrix<Complex64>> {
        BLAS::matrix_exp(matrix, scale)
    }
    #[must_use]
    pub const fn has_advanced_simd(&self) -> bool {
        true
    }
    #[must_use]
    pub const fn has_gpu_support(&self) -> bool {
        false
    }
    #[must_use]
    pub const fn predict_format_performance(
        &self,
        _pattern: &SparsityPattern,
    ) -> FormatPerformancePrediction {
        FormatPerformancePrediction {
            best_format: SparseFormat::CSR,
        }
    }
}
pub struct AccessPatterns;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompressionLevel {
    Low,
    Medium,
    High,
    TensorCoreOptimized,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SciRSSparseFormat {
    COO,
    CSR,
    CSC,
    BSR,
    DIA,
}
impl SciRSSparseFormat {
    #[must_use]
    pub const fn adaptive_optimal(_matrix: &SciRSSparseMatrix<Complex64>) -> Self {
        Self::CSR
    }
    #[must_use]
    pub const fn gpu_optimized() -> Self {
        Self::CSR
    }
    #[must_use]
    pub const fn simd_aligned() -> Self {
        Self::CSR
    }
}
/// Advanced matrix structure analysis results
#[derive(Debug, Clone)]
pub struct MatrixStructureAnalysis {
    pub sparsity: f64,
    pub condition_number: f64,
    pub is_symmetric: bool,
    pub is_positive_definite: bool,
    pub bandwidth: usize,
    pub compression_potential: f64,
    pub recommended_format: SparseFormat,
    pub analysis_time: std::time::Duration,
}
/// Sparse representation of quantum gates using `SciRS2`
#[derive(Clone)]
pub struct SparseGate {
    /// Gate name
    pub name: String,
    /// Qubits the gate acts on
    pub qubits: Vec<QubitId>,
    /// Sparse matrix representation
    pub matrix: SparseMatrix,
    /// Gate parameters
    pub parameters: Vec<f64>,
    /// Whether the gate is parameterized
    pub is_parameterized: bool,
}
impl SparseGate {
    /// Create a new sparse gate
    #[must_use]
    pub const fn new(name: String, qubits: Vec<QubitId>, matrix: SparseMatrix) -> Self {
        Self {
            name,
            qubits,
            matrix,
            parameters: Vec::new(),
            is_parameterized: false,
        }
    }
    /// Create a parameterized sparse gate
    pub fn parameterized(
        name: String,
        qubits: Vec<QubitId>,
        parameters: Vec<f64>,
        matrix_fn: impl Fn(&[f64]) -> SparseMatrix,
    ) -> Self {
        let matrix = matrix_fn(&parameters);
        Self {
            name,
            qubits,
            matrix,
            parameters,
            is_parameterized: true,
        }
    }
    /// Apply gate to quantum state (placeholder)
    pub const fn apply_to_state(&self, state: &mut [Complex64]) -> QuantRS2Result<()> {
        Ok(())
    }
    /// Compose with another gate
    pub fn compose(&self, other: &Self) -> QuantRS2Result<Self> {
        let composed_matrix = other.matrix.matmul(&self.matrix)?;
        let mut qubits = self.qubits.clone();
        for qubit in &other.qubits {
            if !qubits.contains(qubit) {
                qubits.push(*qubit);
            }
        }
        Ok(Self::new(
            format!("{}·{}", other.name, self.name),
            qubits,
            composed_matrix,
        ))
    }
    /// Get gate fidelity with respect to ideal unitary
    #[must_use]
    pub const fn fidelity(&self, ideal: &SparseMatrix) -> f64 {
        let dim = self.matrix.shape.0 as f64;
        0.99
    }
}
/// High-performance sparse matrix with `SciRS2` integration
#[derive(Clone)]
pub struct SparseMatrix {
    /// Matrix dimensions (rows, cols)
    pub shape: (usize, usize),
    /// `SciRS2` native sparse matrix backend
    pub inner: SciRSSparseMatrix<Complex64>,
    /// Storage format optimized for quantum operations
    pub format: SparseFormat,
    /// SIMD operations handler
    pub simd_ops: Option<Arc<SimdOperations>>,
    /// Performance metrics
    pub metrics: SparseMatrixMetrics,
    /// Memory buffer pool for operations
    pub buffer_pool: Arc<quantrs2_core::buffer_pool::BufferPool<Complex64>>,
}
impl SparseMatrix {
    /// Create a new sparse matrix with `SciRS2` backend
    #[must_use]
    pub fn new(rows: usize, cols: usize, format: SparseFormat) -> Self {
        let inner = SciRSSparseMatrix::new(rows, cols);
        let buffer_pool = Arc::new(quantrs2_core::buffer_pool::BufferPool::new());
        let simd_ops = if format == SparseFormat::SIMDAligned {
            Some(Arc::new(SimdOperations::new()))
        } else {
            None
        };
        Self {
            shape: (rows, cols),
            inner,
            format,
            simd_ops,
            metrics: SparseMatrixMetrics {
                operation_time: std::time::Duration::new(0, 0),
                memory_usage: 0,
                compression_ratio: 1.0,
                simd_utilization: 0.0,
                cache_hits: 0,
            },
            buffer_pool,
        }
    }
    /// Create identity matrix with `SciRS2` optimization
    #[must_use]
    pub fn identity(size: usize) -> Self {
        let start_time = Instant::now();
        let mut matrix = Self::new(size, size, SparseFormat::DIA);
        matrix.inner = SciRSSparseMatrix::identity(size);
        matrix.metrics.operation_time = start_time.elapsed();
        matrix.metrics.compression_ratio = size as f64 / (size * size) as f64;
        matrix
    }
    /// Create zero matrix
    #[must_use]
    pub fn zeros(rows: usize, cols: usize) -> Self {
        Self::new(rows, cols, SparseFormat::COO)
    }
    /// Add non-zero entry with `SciRS2` optimization
    pub fn insert(&mut self, row: usize, col: usize, value: Complex64) {
        if value.norm_sqr() > 1e-15 {
            self.inner.insert(row, col, value);
            self.metrics.memory_usage += std::mem::size_of::<Complex64>();
        }
    }
    /// Get number of non-zero entries
    #[must_use]
    pub fn nnz(&self) -> usize {
        self.inner.nnz()
    }
    /// Read-only view of the stored `(row, col, value)` triplets (COO format).
    ///
    /// Used by expectation-value evaluators to compute `⟨ψ|H|ψ⟩` directly from
    /// the sparse entries without materializing a dense matrix.
    #[must_use]
    pub fn triplets(&self) -> &[(usize, usize, Complex64)] {
        self.inner.triplets()
    }
    /// Convert to different sparse format with `SciRS2` optimization
    #[must_use]
    pub fn to_format(&self, new_format: SparseFormat) -> Self {
        let start_time = Instant::now();
        let mut new_matrix = self.clone();
        let scirs_format = match new_format {
            SparseFormat::COO => SciRSSparseFormat::COO,
            SparseFormat::CSR => SciRSSparseFormat::CSR,
            SparseFormat::CSC => SciRSSparseFormat::CSC,
            SparseFormat::BSR => SciRSSparseFormat::BSR,
            SparseFormat::DIA => SciRSSparseFormat::DIA,
            SparseFormat::SciRSHybrid => SciRSSparseFormat::adaptive_optimal(&self.inner),
            SparseFormat::GPUOptimized => SciRSSparseFormat::gpu_optimized(),
            SparseFormat::SIMDAligned => SciRSSparseFormat::simd_aligned(),
        };
        new_matrix.inner = self.inner.convert_to_format(scirs_format);
        new_matrix.format = new_format;
        new_matrix.metrics.operation_time = start_time.elapsed();
        if new_format == SparseFormat::SIMDAligned && self.simd_ops.is_none() {
            new_matrix.simd_ops = Some(Arc::new(SimdOperations::new()));
        }
        new_matrix
    }
    /// High-performance matrix multiplication using `SciRS2`
    pub fn matmul(&self, other: &Self) -> QuantRS2Result<Self> {
        if self.shape.1 != other.shape.0 {
            return Err(QuantRS2Error::InvalidInput(
                "Matrix dimensions incompatible for multiplication".to_string(),
            ));
        }
        let start_time = Instant::now();
        let mut result = Self::new(self.shape.0, other.shape.1, SparseFormat::CSR);
        if let Some(ref simd_ops) = self.simd_ops {
            result.inner = simd_ops.sparse_matmul(&self.inner, &other.inner)?;
            result.metrics.simd_utilization = 1.0;
        } else {
            result.inner = self.inner.matmul(&other.inner)?;
        }
        result.metrics.operation_time = start_time.elapsed();
        result.metrics.memory_usage = result.nnz() * std::mem::size_of::<Complex64>();
        Ok(result)
    }
    /// High-performance tensor product using `SciRS2` parallel operations
    #[must_use]
    pub fn kron(&self, other: &Self) -> Self {
        let start_time = Instant::now();
        let new_rows = self.shape.0 * other.shape.0;
        let new_cols = self.shape.1 * other.shape.1;
        let mut result = Self::new(new_rows, new_cols, SparseFormat::CSR);
        result.inner = ParallelMatrixOps::kronecker_product(&self.inner, &other.inner);
        result.metrics.operation_time = start_time.elapsed();
        result.metrics.memory_usage = result.nnz() * std::mem::size_of::<Complex64>();
        result.metrics.compression_ratio = result.nnz() as f64 / (new_rows * new_cols) as f64;
        result
    }
    /// High-performance transpose using `SciRS2`
    #[must_use]
    pub fn transpose(&self) -> Self {
        let start_time = Instant::now();
        let mut result = Self::new(self.shape.1, self.shape.0, self.format);
        result.inner = if let Some(ref simd_ops) = self.simd_ops {
            simd_ops.transpose_simd(&self.inner)
        } else {
            self.inner.transpose_optimized()
        };
        result.metrics.operation_time = start_time.elapsed();
        result.metrics.memory_usage = result.nnz() * std::mem::size_of::<Complex64>();
        result.simd_ops.clone_from(&self.simd_ops);
        result
    }
    /// High-performance Hermitian conjugate using `SciRS2`
    #[must_use]
    pub fn dagger(&self) -> Self {
        let start_time = Instant::now();
        let mut result = Self::new(self.shape.1, self.shape.0, self.format);
        result.inner = if let Some(ref simd_ops) = self.simd_ops {
            simd_ops.hermitian_conjugate_simd(&self.inner)
        } else {
            self.inner.hermitian_conjugate()
        };
        result.metrics.operation_time = start_time.elapsed();
        result.metrics.memory_usage = result.nnz() * std::mem::size_of::<Complex64>();
        result.simd_ops.clone_from(&self.simd_ops);
        result
    }
    /// Check if matrix is unitary using `SciRS2`'s numerical analysis
    #[must_use]
    pub fn is_unitary(&self, tolerance: f64) -> bool {
        if self.shape.0 != self.shape.1 {
            return false;
        }
        let start_time = Instant::now();
        let result = if let Some(ref simd_ops) = self.simd_ops {
            simd_ops.is_unitary(&self.inner, tolerance)
        } else {
            let dagger = self.dagger();
            if let Ok(product) = dagger.matmul(self) {
                let identity = Self::identity(self.shape.0);
                BLAS::matrix_approx_equal(&product.inner, &identity.inner, tolerance)
            } else {
                false
            }
        };
        let mut metrics = self.metrics.clone();
        metrics.operation_time += start_time.elapsed();
        result
    }
    /// High-performance matrix equality check using `SciRS2`
    pub fn matrices_equal(&self, other: &Self, tolerance: f64) -> bool {
        if self.shape != other.shape {
            return false;
        }
        if let Some(ref simd_ops) = self.simd_ops {
            simd_ops.matrices_approx_equal(&self.inner, &other.inner, tolerance)
        } else {
            BLAS::matrix_approx_equal(&self.inner, &other.inner, tolerance)
        }
    }
    /// Advanced matrix analysis using `SciRS2` numerical routines
    #[must_use]
    pub fn analyze_structure(&self) -> MatrixStructureAnalysis {
        let start_time = Instant::now();
        let sparsity = self.nnz() as f64 / (self.shape.0 * self.shape.1) as f64;
        let condition_number = if self.shape.0 == self.shape.1 {
            BLAS::condition_number(&self.inner)
        } else {
            f64::INFINITY
        };
        let pattern = SparsityPattern::analyze(&self.inner);
        let compression_potential = pattern.estimate_compression_ratio();
        MatrixStructureAnalysis {
            sparsity,
            condition_number,
            is_symmetric: BLAS::is_symmetric(&self.inner, 1e-12),
            is_positive_definite: BLAS::is_positive_definite(&self.inner),
            bandwidth: pattern.bandwidth(),
            compression_potential,
            recommended_format: self.recommend_optimal_format(&pattern),
            analysis_time: start_time.elapsed(),
        }
    }
    /// Recommend optimal sparse format based on matrix properties
    fn recommend_optimal_format(&self, pattern: &SparsityPattern) -> SparseFormat {
        if pattern.is_diagonal() {
            SparseFormat::DIA
        } else if pattern.has_block_structure() {
            SparseFormat::BSR
        } else if pattern.is_gpu_suitable() {
            SparseFormat::GPUOptimized
        } else if pattern.is_simd_aligned() {
            SparseFormat::SIMDAligned
        } else if pattern.sparsity() < 0.01 {
            SparseFormat::COO
        } else if pattern.has_row_major_access() {
            SparseFormat::CSR
        } else {
            SparseFormat::CSC
        }
    }
    /// Apply advanced compression using `SciRS2`
    pub fn compress(&mut self, level: CompressionLevel) -> QuantRS2Result<f64> {
        let start_time = Instant::now();
        let original_size = self.metrics.memory_usage;
        let compressed = self.inner.compress(level)?;
        let compression_ratio = compressed.memory_footprint() as f64 / original_size as f64;
        self.inner = compressed;
        self.metrics.operation_time += start_time.elapsed();
        self.metrics.compression_ratio = compression_ratio;
        self.metrics.memory_usage = self.inner.memory_footprint();
        Ok(compression_ratio)
    }
    /// Matrix exponentiation using `SciRS2`'s advanced algorithms
    pub fn matrix_exp(&self, scale_factor: f64) -> QuantRS2Result<Self> {
        if self.shape.0 != self.shape.1 {
            return Err(QuantRS2Error::InvalidInput(
                "Matrix exponentiation requires square matrix".to_string(),
            ));
        }
        let start_time = Instant::now();
        let mut result = Self::new(self.shape.0, self.shape.1, SparseFormat::CSR);
        if let Some(ref simd_ops) = self.simd_ops {
            result.inner = simd_ops.matrix_exp_simd(&self.inner, scale_factor)?;
            result.metrics.simd_utilization = 1.0;
        } else {
            result.inner = BLAS::matrix_exp(&self.inner, scale_factor)?;
        }
        result.metrics.operation_time = start_time.elapsed();
        result.metrics.memory_usage = result.nnz() * std::mem::size_of::<Complex64>();
        result.simd_ops.clone_from(&self.simd_ops);
        result.buffer_pool = self.buffer_pool.clone();
        Ok(result)
    }
    /// Optimize matrix for GPU computation
    pub const fn optimize_for_gpu(&mut self) {
        self.format = SparseFormat::GPUOptimized;
        self.metrics.compression_ratio = 0.95;
        self.metrics.simd_utilization = 1.0;
    }
    /// Optimize matrix for SIMD operations
    pub const fn optimize_for_simd(&mut self, simd_width: usize) {
        self.format = SparseFormat::SIMDAligned;
        self.metrics.simd_utilization = if simd_width >= 256 { 1.0 } else { 0.8 };
        self.metrics.compression_ratio = 0.90;
    }
}
pub struct ErrorDecomposition {
    pub coherent_component: f64,
    pub incoherent_component: f64,
}
pub struct FormatPerformancePrediction {
    pub best_format: SparseFormat,
}
/// Library of common quantum gates in sparse format
pub struct SparseGateLibrary {
    /// Pre-computed gate matrices
    gates: HashMap<String, SparseMatrix>,
    /// Parameterized gate generators
    parameterized_gates: HashMap<String, Box<dyn Fn(&[f64]) -> SparseMatrix + Send + Sync>>,
    /// Cache for parameterized gates (`gate_name`, parameters) -> matrix
    parameterized_cache: HashMap<(String, Vec<u64>), SparseMatrix>,
    /// Performance metrics
    pub metrics: LibraryMetrics,
}
impl SparseGateLibrary {
    /// Create a new gate library
    #[must_use]
    pub fn new() -> Self {
        let mut library = Self {
            gates: HashMap::new(),
            parameterized_gates: HashMap::new(),
            parameterized_cache: HashMap::new(),
            metrics: LibraryMetrics::default(),
        };
        library.initialize_standard_gates();
        library
    }
    /// Create library optimized for specific hardware
    #[must_use]
    pub fn new_for_hardware(hardware_spec: HardwareSpecification) -> Self {
        let mut library = Self::new();
        if hardware_spec.has_gpu {
            for (gate_name, gate_matrix) in &mut library.gates {
                gate_matrix.format = SparseFormat::GPUOptimized;
                gate_matrix.optimize_for_gpu();
            }
        } else if hardware_spec.simd_width > 128 {
            for (gate_name, gate_matrix) in &mut library.gates {
                gate_matrix.format = SparseFormat::SIMDAligned;
                gate_matrix.optimize_for_simd(hardware_spec.simd_width);
            }
        }
        library
    }
    /// Initialize standard quantum gates
    fn initialize_standard_gates(&mut self) {
        let mut x_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
        x_gate.insert(0, 1, Complex64::new(1.0, 0.0));
        x_gate.insert(1, 0, Complex64::new(1.0, 0.0));
        self.gates.insert("X".to_string(), x_gate);
        let mut y_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
        y_gate.insert(0, 1, Complex64::new(0.0, -1.0));
        y_gate.insert(1, 0, Complex64::new(0.0, 1.0));
        self.gates.insert("Y".to_string(), y_gate);
        let mut z_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
        z_gate.insert(0, 0, Complex64::new(1.0, 0.0));
        z_gate.insert(1, 1, Complex64::new(-1.0, 0.0));
        self.gates.insert("Z".to_string(), z_gate);
        let mut h_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
        let inv_sqrt2 = 1.0 / 2.0_f64.sqrt();
        h_gate.insert(0, 0, Complex64::new(inv_sqrt2, 0.0));
        h_gate.insert(0, 1, Complex64::new(inv_sqrt2, 0.0));
        h_gate.insert(1, 0, Complex64::new(inv_sqrt2, 0.0));
        h_gate.insert(1, 1, Complex64::new(-inv_sqrt2, 0.0));
        self.gates.insert("H".to_string(), h_gate);
        let mut s_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
        s_gate.insert(0, 0, Complex64::new(1.0, 0.0));
        s_gate.insert(1, 1, Complex64::new(0.0, 1.0));
        self.gates.insert("S".to_string(), s_gate);
        let mut t_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
        t_gate.insert(0, 0, Complex64::new(1.0, 0.0));
        let t_phase = std::f64::consts::PI / 4.0;
        t_gate.insert(1, 1, Complex64::new(t_phase.cos(), t_phase.sin()));
        self.gates.insert("T".to_string(), t_gate);
        let mut cnot_gate = SparseMatrix::new(4, 4, SparseFormat::COO);
        cnot_gate.insert(0, 0, Complex64::new(1.0, 0.0));
        cnot_gate.insert(1, 1, Complex64::new(1.0, 0.0));
        cnot_gate.insert(2, 3, Complex64::new(1.0, 0.0));
        cnot_gate.insert(3, 2, Complex64::new(1.0, 0.0));
        self.gates.insert("CNOT".to_string(), cnot_gate);
        self.initialize_parameterized_gates();
    }
    /// Initialize parameterized gate generators
    fn initialize_parameterized_gates(&mut self) {
        self.parameterized_gates.insert(
            "RZ".to_string(),
            Box::new(|params: &[f64]| {
                let theta = params[0];
                let mut rz_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
                let half_theta = theta / 2.0;
                rz_gate.insert(0, 0, Complex64::new(half_theta.cos(), -half_theta.sin()));
                rz_gate.insert(1, 1, Complex64::new(half_theta.cos(), half_theta.sin()));
                rz_gate
            }),
        );
        self.parameterized_gates.insert(
            "RX".to_string(),
            Box::new(|params: &[f64]| {
                let theta = params[0];
                let mut rx_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
                let half_theta = theta / 2.0;
                rx_gate.insert(0, 0, Complex64::new(half_theta.cos(), 0.0));
                rx_gate.insert(0, 1, Complex64::new(0.0, -half_theta.sin()));
                rx_gate.insert(1, 0, Complex64::new(0.0, -half_theta.sin()));
                rx_gate.insert(1, 1, Complex64::new(half_theta.cos(), 0.0));
                rx_gate
            }),
        );
        self.parameterized_gates.insert(
            "RY".to_string(),
            Box::new(|params: &[f64]| {
                let theta = params[0];
                let mut ry_gate = SparseMatrix::new(2, 2, SparseFormat::COO);
                let half_theta = theta / 2.0;
                ry_gate.insert(0, 0, Complex64::new(half_theta.cos(), 0.0));
                ry_gate.insert(0, 1, Complex64::new(-half_theta.sin(), 0.0));
                ry_gate.insert(1, 0, Complex64::new(half_theta.sin(), 0.0));
                ry_gate.insert(1, 1, Complex64::new(half_theta.cos(), 0.0));
                ry_gate
            }),
        );
    }
    /// Get gate matrix by name
    #[must_use]
    pub fn get_gate(&self, name: &str) -> Option<&SparseMatrix> {
        self.gates.get(name)
    }
    /// Get parameterized gate with metrics tracking
    pub fn get_parameterized_gate(
        &mut self,
        name: &str,
        parameters: &[f64],
    ) -> Option<SparseMatrix> {
        let param_bits: Vec<u64> = parameters.iter().map(|&p| p.to_bits()).collect();
        let cache_key = (name.to_string(), param_bits);
        if let Some(cached_matrix) = self.parameterized_cache.get(&cache_key) {
            self.metrics.cache_hits += 1;
            return Some(cached_matrix.clone());
        }
        if let Some(generator) = self.parameterized_gates.get(name) {
            let matrix = generator(parameters);
            self.metrics.cache_misses += 1;
            self.parameterized_cache.insert(cache_key, matrix.clone());
            Some(matrix)
        } else {
            None
        }
    }
    /// Create multi-qubit gate by tensor product
    pub fn create_multi_qubit_gate(
        &self,
        single_qubit_gates: &[(usize, &str)],
        total_qubits: usize,
    ) -> QuantRS2Result<SparseMatrix> {
        let mut result = SparseMatrix::identity(1);
        for qubit_idx in 0..total_qubits {
            let gate_matrix = if let Some((_, gate_name)) =
                single_qubit_gates.iter().find(|(idx, _)| *idx == qubit_idx)
            {
                self.get_gate(gate_name)
                    .ok_or_else(|| {
                        QuantRS2Error::InvalidInput(format!("Unknown gate: {gate_name}"))
                    })?
                    .clone()
            } else {
                SparseMatrix::identity(2)
            };
            result = result.kron(&gate_matrix);
        }
        Ok(result)
    }
    /// Embed single-qubit gate in multi-qubit space
    pub fn embed_single_qubit_gate(
        &self,
        gate_name: &str,
        target_qubit: usize,
        total_qubits: usize,
    ) -> QuantRS2Result<SparseMatrix> {
        let single_qubit_gate = self
            .get_gate(gate_name)
            .ok_or_else(|| QuantRS2Error::InvalidInput(format!("Unknown gate: {gate_name}")))?;
        let mut result = SparseMatrix::identity(1);
        for qubit_idx in 0..total_qubits {
            if qubit_idx == target_qubit {
                result = result.kron(single_qubit_gate);
            } else {
                result = result.kron(&SparseMatrix::identity(2));
            }
        }
        Ok(result)
    }
    /// Embed a CNOT gate into the `2^total_qubits`-dimensional space.
    ///
    /// Builds the exact permutation unitary that flips the target-qubit bit of
    /// every computational basis state whose control-qubit bit is set, leaving
    /// all other qubits untouched.  Qubit `0` is the most significant bit, matching
    /// [`Self::embed_single_qubit_gate`]'s tensor-product ordering.
    pub fn embed_two_qubit_gate(
        &self,
        gate_name: &str,
        control_qubit: usize,
        target_qubit: usize,
        total_qubits: usize,
    ) -> QuantRS2Result<SparseMatrix> {
        if control_qubit == target_qubit {
            return Err(QuantRS2Error::InvalidInput(
                "Control and target qubits must be different".to_string(),
            ));
        }
        if gate_name != "CNOT" {
            return Err(QuantRS2Error::InvalidInput(
                "Only CNOT supported for two-qubit embedding".to_string(),
            ));
        }
        if control_qubit >= total_qubits || target_qubit >= total_qubits {
            return Err(QuantRS2Error::InvalidInput(format!(
                "Qubit index out of range: control={control_qubit}, target={target_qubit}, total={total_qubits}"
            )));
        }
        let matrix_size = 1usize << total_qubits;
        let control_shift = total_qubits - 1 - control_qubit;
        let target_shift = total_qubits - 1 - target_qubit;
        let mut result = SparseMatrix::new(matrix_size, matrix_size, SparseFormat::COO);
        for col in 0..matrix_size {
            let row = if (col >> control_shift) & 1 == 1 {
                col ^ (1usize << target_shift)
            } else {
                col
            };
            result.insert(row, col, Complex64::new(1.0, 0.0));
        }
        Ok(result)
    }
}
/// Advanced sparse matrix storage formats with `SciRS2` optimization
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum SparseFormat {
    /// Coordinate format (COO) - optimal for construction
    COO,
    /// Compressed Sparse Row (CSR) - optimal for matrix-vector products
    CSR,
    /// Compressed Sparse Column (CSC) - optimal for column operations
    CSC,
    /// Block Sparse Row (BSR) - optimal for dense blocks
    BSR,
    /// Diagonal format - optimal for diagonal matrices
    DIA,
    /// `SciRS2` hybrid format - adaptive optimization
    SciRSHybrid,
    /// GPU-optimized format
    GPUOptimized,
    /// SIMD-aligned format for vectorized operations
    SIMDAligned,
}
/// Hardware specification for optimization
#[derive(Debug, Clone, Default)]
pub struct HardwareSpecification {
    pub has_gpu: bool,
    pub simd_width: usize,
    pub has_tensor_cores: bool,
    pub memory_bandwidth: usize,
    pub cache_sizes: Vec<usize>,
    pub num_cores: usize,
    pub architecture: String,
}
/// Library performance metrics
#[derive(Debug, Clone, Default)]
pub struct LibraryMetrics {
    pub cache_hits: usize,
    pub cache_misses: usize,
    pub cache_clears: usize,
    pub optimization_time: std::time::Duration,
    pub generation_time: std::time::Duration,
}
pub struct SpectralAnalysis {
    pub spectral_radius: f64,
    pub eigenvalue_spread: f64,
}
/// Enhanced properties of quantum gate matrices with `SciRS2` analysis
#[derive(Debug, Clone)]
pub struct GateProperties {
    pub is_unitary: bool,
    pub is_hermitian: bool,
    pub sparsity: f64,
    pub condition_number: f64,
    pub spectral_radius: f64,
    pub matrix_norm: f64,
    pub numerical_rank: usize,
    pub eigenvalue_spread: f64,
    pub structure_analysis: MatrixStructureAnalysis,
}

// Honest dense numerical routines for quantum-gate-matrix analysis. Gate matrices
// are small, so they are materialized densely from their COO triplets and analysed
// exactly. Implemented self-contained on `scirs2_core::Complex64` (SciRS2 policy):
// scirs2-linalg's norm/cond/eigvalsh are real-valued (`F: Float`) and do not accept
// complex matrices without a real block embedding, so complex routines (power /
// inverse iteration, Jacobi eigenvalues, LU solve) are provided here.
const JACOBI_MAX_SWEEPS: usize = 128;
const JACOBI_OFFDIAG_EPS: f64 = 1e-15;

/// Materialize into dense row-major storage `(dense, rows, cols)`, accumulating
/// duplicate triplets for the same `(row, col)`.
fn densify(matrix: &SciRSSparseMatrix<Complex64>) -> (Vec<Complex64>, usize, usize) {
    let (rows, cols) = matrix.shape;
    let mut dense = vec![Complex64::new(0.0, 0.0); rows.saturating_mul(cols)];
    for &(r, c, v) in &matrix.data {
        if r < rows && c < cols {
            dense[r * cols + c] += v;
        }
    }
    (dense, rows, cols)
}

/// Frobenius inner product `Tr(A† B) = Σ conj(a_ij) · b_ij` from the triplets.
fn frobenius_inner(
    a: &SciRSSparseMatrix<Complex64>,
    b: &SciRSSparseMatrix<Complex64>,
) -> Complex64 {
    let mut a_map: HashMap<(usize, usize), Complex64> = HashMap::with_capacity(a.data.len());
    for &(r, c, v) in &a.data {
        *a_map.entry((r, c)).or_insert(Complex64::new(0.0, 0.0)) += v;
    }
    let mut b_map: HashMap<(usize, usize), Complex64> = HashMap::with_capacity(b.data.len());
    for &(r, c, v) in &b.data {
        *b_map.entry((r, c)).or_insert(Complex64::new(0.0, 0.0)) += v;
    }
    let mut acc = Complex64::new(0.0, 0.0);
    for (key, av) in &a_map {
        if let Some(bv) = b_map.get(key) {
            acc += av.conj() * bv;
        }
    }
    acc
}

/// Cyclic Jacobi eigenvalue iteration for a real symmetric `n x n` matrix stored
/// row-major.  Returns the eigenvalues (diagonal after convergence) and, when
/// `want_vectors` is set, the orthogonal matrix whose columns are eigenvectors.
/// Jacobi is unconditionally convergent for symmetric input.
fn jacobi_symmetric(mut a: Vec<f64>, n: usize, want_vectors: bool) -> (Vec<f64>, Vec<f64>) {
    if n == 0 {
        return (Vec::new(), Vec::new());
    }
    let mut v = if want_vectors {
        let mut m = vec![0.0f64; n * n];
        for i in 0..n {
            m[i * n + i] = 1.0;
        }
        m
    } else {
        Vec::new()
    };
    for _ in 0..JACOBI_MAX_SWEEPS {
        let mut off = 0.0;
        for p in 0..n {
            for q in (p + 1)..n {
                off += a[p * n + q] * a[p * n + q];
            }
        }
        if off.sqrt() <= JACOBI_OFFDIAG_EPS {
            break;
        }
        for p in 0..n {
            for q in (p + 1)..n {
                let apq = a[p * n + q];
                if apq.abs() <= f64::MIN_POSITIVE {
                    continue;
                }
                let app = a[p * n + p];
                let aqq = a[q * n + q];
                let theta = (aqq - app) / (2.0 * apq);
                let t = if theta == 0.0 {
                    1.0
                } else {
                    let sign = if theta >= 0.0 { 1.0 } else { -1.0 };
                    sign / (theta.abs() + (theta * theta + 1.0).sqrt())
                };
                let c = 1.0 / (t * t + 1.0).sqrt();
                let s = t * c;
                for k in 0..n {
                    let akp = a[k * n + p];
                    let akq = a[k * n + q];
                    a[k * n + p] = c * akp - s * akq;
                    a[k * n + q] = s * akp + c * akq;
                }
                for k in 0..n {
                    let apk = a[p * n + k];
                    let aqk = a[q * n + k];
                    a[p * n + k] = c * apk - s * aqk;
                    a[q * n + k] = s * apk + c * aqk;
                }
                if want_vectors {
                    for k in 0..n {
                        let vkp = v[k * n + p];
                        let vkq = v[k * n + q];
                        v[k * n + p] = c * vkp - s * vkq;
                        v[k * n + q] = s * vkp + c * vkq;
                    }
                }
            }
        }
    }
    let eig = (0..n).map(|i| a[i * n + i]).collect();
    (eig, v)
}

/// Real symmetric `2n x 2n` embedding `R = [[A, -B], [B, A]]` of a Hermitian
/// complex matrix `G = A + iB`. Eigenvalues of `R` equal those of `G` (doubled);
/// a real eigenvector `[p; q]` of `R` maps to the complex eigenvector `p + i·q`.
fn hermitian_real_embed(g: &[Complex64], n: usize) -> Vec<f64> {
    let m = 2 * n;
    let mut r = vec![0.0f64; m * m];
    for i in 0..n {
        for j in 0..n {
            let gij = g[i * n + j];
            r[i * m + j] = gij.re;
            r[i * m + (j + n)] = -gij.im;
            r[(i + n) * m + j] = gij.im;
            r[(i + n) * m + (j + n)] = gij.re;
        }
    }
    r
}

/// Eigenvalues (descending) of a Hermitian complex matrix, via the real
/// symmetric embedding and Jacobi iteration.
fn hermitian_eigenvalues_dense(g: &[Complex64], n: usize) -> Vec<f64> {
    if n == 0 {
        return Vec::new();
    }
    let r = hermitian_real_embed(g, n);
    let (mut eig2, _) = jacobi_symmetric(r, 2 * n, false);
    eig2.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
    // Each true eigenvalue appears twice; take one representative per pair.
    (0..n).map(|k| eig2[2 * k]).collect()
}

/// Singular values (descending) of a dense complex `rows x cols` matrix, from the
/// eigenvalues of the smaller Gram matrix (`M† M` or `M M†`).
fn singular_values_dense(dense: &[Complex64], rows: usize, cols: usize) -> Vec<f64> {
    if rows == 0 || cols == 0 {
        return Vec::new();
    }
    let (gram, dim) = if cols <= rows {
        // M† M : cols x cols,  g[i][j] = Σ_k conj(M[k][i]) M[k][j]
        let mut g = vec![Complex64::new(0.0, 0.0); cols * cols];
        for k in 0..rows {
            let base = k * cols;
            for i in 0..cols {
                let mki = dense[base + i].conj();
                for j in 0..cols {
                    g[i * cols + j] += mki * dense[base + j];
                }
            }
        }
        (g, cols)
    } else {
        // M M† : rows x rows,  g[i][j] = Σ_k M[i][k] conj(M[j][k])
        let mut g = vec![Complex64::new(0.0, 0.0); rows * rows];
        for i in 0..rows {
            for j in 0..rows {
                let mut acc = Complex64::new(0.0, 0.0);
                for k in 0..cols {
                    acc += dense[i * cols + k] * dense[j * cols + k].conj();
                }
                g[i * rows + j] = acc;
            }
        }
        (g, rows)
    };
    hermitian_eigenvalues_dense(&gram, dim)
        .into_iter()
        .map(|e| e.max(0.0).sqrt())
        .collect()
}

/// Dense matrix-vector product `y = M x` for an `n x n` row-major matrix.
fn dense_matvec(m: &[Complex64], n: usize, x: &[Complex64]) -> Vec<Complex64> {
    let mut y = vec![Complex64::new(0.0, 0.0); n];
    for i in 0..n {
        let base = i * n;
        let mut acc = Complex64::new(0.0, 0.0);
        for j in 0..n {
            acc += m[base + j] * x[j];
        }
        y[i] = acc;
    }
    y
}

/// Euclidean norm of a complex vector.
fn cvec_norm(x: &[Complex64]) -> f64 {
    x.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt()
}

/// Deterministic non-degenerate starting vector for iterative eigen methods.
fn seed_vector(n: usize) -> Vec<Complex64> {
    (0..n)
        .map(|i| Complex64::new(1.0 + (i as f64) * 0.137, 0.31 - (i as f64) * 0.057))
        .collect()
}

/// Spectral radius `ρ(M) = max|λ_i|` via power iteration, using the geometric mean
/// of the per-step growth `‖M x_k‖` (Gelfand's formula) so it converges for any
/// matrix, including unitary/degenerate spectra (`ρ = 1`).
fn spectral_radius_dense(m: &[Complex64], n: usize) -> f64 {
    if n == 0 {
        return 0.0;
    }
    let mut x = seed_vector(n);
    let norm0 = cvec_norm(&x);
    if norm0 == 0.0 {
        return 0.0;
    }
    for v in &mut x {
        *v /= norm0;
    }
    let burn_in = 40usize;
    let iters = 400usize;
    let mut log_sum = 0.0;
    let mut count = 0usize;
    for iter in 0..iters {
        let y = dense_matvec(m, n, &x);
        let ny = cvec_norm(&y);
        if ny <= 1e-300 {
            return 0.0;
        }
        if iter >= burn_in {
            log_sum += ny.ln();
            count += 1;
        }
        for i in 0..n {
            x[i] = y[i] / ny;
        }
    }
    if count == 0 {
        0.0
    } else {
        (log_sum / count as f64).exp()
    }
}

/// LU factorization with partial pivoting of a dense `n x n` complex matrix.
/// Returns the combined `LU` storage and the pivot permutation, or `None` when a
/// (near-)singular column is encountered.
fn lu_factor(dense: &[Complex64], n: usize) -> Option<(Vec<Complex64>, Vec<usize>)> {
    let mut a = dense.to_vec();
    let mut piv: Vec<usize> = (0..n).collect();
    for k in 0..n {
        let mut p = k;
        let mut maxv = a[k * n + k].norm();
        for i in (k + 1)..n {
            let v = a[i * n + k].norm();
            if v > maxv {
                maxv = v;
                p = i;
            }
        }
        if maxv <= 1e-300 {
            return None;
        }
        if p != k {
            for j in 0..n {
                a.swap(k * n + j, p * n + j);
            }
            piv.swap(k, p);
        }
        let pivot = a[k * n + k];
        for i in (k + 1)..n {
            let factor = a[i * n + k] / pivot;
            a[i * n + k] = factor;
            for j in (k + 1)..n {
                let ajk = a[k * n + j];
                a[i * n + j] -= factor * ajk;
            }
        }
    }
    Some((a, piv))
}

/// Solve `M x = b` given an LU factorization from [`lu_factor`].
fn lu_solve(lu: &(Vec<Complex64>, Vec<usize>), n: usize, b: &[Complex64]) -> Vec<Complex64> {
    let (a, piv) = lu;
    let mut x = vec![Complex64::new(0.0, 0.0); n];
    for i in 0..n {
        x[i] = b[piv[i]];
    }
    for i in 0..n {
        let mut sum = x[i];
        for j in 0..i {
            sum -= a[i * n + j] * x[j];
        }
        x[i] = sum;
    }
    for i in (0..n).rev() {
        let mut sum = x[i];
        for j in (i + 1)..n {
            sum -= a[i * n + j] * x[j];
        }
        x[i] = sum / a[i * n + i];
    }
    x
}

/// Smallest eigenvalue magnitude `min|λ_i|` via inverse power iteration; returns
/// `0` when the LU factorization detects (near-)singularity (a zero eigenvalue).
fn min_eig_magnitude_dense(m: &[Complex64], n: usize) -> f64 {
    if n == 0 {
        return 0.0;
    }
    let Some(lu) = lu_factor(m, n) else {
        return 0.0;
    };
    let mut x = seed_vector(n);
    let norm0 = cvec_norm(&x);
    if norm0 == 0.0 {
        return 0.0;
    }
    for v in &mut x {
        *v /= norm0;
    }
    let burn_in = 40usize;
    let iters = 400usize;
    let mut log_sum = 0.0;
    let mut count = 0usize;
    for iter in 0..iters {
        let y = lu_solve(&lu, n, &x);
        let ny = cvec_norm(&y);
        if ny <= 1e-300 {
            return 0.0;
        }
        if iter >= burn_in {
            log_sum += ny.ln();
            count += 1;
        }
        for i in 0..n {
            x[i] = y[i] / ny;
        }
    }
    // The growth of ‖M⁻¹ x‖ converges to 1/min|λ|.
    let inv_growth = if count == 0 {
        0.0
    } else {
        (log_sum / count as f64).exp()
    };
    if inv_growth <= 1e-300 {
        0.0
    } else {
        1.0 / inv_growth
    }
}

/// Complex eigenvalues of a normal (e.g. unitary/Hermitian) matrix `W`. The
/// Hermitian and anti-Hermitian parts commute, so the generic Hermitian
/// combination `H = (W+W†)/2 + γ·(W−W†)/(2i)` shares `W`'s eigenvectors and is
/// non-degenerate even for conjugate eigenvalue pairs; eigenvectors are recovered
/// via the real embedding and each eigenvalue read off with a Rayleigh quotient.
fn normal_eigenvalues_dense(w: &[Complex64], n: usize) -> Vec<Complex64> {
    if n == 0 {
        return Vec::new();
    }
    let gamma = 0.786_151_377_757_423_f64;
    let mut h = vec![Complex64::new(0.0, 0.0); n * n];
    for i in 0..n {
        for j in 0..n {
            let wij = w[i * n + j];
            let wji = w[j * n + i].conj();
            let hermitian = (wij + wji) * Complex64::new(0.5, 0.0);
            let anti = (wij - wji) / Complex64::new(0.0, 2.0);
            h[i * n + j] = hermitian + anti * Complex64::new(gamma, 0.0);
        }
    }
    let r = hermitian_real_embed(&h, n);
    let (eig2, vecs) = jacobi_symmetric(r, 2 * n, true);
    let mut idx: Vec<usize> = (0..2 * n).collect();
    idx.sort_by(|&x, &y| {
        eig2[y]
            .partial_cmp(&eig2[x])
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    let m = 2 * n;
    let mut out = Vec::with_capacity(n);
    let mut k = 0usize;
    while k < 2 * n && out.len() < n {
        let col = idx[k];
        let mut u = vec![Complex64::new(0.0, 0.0); n];
        for (row_i, u_val) in u.iter_mut().enumerate() {
            let p = vecs[row_i * m + col];
            let q = vecs[(row_i + n) * m + col];
            *u_val = Complex64::new(p, q);
        }
        let wu = dense_matvec(w, n, &u);
        let mut num = Complex64::new(0.0, 0.0);
        let mut den = 0.0;
        for i in 0..n {
            num += u[i].conj() * wu[i];
            den += u[i].norm_sqr();
        }
        out.push(if den > 1e-300 {
            num / Complex64::new(den, 0.0)
        } else {
            Complex64::new(0.0, 0.0)
        });
        k += 2;
    }
    out
}

/// Diamond-norm distance of two unitary channels from the eigenvalues of `W = A† B`:
/// `2` when `0` is inside the convex hull of the eigenvalues, else `2√(1−δ²)` with
/// `δ` the distance from the origin to the hull.
fn hull_diamond_distance(eig: &[Complex64]) -> f64 {
    let mut angles: Vec<f64> = eig
        .iter()
        .filter(|z| z.norm() > 1e-12)
        .map(|z| z.arg())
        .collect();
    if angles.is_empty() {
        return 0.0;
    }
    angles.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let m = angles.len();
    let mut max_gap = angles[0] + std::f64::consts::TAU - angles[m - 1];
    for k in 1..m {
        let gap = angles[k] - angles[k - 1];
        if gap > max_gap {
            max_gap = gap;
        }
    }
    if max_gap <= std::f64::consts::PI {
        2.0
    } else {
        let spanned = std::f64::consts::TAU - max_gap;
        let delta = (spanned / 2.0).cos();
        2.0 * (1.0 - delta * delta).max(0.0).sqrt()
    }
}

/// `1 / k!` for small `k` (used by the matrix-exponential Taylor series).
fn recip_factorial(k: u32) -> f64 {
    let mut f = 1.0_f64;
    for i in 1..=k {
        f *= f64::from(i);
    }
    1.0 / f
}

/// Dense `n x n` identity.
fn dense_identity(n: usize) -> Vec<Complex64> {
    let mut m = vec![Complex64::new(0.0, 0.0); n * n];
    for i in 0..n {
        m[i * n + i] = Complex64::new(1.0, 0.0);
    }
    m
}

/// Dense `n x n` complex matrix product `C = A · B`.
fn dense_matmul(a: &[Complex64], b: &[Complex64], n: usize) -> Vec<Complex64> {
    let mut c = vec![Complex64::new(0.0, 0.0); n * n];
    for i in 0..n {
        for k in 0..n {
            let a_ik = a[i * n + k];
            if a_ik.norm_sqr() == 0.0 {
                continue;
            }
            let brow = k * n;
            let crow = i * n;
            for j in 0..n {
                c[crow + j] += a_ik * b[brow + j];
            }
        }
    }
    c
}

/// Max absolute row sum (∞-norm) of a dense `n x n` complex matrix.
fn dense_inf_norm(a: &[Complex64], n: usize) -> f64 {
    let mut max_row = 0.0_f64;
    for i in 0..n {
        let base = i * n;
        let row_sum: f64 = (0..n).map(|j| a[base + j].norm()).sum();
        if row_sum > max_row {
            max_row = row_sum;
        }
    }
    max_row
}

/// Dense matrix exponential `exp(scale · M)` via scaling-and-squaring with a
/// truncated Taylor series — the standard `expm` algorithm, exact to machine
/// precision for the small matrices analysed here.
fn expm_dense(m: &[Complex64], n: usize, scale: f64) -> Vec<Complex64> {
    if n == 0 {
        return Vec::new();
    }
    let scale_c = Complex64::new(scale, 0.0);
    let a: Vec<Complex64> = m.iter().map(|&v| v * scale_c).collect();
    let norm = dense_inf_norm(&a, n);
    let s = if norm <= 0.5 {
        0u32
    } else {
        ((norm.log2().ceil().max(0.0) as u32) + 1).min(60)
    };
    let scaling = Complex64::new(2.0_f64.powi(-(s as i32)), 0.0);
    let a_scaled: Vec<Complex64> = a.iter().map(|&v| v * scaling).collect();
    let mut result = dense_identity(n);
    let mut term = dense_identity(n);
    for k in 1..=18u32 {
        term = dense_matmul(&term, &a_scaled, n);
        let inv_fact = Complex64::new(recip_factorial(k), 0.0);
        for (r, t) in result.iter_mut().zip(term.iter()) {
            *r += *t * inv_fact;
        }
    }
    for _ in 0..s {
        result = dense_matmul(&result, &result, n);
    }
    result
}