scirs2-sparse 0.4.2

Sparse matrix module for SciRS2 (scirs2-sparse)
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
#![allow(unused_variables)]
#![allow(unused_assignments)]
#![allow(unused_mut)]

use crate::error::{SparseError, SparseResult};
use crate::linalg::interface::LinearOperator;
use scirs2_core::numeric::{Float, NumAssign, SparseElement};
use std::iter::Sum;

/// Result of an iterative solver
#[derive(Debug, Clone)]
pub struct IterationResult<F> {
    pub x: Vec<F>,
    pub iterations: usize,
    pub residual_norm: F,
    pub converged: bool,
    pub message: String,
}

/// Options for conjugate gradient solver
pub struct CGOptions<F> {
    pub max_iter: usize,
    pub rtol: F,
    pub atol: F,
    pub x0: Option<Vec<F>>,
    pub preconditioner: Option<Box<dyn LinearOperator<F>>>,
}

impl<F: Float> Default for CGOptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            x0: None,
            preconditioner: None,
        }
    }
}

/// Conjugate gradient solver for symmetric positive definite systems
///
/// Solves Ax = b where A is symmetric positive definite
#[allow(dead_code)]
pub fn cg<F>(
    a: &dyn LinearOperator<F>,
    b: &[F],
    options: CGOptions<F>,
) -> SparseResult<IterationResult<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static,
{
    let (rows, cols) = a.shape();
    if rows != cols {
        return Err(SparseError::ValueError(
            "Matrix must be square for CG solver".to_string(),
        ));
    }
    if b.len() != rows {
        return Err(SparseError::DimensionMismatch {
            expected: rows,
            found: b.len(),
        });
    }

    let n = rows;

    // Initialize solution
    let mut x: Vec<F> = match &options.x0 {
        Some(x0) => {
            if x0.len() != n {
                return Err(SparseError::DimensionMismatch {
                    expected: n,
                    found: x0.len(),
                });
            }
            x0.clone()
        }
        None => vec![F::sparse_zero(); n],
    };

    // Compute initial residual: r = b - A*x
    let ax = a.matvec(&x)?;
    let mut r: Vec<F> = b.iter().zip(&ax).map(|(&bi, &axi)| bi - axi).collect();

    // Apply preconditioner if provided
    let mut z = if let Some(m) = &options.preconditioner {
        m.matvec(&r)?
    } else {
        r.clone()
    };

    let mut p = z.clone();
    let mut rz_old = dot(&r, &z);

    // Check for convergence
    let bnorm = norm2(b);
    let tolerance = F::max(options.atol, options.rtol * bnorm);

    let mut iterations = 0;
    while iterations < options.max_iter {
        // Compute Ap
        let ap = a.matvec(&p)?;

        // Compute alpha = (r,z) / (p,Ap)
        let pap = dot(&p, &ap);
        if pap <= F::sparse_zero() {
            return Ok(IterationResult {
                x,
                iterations,
                residual_norm: norm2(&r),
                converged: false,
                message: "Matrix not positive definite (p^T*A*p <= 0)".to_string(),
            });
        }
        let alpha = rz_old / pap;

        // Update solution: x = x + alpha*p
        for i in 0..n {
            x[i] += alpha * p[i];
        }

        // Update residual: r = r - alpha*Ap
        for i in 0..n {
            r[i] -= alpha * ap[i];
        }

        // Check for convergence
        let rnorm = norm2(&r);
        if rnorm <= tolerance {
            return Ok(IterationResult {
                x,
                iterations: iterations + 1,
                residual_norm: rnorm,
                converged: true,
                message: "Converged".to_string(),
            });
        }

        // Apply preconditioner
        z = if let Some(m) = &options.preconditioner {
            m.matvec(&r)?
        } else {
            r.clone()
        };

        // Compute beta = (r_{i+1},z_{i+1}) / (r_i,z_i)
        let rz_new = dot(&r, &z);
        let beta = rz_new / rz_old;

        // Update direction: p = z + beta*p
        for i in 0..n {
            p[i] = z[i] + beta * p[i];
        }

        rz_old = rz_new;
        iterations += 1;
    }

    Ok(IterationResult {
        x,
        iterations,
        residual_norm: norm2(&r),
        converged: false,
        message: "Maximum iterations reached".to_string(),
    })
}

/// Options for BiCG solver
pub struct BiCGOptions<F> {
    pub max_iter: usize,
    pub rtol: F,
    pub atol: F,
    pub x0: Option<Vec<F>>,
    pub left_preconditioner: Option<Box<dyn LinearOperator<F>>>,
    pub right_preconditioner: Option<Box<dyn LinearOperator<F>>>,
}

impl<F: Float> Default for BiCGOptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            x0: None,
            left_preconditioner: None,
            right_preconditioner: None,
        }
    }
}

/// Biconjugate Gradient solver
///
/// Solves Ax = b where A is non-symmetric.
#[allow(dead_code)]
pub fn bicg<F>(
    a: &dyn LinearOperator<F>,
    b: &[F],
    options: BiCGOptions<F>,
) -> SparseResult<IterationResult<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static,
{
    let (rows, cols) = a.shape();
    if rows != cols {
        return Err(SparseError::ValueError(
            "Matrix must be square for BiCG solver".to_string(),
        ));
    }
    if b.len() != rows {
        return Err(SparseError::DimensionMismatch {
            expected: rows,
            found: b.len(),
        });
    }

    let n = rows;

    // Initialize solution
    let mut x: Vec<F> = match &options.x0 {
        Some(x0) => {
            if x0.len() != n {
                return Err(SparseError::DimensionMismatch {
                    expected: n,
                    found: x0.len(),
                });
            }
            x0.clone()
        }
        None => vec![F::sparse_zero(); n],
    };

    // Compute initial residual: r = b - A*x
    let ax = a.matvec(&x)?;
    let mut r: Vec<F> = b.iter().zip(&ax).map(|(&bi, &axi)| bi - axi).collect();

    // Initialize r_star (shadow residual) = r
    let mut r_star = r.clone();

    // Apply preconditioners to initial residuals
    let mut z = if let Some(m1) = &options.left_preconditioner {
        m1.matvec(&r)?
    } else {
        r.clone()
    };

    let mut z_star = if let Some(m2) = &options.right_preconditioner {
        m2.matvec(&r_star)?
    } else {
        r_star.clone()
    };

    let mut p = z.clone();
    let mut p_star = z_star.clone();

    let mut rho_old = dot(&r_star, &z);

    let bnorm = norm2(b);
    let tolerance = F::max(options.atol, options.rtol * bnorm);

    let mut iterations = 0;
    while iterations < options.max_iter {
        // Compute q = A*p and q_star = A^T*p_star
        let mut q = a.matvec(&p)?;
        if let Some(m2) = &options.right_preconditioner {
            q = m2.matvec(&q)?;
        }

        let mut q_star = a.rmatvec(&p_star)?;
        if let Some(m1) = &options.left_preconditioner {
            q_star = m1.matvec(&q_star)?;
        }

        // Compute alpha = rho_old / (p_star, q)
        let alpha_den = dot(&p_star, &q);
        if alpha_den.abs()
            < F::epsilon() * F::from(10).expect("Failed to convert constant to float")
        {
            return Ok(IterationResult {
                x,
                iterations,
                residual_norm: norm2(&r),
                converged: false,
                message: "BiCG breakdown: (p_star, q) ≈ 0".to_string(),
            });
        }
        let alpha = rho_old / alpha_den;

        // Update solution and residuals
        for i in 0..n {
            x[i] += alpha * p[i];
            r[i] -= alpha * q[i];
            r_star[i] -= alpha * q_star[i];
        }

        // Check for convergence - compute residual norm BEFORE the next iteration
        let rnorm = norm2(&r);
        if rnorm <= tolerance {
            return Ok(IterationResult {
                x,
                iterations: iterations + 1,
                residual_norm: rnorm,
                converged: true,
                message: "Converged".to_string(),
            });
        }

        // Apply preconditioners
        z = if let Some(m1) = &options.left_preconditioner {
            m1.matvec(&r)?
        } else {
            r.clone()
        };

        z_star = if let Some(m2) = &options.right_preconditioner {
            m2.matvec(&r_star)?
        } else {
            r_star.clone()
        };

        // Compute new rho
        let rho = dot(&r_star, &z);
        if rho.abs() < F::epsilon() * F::from(10).expect("Failed to convert constant to float") {
            return Ok(IterationResult {
                x,
                iterations: iterations + 1,
                residual_norm: rnorm,
                converged: false,
                message: "BiCG breakdown: rho ≈ 0".to_string(),
            });
        }

        // Compute beta = rho / rho_old
        let beta = rho / rho_old;

        // Update search directions
        for i in 0..n {
            p[i] = z[i] + beta * p[i];
            p_star[i] = z_star[i] + beta * p_star[i];
        }

        rho_old = rho;
        iterations += 1;
    }

    Ok(IterationResult {
        x,
        iterations,
        residual_norm: norm2(&r),
        converged: false,
        message: "Maximum iterations reached".to_string(),
    })
}

/// Options for BiCGSTAB solver
pub struct BiCGSTABOptions<F> {
    pub max_iter: usize,
    pub rtol: F,
    pub atol: F,
    pub x0: Option<Vec<F>>,
    pub left_preconditioner: Option<Box<dyn LinearOperator<F>>>,
    pub right_preconditioner: Option<Box<dyn LinearOperator<F>>>,
}

impl<F: Float> Default for BiCGSTABOptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            x0: None,
            left_preconditioner: None,
            right_preconditioner: None,
        }
    }
}

/// Result from BiCGSTAB solver
pub type BiCGSTABResult<F> = IterationResult<F>;

/// BiConjugate Gradient Stabilized method
///
/// An improved version of BiCG that avoids the irregular convergence patterns
/// and has better numerical stability. Works for general non-symmetric systems.
#[allow(dead_code)]
pub fn bicgstab<F>(
    a: &dyn LinearOperator<F>,
    b: &[F],
    options: BiCGSTABOptions<F>,
) -> SparseResult<BiCGSTABResult<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static,
{
    let (rows, cols) = a.shape();
    if rows != cols {
        return Err(SparseError::ValueError(
            "Matrix must be square for BiCGSTAB solver".to_string(),
        ));
    }
    if b.len() != rows {
        return Err(SparseError::DimensionMismatch {
            expected: rows,
            found: b.len(),
        });
    }

    let n = rows;

    // Initialize solution
    let mut x: Vec<F> = match &options.x0 {
        Some(x0) => {
            if x0.len() != n {
                return Err(SparseError::DimensionMismatch {
                    expected: n,
                    found: x0.len(),
                });
            }
            x0.clone()
        }
        None => vec![F::sparse_zero(); n],
    };

    // Compute initial residual: r = b - A*x
    let ax = a.matvec(&x)?;
    let mut r: Vec<F> = b.iter().zip(&ax).map(|(&bi, &axi)| bi - axi).collect();

    // Check if initial guess is solution
    let mut rnorm = norm2(&r);
    let bnorm = norm2(b);
    let tolerance = F::max(options.atol, options.rtol * bnorm);

    if rnorm <= tolerance {
        return Ok(BiCGSTABResult {
            x,
            iterations: 0,
            residual_norm: rnorm,
            converged: true,
            message: "Converged with initial guess".to_string(),
        });
    }

    // Choose shadow residual (r_hat) as r0
    let r_hat = r.clone();

    let mut v = vec![F::sparse_zero(); n];
    let mut p = vec![F::sparse_zero(); n];
    let mut y = vec![F::sparse_zero(); n];
    let mut s = vec![F::sparse_zero(); n];
    let mut t: Vec<F>;

    let mut rho_old = F::sparse_one();
    let mut alpha = F::sparse_zero();
    let mut omega = F::sparse_one();

    // Main iteration loop
    let mut iterations = 0;
    while iterations < options.max_iter {
        // Compute rho = (r_hat, r)
        let rho = dot(&r_hat, &r);

        // Check for breakdown
        if rho.abs() < F::epsilon() * F::from(10).expect("Failed to convert constant to float") {
            return Ok(BiCGSTABResult {
                x,
                iterations,
                residual_norm: rnorm,
                converged: false,
                message: "BiCGSTAB breakdown: rho ≈ 0".to_string(),
            });
        }

        // Compute beta and update p
        let beta = (rho / rho_old) * (alpha / omega);

        // p = r + beta * (p - omega * v)
        for i in 0..n {
            p[i] = r[i] + beta * (p[i] - omega * v[i]);
        }

        // Apply left preconditioner if provided
        let p_tilde = match &options.left_preconditioner {
            Some(m1) => m1.matvec(&p)?,
            None => p.clone(),
        };

        // Compute v = A * p_tilde
        v = a.matvec(&p_tilde)?;

        // Apply right preconditioner if provided
        if let Some(m2) = &options.right_preconditioner {
            v = m2.matvec(&v)?;
        }

        // Compute alpha = rho / (r_hat, v)
        let den = dot(&r_hat, &v);
        if den.abs() < F::epsilon() * F::from(10).expect("Failed to convert constant to float") {
            return Ok(BiCGSTABResult {
                x,
                iterations,
                residual_norm: rnorm,
                converged: false,
                message: "BiCGSTAB breakdown: (r_hat, v) ≈ 0".to_string(),
            });
        }
        alpha = rho / den;

        // Check if alpha is reasonable
        if !alpha.is_finite() {
            return Ok(BiCGSTABResult {
                x,
                iterations,
                residual_norm: rnorm,
                converged: false,
                message: "BiCGSTAB breakdown: alpha is not finite".to_string(),
            });
        }

        // Update solution and residual: s = r - alpha * v
        for i in 0..n {
            y[i] = x[i] + alpha * p_tilde[i];
            s[i] = r[i] - alpha * v[i];
        }

        // Check convergence
        let snorm = norm2(&s);
        if snorm <= tolerance {
            // Final update: x = y
            x = y;

            // Apply right preconditioner to final solution if provided
            if let Some(m2) = &options.right_preconditioner {
                x = m2.matvec(&x)?;
            }

            return Ok(BiCGSTABResult {
                x,
                iterations: iterations + 1,
                residual_norm: snorm,
                converged: true,
                message: "Converged".to_string(),
            });
        }

        // Apply left preconditioner to s if provided
        let s_tilde = match &options.left_preconditioner {
            Some(m1) => m1.matvec(&s)?,
            None => s.clone(),
        };

        // Compute t = A * s_tilde
        t = a.matvec(&s_tilde)?;

        // Apply right preconditioner if provided
        if let Some(m2) = &options.right_preconditioner {
            t = m2.matvec(&t)?;
        }

        // Compute omega = (t, s) / (t, t)
        let ts = dot(&t, &s);
        let tt = dot(&t, &t);

        if tt < F::epsilon() * F::from(10).expect("Failed to convert constant to float") {
            return Ok(BiCGSTABResult {
                x,
                iterations,
                residual_norm: rnorm,
                converged: false,
                message: "BiCGSTAB breakdown: (t, t) ≈ 0".to_string(),
            });
        }

        omega = ts / tt;

        // Check if omega is reasonable
        if !omega.is_finite()
            || omega.abs()
                < F::epsilon() * F::from(10).expect("Failed to convert constant to float")
        {
            return Ok(BiCGSTABResult {
                x,
                iterations,
                residual_norm: rnorm,
                converged: false,
                message: "BiCGSTAB breakdown: omega is not finite or too small".to_string(),
            });
        }

        // Update solution: x = y + omega * s_tilde
        for i in 0..n {
            x[i] = y[i] + omega * s_tilde[i];
            r[i] = s[i] - omega * t[i];
        }

        // Apply right preconditioner to final solution if provided
        if let Some(m2) = &options.right_preconditioner {
            x = m2.matvec(&x)?;
        }

        rnorm = norm2(&r);

        // Check for convergence
        if rnorm <= tolerance {
            return Ok(BiCGSTABResult {
                x,
                iterations: iterations + 1,
                residual_norm: rnorm,
                converged: true,
                message: "Converged".to_string(),
            });
        }

        rho_old = rho;
        iterations += 1;
    }

    Ok(BiCGSTABResult {
        x,
        iterations,
        residual_norm: rnorm,
        converged: false,
        message: "Maximum iterations reached".to_string(),
    })
}

/// Options for GMRES solver
pub struct GMRESOptions<F> {
    pub max_iter: usize,
    pub restart: usize,
    pub rtol: F,
    pub atol: F,
    pub x0: Option<Vec<F>>,
    pub preconditioner: Option<Box<dyn LinearOperator<F>>>,
}

impl<F: Float> Default for GMRESOptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            restart: 30,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            x0: None,
            preconditioner: None,
        }
    }
}

/// Generalized Minimal Residual Method
///
/// Solves Ax = b for general non-symmetric systems. GMRES is particularly
/// robust but requires more memory than other methods due to the need to
/// store the Krylov basis vectors.
#[allow(dead_code)]
pub fn gmres<F>(
    a: &dyn LinearOperator<F>,
    b: &[F],
    options: GMRESOptions<F>,
) -> SparseResult<IterationResult<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static,
{
    let (rows, cols) = a.shape();
    if rows != cols {
        return Err(SparseError::ValueError(
            "Matrix must be square for GMRES solver".to_string(),
        ));
    }
    if b.len() != rows {
        return Err(SparseError::DimensionMismatch {
            expected: rows,
            found: b.len(),
        });
    }

    let n = rows;
    let restart = options.restart.min(n);

    // Initialize solution
    let mut x: Vec<F> = match &options.x0 {
        Some(x0) => {
            if x0.len() != n {
                return Err(SparseError::DimensionMismatch {
                    expected: n,
                    found: x0.len(),
                });
            }
            x0.clone()
        }
        None => vec![F::sparse_zero(); n],
    };

    // Compute initial residual: r = b - A*x
    let ax = a.matvec(&x)?;
    let mut r: Vec<F> = b.iter().zip(&ax).map(|(&bi, &axi)| bi - axi).collect();

    // Apply preconditioner if provided
    if let Some(m) = &options.preconditioner {
        r = m.matvec(&r)?;
    }

    let mut rnorm = norm2(&r);
    let bnorm = norm2(b);
    let tolerance = F::max(options.atol, options.rtol * bnorm);

    let mut outer_iterations = 0;

    // Outer iteration loop (restarts)
    while outer_iterations < options.max_iter && rnorm > tolerance {
        // Initialize Krylov subspace
        let mut v = vec![vec![F::sparse_zero(); n]; restart + 1];
        let mut h = vec![vec![F::sparse_zero(); restart]; restart + 1];
        let mut cs = vec![F::sparse_zero(); restart]; // Cosines for Givens rotations
        let mut sn = vec![F::sparse_zero(); restart]; // Sines for Givens rotations
        let mut s = vec![F::sparse_zero(); restart + 1]; // RHS for triangular system

        // Set up initial vector
        v[0] = r.iter().map(|&ri| ri / rnorm).collect();
        s[0] = rnorm;

        // Arnoldi iteration
        let mut inner_iter = 0;
        while inner_iter < restart && inner_iter + outer_iterations < options.max_iter {
            // Compute w = A * v[j]
            let mut w = a.matvec(&v[inner_iter])?;

            // Apply preconditioner if provided
            if let Some(m) = &options.preconditioner {
                w = m.matvec(&w)?;
            }

            // Orthogonalize against previous vectors
            for i in 0..=inner_iter {
                h[i][inner_iter] = dot(&v[i], &w);
                for (k, w_elem) in w.iter_mut().enumerate().take(n) {
                    *w_elem -= h[i][inner_iter] * v[i][k];
                }
            }

            h[inner_iter + 1][inner_iter] = norm2(&w);

            // Check for breakdown
            if h[inner_iter + 1][inner_iter]
                < F::epsilon() * F::from(10).expect("Failed to convert constant to float")
            {
                break;
            }

            // Normalize w and store in v[j+1]
            v[inner_iter + 1] = w
                .iter()
                .map(|&wi| wi / h[inner_iter + 1][inner_iter])
                .collect();

            // Apply previous Givens rotations
            for i in 0..inner_iter {
                let temp = cs[i] * h[i][inner_iter] + sn[i] * h[i + 1][inner_iter];
                h[i + 1][inner_iter] = -sn[i] * h[i][inner_iter] + cs[i] * h[i + 1][inner_iter];
                h[i][inner_iter] = temp;
            }

            // Compute new Givens rotation
            let rho = (h[inner_iter][inner_iter] * h[inner_iter][inner_iter]
                + h[inner_iter + 1][inner_iter] * h[inner_iter + 1][inner_iter])
                .sqrt();
            cs[inner_iter] = h[inner_iter][inner_iter] / rho;
            sn[inner_iter] = h[inner_iter + 1][inner_iter] / rho;

            // Apply new Givens rotation
            h[inner_iter][inner_iter] = rho;
            h[inner_iter + 1][inner_iter] = F::sparse_zero();

            let temp = cs[inner_iter] * s[inner_iter] + sn[inner_iter] * s[inner_iter + 1];
            s[inner_iter + 1] =
                -sn[inner_iter] * s[inner_iter] + cs[inner_iter] * s[inner_iter + 1];
            s[inner_iter] = temp;

            inner_iter += 1;

            // Check for convergence
            let residual = s[inner_iter].abs();
            if residual <= tolerance {
                break;
            }
        }

        // Solve the upper triangular system
        let mut y = vec![F::sparse_zero(); inner_iter];
        for i in (0..inner_iter).rev() {
            y[i] = s[i];
            for j in i + 1..inner_iter {
                let y_j = y[j];
                y[i] -= h[i][j] * y_j;
            }
            y[i] /= h[i][i];
        }

        // Update solution
        for i in 0..inner_iter {
            for (j, x_val) in x.iter_mut().enumerate().take(n) {
                *x_val += y[i] * v[i][j];
            }
        }

        // Compute new residual
        let ax = a.matvec(&x)?;
        r = b.iter().zip(&ax).map(|(&bi, &axi)| bi - axi).collect();

        // Apply preconditioner if provided
        if let Some(m) = &options.preconditioner {
            r = m.matvec(&r)?;
        }

        rnorm = norm2(&r);
        outer_iterations += inner_iter;

        if rnorm <= tolerance {
            break;
        }
    }

    Ok(IterationResult {
        x,
        iterations: outer_iterations,
        residual_norm: rnorm,
        converged: rnorm <= tolerance,
        message: if rnorm <= tolerance {
            "Converged".to_string()
        } else {
            "Maximum iterations reached".to_string()
        },
    })
}

/// Trait for iterative solvers
pub trait IterativeSolver<F: Float> {
    /// Solve the linear system Ax = b
    fn solve(&self, a: &dyn LinearOperator<F>, b: &[F]) -> SparseResult<IterationResult<F>>;
}

// Helper functions

/// Compute the dot product of two vectors
pub(crate) fn dot<F: Float + Sum>(x: &[F], y: &[F]) -> F {
    x.iter().zip(y).map(|(&xi, &yi)| xi * yi).sum()
}

/// Compute the 2-norm of a vector
pub(crate) fn norm2<F: Float + Sum>(x: &[F]) -> F {
    dot(x, x).sqrt()
}

/// Options for LSQR solver
pub struct LSQROptions<F> {
    #[allow(dead_code)]
    pub max_iter: usize,
    #[allow(dead_code)]
    pub rtol: F,
    #[allow(dead_code)]
    pub atol: F,
    #[allow(dead_code)]
    pub btol: F,
    #[allow(dead_code)]
    pub x0: Option<Vec<F>>,
}

impl<F: Float> Default for LSQROptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            btol: F::from(1e-8).expect("Failed to convert constant to float"),
            x0: None,
        }
    }
}

/// Options for LSMR solver
#[allow(dead_code)]
pub struct LSMROptions<F> {
    pub max_iter: usize,
    pub rtol: F,
    pub atol: F,
    pub btol: F,
    pub x0: Option<Vec<F>>,
    pub damp: F,
}

impl<F: Float + SparseElement> Default for LSMROptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            btol: F::from(1e-8).expect("Failed to convert constant to float"),
            x0: None,
            damp: F::sparse_zero(),
        }
    }
}

/// Options for GCROT solver
#[allow(dead_code)]
pub struct GCROTOptions<F> {
    pub max_iter: usize,
    pub restart: usize,
    pub truncate: usize,
    pub rtol: F,
    pub atol: F,
    pub x0: Option<Vec<F>>,
    pub preconditioner: Option<Box<dyn LinearOperator<F>>>,
}

impl<F: Float> Default for GCROTOptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            restart: 30,
            truncate: 2,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            x0: None,
            preconditioner: None,
        }
    }
}

/// Options for TFQMR solver
#[allow(dead_code)]
pub struct TFQMROptions<F> {
    pub max_iter: usize,
    pub rtol: F,
    pub atol: F,
    pub x0: Option<Vec<F>>,
    pub preconditioner: Option<Box<dyn LinearOperator<F>>>,
}

impl<F: Float> Default for TFQMROptions<F> {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            rtol: F::from(1e-8).expect("Failed to convert constant to float"),
            atol: F::from(1e-12).expect("Failed to convert constant to float"),
            x0: None,
            preconditioner: None,
        }
    }
}

/// Stable implementation of Givens rotation
///
/// Computes (c, s, r) such that [ c  s] [a] = [r]
///                                [-s  c] [b]   [0]
fn sym_ortho<F: Float + SparseElement>(a: F, b: F) -> (F, F, F) {
    use scirs2_core::numeric::One;

    let zero = F::sparse_zero();
    let one = <F as One>::one();

    if b == zero {
        return (if a >= zero { one } else { -one }, zero, a.abs());
    } else if a == zero {
        return (zero, if b >= zero { one } else { -one }, b.abs());
    } else if b.abs() > a.abs() {
        let tau = a / b;
        let s_sign = if b >= zero { one } else { -one };
        let s = s_sign / (one + tau * tau).sqrt();
        let c = s * tau;
        let r = b / s;
        (c, s, r)
    } else {
        let tau = b / a;
        let c_sign = if a >= zero { one } else { -one };
        let c = c_sign / (one + tau * tau).sqrt();
        let s = c * tau;
        let r = a / c;
        (c, s, r)
    }
}

/// Least Squares QR (LSQR) solver
///
/// Solves the least squares problem min ||Ax - b||_2 or the system Ax = b
/// using the LSQR algorithm. Suitable for large sparse least squares problems.
///
/// Implementation follows the SciPy reference based on:
/// C. C. Paige and M. A. Saunders (1982), "LSQR: An algorithm for sparse linear
/// equations and sparse least squares", ACM TOMS 8(1), 43-71.
///
/// Uses stable Givens rotations for numerical stability.
#[allow(dead_code)]
pub fn lsqr<F>(
    a: &dyn LinearOperator<F>,
    b: &[F],
    options: LSQROptions<F>,
) -> SparseResult<IterationResult<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static,
{
    let (m, n) = a.shape();
    if b.len() != m {
        return Err(SparseError::DimensionMismatch {
            expected: m,
            found: b.len(),
        });
    }

    // Initialize solution
    let mut x: Vec<F> = match &options.x0 {
        Some(x0) => {
            if x0.len() != n {
                return Err(SparseError::DimensionMismatch {
                    expected: n,
                    found: x0.len(),
                });
            }
            x0.clone()
        }
        None => vec![F::sparse_zero(); n],
    };

    // Set up the first vectors u and v for the bidiagonalization.
    // These satisfy  beta*u = b - A@x,  alfa*v = A'@u.
    let mut u: Vec<F> = b.to_vec();
    let bnorm = norm2(b);

    // Initialize from x0 if provided
    if x.iter().any(|&xi| xi != F::sparse_zero()) {
        let ax = a.matvec(&x)?;
        for i in 0..u.len() {
            u[i] -= ax[i];
        }
    }

    let mut beta = norm2(&u);
    if beta == F::sparse_zero() {
        return Ok(IterationResult {
            x,
            iterations: 0,
            residual_norm: F::sparse_zero(),
            converged: true,
            message: "Zero initial residual".to_string(),
        });
    }

    // Normalize u: u = u/beta
    for elem in &mut u {
        *elem /= beta;
    }

    // v = A'*u
    let mut v = a.rmatvec(&u)?;
    let mut alfa = norm2(&v);

    // Normalize v: v = v/alfa
    if alfa > F::sparse_zero() {
        for elem in &mut v {
            *elem /= alfa;
        }
    }

    let mut w = v.clone();

    // Initialize variables (matching SciPy naming)
    let mut rhobar = alfa;
    let mut phibar = beta;

    let tolerance = F::max(options.atol, options.rtol * bnorm);

    for iterations in 0..options.max_iter {
        // Perform the next step of the bidiagonalization to obtain the
        // next  beta, u, alfa, v. These satisfy the relations
        //     beta*u  =  A@v   -  alfa*u,
        //     alfa*v  =  A'@u  -  beta*v.

        // u = A.matvec(v) - alfa * u
        let av = a.matvec(&v)?;
        for i in 0..u.len() {
            u[i] = av[i] - alfa * u[i];
        }
        beta = norm2(&u);

        if beta > F::sparse_zero() {
            // u = (1/beta) * u
            for elem in &mut u {
                *elem /= beta;
            }

            // v = A.rmatvec(u) - beta * v
            let atu = a.rmatvec(&u)?;
            for i in 0..v.len() {
                v[i] = atu[i] - beta * v[i];
            }
            alfa = norm2(&v);

            if alfa > F::sparse_zero() {
                // v = (1/alfa) * v
                for elem in &mut v {
                    *elem /= alfa;
                }
            }
        }

        // Use a plane rotation to eliminate the subdiagonal element (beta)
        // of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.
        let (cs, sn, rho) = sym_ortho(rhobar, beta);

        let theta = sn * alfa;
        rhobar = -cs * alfa;
        let phi = cs * phibar;
        phibar = sn * phibar;

        // Update x and w.
        let t1 = phi / rho;
        let t2 = -theta / rho;

        for i in 0..x.len() {
            x[i] += t1 * w[i];
        }
        for i in 0..w.len() {
            w[i] = v[i] + t2 * w[i];
        }

        // Check convergence
        let residual_norm = phibar.abs();
        if residual_norm <= tolerance {
            return Ok(IterationResult {
                x,
                iterations: iterations + 1,
                residual_norm,
                converged: true,
                message: "Converged".to_string(),
            });
        }
    }

    Ok(IterationResult {
        x,
        iterations: options.max_iter,
        residual_norm: phibar.abs(),
        converged: false,
        message: "Maximum iterations reached".to_string(),
    })
}

/// Least Squares Minimal Residual (LSMR) solver
///
/// An enhanced version of LSQR with better numerical properties.
/// Implementation follows SciPy reference based on:
/// D. C.-L. Fong and M. A. Saunders (2011), "LSMR: An iterative algorithm
/// for sparse least-squares problems", SIAM J. Sci. Comput., 33(5), 2950-2971.
#[allow(dead_code)]
pub fn lsmr<F>(
    a: &dyn LinearOperator<F>,
    b: &[F],
    options: LSMROptions<F>,
) -> SparseResult<IterationResult<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static,
{
    use scirs2_core::numeric::One;

    let (m, n) = a.shape();
    if b.len() != m {
        return Err(SparseError::DimensionMismatch {
            expected: m,
            found: b.len(),
        });
    }

    let zero = F::sparse_zero();
    let one = <F as One>::one();

    // Initialize solution
    let mut x: Vec<F> = match &options.x0 {
        Some(x0) => {
            if x0.len() != n {
                return Err(SparseError::DimensionMismatch {
                    expected: n,
                    found: x0.len(),
                });
            }
            x0.clone()
        }
        None => vec![zero; n],
    };

    // Set up the first vectors u and v for the bidiagonalization.
    let mut u: Vec<F> = b.to_vec();
    let normb = norm2(b);

    // Initialize from x0 if provided
    if x.iter().any(|&xi| xi != zero) {
        let ax = a.matvec(&x)?;
        for i in 0..u.len() {
            u[i] -= ax[i];
        }
    }

    let mut beta = norm2(&u);
    if beta == zero {
        return Ok(IterationResult {
            x,
            iterations: 0,
            residual_norm: zero,
            converged: true,
            message: "Zero initial residual".to_string(),
        });
    }

    // u = u / beta
    for elem in &mut u {
        *elem /= beta;
    }

    // v = A' * u
    let mut v = a.rmatvec(&u)?;
    let mut alpha = norm2(&v);

    // v = v / alpha
    if alpha > zero {
        for elem in &mut v {
            *elem /= alpha;
        }
    }

    // Initialize variables for 1st iteration.
    let mut alphabar = alpha;
    let mut zetabar = alpha * beta;
    let mut rho = one;
    let mut rhobar = one;
    let mut cbar = one;
    let mut sbar = zero;

    let mut h = v.clone();
    let mut hbar: Vec<F> = vec![zero; n];

    let tolerance = F::max(options.atol, options.rtol * normb);

    for itn in 0..options.max_iter {
        // Perform the next step of the bidiagonalization.
        // u = A * v - alpha * u
        let av = a.matvec(&v)?;
        for i in 0..u.len() {
            u[i] = av[i] - alpha * u[i];
        }
        beta = norm2(&u);

        if beta > zero {
            // u = u / beta
            for elem in &mut u {
                *elem /= beta;
            }

            // v = A' * u - beta * v
            let atu = a.rmatvec(&u)?;
            for i in 0..v.len() {
                v[i] = atu[i] - beta * v[i];
            }
            alpha = norm2(&v);

            if alpha > zero {
                for elem in &mut v {
                    *elem /= alpha;
                }
            }
        }

        // Use a plane rotation (Q_i) to turn B_i to R_i.
        let rhoold = rho;
        let (c, s, rho_new) = sym_ortho(alphabar, beta);
        rho = rho_new;
        let thetanew = s * alpha;
        alphabar = c * alpha;

        // Use a plane rotation (Qbar_i) to turn R_i^T to R_i^bar.
        let rhobarold = rhobar;
        let zetaold = zetabar / (rhoold * rhobarold);
        let thetabar = sbar * rho;
        let rhotemp = cbar * rho;
        let (cbar_new, sbar_new, rhobar_new) = sym_ortho(rhotemp, thetanew);
        cbar = cbar_new;
        sbar = sbar_new;
        rhobar = rhobar_new;
        let zeta = cbar * zetabar;
        zetabar = -sbar * zetabar;

        // Update h, hbar, x.
        let factor = thetabar * rho / (rhoold * rhobarold);
        for i in 0..n {
            hbar[i] = h[i] - factor * hbar[i];
        }
        let update_factor = zeta / (rho * rhobar);
        for i in 0..n {
            x[i] += update_factor * hbar[i];
        }
        let h_factor = thetanew / rho;
        for i in 0..n {
            h[i] = v[i] - h_factor * h[i];
        }

        // Check convergence based on zetabar (estimates ||A'r||)
        let normar = zetabar.abs();
        if normar <= tolerance {
            return Ok(IterationResult {
                x,
                iterations: itn + 1,
                residual_norm: normar,
                converged: true,
                message: "Converged".to_string(),
            });
        }
    }

    Ok(IterationResult {
        x,
        iterations: options.max_iter,
        residual_norm: zetabar.abs(),
        converged: false,
        message: "Maximum iterations reached".to_string(),
    })
}

/// Transpose-Free Quasi-Minimal Residual (TFQMR) solver
///
/// A transpose-free variant of QMR that avoids the need for A^T.
/// Implementation follows SciPy's tfqmr based on R.W. Freund (1993).
///
/// Reference:
/// R. W. Freund, "A Transpose-Free Quasi-Minimal Residual Algorithm for
/// Non-Hermitian Linear Systems", SIAM J. Sci. Comput., 14(2), 470-482, 1993.
#[allow(dead_code)]
pub fn tfqmr<F>(
    a: &dyn LinearOperator<F>,
    b: &[F],
    options: TFQMROptions<F>,
) -> SparseResult<IterationResult<F>>
where
    F: Float + NumAssign + Sum + SparseElement + 'static,
{
    let (rows, cols) = a.shape();
    if rows != cols {
        return Err(SparseError::ValueError(
            "Matrix must be square for TFQMR solver".to_string(),
        ));
    }
    if b.len() != rows {
        return Err(SparseError::DimensionMismatch {
            expected: rows,
            found: b.len(),
        });
    }

    let n = rows;
    let one = F::sparse_one();
    let zero = F::sparse_zero();

    // Initialize solution
    let mut x: Vec<F> = match &options.x0 {
        Some(x0) => {
            if x0.len() != n {
                return Err(SparseError::DimensionMismatch {
                    expected: n,
                    found: x0.len(),
                });
            }
            x0.clone()
        }
        None => vec![zero; n],
    };

    // Compute initial residual r = b - A*x
    let ax = a.matvec(&x)?;
    let r: Vec<F> = b.iter().zip(&ax).map(|(&bi, &axi)| bi - axi).collect();

    let r0norm = norm2(&r);
    let bnorm = norm2(b);
    let tolerance = F::max(options.atol, options.rtol * bnorm);

    if r0norm <= tolerance || r0norm == zero {
        return Ok(IterationResult {
            x,
            iterations: 0,
            residual_norm: r0norm,
            converged: true,
            message: "Converged with initial guess".to_string(),
        });
    }

    // Initialize vectors following SciPy's notation
    let mut u = r.clone();
    let mut w = r.clone();
    let rstar = r.clone(); // Shadow residual (r_tilde in some notations)

    // v = M^{-1} * A * r (with preconditioner)
    let ar = a.matvec(&r)?;
    let mut v = match &options.preconditioner {
        Some(m) => m.matvec(&ar)?,
        None => ar,
    };
    let mut uhat = v.clone();

    let mut d: Vec<F> = vec![zero; n];
    let mut theta = zero;
    let mut eta = zero;

    // rho = <rstar, r> (always real since rstar == r initially)
    let mut rho = dot(&rstar, &r);
    let mut rho_last = rho;
    let mut tau = r0norm;

    for iter in 0..options.max_iter {
        let even = iter % 2 == 0;

        // On even iterations, compute alpha and uNext
        let mut alpha = zero;
        let mut u_next: Vec<F> = vec![zero; n];

        if even {
            let vtrstar = dot(&rstar, &v);
            if vtrstar == zero {
                return Ok(IterationResult {
                    x,
                    iterations: iter,
                    residual_norm: tau,
                    converged: false,
                    message: "TFQMR breakdown: v'*rstar = 0".to_string(),
                });
            }
            alpha = rho / vtrstar;

            // uNext = u - alpha * v
            for i in 0..n {
                u_next[i] = u[i] - alpha * v[i];
            }
        }

        // w = w - alpha * uhat (every iteration)
        // Need alpha from either current even step or previous even step
        let alpha_used = if even {
            alpha
        } else {
            // On odd iterations, alpha comes from the previous even iteration
            // We need to save alpha across iterations
            rho / dot(&rstar, &v)
        };

        for i in 0..n {
            w[i] -= alpha_used * uhat[i];
        }

        // d = u + (theta^2 / alpha) * eta * d
        let theta_sq_over_alpha =
            if alpha_used.abs() > F::from(1e-300).expect("Failed to convert constant to float") {
                theta * theta / alpha_used
            } else {
                zero
            };
        for i in 0..n {
            d[i] = u[i] + theta_sq_over_alpha * eta * d[i];
        }

        // theta = ||w|| / tau
        theta = norm2(&w) / tau;

        // c = 1 / sqrt(1 + theta^2)
        let c = one / (one + theta * theta).sqrt();

        // tau = tau * theta * c
        tau = tau * theta * c;

        // eta = c^2 * alpha
        eta = c * c * alpha_used;

        // z = M^{-1} * d (apply preconditioner to d)
        let z = match &options.preconditioner {
            Some(m) => m.matvec(&d)?,
            None => d.clone(),
        };

        // x = x + eta * z
        for i in 0..n {
            x[i] += eta * z[i];
        }

        // Convergence criterion: tau * sqrt(iter+1) < tolerance
        let iter_f = F::from(iter + 1).expect("Failed to convert to float");
        if tau * iter_f.sqrt() < tolerance {
            return Ok(IterationResult {
                x,
                iterations: iter + 1,
                residual_norm: tau,
                converged: true,
                message: "Converged".to_string(),
            });
        }

        if !even {
            // Odd iteration updates
            // rho = <rstar, w>
            rho = dot(&rstar, &w);

            if rho == zero {
                return Ok(IterationResult {
                    x,
                    iterations: iter + 1,
                    residual_norm: tau,
                    converged: false,
                    message: "TFQMR breakdown: rho = 0".to_string(),
                });
            }

            let beta = rho / rho_last;

            // u = w + beta * u
            for i in 0..n {
                u[i] = w[i] + beta * u[i];
            }

            // v = beta * uhat + beta^2 * v
            for i in 0..n {
                v[i] = beta * uhat[i] + beta * beta * v[i];
            }

            // uhat = M^{-1} * A * u
            let au = a.matvec(&u)?;
            uhat = match &options.preconditioner {
                Some(m) => m.matvec(&au)?,
                None => au,
            };

            // v = v + uhat
            for i in 0..n {
                v[i] += uhat[i];
            }
        } else {
            // Even iteration updates
            // uhat = M^{-1} * A * uNext
            let au_next = a.matvec(&u_next)?;
            uhat = match &options.preconditioner {
                Some(m) => m.matvec(&au_next)?,
                None => au_next,
            };

            // u = uNext
            u = u_next;

            // rho_last = rho
            rho_last = rho;
        }
    }

    Ok(IterationResult {
        x,
        iterations: options.max_iter,
        residual_norm: tau,
        converged: false,
        message: "Maximum iterations reached".to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::csr::CsrMatrix;
    use crate::linalg::interface::AsLinearOperator;

    #[test]
    fn test_cg_identity() {
        // Test CG on identity matrix: I * x = b => x = b
        let identity = crate::linalg::interface::IdentityOperator::<f64>::new(3);
        let b = vec![1.0, 2.0, 3.0];
        let options = CGOptions::default();
        let result = cg(&identity, &b, options).expect("Operation failed");

        assert!(result.converged);
        for (xi, bi) in result.x.iter().zip(&b) {
            assert!((xi - bi).abs() < 1e-3);
        }
    }

    #[test]
    fn test_cg_diagonal() {
        // Test CG on diagonal matrix
        let diag = crate::linalg::interface::DiagonalOperator::new(vec![2.0, 3.0, 4.0]);
        let b = vec![2.0, 6.0, 12.0];
        let options = CGOptions::default();
        let result = cg(&diag, &b, options).expect("Operation failed");

        assert!(result.converged);
        let expected = vec![1.0, 2.0, 3.0];
        for (xi, ei) in result.x.iter().zip(&expected) {
            assert!((xi - ei).abs() < 1e-3);
        }
    }

    #[test]
    fn test_cg_sparse_matrix() {
        // Test CG on a sparse positive definite matrix
        let rows = vec![0, 0, 0, 1, 1, 1, 2, 2, 2];
        let cols = vec![0, 1, 2, 0, 1, 2, 0, 1, 2];
        let data = vec![4.0, -1.0, -1.0, -1.0, 4.0, -1.0, -1.0, -1.0, 4.0];
        let shape = (3, 3);

        let matrix = CsrMatrix::new(data, rows, cols, shape).expect("Operation failed");
        let op = matrix.as_linear_operator();

        let b = vec![1.0, 2.0, 3.0];
        let options = CGOptions::default();
        let result = cg(op.as_ref(), &b, options).expect("Operation failed");

        assert!(result.converged);
        // Verify solution by checking Ax = b
        let ax = op.matvec(&result.x).expect("Operation failed");
        for (axi, bi) in ax.iter().zip(&b) {
            assert!((axi - bi).abs() < 1e-9);
        }
    }

    #[test]
    fn test_bicgstab_identity() {
        // Test BiCGSTAB on identity matrix: I * x = b => x = b
        let identity = crate::linalg::interface::IdentityOperator::<f64>::new(3);
        let b = vec![1.0, 2.0, 3.0];
        let options = BiCGSTABOptions::default();
        let result = bicgstab(&identity, &b, options).expect("Operation failed");

        assert!(result.converged);
        for (xi, bi) in result.x.iter().zip(&b) {
            assert!((xi - bi).abs() < 1e-3);
        }
    }

    #[test]
    fn test_bicgstab_diagonal() {
        // Test BiCGSTAB on diagonal matrix
        let diag = crate::linalg::interface::DiagonalOperator::new(vec![2.0, 3.0, 4.0]);
        let b = vec![2.0, 6.0, 12.0];
        let options = BiCGSTABOptions::default();
        let result = bicgstab(&diag, &b, options).expect("Operation failed");

        assert!(result.converged);
        let expected = vec![1.0, 2.0, 3.0];
        for (xi, ei) in result.x.iter().zip(&expected) {
            assert!((xi - ei).abs() < 1e-3);
        }
    }

    #[test]
    fn test_bicgstab_non_symmetric() {
        // Test BiCGSTAB on a non-symmetric matrix
        let rows = vec![0, 0, 0, 1, 1, 1, 2, 2, 2];
        let cols = vec![0, 1, 2, 0, 1, 2, 0, 1, 2];
        let data = vec![4.0, -1.0, -2.0, -1.0, 4.0, -1.0, 0.0, -1.0, 3.0];
        let shape = (3, 3);

        let matrix = CsrMatrix::new(data, rows, cols, shape).expect("Operation failed");
        let op = matrix.as_linear_operator();

        let b = vec![1.0, 2.0, 1.0];
        let options = BiCGSTABOptions::default();
        let result = bicgstab(op.as_ref(), &b, options).expect("Operation failed");

        assert!(result.converged);
        // Verify solution by checking Ax = b
        let ax = op.matvec(&result.x).expect("Operation failed");
        for (axi, bi) in ax.iter().zip(&b) {
            assert!((axi - bi).abs() < 1e-9);
        }
    }

    #[test]
    fn test_lsqr_identity() {
        // Test LSQR on identity matrix
        let identity = crate::linalg::interface::IdentityOperator::<f64>::new(3);
        let b = vec![1.0, 2.0, 3.0];
        let options = LSQROptions::default();
        let result = lsqr(&identity, &b, options).expect("Operation failed");

        println!("Identity test - Expected: {:?}, Got: {:?}", b, result.x);
        println!(
            "Converged: {}, Iterations: {}",
            result.converged, result.iterations
        );

        assert!(result.converged);
        for (xi, bi) in result.x.iter().zip(&b) {
            assert!((xi - bi).abs() < 1e-3);
        }
    }

    #[test]
    fn test_lsqr_diagonal() {
        // Test LSQR on diagonal matrix
        let diag = crate::linalg::interface::DiagonalOperator::new(vec![2.0, 3.0, 4.0]);
        let b = vec![2.0, 6.0, 12.0];
        let options = LSQROptions::default();
        let result = lsqr(&diag, &b, options).expect("Operation failed");

        assert!(result.converged);
        let expected = vec![1.0, 2.0, 3.0];
        for (xi, ei) in result.x.iter().zip(&expected) {
            assert!((xi - ei).abs() < 1e-3);
        }
    }

    #[test]
    fn test_lsmr_identity() {
        // Test LSMR on identity matrix
        let identity = crate::linalg::interface::IdentityOperator::<f64>::new(3);
        let b = vec![1.0, 2.0, 3.0];
        let options = LSMROptions::default();
        let result = lsmr(&identity, &b, options).expect("Operation failed");

        assert!(result.converged);
        for (xi, bi) in result.x.iter().zip(&b) {
            assert!((xi - bi).abs() < 1e-3);
        }
    }

    #[test]
    fn test_lsmr_diagonal() {
        // Test LSMR on diagonal matrix
        let diag = crate::linalg::interface::DiagonalOperator::new(vec![2.0, 3.0, 4.0]);
        let b = vec![2.0, 6.0, 12.0];
        let options = LSMROptions::default();
        let result = lsmr(&diag, &b, options).expect("Operation failed");

        assert!(result.converged);
        let expected = vec![1.0, 2.0, 3.0];
        for (xi, ei) in result.x.iter().zip(&expected) {
            assert!((xi - ei).abs() < 1e-3);
        }
    }

    #[test]
    fn test_tfqmr_identity() {
        // Test TFQMR on identity matrix
        let identity = crate::linalg::interface::IdentityOperator::<f64>::new(3);
        let b = vec![1.0, 2.0, 3.0];
        let options = TFQMROptions::default();
        let result = tfqmr(&identity, &b, options).expect("Operation failed");

        assert!(result.converged);
        for (xi, bi) in result.x.iter().zip(&b) {
            assert!((xi - bi).abs() < 1e-3);
        }
    }

    #[test]
    fn test_tfqmr_diagonal() {
        // Test TFQMR on diagonal matrix
        let diag = crate::linalg::interface::DiagonalOperator::new(vec![2.0, 3.0, 4.0]);
        let b = vec![2.0, 6.0, 12.0];
        let options = TFQMROptions::default();
        let result = tfqmr(&diag, &b, options).expect("Operation failed");

        assert!(result.converged, "TFQMR did not converge");
        let expected = vec![1.0, 2.0, 3.0];
        for (xi, ei) in result.x.iter().zip(&expected) {
            assert!((xi - ei).abs() < 1e-3);
        }
    }

    #[test]
    fn test_lsqr_least_squares() {
        // Test LSQR on overdetermined system (m > n)
        let rows = vec![0, 0, 1, 1, 2, 2, 3, 3];
        let cols = vec![0, 1, 0, 1, 0, 1, 0, 1];
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
        let shape = (4, 2);

        let matrix = CsrMatrix::new(data, rows, cols, shape).expect("Operation failed");
        let op = matrix.as_linear_operator();

        let b = vec![1.0, 2.0, 3.0, 4.0];
        let options = LSQROptions::default();
        let result = lsqr(op.as_ref(), &b, options).expect("Operation failed");

        // LSQR should converge for overdetermined systems
        assert!(result.converged || result.residual_norm < 1e-6);
    }

    #[test]
    fn test_solver_options_defaults() {
        let lsqr_opts = LSQROptions::<f64>::default();
        assert_eq!(lsqr_opts.max_iter, 1000);
        assert!(lsqr_opts.x0.is_none());

        let lsmr_opts = LSMROptions::<f64>::default();
        assert_eq!(lsmr_opts.max_iter, 1000);
        assert_eq!(lsmr_opts.damp, 0.0);
        assert!(lsmr_opts.x0.is_none());

        let tfqmr_opts = TFQMROptions::<f64>::default();
        assert_eq!(tfqmr_opts.max_iter, 1000);
        assert!(tfqmr_opts.x0.is_none());
        assert!(tfqmr_opts.preconditioner.is_none());
    }
}