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
//! Basic linear algebra operations with Array
//! Includes matrix multiplication, dot product, matrix inversion, etc.
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use crate::array::Array;
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use crate::error::{NumRs2Error, Result};
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use num_traits::{Float, ToPrimitive};
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use std::fmt::Debug;
// Matrix decomposition submodule
#[path = "../linalg_decomposition.rs"]
pub mod decomposition;
// Solve operations submodule
#[path = "../linalg_solve.rs"]
pub mod solve;
// Import submodules
pub mod iterative_solvers;
pub mod matrix_ops;
pub mod randomized;
pub mod tensor_decomp;
pub mod tensor_ops;
pub mod vector_ops;
// Re-export all functions for backward compatibility - conditional on lapack feature
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub use decomposition::{cholesky, eig, qr, svd};
#[cfg(feature = "lapack")]
pub use solve::{inv, solve};
// Re-export conditional features
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub use decomposition::matrix_rank;
#[cfg(feature = "lapack")]
pub use matrix_ops::{det, matrix_power};
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub use solve::pinv;
pub use tensor_ops::{einsum, kron, tensordot};
pub use vector_ops::{complex_vdot, inner, norm, outer, trace, vdot};
// Randomized linear algebra
pub use randomized::{
random_projection, randomized_low_rank_approximation, randomized_range_finder, randomized_svd,
ProjectionType,
};
// Tensor decompositions
pub use tensor_decomp::{
cp_als, cp_als_with_config, cp_reconstruct, nonnegative_cp_als, tucker_decomposition,
tucker_reconstruct, CpResult, DecompConfig, TuckerResult,
};
// Additional standalone functions for improved compatibility
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub use crate::new_modules::matrix_decomp::{
lstsq, lu, pivoted_cholesky, slogdet, svd as svd_enhanced,
};
/// Set the number of threads for LAPACK operations
pub fn set_lapack_threads(threads: usize) {
// We can use blas_src's set_num_threads when it's available
// For now, we'll just provide this as a placeholder
let _threads = threads;
}
/// Implementation for when matrix_decomp feature is enabled
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
impl<T> Array<T>
where
T: Float
+ Clone
+ Debug
+ std::ops::AddAssign
+ std::ops::MulAssign
+ std::ops::DivAssign
+ std::ops::SubAssign
+ std::fmt::Display,
{
/// Compute the determinant of a matrix using LU decomposition for large matrices
/// and direct formula for small matrices.
///
/// This implementation includes:
/// 1. Optimized direct formulas for 1x1, 2x2, and 3x3 matrices
/// 2. LU decomposition with partial pivoting for larger matrices
/// 3. Scaling to prevent overflow/underflow in intermediate calculations
/// 4. Near-zero detection with appropriate thresholds
pub fn det(&self) -> Result<T> {
// Verify the array is square
let shape = self.shape();
if shape.len() != 2 || shape[0] != shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"determinant requires a square matrix".to_string(),
));
}
// Optimized path for small matrices (1x1, 2x2, 3x3)
let n = shape[0];
let data = self.to_vec();
// For 1x1 matrix, determinant is the single element
if n == 1 {
return Ok(data[0]);
}
// For 2x2 matrix, use direct formula: ad - bc
else if n == 2 {
return Ok(data[0] * data[3] - data[1] * data[2]);
}
// For 3x3 matrix, use cofactor expansion (optimized)
else if n == 3 {
// For 3x3 matrix using cofactor expansion
let det = data[0] * (data[4] * data[8] - data[5] * data[7])
- data[1] * (data[3] * data[8] - data[5] * data[6])
+ data[2] * (data[3] * data[7] - data[4] * data[6]);
return Ok(det);
}
// For 4x4 matrix, use cofactor expansion with smaller determinants
else if n == 4 {
// Use optimized cofactor expansion for 4x4
let mut det = T::zero();
// First row cofactor expansion
for j in 0..4 {
// Get the 3x3 minor by removing row 0 and column j
let mut minor_data = Vec::with_capacity(9);
for row in 1..4 {
for col in 0..4 {
if col != j {
minor_data.push(data[row * 4 + col]);
}
}
}
// Create 3x3 submatrix for minor
let minor = Array::from_vec(minor_data).reshape(&[3, 3]);
// Compute 3x3 determinant (we know this works from the 3x3 case)
let minor_det = minor.det()?;
// Add to determinant with appropriate sign
let sign = if j % 2 == 0 { T::one() } else { -T::one() };
det += sign * data[j] * minor_det;
}
return Ok(det);
}
// For larger matrices (n > 4), use LU decomposition
// This is more numerically stable and efficient
// Step 1: Obtain LU decomposition with pivoting
// We'll use the implementation in matrix_decomp module
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use crate::new_modules::matrix_decomp::lu;
// Calculate LU decomposition
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
let (_, u, p) = lu(self)?;
#[cfg(not(feature = "matrix_decomp"))]
return Err(NumRs2Error::FeatureNotEnabled(
"matrix_decomp feature required for LU decomposition".to_string(),
));
// For LU decomposition with row pivoting (PA = LU),
// det(A) = det(P) * det(L) * det(U)
// det(L) = 1 (since L has 1's on diagonal)
// det(U) = product of diagonal elements
// det(P) = (-1)^s where s is the number of row swaps
// Calculate determinant of U (product of diagonal elements)
let mut det_u = T::one();
for i in 0..n {
det_u *= u.get(&[i, i])?;
}
// Calculate determinant of P (parity of permutation)
// We need to count the number of swaps in the permutation
let p_vec = p.to_vec();
let mut visited = vec![false; n];
let mut parity = 0;
for i in 0..n {
if !visited[i] {
let mut j = i;
let mut cycle_length = 0;
while !visited[j] {
visited[j] = true;
j = p_vec[j];
cycle_length += 1;
}
// A cycle of length k requires k-1 swaps
if cycle_length > 1 {
parity += cycle_length - 1;
}
}
}
// Calculate final determinant
let det_p = if parity % 2 == 0 { T::one() } else { -T::one() };
Ok(det_p * det_u)
}
/// Compute the inverse of a matrix
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 matrices
/// 2. LU decomposition with partial pivoting for larger matrices
/// 3. Numerical stability checks with appropriate condition number thresholds
/// 4. Proper error handling for singular or ill-conditioned matrices
pub fn inv(&self) -> Result<Array<T>> {
// Check if the matrix is square
let shape = self.shape();
if shape.len() != 2 || shape[0] != shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"inverse requires a square matrix".to_string(),
));
}
let n = shape[0];
// Check if the matrix is invertible using determinant
// This is efficient for small matrices and catches perfect singularity
let det = self.det()?;
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"matrix is singular and cannot be inverted".to_string(),
));
}
// For small matrices, use direct formulas for better efficiency and accuracy
if n == 1 {
// For 1x1 matrix, inverse is 1/a
let a = self.get(&[0, 0])?;
let result = vec![T::one() / a];
return Ok(Array::from_vec(result).reshape(&[1, 1]));
} else if n == 2 {
// For 2x2 matrix, use the formula:
// [a b]^-1 = (1/det) * [d -b]
// [c d] [-c a]
let data = self.to_vec();
let a = data[0];
let b = data[1];
let c = data[2];
let d = data[3];
let inv_det = T::one() / det;
let result = vec![d * inv_det, -b * inv_det, -c * inv_det, a * inv_det];
return Ok(Array::from_vec(result).reshape(&[2, 2]));
} else if n == 3 {
// For 3x3 matrix, use adjugate formula:
// A^-1 = (1/det) * adj(A)
let data = self.to_vec();
// Compute cofactors
let c00 = data[4] * data[8] - data[5] * data[7];
let c01 = -(data[3] * data[8] - data[5] * data[6]);
let c02 = data[3] * data[7] - data[4] * data[6];
let c10 = -(data[1] * data[8] - data[2] * data[7]);
let c11 = data[0] * data[8] - data[2] * data[6];
let c12 = -(data[0] * data[7] - data[1] * data[6]);
let c20 = data[1] * data[5] - data[2] * data[4];
let c21 = -(data[0] * data[5] - data[2] * data[3]);
let c22 = data[0] * data[4] - data[1] * data[3];
// Construct the adjugate (transpose of cofactor matrix)
let inv_det = T::one() / det;
let result = vec![
c00 * inv_det,
c10 * inv_det,
c20 * inv_det,
c01 * inv_det,
c11 * inv_det,
c21 * inv_det,
c02 * inv_det,
c12 * inv_det,
c22 * inv_det,
];
return Ok(Array::from_vec(result).reshape(&[3, 3]));
}
// For larger matrices, use LU decomposition
// Get LU decomposition with pivoting: PA = LU
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use crate::new_modules::matrix_decomp::lu;
// Step 1: Calculate LU decomposition
#[cfg(feature = "matrix_decomp")]
let (l, u, p) = lu(self)?;
#[cfg(not(feature = "matrix_decomp"))]
return Err(NumRs2Error::FeatureNotEnabled(
"matrix_decomp feature required for LU decomposition".to_string(),
));
// Step 2: Create a result matrix
let mut result = Array::zeros(&[n, n]);
// Step 3: Solve LUX = I column by column to find A^-1
// For each column of the identity matrix...
for j in 0..n {
// Create the j-th column of identity matrix
let mut b = vec![T::zero(); n];
b[j] = T::one();
// Step 3.1: Apply permutation to b (Pb)
let mut pb = vec![T::zero(); n];
#[allow(clippy::needless_range_loop)]
for i in 0..n {
let p_idx = p.get(&[i])?.to_usize().unwrap_or(i);
pb[i] = b[p_idx];
}
// Step 3.2: Forward substitution to solve Ly = Pb
let mut y = vec![T::zero(); n];
for i in 0..n {
let mut sum = pb[i];
#[allow(clippy::needless_range_loop)]
for k in 0..i {
sum -= l.get(&[i, k])? * y[k];
}
y[i] = sum; // L has 1's on diagonal
}
// Step 3.3: Back substitution to solve Ux = y
let mut x = vec![T::zero(); n];
for i in (0..n).rev() {
let mut sum = y[i];
#[allow(clippy::needless_range_loop)]
for k in (i + 1)..n {
sum -= u.get(&[i, k])? * x[k];
}
x[i] = sum / u.get(&[i, i])?;
}
// Step 3.4: Store the solution in the j-th column of the result
#[allow(clippy::needless_range_loop)]
for i in 0..n {
result.set(&[i, j], x[i])?;
}
}
// Step 4: Verify numerical stability
// In a real implementation, we would check the condition number
// and provide a warning for ill-conditioned matrices
// For debugging: check that A * A^-1 ≈ I
// This is expensive so we'd only do it in debug mode
#[cfg(debug_assertions)]
{
let product = self.matmul(&result)?;
let mut max_error = T::zero();
for i in 0..n {
for j in 0..n {
let expected = if i == j { T::one() } else { T::zero() };
let actual = product.get(&[i, j])?;
let error = num_traits::Float::abs(actual - expected);
if error > max_error {
max_error = error;
}
}
}
let eps = T::epsilon();
let acceptable_error = eps
* T::from(n).expect("n is a valid usize")
* T::from(100.0).expect("100.0 is a valid f64 constant");
if max_error > acceptable_error {
eprintln!(
"Warning: Matrix inversion may be numerically unstable. Max error: {}",
max_error
);
}
}
Ok(result)
}
/// Solve a linear system Ax = b
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 systems
/// 2. LU decomposition with partial pivoting for larger systems
/// 3. Numerical stability checks with appropriate condition number thresholds
/// 4. Proper error handling for singular or ill-conditioned matrices
pub fn solve(&self, b: &Array<T>) -> Result<Array<T>> {
// Check dimensions
let a_shape = self.shape();
let b_shape = b.shape();
if a_shape.len() != 2 || a_shape[0] != a_shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"solve requires a square coefficient matrix".to_string(),
));
}
if b_shape.len() != 1 || b_shape[0] != a_shape[0] {
return Err(NumRs2Error::ShapeMismatch {
expected: vec![a_shape[0]],
actual: b_shape,
});
}
let n = a_shape[0];
// Quick check for singularity using determinant
// This is efficient for small matrices and catches perfect singularity
let det = self.det()?;
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular and cannot be solved".to_string(),
));
}
// Special fast paths for small systems
if n == 1 {
// 1x1 system - trivial solution
let a_val = self.get(&[0, 0])?;
let b_val = b.get(&[0])?;
return Ok(Array::from_vec(vec![b_val / a_val]));
} else if n == 2 {
// 2x2 system - use Cramer's rule
let a_data = self.to_vec();
let b_data = b.to_vec();
let x1 = (b_data[0] * a_data[3] - a_data[1] * b_data[1]) / det;
let x2 = (a_data[0] * b_data[1] - b_data[0] * a_data[2]) / det;
return Ok(Array::from_vec(vec![x1, x2]));
} else if n == 3 {
// 3x3 system - use direct formula
let a_data = self.to_vec();
let b_data = b.to_vec();
// Compute determinant and cofactors
let a11 = a_data[0];
let a12 = a_data[1];
let a13 = a_data[2];
let a21 = a_data[3];
let a22 = a_data[4];
let a23 = a_data[5];
let a31 = a_data[6];
let a32 = a_data[7];
let a33 = a_data[8];
// Calculate cofactors for direct solution
let c11 = a22 * a33 - a23 * a32;
let c12 = -(a21 * a33 - a23 * a31);
let c13 = a21 * a32 - a22 * a31;
let c21 = -(a12 * a33 - a13 * a32);
let c22 = a11 * a33 - a13 * a31;
let c23 = -(a11 * a32 - a12 * a31);
let c31 = a12 * a23 - a13 * a22;
let c32 = -(a11 * a23 - a13 * a21);
let c33 = a11 * a22 - a12 * a21;
let inv_det = T::one() / det;
// Multiply inverse of A (which is adjugate/det) by b
let x1 = (c11 * b_data[0] + c21 * b_data[1] + c31 * b_data[2]) * inv_det;
let x2 = (c12 * b_data[0] + c22 * b_data[1] + c32 * b_data[2]) * inv_det;
let x3 = (c13 * b_data[0] + c23 * b_data[1] + c33 * b_data[2]) * inv_det;
return Ok(Array::from_vec(vec![x1, x2, x3]));
}
// For larger systems, use SCIRS
use crate::interop::scirs_compat::solve_linear_system;
solve_linear_system(self, b)
}
/// Solve a linear system Ax = b
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 systems
/// 2. LU decomposition with partial pivoting for larger systems
/// 3. Numerical stability checks with appropriate condition number thresholds
/// 4. Proper error handling for singular or ill-conditioned matrices
#[cfg(all(feature = "matrix_decomp", not(feature = "scirs")))]
pub fn solve(&self, b: &Array<T>) -> Result<Array<T>> {
// Check dimensions
let a_shape = self.shape();
let b_shape = b.shape();
if a_shape.len() != 2 || a_shape[0] != a_shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"solve requires a square coefficient matrix".to_string(),
));
}
if b_shape.len() != 1 || b_shape[0] != a_shape[0] {
return Err(NumRs2Error::ShapeMismatch {
expected: vec![a_shape[0]],
actual: b_shape,
});
}
let n = a_shape[0];
// Quick check for singularity using determinant
// This is efficient for small matrices and catches perfect singularity
let det = self.det()?;
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular and cannot be solved".to_string(),
));
}
// Special fast paths for small systems
if n == 1 {
// 1x1 system - trivial solution
let a_val = self.get(&[0, 0])?;
let b_val = b.get(&[0])?;
return Ok(Array::from_vec(vec![b_val / a_val]));
} else if n == 2 {
// 2x2 system - use Cramer's rule
let a_data = self.to_vec();
let b_data = b.to_vec();
let x1 = (b_data[0] * a_data[3] - a_data[1] * b_data[1]) / det;
let x2 = (a_data[0] * b_data[1] - b_data[0] * a_data[2]) / det;
return Ok(Array::from_vec(vec![x1, x2]));
} else if n == 3 {
// 3x3 system - use direct formula
let a_data = self.to_vec();
let b_data = b.to_vec();
// Compute determinant and cofactors
let a11 = a_data[0];
let a12 = a_data[1];
let a13 = a_data[2];
let a21 = a_data[3];
let a22 = a_data[4];
let a23 = a_data[5];
let a31 = a_data[6];
let a32 = a_data[7];
let a33 = a_data[8];
// Calculate cofactors for direct solution
let c11 = a22 * a33 - a23 * a32;
let c12 = -(a21 * a33 - a23 * a31);
let c13 = a21 * a32 - a22 * a31;
let c21 = -(a12 * a33 - a13 * a32);
let c22 = a11 * a33 - a13 * a31;
let c23 = -(a11 * a32 - a12 * a31);
let c31 = a12 * a23 - a13 * a22;
let c32 = -(a11 * a23 - a13 * a21);
let c33 = a11 * a22 - a12 * a21;
let inv_det = T::one() / det;
// Multiply inverse of A (which is adjugate/det) by b
let x1 = (c11 * b_data[0] + c21 * b_data[1] + c31 * b_data[2]) * inv_det;
let x2 = (c12 * b_data[0] + c22 * b_data[1] + c32 * b_data[2]) * inv_det;
let x3 = (c13 * b_data[0] + c23 * b_data[1] + c33 * b_data[2]) * inv_det;
return Ok(Array::from_vec(vec![x1, x2, x3]));
}
// For larger systems, use LU decomposition with partial pivoting
// Get LU decomposition with pivoting: PA = LU
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use crate::new_modules::matrix_decomp::lu;
// Step 1: Calculate LU decomposition
#[cfg(feature = "matrix_decomp")]
let (l, u, p) = lu(self)?;
#[cfg(not(feature = "matrix_decomp"))]
return Err(NumRs2Error::FeatureNotEnabled(
"matrix_decomp feature required for LU decomposition".to_string(),
));
// Step 2: Apply permutation to b (Pb)
let mut pb = vec![T::zero(); n];
#[allow(clippy::needless_range_loop)]
for i in 0..n {
let p_idx = p.get(&[i])?.to_usize().unwrap_or(i);
pb[i] = b.get(&[p_idx])?;
}
// Step 3: Forward substitution to solve Ly = Pb
let mut y = vec![T::zero(); n];
for i in 0..n {
let mut sum = pb[i];
#[allow(clippy::needless_range_loop)]
for k in 0..i {
sum -= l.get(&[i, k])? * y[k];
}
y[i] = sum; // L has 1's on diagonal
}
// Step 4: Back substitution to solve Ux = y
let mut x = vec![T::zero(); n];
for i in (0..n).rev() {
let mut sum = y[i];
#[allow(clippy::needless_range_loop)]
for k in (i + 1)..n {
sum -= u.get(&[i, k])? * x[k];
}
x[i] = sum / u.get(&[i, i])?;
}
// Step 5: Return the solution vector
Ok(Array::from_vec(x))
}
/// Solve a linear system Ax = b
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 systems
/// 2. Gaussian elimination with partial pivoting for larger systems
/// 3. Numerical stability checks with appropriate condition number thresholds
/// 4. Proper error handling for singular or ill-conditioned matrices
#[cfg(not(feature = "matrix_decomp"))]
pub fn solve(&self, b: &Array<T>) -> Result<Array<T>> {
// Check dimensions
let a_shape = self.shape();
let b_shape = b.shape();
if a_shape.len() != 2 || a_shape[0] != a_shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"solve requires a square coefficient matrix".to_string(),
));
}
if b_shape.len() != 1 || b_shape[0] != a_shape[0] {
return Err(NumRs2Error::ShapeMismatch {
expected: vec![a_shape[0]],
actual: b_shape,
});
}
let n = a_shape[0];
// Fast paths for small systems
if n == 1 {
// 1x1 system - trivial solution
let a_val = self.get(&[0, 0])?;
if a_val == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular and cannot be solved".to_string(),
));
}
let b_val = b.get(&[0])?;
return Ok(Array::from_vec(vec![b_val / a_val]));
} else if n == 2 {
// 2x2 system - use Cramer's rule
let a_data = self.to_vec();
let b_data = b.to_vec();
let det = a_data[0] * a_data[3] - a_data[1] * a_data[2];
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular".to_string(),
));
}
let x1 = (b_data[0] * a_data[3] - a_data[1] * b_data[1]) / det;
let x2 = (a_data[0] * b_data[1] - b_data[0] * a_data[2]) / det;
return Ok(Array::from_vec(vec![x1, x2]));
} else if n == 3 {
// 3x3 system - use direct formula through cofactors
let a_data = self.to_vec();
let b_data = b.to_vec();
// Calculate determinant
let det = a_data[0] * (a_data[4] * a_data[8] - a_data[5] * a_data[7])
- a_data[1] * (a_data[3] * a_data[8] - a_data[5] * a_data[6])
+ a_data[2] * (a_data[3] * a_data[7] - a_data[4] * a_data[6]);
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular".to_string(),
));
}
// Compute determinant and cofactors
let a11 = a_data[0];
let a12 = a_data[1];
let a13 = a_data[2];
let a21 = a_data[3];
let a22 = a_data[4];
let a23 = a_data[5];
let a31 = a_data[6];
let a32 = a_data[7];
let a33 = a_data[8];
// Calculate cofactors for direct solution
let c11 = a22 * a33 - a23 * a32;
let c12 = -(a21 * a33 - a23 * a31);
let c13 = a21 * a32 - a22 * a31;
let c21 = -(a12 * a33 - a13 * a32);
let c22 = a11 * a33 - a13 * a31;
let c23 = -(a11 * a32 - a12 * a31);
let c31 = a12 * a23 - a13 * a22;
let c32 = -(a11 * a23 - a13 * a21);
let c33 = a11 * a22 - a12 * a21;
let inv_det = T::one() / det;
// Multiply inverse of A (which is adjugate/det) by b
let x1 = (c11 * b_data[0] + c21 * b_data[1] + c31 * b_data[2]) * inv_det;
let x2 = (c12 * b_data[0] + c22 * b_data[1] + c32 * b_data[2]) * inv_det;
let x3 = (c13 * b_data[0] + c23 * b_data[1] + c33 * b_data[2]) * inv_det;
return Ok(Array::from_vec(vec![x1, x2, x3]));
}
// For larger systems, use Gaussian elimination with partial pivoting
// Create an augmented matrix [A|b]
let mut aug = Array::zeros(&[n, n + 1]);
// Fill in the augmented matrix
for i in 0..n {
for j in 0..n {
aug.set(&[i, j], self.get(&[i, j])?)?;
}
aug.set(&[i, n], b.get(&[i])?)?;
}
// Gaussian elimination with partial pivoting
for i in 0..n {
// Find pivot (maximum absolute value in current column)
let mut max_val = num_traits::Float::abs(aug.get(&[i, i])?);
let mut max_row = i;
for j in (i + 1)..n {
let abs_val = num_traits::Float::abs(aug.get(&[j, i])?);
if abs_val > max_val {
max_val = abs_val;
max_row = j;
}
}
// Check for singularity
let eps = T::epsilon();
if max_val < eps * T::from(n).expect("n is a valid usize") {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is numerically singular".to_string(),
));
}
// Swap rows if needed
if max_row != i {
for j in i..(n + 1) {
let temp = aug.get(&[i, j])?;
aug.set(&[i, j], aug.get(&[max_row, j])?)?;
aug.set(&[max_row, j], temp)?;
}
}
// Eliminate below
for j in (i + 1)..n {
let factor = aug.get(&[j, i])? / aug.get(&[i, i])?;
for k in i..(n + 1) {
let val = aug.get(&[j, k])? - factor * aug.get(&[i, k])?;
aug.set(&[j, k], val)?;
}
}
}
// Back substitution
let mut x = vec![T::zero(); n];
for i in (0..n).rev() {
let mut sum = aug.get(&[i, n])?;
for j in (i + 1)..n {
sum -= aug.get(&[i, j])? * x[j];
}
x[i] = sum / aug.get(&[i, i])?;
}
Ok(Array::from_vec(x))
}
/// Compute the singular value decomposition of a matrix
pub fn svd(&self) -> Result<(Array<T>, Array<T>, Array<T>)> {
// Use the implementation from new_modules::matrix_decomp
use crate::new_modules::matrix_decomp::svd;
let (u, s_real, vt) = svd(self)?;
// Convert singular values from Real to T
// Since T is a Float type and Real is its real component type,
// for real-valued matrices T == Real, so this is safe
let s_vec: Vec<T> = s_real
.to_vec()
.into_iter()
.map(|val| {
// Convert from Real to T (for real matrices, this is identity)
num_traits::NumCast::from(val).unwrap_or(T::zero())
})
.collect();
let s = Array::from_vec(s_vec);
Ok((u, s, vt))
}
/// Compute the eigenvalues and eigenvectors of a square matrix
pub fn eig(&self) -> Result<(Array<T>, Array<T>)> {
// Check if the matrix is square
let shape = self.shape();
if shape.len() != 2 || shape[0] != shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"eigendecomposition requires a square matrix".to_string(),
));
}
// This would use ndarray-linalg's eigenvalue computation in a full version
// For now, we'll just return placeholder values
let n = shape[0];
let eigenvalues = Array::zeros(&[n]);
let eigenvectors = Array::zeros(&[n, n]);
Ok((eigenvalues, eigenvectors))
}
/// Compute the Cholesky decomposition of a matrix
pub fn cholesky(&self) -> Result<Array<T>> {
// Use the implementation from new_modules::matrix_decomp
use crate::new_modules::matrix_decomp::cholesky;
cholesky(self)
}
/// Compute the QR decomposition of a matrix
pub fn qr(&self) -> Result<(Array<T>, Array<T>)> {
// Use the implementation from new_modules::matrix_decomp
use crate::new_modules::matrix_decomp::qr;
qr(self)
}
}
/// A simplified direct implementation of linear algebra functions for Array
#[cfg(not(feature = "matrix_decomp"))]
impl<T> Array<T>
where
T: Float
+ Clone
+ Debug
+ std::ops::AddAssign
+ std::ops::MulAssign
+ std::ops::SubAssign
+ std::fmt::Display,
{
/// Compute the determinant of a matrix using LU decomposition for large matrices
/// and direct formula for small matrices.
///
/// This implementation includes:
/// 1. Optimized direct formulas for 1x1, 2x2, and 3x3 matrices
/// 2. LU decomposition with partial pivoting for larger matrices
/// 3. Scaling to prevent overflow/underflow in intermediate calculations
/// 4. Near-zero detection with appropriate thresholds
pub fn det(&self) -> Result<T> {
// Verify the array is square
let shape = self.shape();
if shape.len() != 2 || shape[0] != shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"determinant requires a square matrix".to_string(),
));
}
// Optimized path for small matrices (1x1, 2x2, 3x3)
let n = shape[0];
let data = self.to_vec();
// For 1x1 matrix, determinant is the single element
if n == 1 {
return Ok(data[0]);
}
// For 2x2 matrix, use direct formula: ad - bc
else if n == 2 {
return Ok(data[0] * data[3] - data[1] * data[2]);
}
// For 3x3 matrix, use cofactor expansion (optimized)
else if n == 3 {
// For 3x3 matrix using cofactor expansion
let det = data[0] * (data[4] * data[8] - data[5] * data[7])
- data[1] * (data[3] * data[8] - data[5] * data[6])
+ data[2] * (data[3] * data[7] - data[4] * data[6]);
return Ok(det);
}
// For 4x4 matrix, use cofactor expansion with smaller determinants
else if n == 4 {
// Use optimized cofactor expansion for 4x4
let mut det = T::zero();
// First row cofactor expansion
for j in 0..4 {
// Get the 3x3 minor by removing row 0 and column j
let mut minor_data = Vec::with_capacity(9);
for row in 1..4 {
for col in 0..4 {
if col != j {
minor_data.push(data[row * 4 + col]);
}
}
}
// Create 3x3 submatrix for minor
let minor = Array::from_vec(minor_data).reshape(&[3, 3]);
// Compute 3x3 determinant (we know this works from the 3x3 case)
let minor_det = minor.det()?;
// Add to determinant with appropriate sign
let sign = if j % 2 == 0 { T::one() } else { -T::one() };
det += sign * data[j] * minor_det;
}
return Ok(det);
}
// For larger matrices (n > 4), use in-place LU decomposition
// Step 1: Perform Gaussian elimination with scaled partial pivoting
let mut a_copy = self.clone();
let mut det_sign = T::one(); // Track sign changes due to row swaps
// Scale factors for each row (for numerical stability)
let mut row_scale = vec![T::zero(); n];
for i in 0..n {
let mut max_in_row = T::zero();
for j in 0..n {
let abs_val = num_traits::Float::abs(a_copy.get(&[i, j])?);
if abs_val > max_in_row {
max_in_row = abs_val;
}
}
// If row is all zeros, determinant is zero
if max_in_row == T::zero() {
return Ok(T::zero());
}
row_scale[i] = T::one() / max_in_row;
}
// LU decomposition in-place with partial pivoting
for k in 0..n - 1 {
// Find pivot using scaled partial pivoting
let mut p_row = k;
let mut p_val = num_traits::Float::abs(a_copy.get(&[k, k])?) * row_scale[k];
for i in k + 1..n {
let val = num_traits::Float::abs(a_copy.get(&[i, k])?) * row_scale[i];
if val > p_val {
p_row = i;
p_val = val;
}
}
// Check for numerical singularity
if p_val < T::epsilon() * T::from(100.0).expect("100.0 is a valid f64 constant") {
// Matrix is numerically singular - determinant is effectively zero
return Ok(T::zero());
}
// Swap rows if needed
if p_row != k {
for j in 0..n {
let temp = a_copy.get(&[k, j])?;
a_copy.set(&[k, j], a_copy.get(&[p_row, j])?)?;
a_copy.set(&[p_row, j], temp)?;
}
// Swap scale factors too
row_scale.swap(k, p_row);
// Each row swap changes the sign of the determinant
det_sign = -det_sign;
}
// Perform elimination
let pivot = a_copy.get(&[k, k])?;
for i in k + 1..n {
let factor = a_copy.get(&[i, k])? / pivot;
a_copy.set(&[i, k], factor)?; // Store multiplier in L part
for j in k + 1..n {
let val = a_copy.get(&[i, j])? - factor * a_copy.get(&[k, j])?;
a_copy.set(&[i, j], val)?;
}
}
}
// Compute determinant as product of diagonal elements times the sign
let mut det = det_sign;
for i in 0..n {
det *= a_copy.get(&[i, i])?;
}
Ok(det)
}
/// Compute the inverse of a matrix
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 matrices
/// 2. Gaussian elimination with pivoting for larger matrices
/// 3. Numerical stability checks with appropriate tolerances
/// 4. Proper error handling for singular or ill-conditioned matrices
pub fn inv(&self) -> Result<Array<T>> {
// Check if the matrix is square
let shape = self.shape();
if shape.len() != 2 || shape[0] != shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"inverse requires a square matrix".to_string(),
));
}
let n = shape[0];
// Check if the matrix is invertible using determinant
// This is efficient for small matrices and catches perfect singularity
let det = self.det()?;
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"matrix is singular and cannot be inverted".to_string(),
));
}
// For small matrices, use direct formulas for better efficiency and accuracy
if n == 1 {
// For 1x1 matrix, inverse is 1/a
let a = self.get(&[0, 0])?;
let result = vec![T::one() / a];
return Ok(Array::from_vec(result).reshape(&[1, 1]));
} else if n == 2 {
// For 2x2 matrix, use the formula:
// [a b]^-1 = (1/det) * [d -b]
// [c d] [-c a]
let data = self.to_vec();
let a = data[0];
let b = data[1];
let c = data[2];
let d = data[3];
let inv_det = T::one() / det;
let result = vec![d * inv_det, -b * inv_det, -c * inv_det, a * inv_det];
return Ok(Array::from_vec(result).reshape(&[2, 2]));
} else if n == 3 {
// For 3x3 matrix, use adjugate formula:
// A^-1 = (1/det) * adj(A)
let data = self.to_vec();
// Compute cofactors
let c00 = data[4] * data[8] - data[5] * data[7];
let c01 = -(data[3] * data[8] - data[5] * data[6]);
let c02 = data[3] * data[7] - data[4] * data[6];
let c10 = -(data[1] * data[8] - data[2] * data[7]);
let c11 = data[0] * data[8] - data[2] * data[6];
let c12 = -(data[0] * data[7] - data[1] * data[6]);
let c20 = data[1] * data[5] - data[2] * data[4];
let c21 = -(data[0] * data[5] - data[2] * data[3]);
let c22 = data[0] * data[4] - data[1] * data[3];
// Construct the adjugate (transpose of cofactor matrix)
let inv_det = T::one() / det;
let result = vec![
c00 * inv_det,
c10 * inv_det,
c20 * inv_det,
c01 * inv_det,
c11 * inv_det,
c21 * inv_det,
c02 * inv_det,
c12 * inv_det,
c22 * inv_det,
];
return Ok(Array::from_vec(result).reshape(&[3, 3]));
}
// For larger matrices, use Gaussian elimination with identity matrix augmentation
// This is a classic method for matrix inversion without requiring external libraries
// Step 1: Create an augmented matrix [A|I]
let mut aug = Array::zeros(&[n, 2 * n]);
// Fill the left side with our matrix
for i in 0..n {
for j in 0..n {
aug.set(&[i, j], self.get(&[i, j])?)?;
}
}
// Fill the right side with identity matrix
for i in 0..n {
aug.set(&[i, i + n], T::one())?;
}
// Step 2: Compute row-echelon form using Gaussian elimination with pivoting
for i in 0..n {
// Find pivot (maximum value in current column)
let mut max_val = num_traits::Float::abs(aug.get(&[i, i])?);
let mut max_row = i;
for j in (i + 1)..n {
let abs_val = num_traits::Float::abs(aug.get(&[j, i])?);
if abs_val > max_val {
max_val = abs_val;
max_row = j;
}
}
// Check for singularity
let eps = T::epsilon();
if max_val < eps * T::from(n).expect("n is a valid usize") {
return Err(NumRs2Error::InvalidOperation(
"matrix is numerically singular and cannot be inverted".to_string(),
));
}
// Swap rows if needed
if max_row != i {
for j in 0..(2 * n) {
let temp = aug.get(&[i, j])?;
aug.set(&[i, j], aug.get(&[max_row, j])?)?;
aug.set(&[max_row, j], temp)?;
}
}
// Scale current row to get 1 on diagonal
let pivot = aug.get(&[i, i])?;
for j in 0..(2 * n) {
let val = aug.get(&[i, j])? / pivot;
aug.set(&[i, j], val)?;
}
// Eliminate current column for all other rows
for j in 0..n {
if j != i {
let factor = aug.get(&[j, i])?;
for k in 0..(2 * n) {
let val = aug.get(&[j, k])? - factor * aug.get(&[i, k])?;
aug.set(&[j, k], val)?;
}
}
}
}
// Step 3: Extract the right side, which is now A^-1
let mut result = Array::zeros(&[n, n]);
for i in 0..n {
for j in 0..n {
result.set(&[i, j], aug.get(&[i, j + n])?)?;
}
}
// Step 4: Verify numerical stability
#[cfg(debug_assertions)]
{
let product = self.matmul(&result)?;
let mut max_error = T::zero();
for i in 0..n {
for j in 0..n {
let expected = if i == j { T::one() } else { T::zero() };
let actual = product.get(&[i, j])?;
let error = num_traits::Float::abs(actual - expected);
if error > max_error {
max_error = error;
}
}
}
let eps = T::epsilon();
let acceptable_error = eps
* T::from(n).expect("n is a valid usize")
* T::from(100.0).expect("100.0 is a valid f64 constant");
if max_error > acceptable_error {
eprintln!(
"Warning: Matrix inversion may be numerically unstable. Max error: {}",
max_error
);
}
}
Ok(result)
}
/// Solve a linear system Ax = b
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 systems
/// 2. LU decomposition with partial pivoting for larger systems
/// 3. Numerical stability checks with appropriate condition number thresholds
/// 4. Proper error handling for singular or ill-conditioned matrices
pub fn solve(&self, b: &Array<T>) -> Result<Array<T>> {
// Check dimensions
let a_shape = self.shape();
let b_shape = b.shape();
if a_shape.len() != 2 || a_shape[0] != a_shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"solve requires a square coefficient matrix".to_string(),
));
}
if b_shape.len() != 1 || b_shape[0] != a_shape[0] {
return Err(NumRs2Error::ShapeMismatch {
expected: vec![a_shape[0]],
actual: b_shape,
});
}
let n = a_shape[0];
// Quick check for singularity using determinant
// This is efficient for small matrices and catches perfect singularity
let det = self.det()?;
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular and cannot be solved".to_string(),
));
}
// Special fast paths for small systems
if n == 1 {
// 1x1 system - trivial solution
let a_val = self.get(&[0, 0])?;
let b_val = b.get(&[0])?;
return Ok(Array::from_vec(vec![b_val / a_val]));
} else if n == 2 {
// 2x2 system - use Cramer's rule
let a_data = self.to_vec();
let b_data = b.to_vec();
let x1 = (b_data[0] * a_data[3] - a_data[1] * b_data[1]) / det;
let x2 = (a_data[0] * b_data[1] - b_data[0] * a_data[2]) / det;
return Ok(Array::from_vec(vec![x1, x2]));
} else if n == 3 {
// 3x3 system - use direct formula
let a_data = self.to_vec();
let b_data = b.to_vec();
// Compute determinant and cofactors
let a11 = a_data[0];
let a12 = a_data[1];
let a13 = a_data[2];
let a21 = a_data[3];
let a22 = a_data[4];
let a23 = a_data[5];
let a31 = a_data[6];
let a32 = a_data[7];
let a33 = a_data[8];
// Calculate cofactors for direct solution
let c11 = a22 * a33 - a23 * a32;
let c12 = -(a21 * a33 - a23 * a31);
let c13 = a21 * a32 - a22 * a31;
let c21 = -(a12 * a33 - a13 * a32);
let c22 = a11 * a33 - a13 * a31;
let c23 = -(a11 * a32 - a12 * a31);
let c31 = a12 * a23 - a13 * a22;
let c32 = -(a11 * a23 - a13 * a21);
let c33 = a11 * a22 - a12 * a21;
let inv_det = T::one() / det;
// Multiply inverse of A (which is adjugate/det) by b
let x1 = (c11 * b_data[0] + c21 * b_data[1] + c31 * b_data[2]) * inv_det;
let x2 = (c12 * b_data[0] + c22 * b_data[1] + c32 * b_data[2]) * inv_det;
let x3 = (c13 * b_data[0] + c23 * b_data[1] + c33 * b_data[2]) * inv_det;
return Ok(Array::from_vec(vec![x1, x2, x3]));
}
// For larger systems, use SCIRS
use crate::interop::scirs_compat::solve_linear_system;
solve_linear_system(self, b)
}
/// Solve a linear system Ax = b
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 systems
/// 2. LU decomposition with partial pivoting for larger systems
/// 3. Numerical stability checks with appropriate condition number thresholds
/// 4. Proper error handling for singular or ill-conditioned matrices
#[cfg(all(feature = "matrix_decomp", not(feature = "scirs")))]
pub fn solve(&self, b: &Array<T>) -> Result<Array<T>> {
// Check dimensions
let a_shape = self.shape();
let b_shape = b.shape();
if a_shape.len() != 2 || a_shape[0] != a_shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"solve requires a square coefficient matrix".to_string(),
));
}
if b_shape.len() != 1 || b_shape[0] != a_shape[0] {
return Err(NumRs2Error::ShapeMismatch {
expected: vec![a_shape[0]],
actual: b_shape,
});
}
let n = a_shape[0];
// Quick check for singularity using determinant
// This is efficient for small matrices and catches perfect singularity
let det = self.det()?;
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular and cannot be solved".to_string(),
));
}
// Special fast paths for small systems
if n == 1 {
// 1x1 system - trivial solution
let a_val = self.get(&[0, 0])?;
let b_val = b.get(&[0])?;
return Ok(Array::from_vec(vec![b_val / a_val]));
} else if n == 2 {
// 2x2 system - use Cramer's rule
let a_data = self.to_vec();
let b_data = b.to_vec();
let x1 = (b_data[0] * a_data[3] - a_data[1] * b_data[1]) / det;
let x2 = (a_data[0] * b_data[1] - b_data[0] * a_data[2]) / det;
return Ok(Array::from_vec(vec![x1, x2]));
} else if n == 3 {
// 3x3 system - use direct formula
let a_data = self.to_vec();
let b_data = b.to_vec();
// Compute determinant and cofactors
let a11 = a_data[0];
let a12 = a_data[1];
let a13 = a_data[2];
let a21 = a_data[3];
let a22 = a_data[4];
let a23 = a_data[5];
let a31 = a_data[6];
let a32 = a_data[7];
let a33 = a_data[8];
// Calculate cofactors for direct solution
let c11 = a22 * a33 - a23 * a32;
let c12 = -(a21 * a33 - a23 * a31);
let c13 = a21 * a32 - a22 * a31;
let c21 = -(a12 * a33 - a13 * a32);
let c22 = a11 * a33 - a13 * a31;
let c23 = -(a11 * a32 - a12 * a31);
let c31 = a12 * a23 - a13 * a22;
let c32 = -(a11 * a23 - a13 * a21);
let c33 = a11 * a22 - a12 * a21;
let inv_det = T::one() / det;
// Multiply inverse of A (which is adjugate/det) by b
let x1 = (c11 * b_data[0] + c21 * b_data[1] + c31 * b_data[2]) * inv_det;
let x2 = (c12 * b_data[0] + c22 * b_data[1] + c32 * b_data[2]) * inv_det;
let x3 = (c13 * b_data[0] + c23 * b_data[1] + c33 * b_data[2]) * inv_det;
return Ok(Array::from_vec(vec![x1, x2, x3]));
}
// For larger systems, use LU decomposition with partial pivoting
// Get LU decomposition with pivoting: PA = LU
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
use crate::new_modules::matrix_decomp::lu;
// Step 1: Calculate LU decomposition
#[cfg(feature = "matrix_decomp")]
let (l, u, p) = lu(self)?;
#[cfg(not(feature = "matrix_decomp"))]
return Err(NumRs2Error::FeatureNotEnabled(
"matrix_decomp feature required for LU decomposition".to_string(),
));
// Step 2: Apply permutation to b (Pb)
let mut pb = vec![T::zero(); n];
#[allow(clippy::needless_range_loop)]
for i in 0..n {
let p_idx = p.get(&[i])?.to_usize().unwrap_or(i);
pb[i] = b.get(&[p_idx])?;
}
// Step 3: Forward substitution to solve Ly = Pb
let mut y = vec![T::zero(); n];
for i in 0..n {
let mut sum = pb[i];
#[allow(clippy::needless_range_loop)]
for k in 0..i {
sum -= l.get(&[i, k])? * y[k];
}
y[i] = sum; // L has 1's on diagonal
}
// Step 4: Back substitution to solve Ux = y
let mut x = vec![T::zero(); n];
for i in (0..n).rev() {
let mut sum = y[i];
#[allow(clippy::needless_range_loop)]
for k in (i + 1)..n {
sum -= u.get(&[i, k])? * x[k];
}
x[i] = sum / u.get(&[i, i])?;
}
// Step 5: Return the solution vector
Ok(Array::from_vec(x))
}
/// Solve a linear system Ax = b
///
/// This implementation includes:
/// 1. Fast direct formulas for 1x1, 2x2, and 3x3 systems
/// 2. Gaussian elimination with partial pivoting for larger systems
/// 3. Numerical stability checks with appropriate condition number thresholds
/// 4. Proper error handling for singular or ill-conditioned matrices
#[cfg(not(feature = "matrix_decomp"))]
pub fn solve(&self, b: &Array<T>) -> Result<Array<T>> {
// Check dimensions
let a_shape = self.shape();
let b_shape = b.shape();
if a_shape.len() != 2 || a_shape[0] != a_shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"solve requires a square coefficient matrix".to_string(),
));
}
if b_shape.len() != 1 || b_shape[0] != a_shape[0] {
return Err(NumRs2Error::ShapeMismatch {
expected: vec![a_shape[0]],
actual: b_shape,
});
}
let n = a_shape[0];
// Fast paths for small systems
if n == 1 {
// 1x1 system - trivial solution
let a_val = self.get(&[0, 0])?;
if a_val == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular and cannot be solved".to_string(),
));
}
let b_val = b.get(&[0])?;
return Ok(Array::from_vec(vec![b_val / a_val]));
} else if n == 2 {
// 2x2 system - use Cramer's rule
let a_data = self.to_vec();
let b_data = b.to_vec();
let det = a_data[0] * a_data[3] - a_data[1] * a_data[2];
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular".to_string(),
));
}
let x1 = (b_data[0] * a_data[3] - a_data[1] * b_data[1]) / det;
let x2 = (a_data[0] * b_data[1] - b_data[0] * a_data[2]) / det;
return Ok(Array::from_vec(vec![x1, x2]));
} else if n == 3 {
// 3x3 system - use direct formula through cofactors
let a_data = self.to_vec();
let b_data = b.to_vec();
// Calculate determinant
let det = a_data[0] * (a_data[4] * a_data[8] - a_data[5] * a_data[7])
- a_data[1] * (a_data[3] * a_data[8] - a_data[5] * a_data[6])
+ a_data[2] * (a_data[3] * a_data[7] - a_data[4] * a_data[6]);
if det == T::zero() {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is singular".to_string(),
));
}
// Compute determinant and cofactors
let a11 = a_data[0];
let a12 = a_data[1];
let a13 = a_data[2];
let a21 = a_data[3];
let a22 = a_data[4];
let a23 = a_data[5];
let a31 = a_data[6];
let a32 = a_data[7];
let a33 = a_data[8];
// Calculate cofactors for direct solution
let c11 = a22 * a33 - a23 * a32;
let c12 = -(a21 * a33 - a23 * a31);
let c13 = a21 * a32 - a22 * a31;
let c21 = -(a12 * a33 - a13 * a32);
let c22 = a11 * a33 - a13 * a31;
let c23 = -(a11 * a32 - a12 * a31);
let c31 = a12 * a23 - a13 * a22;
let c32 = -(a11 * a23 - a13 * a21);
let c33 = a11 * a22 - a12 * a21;
let inv_det = T::one() / det;
// Multiply inverse of A (which is adjugate/det) by b
let x1 = (c11 * b_data[0] + c21 * b_data[1] + c31 * b_data[2]) * inv_det;
let x2 = (c12 * b_data[0] + c22 * b_data[1] + c32 * b_data[2]) * inv_det;
let x3 = (c13 * b_data[0] + c23 * b_data[1] + c33 * b_data[2]) * inv_det;
return Ok(Array::from_vec(vec![x1, x2, x3]));
}
// For larger systems, use Gaussian elimination with partial pivoting
// Create an augmented matrix [A|b]
let mut aug = Array::zeros(&[n, n + 1]);
// Fill in the augmented matrix
for i in 0..n {
for j in 0..n {
aug.set(&[i, j], self.get(&[i, j])?)?;
}
aug.set(&[i, n], b.get(&[i])?)?;
}
// Gaussian elimination with partial pivoting
for i in 0..n {
// Find pivot (maximum absolute value in current column)
let mut max_val = num_traits::Float::abs(aug.get(&[i, i])?);
let mut max_row = i;
for j in (i + 1)..n {
let abs_val = num_traits::Float::abs(aug.get(&[j, i])?);
if abs_val > max_val {
max_val = abs_val;
max_row = j;
}
}
// Check for singularity
let eps = T::epsilon();
if max_val < eps * T::from(n).expect("n is a valid usize") {
return Err(NumRs2Error::InvalidOperation(
"coefficient matrix is numerically singular".to_string(),
));
}
// Swap rows if needed
if max_row != i {
for j in i..(n + 1) {
let temp = aug.get(&[i, j])?;
aug.set(&[i, j], aug.get(&[max_row, j])?)?;
aug.set(&[max_row, j], temp)?;
}
}
// Eliminate below
for j in (i + 1)..n {
let factor = aug.get(&[j, i])? / aug.get(&[i, i])?;
for k in i..(n + 1) {
let val = aug.get(&[j, k])? - factor * aug.get(&[i, k])?;
aug.set(&[j, k], val)?;
}
}
}
// Back substitution
let mut x = vec![T::zero(); n];
for i in (0..n).rev() {
let mut sum = aug.get(&[i, n])?;
for j in (i + 1)..n {
sum -= aug.get(&[i, j])? * x[j];
}
x[i] = sum / aug.get(&[i, i])?;
}
Ok(Array::from_vec(x))
}
/// Compute the singular value decomposition of a matrix
pub fn svd(&self) -> Result<(Array<T>, Array<T>, Array<T>)> {
// Use the implementation from new_modules::matrix_decomp
use crate::new_modules::matrix_decomp::svd;
let (u, s_real, vt) = svd(self)?;
// Convert singular values from Real to T
// Since T is a Float type and Real is its real component type,
// for real-valued matrices T == Real, so this is safe
let s_vec: Vec<T> = s_real
.to_vec()
.into_iter()
.map(|val| {
// Convert from Real to T (for real matrices, this is identity)
num_traits::NumCast::from(val).unwrap_or(T::zero())
})
.collect();
let s = Array::from_vec(s_vec);
Ok((u, s, vt))
}
/// Compute the eigenvalues and eigenvectors of a square matrix
pub fn eig(&self) -> Result<(Array<T>, Array<T>)> {
// Check if the matrix is square
let shape = self.shape();
if shape.len() != 2 || shape[0] != shape[1] {
return Err(NumRs2Error::DimensionMismatch(
"eigendecomposition requires a square matrix".to_string(),
));
}
// This would use ndarray-linalg's eigenvalue computation in a full version
// For now, we'll just return placeholder values
let n = shape[0];
let eigenvalues = Array::zeros(&[n]);
let eigenvectors = Array::zeros(&[n, n]);
Ok((eigenvalues, eigenvectors))
}
/// Compute the Cholesky decomposition of a matrix
pub fn cholesky(&self) -> Result<Array<T>> {
// Use the implementation from new_modules::matrix_decomp
use crate::new_modules::matrix_decomp::cholesky;
cholesky(self)
}
/// Compute the QR decomposition of a matrix
pub fn qr(&self) -> Result<(Array<T>, Array<T>)> {
// Use the implementation from new_modules::matrix_decomp
use crate::new_modules::matrix_decomp::qr;
qr(self)
}
}