nabled-ml 0.0.10

ML-oriented algorithms built on ndarray-native nabled primitives
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
//! Statistical utilities over ndarray matrices.

use std::fmt;

use nabled_core::scalar::NabledReal;
use ndarray::{Array1, Array2, ArrayBase, ArrayView2, Axis, DataMut, Ix1, Ix2};
use num_complex::Complex64;

/// Error type for matrix statistics.
#[derive(Debug, Clone, PartialEq)]
pub enum StatsError {
    /// Matrix is empty.
    EmptyMatrix,
    /// Matrix needs at least two rows.
    InsufficientSamples,
    /// Input or output shapes are incompatible.
    InvalidInput(String),
    /// Numerical instability detected.
    NumericalInstability,
}

impl fmt::Display for StatsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StatsError::EmptyMatrix => write!(f, "Matrix cannot be empty"),
            StatsError::InsufficientSamples => {
                write!(f, "At least two observations are required")
            }
            StatsError::InvalidInput(message) => write!(f, "Invalid input: {message}"),
            StatsError::NumericalInstability => write!(f, "Numerical instability detected"),
        }
    }
}

impl std::error::Error for StatsError {}

fn usize_to_scalar<T: NabledReal>(value: usize) -> T {
    T::from_usize(value).unwrap_or(T::max_value())
}

fn complex_is_finite(value: Complex64) -> bool { value.re.is_finite() && value.im.is_finite() }

fn validate_vector_output_len<T, S>(
    output: &ArrayBase<S, Ix1>,
    expected_len: usize,
    name: &str,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = T>,
{
    if output.len() != expected_len {
        return Err(StatsError::InvalidInput(format!(
            "{name} output length must match expected length {expected_len}",
        )));
    }
    Ok(())
}

fn validate_matrix_output_shape<T, S>(
    output: &ArrayBase<S, Ix2>,
    expected_rows: usize,
    expected_cols: usize,
    name: &str,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = T>,
{
    if output.nrows() != expected_rows || output.ncols() != expected_cols {
        return Err(StatsError::InvalidInput(format!(
            "{name} output shape must be ({expected_rows}, {expected_cols})",
        )));
    }
    Ok(())
}

fn column_means_into_impl<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix1>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    validate_vector_output_len(output, matrix.ncols(), "column_means")?;

    if matrix.nrows() == 0 {
        output.fill(T::zero());
        return Ok(());
    }

    let denom = usize_to_scalar::<T>(matrix.nrows());
    for col in 0..matrix.ncols() {
        let mut sum = T::zero();
        for row in 0..matrix.nrows() {
            sum += matrix[[row, col]];
        }
        output[col] = sum / denom;
    }

    Ok(())
}

fn column_means_impl<T: NabledReal>(matrix: &ArrayView2<'_, T>) -> Array1<T> {
    matrix.mean_axis(Axis(0)).unwrap_or_else(|| Array1::zeros(matrix.ncols()))
}

/// Compute column means.
#[must_use]
pub fn column_means<T: NabledReal>(matrix: &Array2<T>) -> Array1<T> {
    column_means_impl(&matrix.view())
}

/// Compute column means from a matrix view.
#[must_use]
pub fn column_means_view<T: NabledReal>(matrix: &ArrayView2<'_, T>) -> Array1<T> {
    column_means_impl(matrix)
}

/// Compute column means into caller-provided output.
///
/// # Errors
/// Returns an error if `output` does not match the column count.
pub fn column_means_into<T, S>(
    matrix: &Array2<T>,
    output: &mut ArrayBase<S, Ix1>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    column_means_into_impl(&matrix.view(), output)
}

/// Compute column means from a matrix view into caller-provided output.
///
/// # Errors
/// Returns an error if `output` does not match the column count.
pub fn column_means_view_into<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix1>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    column_means_into_impl(matrix, output)
}

fn center_columns_impl<T: NabledReal>(matrix: &ArrayView2<'_, T>) -> Array2<T> {
    let means = column_means_impl(matrix);
    let mut centered = Array2::<T>::zeros((matrix.nrows(), matrix.ncols()));
    for row in 0..matrix.nrows() {
        for col in 0..matrix.ncols() {
            centered[[row, col]] = matrix[[row, col]] - means[col];
        }
    }
    centered
}

/// Center columns by subtracting their means.
#[must_use]
pub fn center_columns<T: NabledReal>(matrix: &Array2<T>) -> Array2<T> {
    center_columns_impl(&matrix.view())
}

/// Center columns by subtracting their means from a matrix view.
#[must_use]
pub fn center_columns_view<T: NabledReal>(matrix: &ArrayView2<'_, T>) -> Array2<T> {
    center_columns_impl(matrix)
}

fn center_columns_into_impl<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    validate_matrix_output_shape(output, matrix.nrows(), matrix.ncols(), "center_columns")?;

    let mut means = Array1::<T>::zeros(matrix.ncols());
    column_means_into_impl(matrix, &mut means)?;

    for row in 0..matrix.nrows() {
        for col in 0..matrix.ncols() {
            output[[row, col]] = matrix[[row, col]] - means[col];
        }
    }

    Ok(())
}

/// Center columns by subtracting their means into caller-provided output.
///
/// # Errors
/// Returns an error if `output` does not match the input shape.
pub fn center_columns_into<T, S>(
    matrix: &Array2<T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    center_columns_into_impl(&matrix.view(), output)
}

/// Center columns by subtracting their means from a matrix view into caller-provided output.
///
/// # Errors
/// Returns an error if `output` does not match the input shape.
pub fn center_columns_view_into<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    center_columns_into_impl(matrix, output)
}

fn covariance_matrix_impl<T: NabledReal>(
    matrix: &ArrayView2<'_, T>,
) -> Result<Array2<T>, StatsError> {
    if matrix.is_empty() {
        return Err(StatsError::EmptyMatrix);
    }
    if matrix.nrows() < 2 {
        return Err(StatsError::InsufficientSamples);
    }

    let centered = center_columns_impl(matrix);
    let covariance: Array2<T> =
        centered.t().dot(&centered) / usize_to_scalar::<T>(matrix.nrows() - 1);

    if covariance.iter().any(|value| !value.is_finite()) {
        return Err(StatsError::NumericalInstability);
    }

    Ok(covariance)
}

/// Compute sample covariance matrix.
///
/// # Errors
/// Returns an error for empty input or fewer than two samples.
pub fn covariance_matrix<T: NabledReal>(matrix: &Array2<T>) -> Result<Array2<T>, StatsError> {
    covariance_matrix_impl(&matrix.view())
}

/// Compute sample covariance matrix from a matrix view.
///
/// # Errors
/// Returns an error for empty input or fewer than two samples.
pub fn covariance_matrix_view<T: NabledReal>(
    matrix: &ArrayView2<'_, T>,
) -> Result<Array2<T>, StatsError> {
    covariance_matrix_impl(matrix)
}

fn covariance_matrix_into_impl<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    if matrix.is_empty() {
        return Err(StatsError::EmptyMatrix);
    }
    if matrix.nrows() < 2 {
        return Err(StatsError::InsufficientSamples);
    }
    validate_matrix_output_shape(output, matrix.ncols(), matrix.ncols(), "covariance_matrix")?;

    let mut means = Array1::<T>::zeros(matrix.ncols());
    column_means_into_impl(matrix, &mut means)?;
    let denom = usize_to_scalar::<T>(matrix.nrows() - 1);

    for i in 0..matrix.ncols() {
        for j in i..matrix.ncols() {
            let mut sum = T::zero();
            for row in 0..matrix.nrows() {
                let left = matrix[[row, i]] - means[i];
                let right = matrix[[row, j]] - means[j];
                sum += left * right;
            }
            let value = sum / denom;
            output[[i, j]] = value;
            if i != j {
                output[[j, i]] = value;
            }
        }
    }

    if output.iter().any(|value| !value.is_finite()) {
        return Err(StatsError::NumericalInstability);
    }

    Ok(())
}

/// Compute sample covariance matrix into caller-provided output.
///
/// # Errors
/// Returns an error for empty input, fewer than two samples, or incompatible output shape.
pub fn covariance_matrix_into<T, S>(
    matrix: &Array2<T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    covariance_matrix_into_impl(&matrix.view(), output)
}

/// Compute sample covariance matrix from a matrix view into caller-provided output.
///
/// # Errors
/// Returns an error for empty input, fewer than two samples, or incompatible output shape.
pub fn covariance_matrix_view_into<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    covariance_matrix_into_impl(matrix, output)
}

fn correlation_matrix_impl<T: NabledReal>(
    matrix: &ArrayView2<'_, T>,
) -> Result<Array2<T>, StatsError> {
    let covariance = covariance_matrix_impl(matrix)?;
    let n = covariance.nrows();
    let mut correlation = Array2::<T>::zeros((n, n));

    for i in 0..n {
        let sigma_i = covariance[[i, i]].sqrt();
        for j in 0..n {
            let sigma_j = covariance[[j, j]].sqrt();
            let denom = (sigma_i * sigma_j).max(T::epsilon());
            correlation[[i, j]] = covariance[[i, j]] / denom;
        }
    }

    Ok(correlation)
}

/// Compute correlation matrix.
///
/// # Errors
/// Returns an error if covariance computation fails.
pub fn correlation_matrix<T: NabledReal>(matrix: &Array2<T>) -> Result<Array2<T>, StatsError> {
    correlation_matrix_impl(&matrix.view())
}

/// Compute correlation matrix from a matrix view.
///
/// # Errors
/// Returns an error if covariance computation fails.
pub fn correlation_matrix_view<T: NabledReal>(
    matrix: &ArrayView2<'_, T>,
) -> Result<Array2<T>, StatsError> {
    correlation_matrix_impl(matrix)
}

fn correlation_matrix_into_impl<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    covariance_matrix_into_impl(matrix, output)?;
    let mut sigmas = Array1::<T>::zeros(output.nrows());
    for i in 0..output.nrows() {
        sigmas[i] = output[[i, i]].sqrt();
    }

    for i in 0..output.nrows() {
        let sigma_i = sigmas[i];
        for j in 0..output.ncols() {
            let sigma_j = sigmas[j];
            let denom = (sigma_i * sigma_j).max(T::epsilon());
            output[[i, j]] /= denom;
        }
    }

    if output.iter().any(|value| !value.is_finite()) {
        return Err(StatsError::NumericalInstability);
    }

    Ok(())
}

/// Compute correlation matrix into caller-provided output.
///
/// # Errors
/// Returns an error if covariance computation fails or `output` shape is incompatible.
pub fn correlation_matrix_into<T, S>(
    matrix: &Array2<T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    correlation_matrix_into_impl(&matrix.view(), output)
}

/// Compute correlation matrix from a matrix view into caller-provided output.
///
/// # Errors
/// Returns an error if covariance computation fails or `output` shape is incompatible.
pub fn correlation_matrix_view_into<T, S>(
    matrix: &ArrayView2<'_, T>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    T: NabledReal,
    S: DataMut<Elem = T>,
{
    correlation_matrix_into_impl(matrix, output)
}

fn column_means_complex_impl(matrix: &ArrayView2<'_, Complex64>) -> Array1<Complex64> {
    if matrix.nrows() == 0 {
        return Array1::zeros(matrix.ncols());
    }

    let mut means = Array1::<Complex64>::zeros(matrix.ncols());
    for col in 0..matrix.ncols() {
        let mut sum = Complex64::new(0.0, 0.0);
        for row in 0..matrix.nrows() {
            sum += matrix[[row, col]];
        }
        means[col] = sum / usize_to_scalar::<f64>(matrix.nrows());
    }
    means
}

/// Compute complex column means.
#[must_use]
pub fn column_means_complex(matrix: &Array2<Complex64>) -> Array1<Complex64> {
    column_means_complex_impl(&matrix.view())
}

/// Compute complex column means from a matrix view.
#[must_use]
pub fn column_means_complex_view(matrix: &ArrayView2<'_, Complex64>) -> Array1<Complex64> {
    column_means_complex_impl(matrix)
}

fn column_means_complex_into_impl<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix1>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    validate_vector_output_len(output, matrix.ncols(), "column_means_complex")?;

    if matrix.nrows() == 0 {
        output.fill(Complex64::new(0.0, 0.0));
        return Ok(());
    }

    let denom = usize_to_scalar::<f64>(matrix.nrows());
    for col in 0..matrix.ncols() {
        let mut sum = Complex64::new(0.0, 0.0);
        for row in 0..matrix.nrows() {
            sum += matrix[[row, col]];
        }
        output[col] = sum / denom;
    }

    Ok(())
}

/// Compute complex column means into caller-provided output.
///
/// # Errors
/// Returns an error if `output` does not match the column count.
pub fn column_means_complex_into<S>(
    matrix: &Array2<Complex64>,
    output: &mut ArrayBase<S, Ix1>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    column_means_complex_into_impl(&matrix.view(), output)
}

/// Compute complex column means from a matrix view into caller-provided output.
///
/// # Errors
/// Returns an error if `output` does not match the column count.
pub fn column_means_complex_view_into<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix1>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    column_means_complex_into_impl(matrix, output)
}

fn center_columns_complex_impl(matrix: &ArrayView2<'_, Complex64>) -> Array2<Complex64> {
    let means = column_means_complex_impl(matrix);
    let mut centered = Array2::<Complex64>::zeros((matrix.nrows(), matrix.ncols()));
    for row in 0..matrix.nrows() {
        for col in 0..matrix.ncols() {
            centered[[row, col]] = matrix[[row, col]] - means[col];
        }
    }
    centered
}

/// Center complex columns by subtracting their means.
#[must_use]
pub fn center_columns_complex(matrix: &Array2<Complex64>) -> Array2<Complex64> {
    center_columns_complex_impl(&matrix.view())
}

/// Center complex columns by subtracting their means from a matrix view.
#[must_use]
pub fn center_columns_complex_view(matrix: &ArrayView2<'_, Complex64>) -> Array2<Complex64> {
    center_columns_complex_impl(matrix)
}

fn center_columns_complex_into_impl<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    validate_matrix_output_shape(output, matrix.nrows(), matrix.ncols(), "center_columns_complex")?;

    let mut means = Array1::<Complex64>::zeros(matrix.ncols());
    column_means_complex_into_impl(matrix, &mut means)?;

    for row in 0..matrix.nrows() {
        for col in 0..matrix.ncols() {
            output[[row, col]] = matrix[[row, col]] - means[col];
        }
    }

    Ok(())
}

/// Center complex columns by subtracting their means into caller-provided output.
///
/// # Errors
/// Returns an error if `output` does not match the input shape.
pub fn center_columns_complex_into<S>(
    matrix: &Array2<Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    center_columns_complex_into_impl(&matrix.view(), output)
}

/// Center complex columns by subtracting their means from a matrix view into caller-provided
/// output.
///
/// # Errors
/// Returns an error if `output` does not match the input shape.
pub fn center_columns_complex_view_into<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    center_columns_complex_into_impl(matrix, output)
}

fn covariance_matrix_complex_impl(
    matrix: &ArrayView2<'_, Complex64>,
) -> Result<Array2<Complex64>, StatsError> {
    if matrix.is_empty() {
        return Err(StatsError::EmptyMatrix);
    }
    if matrix.nrows() < 2 {
        return Err(StatsError::InsufficientSamples);
    }

    let centered = center_columns_complex_impl(matrix);
    let conjugate_transpose = centered.t().mapv(|value| value.conj());
    let covariance: Array2<Complex64> =
        conjugate_transpose.dot(&centered) / usize_to_scalar::<f64>(matrix.nrows() - 1);

    if covariance.iter().any(|value| !complex_is_finite(*value)) {
        return Err(StatsError::NumericalInstability);
    }

    Ok(covariance)
}

/// Compute sample covariance matrix for complex observations.
///
/// # Errors
/// Returns an error for empty input or fewer than two samples.
pub fn covariance_matrix_complex(
    matrix: &Array2<Complex64>,
) -> Result<Array2<Complex64>, StatsError> {
    covariance_matrix_complex_impl(&matrix.view())
}

/// Compute sample covariance matrix for complex observations from a matrix view.
///
/// # Errors
/// Returns an error for empty input or fewer than two samples.
pub fn covariance_matrix_complex_view(
    matrix: &ArrayView2<'_, Complex64>,
) -> Result<Array2<Complex64>, StatsError> {
    covariance_matrix_complex_impl(matrix)
}

fn covariance_matrix_complex_into_impl<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    if matrix.is_empty() {
        return Err(StatsError::EmptyMatrix);
    }
    if matrix.nrows() < 2 {
        return Err(StatsError::InsufficientSamples);
    }
    validate_matrix_output_shape(
        output,
        matrix.ncols(),
        matrix.ncols(),
        "covariance_matrix_complex",
    )?;

    let mut means = Array1::<Complex64>::zeros(matrix.ncols());
    column_means_complex_into_impl(matrix, &mut means)?;
    let denom = usize_to_scalar::<f64>(matrix.nrows() - 1);

    for i in 0..matrix.ncols() {
        for j in i..matrix.ncols() {
            let mut sum = Complex64::new(0.0, 0.0);
            for row in 0..matrix.nrows() {
                let left = matrix[[row, i]] - means[i];
                let right = matrix[[row, j]] - means[j];
                sum += left.conj() * right;
            }
            let value = sum / denom;
            output[[i, j]] = value;
            if i != j {
                output[[j, i]] = value.conj();
            }
        }
    }

    if output.iter().any(|value| !complex_is_finite(*value)) {
        return Err(StatsError::NumericalInstability);
    }

    Ok(())
}

/// Compute sample covariance matrix for complex observations into caller-provided output.
///
/// # Errors
/// Returns an error for empty input, fewer than two samples, or incompatible output shape.
pub fn covariance_matrix_complex_into<S>(
    matrix: &Array2<Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    covariance_matrix_complex_into_impl(&matrix.view(), output)
}

/// Compute sample covariance matrix for complex observations from a matrix view into
/// caller-provided output.
///
/// # Errors
/// Returns an error for empty input, fewer than two samples, or incompatible output shape.
pub fn covariance_matrix_complex_view_into<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    covariance_matrix_complex_into_impl(matrix, output)
}

fn correlation_matrix_complex_impl(
    matrix: &ArrayView2<'_, Complex64>,
) -> Result<Array2<Complex64>, StatsError> {
    let covariance = covariance_matrix_complex_impl(matrix)?;
    let n = covariance.nrows();
    let mut correlation = Array2::<Complex64>::zeros((n, n));

    for i in 0..n {
        let sigma_i = covariance[[i, i]].re.max(0.0).sqrt();
        for j in 0..n {
            let sigma_j = covariance[[j, j]].re.max(0.0).sqrt();
            let denom = (sigma_i * sigma_j).max(f64::EPSILON);
            correlation[[i, j]] = covariance[[i, j]] / denom;
        }
    }

    if correlation.iter().any(|value| !complex_is_finite(*value)) {
        return Err(StatsError::NumericalInstability);
    }

    Ok(correlation)
}

/// Compute correlation matrix for complex observations.
///
/// # Errors
/// Returns an error if covariance computation fails.
pub fn correlation_matrix_complex(
    matrix: &Array2<Complex64>,
) -> Result<Array2<Complex64>, StatsError> {
    correlation_matrix_complex_impl(&matrix.view())
}

/// Compute correlation matrix for complex observations from a matrix view.
///
/// # Errors
/// Returns an error if covariance computation fails.
pub fn correlation_matrix_complex_view(
    matrix: &ArrayView2<'_, Complex64>,
) -> Result<Array2<Complex64>, StatsError> {
    correlation_matrix_complex_impl(matrix)
}

fn correlation_matrix_complex_into_impl<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    covariance_matrix_complex_into_impl(matrix, output)?;
    let mut sigmas = Array1::<f64>::zeros(output.nrows());
    for i in 0..output.nrows() {
        sigmas[i] = output[[i, i]].re.max(0.0).sqrt();
    }

    for i in 0..output.nrows() {
        let sigma_i = sigmas[i];
        for j in 0..output.ncols() {
            let sigma_j = sigmas[j];
            let denom = (sigma_i * sigma_j).max(f64::EPSILON);
            output[[i, j]] /= denom;
        }
    }

    if output.iter().any(|value| !complex_is_finite(*value)) {
        return Err(StatsError::NumericalInstability);
    }

    Ok(())
}

/// Compute correlation matrix for complex observations into caller-provided output.
///
/// # Errors
/// Returns an error if covariance computation fails or `output` shape is incompatible.
pub fn correlation_matrix_complex_into<S>(
    matrix: &Array2<Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    correlation_matrix_complex_into_impl(&matrix.view(), output)
}

/// Compute correlation matrix for complex observations from a matrix view into caller-provided
/// output.
///
/// # Errors
/// Returns an error if covariance computation fails or `output` shape is incompatible.
pub fn correlation_matrix_complex_view_into<S>(
    matrix: &ArrayView2<'_, Complex64>,
    output: &mut ArrayBase<S, Ix2>,
) -> Result<(), StatsError>
where
    S: DataMut<Elem = Complex64>,
{
    correlation_matrix_complex_into_impl(matrix, output)
}

// --- Physical AI streaming / rolling extensions ---

pub mod online {
    #![allow(clippy::missing_errors_doc)]
    use nabled_core::scalar::NabledReal;

    /// Online mean accumulator (Welford-style count/mean).
    #[derive(Debug, Clone, PartialEq)]
    pub struct OnlineMean<T> {
        count: usize,
        mean:  T,
    }

    impl<T: NabledReal> Default for OnlineMean<T> {
        fn default() -> Self { Self { count: 0, mean: T::zero() } }
    }

    impl<T: NabledReal> OnlineMean<T> {
        pub fn push(&mut self, value: T) {
            self.count += 1;
            let n = T::from_usize(self.count).unwrap_or(T::one());
            self.mean += (value - self.mean) / n;
        }

        #[must_use]
        pub fn mean(&self) -> T { self.mean }

        pub fn reset(&mut self) {
            self.count = 0;
            self.mean = T::zero();
        }
    }

    /// Online variance accumulator (Welford).
    #[derive(Debug, Clone, PartialEq)]
    pub struct OnlineVariance<T> {
        count: usize,
        mean:  T,
        m2:    T,
    }

    impl<T: NabledReal> Default for OnlineVariance<T> {
        fn default() -> Self { Self { count: 0, mean: T::zero(), m2: T::zero() } }
    }

    impl<T: NabledReal> OnlineVariance<T> {
        pub fn push(&mut self, value: T) {
            self.count += 1;
            let n = T::from_usize(self.count).unwrap_or(T::one());
            let delta = value - self.mean;
            self.mean += delta / n;
            let delta2 = value - self.mean;
            self.m2 += delta * delta2;
        }

        #[must_use]
        pub fn mean(&self) -> T { self.mean }

        #[must_use]
        pub fn variance(&self) -> T {
            if self.count < 2 {
                return T::zero();
            }
            self.m2 / T::from_usize(self.count - 1).unwrap_or(T::one())
        }

        pub fn reset(&mut self) {
            self.count = 0;
            self.mean = T::zero();
            self.m2 = T::zero();
        }
    }
}

pub mod ewma {
    #![allow(clippy::missing_errors_doc)]
    use nabled_core::scalar::NabledReal;
    use ndarray::{Array1, ArrayBase, ArrayView1, DataMut, Ix1};

    use super::StatsError;

    /// Incremental EWMA state.
    #[derive(Debug, Clone, PartialEq)]
    pub struct EwmaState<T> {
        alpha: T,
        value: Option<T>,
    }

    impl<T: NabledReal> EwmaState<T> {
        pub fn new(alpha: T) -> Self { Self { alpha, value: None } }

        pub fn push(&mut self, sample: T) -> T {
            if let Some(prev) = self.value {
                let next = self.alpha * sample + (T::one() - self.alpha) * prev;
                self.value = Some(next);
                next
            } else {
                self.value = Some(sample);
                sample
            }
        }
    }

    #[must_use]
    pub fn ewma<T: NabledReal>(signal: &Array1<T>, alpha: T) -> Array1<T> {
        ewma_view(&signal.view(), alpha)
    }

    #[must_use]
    pub fn ewma_view<T: NabledReal>(signal: &ArrayView1<'_, T>, alpha: T) -> Array1<T> {
        let mut out = Array1::<T>::zeros(signal.len());
        drop(ewma_into(signal, alpha, &mut out));
        out
    }

    pub fn ewma_into<T, S>(
        signal: &ArrayView1<'_, T>,
        alpha: T,
        output: &mut ArrayBase<S, Ix1>,
    ) -> Result<(), StatsError>
    where
        T: NabledReal,
        S: DataMut<Elem = T>,
    {
        if output.len() != signal.len() {
            return Err(StatsError::InvalidInput("ewma output length mismatch".to_string()));
        }
        let mut state = EwmaState::new(alpha);
        for (i, &sample) in signal.iter().enumerate() {
            output[i] = state.push(sample);
        }
        Ok(())
    }
}

pub mod rolling {
    #![allow(clippy::missing_errors_doc)]
    use nabled_core::scalar::NabledReal;
    use ndarray::{Array1, Array2, ArrayBase, ArrayView1, ArrayView2, DataMut, Ix1, Ix2};

    use super::StatsError;

    #[must_use]
    pub fn rolling_mean<T: NabledReal>(signal: &ArrayView1<'_, T>, window: usize) -> Array1<T> {
        let mut out = Array1::<T>::zeros(signal.len());
        drop(rolling_mean_into(signal, window, &mut out));
        out
    }

    pub fn rolling_mean_view<T: NabledReal>(
        signal: &ArrayView1<'_, T>,
        window: usize,
    ) -> Array1<T> {
        rolling_mean(signal, window)
    }

    pub fn rolling_mean_into<T, S>(
        signal: &ArrayView1<'_, T>,
        window: usize,
        output: &mut ArrayBase<S, Ix1>,
    ) -> Result<(), StatsError>
    where
        T: NabledReal,
        S: DataMut<Elem = T>,
    {
        if window == 0 {
            return Err(StatsError::InvalidInput("window must be positive".to_string()));
        }
        if output.len() != signal.len() {
            return Err(StatsError::InvalidInput(
                "rolling_mean output length mismatch".to_string(),
            ));
        }
        for i in 0..signal.len() {
            let start = i.saturating_sub(window - 1);
            let slice = signal.slice(ndarray::s![start..=i]);
            let sum = slice.iter().fold(T::zero(), |acc, v| acc + *v);
            let count = T::from_usize(slice.len()).unwrap_or(T::one());
            output[i] = sum / count;
        }
        Ok(())
    }

    #[must_use]
    pub fn rolling_variance<T: NabledReal>(signal: &ArrayView1<'_, T>, window: usize) -> Array1<T> {
        let mut out = Array1::<T>::zeros(signal.len());
        drop(rolling_variance_into(signal, window, &mut out));
        out
    }

    pub fn rolling_variance_into<T, S>(
        signal: &ArrayView1<'_, T>,
        window: usize,
        output: &mut ArrayBase<S, Ix1>,
    ) -> Result<(), StatsError>
    where
        T: NabledReal,
        S: DataMut<Elem = T>,
    {
        if window == 0 {
            return Err(StatsError::InvalidInput("window must be positive".to_string()));
        }
        if output.len() != signal.len() {
            return Err(StatsError::InvalidInput(
                "rolling_variance output length mismatch".to_string(),
            ));
        }
        for i in 0..signal.len() {
            let start = i.saturating_sub(window - 1);
            let slice = signal.slice(ndarray::s![start..=i]);
            let mean = slice.iter().fold(T::zero(), |acc, v| acc + *v)
                / T::from_usize(slice.len()).unwrap_or(T::one());
            let var = slice
                .iter()
                .map(|v| {
                    let d = *v - mean;
                    d * d
                })
                .fold(T::zero(), |acc, v| acc + v)
                / T::from_usize(slice.len()).unwrap_or(T::one());
            output[i] = var;
        }
        Ok(())
    }

    #[must_use]
    pub fn rolling_covariance<T: NabledReal>(
        matrix: &ArrayView2<'_, T>,
        window: usize,
    ) -> Array2<T> {
        let mut out = Array2::<T>::zeros((matrix.nrows(), matrix.ncols() * matrix.ncols()));
        drop(rolling_covariance_into(matrix, window, &mut out));
        out
    }

    pub fn rolling_covariance_view<T: NabledReal>(
        matrix: &ArrayView2<'_, T>,
        window: usize,
    ) -> Array2<T> {
        rolling_covariance(matrix, window)
    }

    pub fn rolling_covariance_into<T, S>(
        matrix: &ArrayView2<'_, T>,
        window: usize,
        output: &mut ArrayBase<S, Ix2>,
    ) -> Result<(), StatsError>
    where
        T: NabledReal,
        S: DataMut<Elem = T>,
    {
        let cols = matrix.ncols();
        if output.nrows() != matrix.nrows() || output.ncols() != cols * cols {
            return Err(StatsError::InvalidInput(
                "rolling_covariance output shape mismatch".to_string(),
            ));
        }
        if window == 0 {
            return Err(StatsError::InvalidInput("window must be positive".to_string()));
        }
        for row in 0..matrix.nrows() {
            let start = row.saturating_sub(window - 1);
            let block = matrix.slice(ndarray::s![start..=row, ..]);
            let cov = if block.nrows() >= 2 {
                super::covariance_matrix_view(&block)?
            } else {
                Array2::<T>::zeros((cols, cols))
            };
            for i in 0..cols {
                for j in 0..cols {
                    output[[row, i * cols + j]] = cov[[i, j]];
                }
            }
        }
        Ok(())
    }
}

pub mod lag {
    #![allow(clippy::missing_errors_doc)]
    use nabled_core::scalar::NabledReal;
    use ndarray::{Array2, ArrayView2};

    use super::StatsError;

    /// Zero-copy lag view: rows `[0..n-lag)` of `matrix` aligned with rows `[lag..n)`.
    pub fn lag_view<'a, T>(
        matrix: &'a ArrayView2<'_, T>,
        lag: usize,
    ) -> Result<ArrayView2<'a, T>, StatsError> {
        if lag >= matrix.nrows() {
            return Err(StatsError::InvalidInput(format!(
                "lag {lag} must be less than row count {}",
                matrix.nrows()
            )));
        }
        Ok(matrix.slice(ndarray::s![..matrix.nrows() - lag, ..]))
    }

    /// Shift columns down by `lag` rows, filling top rows with zero.
    pub fn shift_columns_into<T: NabledReal>(
        matrix: &ArrayView2<'_, T>,
        lag: usize,
        output: &mut Array2<T>,
    ) -> Result<(), StatsError> {
        if output.dim() != matrix.dim() {
            return Err(StatsError::InvalidInput(
                "shift_columns_into output shape mismatch".to_string(),
            ));
        }
        output.fill(T::zero());
        if lag >= matrix.nrows() {
            return Ok(());
        }
        let rows = matrix.nrows() - lag;
        output.slice_mut(ndarray::s![lag.., ..]).assign(&matrix.slice(ndarray::s![..rows, ..]));
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use ndarray::{Array1, Array2};
    use num_complex::Complex64;

    use super::*;

    #[test]
    fn covariance_and_correlation_are_well_formed() {
        let matrix =
            Array2::from_shape_vec((4, 2), vec![1.0_f64, 3.0, 2.0, 2.0, 3.0, 1.0, 4.0, 0.0])
                .unwrap();
        let covariance = covariance_matrix(&matrix).unwrap();
        let correlation = correlation_matrix(&matrix).unwrap();
        assert_eq!(covariance.dim(), (2, 2));
        assert_eq!(correlation.dim(), (2, 2));
    }

    #[test]
    fn stats_rejects_empty_and_insufficient_inputs() {
        let empty = Array2::<f64>::zeros((0, 0));
        assert!(matches!(covariance_matrix(&empty), Err(StatsError::EmptyMatrix)));

        let one_row = Array2::from_shape_vec((1, 2), vec![1.0, 2.0]).unwrap();
        assert!(matches!(covariance_matrix(&one_row), Err(StatsError::InsufficientSamples)));
    }

    #[test]
    fn center_columns_zeroes_means() {
        let matrix =
            Array2::from_shape_vec((3, 2), vec![1.0_f64, 2.0, 2.0, 3.0, 3.0, 4.0]).unwrap();
        let centered = center_columns(&matrix);
        let means = column_means(&centered);
        assert!(means.iter().all(|value| num_traits::Float::abs(*value) < 1e-12));
    }

    #[test]
    fn column_means_handles_empty_input() {
        let matrix = Array2::<f64>::zeros((0, 3));
        let means = column_means(&matrix);
        assert_eq!(means.len(), 3);
        assert!(means.iter().all(|value| *value == 0.0));
    }

    #[test]
    fn covariance_reports_numerical_instability() {
        let matrix = Array2::from_shape_vec((2, 2), vec![f64::MAX, 0.0, -f64::MAX, 0.0]).unwrap();
        let result = covariance_matrix(&matrix);
        assert!(matches!(result, Err(StatsError::NumericalInstability)));
    }

    #[test]
    fn correlation_handles_zero_variance_column() {
        let matrix =
            Array2::from_shape_vec((3, 2), vec![1.0_f64, 10.0, 1.0, 20.0, 1.0, 30.0]).unwrap();
        let correlation = correlation_matrix(&matrix).unwrap();
        assert!(correlation[[0, 0]].is_finite());
        assert!(correlation[[0, 1]].is_finite());
        assert!(correlation[[1, 0]].is_finite());
        assert!(correlation[[1, 1]].is_finite());
    }

    #[test]
    fn view_variants_match_owned() {
        let matrix =
            Array2::from_shape_vec((4, 2), vec![1.0_f64, 3.0, 2.0, 2.0, 3.0, 1.0, 4.0, 0.0])
                .unwrap();
        let means_owned = column_means(&matrix);
        let means_view = column_means_view(&matrix.view());
        let centered_owned = center_columns(&matrix);
        let centered_view = center_columns_view(&matrix.view());
        let covariance_owned = covariance_matrix(&matrix).unwrap();
        let covariance_view = covariance_matrix_view(&matrix.view()).unwrap();
        let correlation_owned = correlation_matrix(&matrix).unwrap();
        let correlation_view = correlation_matrix_view(&matrix.view()).unwrap();

        for i in 0..means_owned.len() {
            assert!((means_owned[i] - means_view[i]).abs() < 1e-12);
        }
        for i in 0..matrix.nrows() {
            for j in 0..matrix.ncols() {
                assert!((centered_owned[[i, j]] - centered_view[[i, j]]).abs() < 1e-12);
            }
        }
        for i in 0..2 {
            for j in 0..2 {
                assert!((covariance_owned[[i, j]] - covariance_view[[i, j]]).abs() < 1e-12);
                assert!((correlation_owned[[i, j]] - correlation_view[[i, j]]).abs() < 1e-12);
            }
        }
    }

    #[test]
    fn complex_covariance_and_correlation_are_well_formed() {
        let matrix = Array2::from_shape_vec((4, 2), vec![
            Complex64::new(1.0, 0.0),
            Complex64::new(3.0, 1.0),
            Complex64::new(2.0, -1.0),
            Complex64::new(2.0, 0.5),
            Complex64::new(3.0, 0.2),
            Complex64::new(1.0, -0.3),
            Complex64::new(4.0, 0.7),
            Complex64::new(0.0, 0.0),
        ])
        .unwrap();

        let covariance = covariance_matrix_complex(&matrix).unwrap();
        let correlation = correlation_matrix_complex(&matrix).unwrap();
        assert_eq!(covariance.dim(), (2, 2));
        assert_eq!(correlation.dim(), (2, 2));
    }

    #[test]
    fn complex_view_variants_match_owned() {
        let matrix = Array2::from_shape_vec((3, 2), vec![
            Complex64::new(1.0, 1.0),
            Complex64::new(2.0, -1.0),
            Complex64::new(2.0, 2.0),
            Complex64::new(3.0, 0.0),
            Complex64::new(3.0, -2.0),
            Complex64::new(4.0, 1.0),
        ])
        .unwrap();

        let means_owned = column_means_complex(&matrix);
        let means_view = column_means_complex_view(&matrix.view());
        let centered_owned = center_columns_complex(&matrix);
        let centered_view = center_columns_complex_view(&matrix.view());
        let covariance_owned = covariance_matrix_complex(&matrix).unwrap();
        let covariance_view = covariance_matrix_complex_view(&matrix.view()).unwrap();
        let correlation_owned = correlation_matrix_complex(&matrix).unwrap();
        let correlation_view = correlation_matrix_complex_view(&matrix.view()).unwrap();

        for i in 0..means_owned.len() {
            assert!((means_owned[i] - means_view[i]).norm() < 1e-12);
        }
        for i in 0..matrix.nrows() {
            for j in 0..matrix.ncols() {
                assert!((centered_owned[[i, j]] - centered_view[[i, j]]).norm() < 1e-12);
            }
        }
        for i in 0..2 {
            for j in 0..2 {
                assert!((covariance_owned[[i, j]] - covariance_view[[i, j]]).norm() < 1e-12);
                assert!((correlation_owned[[i, j]] - correlation_view[[i, j]]).norm() < 1e-12);
            }
        }
    }

    #[test]
    fn stats_view_into_reuses_outputs() {
        let matrix =
            Array2::from_shape_vec((4, 2), vec![1.0_f64, 3.0, 2.0, 2.0, 3.0, 1.0, 4.0, 0.0])
                .unwrap();

        let mut means = Array1::<f64>::zeros(2);
        let mut centered = Array2::<f64>::zeros((4, 2));
        let mut covariance = Array2::<f64>::zeros((2, 2));
        let mut correlation = Array2::<f64>::zeros((2, 2));

        column_means_view_into(&matrix.view(), &mut means).unwrap();
        center_columns_view_into(&matrix.view(), &mut centered).unwrap();
        covariance_matrix_view_into(&matrix.view(), &mut covariance).unwrap();
        correlation_matrix_view_into(&matrix.view(), &mut correlation).unwrap();

        assert_eq!(means, column_means(&matrix));
        assert_eq!(centered, center_columns(&matrix));
        assert_eq!(covariance, covariance_matrix(&matrix).unwrap());
        assert_eq!(correlation, correlation_matrix(&matrix).unwrap());
    }

    #[test]
    fn complex_stats_view_into_reuses_outputs() {
        let matrix = Array2::from_shape_vec((3, 2), vec![
            Complex64::new(1.0, 1.0),
            Complex64::new(2.0, -1.0),
            Complex64::new(2.0, 2.0),
            Complex64::new(3.0, 0.0),
            Complex64::new(3.0, -2.0),
            Complex64::new(4.0, 1.0),
        ])
        .unwrap();

        let mut means = Array1::<Complex64>::zeros(2);
        let mut centered = Array2::<Complex64>::zeros((3, 2));
        let mut covariance = Array2::<Complex64>::zeros((2, 2));
        let mut correlation = Array2::<Complex64>::zeros((2, 2));

        column_means_complex_view_into(&matrix.view(), &mut means).unwrap();
        center_columns_complex_view_into(&matrix.view(), &mut centered).unwrap();
        covariance_matrix_complex_view_into(&matrix.view(), &mut covariance).unwrap();
        correlation_matrix_complex_view_into(&matrix.view(), &mut correlation).unwrap();

        assert_eq!(means, column_means_complex(&matrix));
        assert_eq!(centered, center_columns_complex(&matrix));
        assert_eq!(covariance, covariance_matrix_complex(&matrix).unwrap());
        assert_eq!(correlation, correlation_matrix_complex(&matrix).unwrap());
    }

    #[test]
    fn stats_owned_into_paths_cover_empty_valid_and_error_cases() {
        assert_eq!(
            StatsError::InvalidInput("bad shape".to_string()).to_string(),
            "Invalid input: bad shape"
        );

        let matrix =
            Array2::from_shape_vec((4, 2), vec![1.0_f64, 3.0, 2.0, 2.0, 3.0, 1.0, 4.0, 0.0])
                .unwrap();
        let mut means = Array1::<f64>::zeros(2);
        let mut centered = Array2::<f64>::zeros((4, 2));
        let mut covariance = Array2::<f64>::zeros((2, 2));
        let mut correlation = Array2::<f64>::zeros((2, 2));

        column_means_into(&matrix, &mut means).unwrap();
        center_columns_into(&matrix, &mut centered).unwrap();
        covariance_matrix_into(&matrix, &mut covariance).unwrap();
        correlation_matrix_into(&matrix, &mut correlation).unwrap();

        assert_eq!(means, column_means(&matrix));
        assert_eq!(centered, center_columns(&matrix));
        assert_eq!(covariance, covariance_matrix(&matrix).unwrap());
        assert_eq!(correlation, correlation_matrix(&matrix).unwrap());

        let empty_columns = Array2::<f64>::zeros((0, 3));
        let mut empty_means = Array1::<f64>::from_vec(vec![1.0, 1.0, 1.0]);
        column_means_into(&empty_columns, &mut empty_means).unwrap();
        assert!(empty_means.iter().all(|value| *value == 0.0));

        let mut bad_means = Array1::<f64>::zeros(3);
        assert!(matches!(
            column_means_into(&matrix, &mut bad_means),
            Err(StatsError::InvalidInput(_))
        ));

        let mut bad_centered = Array2::<f64>::zeros((4, 3));
        assert!(matches!(
            center_columns_into(&matrix, &mut bad_centered),
            Err(StatsError::InvalidInput(_))
        ));

        let empty = Array2::<f64>::zeros((0, 0));
        let mut empty_covariance = Array2::<f64>::zeros((0, 0));
        assert!(matches!(
            covariance_matrix_into(&empty, &mut empty_covariance),
            Err(StatsError::EmptyMatrix)
        ));

        let one_row = Array2::from_shape_vec((1, 2), vec![1.0, 2.0]).unwrap();
        let mut one_row_covariance = Array2::<f64>::zeros((2, 2));
        assert!(matches!(
            covariance_matrix_into(&one_row, &mut one_row_covariance),
            Err(StatsError::InsufficientSamples)
        ));

        let mut bad_covariance = Array2::<f64>::zeros((3, 3));
        assert!(matches!(
            covariance_matrix_into(&matrix, &mut bad_covariance),
            Err(StatsError::InvalidInput(_))
        ));
        assert!(matches!(
            correlation_matrix_into(&matrix, &mut bad_covariance),
            Err(StatsError::InvalidInput(_))
        ));

        let unstable = Array2::from_shape_vec((2, 2), vec![f64::MAX, 0.0, -f64::MAX, 0.0]).unwrap();
        let mut unstable_covariance = Array2::<f64>::zeros((2, 2));
        assert!(matches!(
            covariance_matrix_into(&unstable, &mut unstable_covariance),
            Err(StatsError::NumericalInstability)
        ));
    }

    #[test]
    fn complex_stats_owned_into_paths_cover_empty_valid_and_error_cases() {
        let matrix = Array2::from_shape_vec((3, 2), vec![
            Complex64::new(1.0, 1.0),
            Complex64::new(2.0, -1.0),
            Complex64::new(2.0, 2.0),
            Complex64::new(3.0, 0.0),
            Complex64::new(3.0, -2.0),
            Complex64::new(4.0, 1.0),
        ])
        .unwrap();
        let mut means = Array1::<Complex64>::zeros(2);
        let mut centered = Array2::<Complex64>::zeros((3, 2));
        let mut covariance = Array2::<Complex64>::zeros((2, 2));
        let mut correlation = Array2::<Complex64>::zeros((2, 2));

        column_means_complex_into(&matrix, &mut means).unwrap();
        center_columns_complex_into(&matrix, &mut centered).unwrap();
        covariance_matrix_complex_into(&matrix, &mut covariance).unwrap();
        correlation_matrix_complex_into(&matrix, &mut correlation).unwrap();

        assert_eq!(means, column_means_complex(&matrix));
        assert_eq!(centered, center_columns_complex(&matrix));
        assert_eq!(covariance, covariance_matrix_complex(&matrix).unwrap());
        assert_eq!(correlation, correlation_matrix_complex(&matrix).unwrap());

        let empty_columns = Array2::<Complex64>::zeros((0, 3));
        let mut empty_means = Array1::<Complex64>::from_vec(vec![
            Complex64::new(1.0, 1.0),
            Complex64::new(1.0, 1.0),
            Complex64::new(1.0, 1.0),
        ]);
        column_means_complex_into(&empty_columns, &mut empty_means).unwrap();
        assert!(empty_means.iter().all(|value| *value == Complex64::new(0.0, 0.0)));

        let mut bad_means = Array1::<Complex64>::zeros(3);
        assert!(matches!(
            column_means_complex_into(&matrix, &mut bad_means),
            Err(StatsError::InvalidInput(_))
        ));

        let mut bad_centered = Array2::<Complex64>::zeros((3, 3));
        assert!(matches!(
            center_columns_complex_into(&matrix, &mut bad_centered),
            Err(StatsError::InvalidInput(_))
        ));

        let empty = Array2::<Complex64>::zeros((0, 0));
        let mut empty_covariance = Array2::<Complex64>::zeros((0, 0));
        assert!(matches!(
            covariance_matrix_complex_into(&empty, &mut empty_covariance),
            Err(StatsError::EmptyMatrix)
        ));

        let one_row = Array2::from_shape_vec((1, 2), vec![
            Complex64::new(1.0, 0.0),
            Complex64::new(2.0, 0.0),
        ])
        .unwrap();
        let mut one_row_covariance = Array2::<Complex64>::zeros((2, 2));
        assert!(matches!(
            covariance_matrix_complex_into(&one_row, &mut one_row_covariance),
            Err(StatsError::InsufficientSamples)
        ));

        let mut bad_covariance = Array2::<Complex64>::zeros((3, 3));
        assert!(matches!(
            covariance_matrix_complex_into(&matrix, &mut bad_covariance),
            Err(StatsError::InvalidInput(_))
        ));
        assert!(matches!(
            correlation_matrix_complex_into(&matrix, &mut bad_covariance),
            Err(StatsError::InvalidInput(_))
        ));

        let unstable = Array2::from_shape_vec((2, 2), vec![
            Complex64::new(f64::MAX, 0.0),
            Complex64::new(0.0, 0.0),
            Complex64::new(-f64::MAX, 0.0),
            Complex64::new(0.0, 0.0),
        ])
        .unwrap();
        let mut unstable_covariance = Array2::<Complex64>::zeros((2, 2));
        assert!(matches!(
            covariance_matrix_complex_into(&unstable, &mut unstable_covariance),
            Err(StatsError::NumericalInstability)
        ));
    }

    #[test]
    fn stats_view_into_rejects_wrong_output_shapes() {
        let matrix =
            Array2::from_shape_vec((4, 2), vec![1.0_f64, 3.0, 2.0, 2.0, 3.0, 1.0, 4.0, 0.0])
                .unwrap();
        let mut bad_means = Array1::<f64>::zeros(3);
        let mut bad_centered = Array2::<f64>::zeros((4, 3));
        let mut bad_covariance = Array2::<f64>::zeros((3, 3));

        assert!(matches!(
            column_means_view_into(&matrix.view(), &mut bad_means),
            Err(StatsError::InvalidInput(_))
        ));
        assert!(matches!(
            center_columns_view_into(&matrix.view(), &mut bad_centered),
            Err(StatsError::InvalidInput(_))
        ));
        assert!(matches!(
            covariance_matrix_view_into(&matrix.view(), &mut bad_covariance),
            Err(StatsError::InvalidInput(_))
        ));
    }

    fn approx_eq(a: f64, b: f64) -> bool { num_traits::Float::abs(a - b) < 1e-10 }

    #[test]
    fn online_mean_and_variance_track_batch_statistics() {
        let mut mean = online::OnlineMean::<f64>::default();
        let mut variance = online::OnlineVariance::<f64>::default();
        for value in [1.0, 2.0, 3.0, 4.0, 5.0] {
            mean.push(value);
            variance.push(value);
        }
        assert!(approx_eq(mean.mean(), 3.0));
        assert!(approx_eq(variance.mean(), 3.0));
        assert!(approx_eq(variance.variance(), 2.5));
    }

    #[test]
    fn online_accumulators_reset_to_initial_state() {
        let mut mean = online::OnlineMean::<f64>::default();
        let mut variance = online::OnlineVariance::<f64>::default();
        mean.push(4.0);
        variance.push(4.0);
        mean.reset();
        variance.reset();
        assert!(approx_eq(mean.mean(), 0.0));
        assert!(approx_eq(variance.mean(), 0.0));
        assert!(approx_eq(variance.variance(), 0.0));
    }

    #[test]
    fn online_variance_is_zero_with_fewer_than_two_samples() {
        let mut variance = online::OnlineVariance::<f64>::default();
        variance.push(2.0);
        assert!(approx_eq(variance.variance(), 0.0));
    }

    #[test]
    fn ewma_state_and_vector_apis_match_expected_smoothing() {
        let signal = Array1::from_vec(vec![10.0_f64, 0.0]);
        let alpha = 0.5;
        let mut state = ewma::EwmaState::new(alpha);
        assert!(approx_eq(state.push(10.0), 10.0));
        assert!(approx_eq(state.push(0.0), 5.0));

        let owned = ewma::ewma(&signal, alpha);
        let viewed = ewma::ewma_view(&signal.view(), alpha);
        assert!(approx_eq(owned[0], 10.0));
        assert!(approx_eq(owned[1], 5.0));
        assert_eq!(owned, viewed);

        let mut output = Array1::<f64>::zeros(2);
        ewma::ewma_into(&signal.view(), alpha, &mut output).unwrap();
        assert_eq!(output, owned);

        let mut bad_output = Array1::<f64>::zeros(3);
        assert!(matches!(
            ewma::ewma_into(&signal.view(), alpha, &mut bad_output),
            Err(StatsError::InvalidInput(_))
        ));
    }

    #[test]
    fn rolling_mean_and_variance_match_manual_windows() {
        let signal = Array1::from_vec(vec![1.0_f64, 2.0, 3.0, 4.0, 5.0]);
        let window = 3;
        let mean = rolling::rolling_mean(&signal.view(), window);
        let mean_view = rolling::rolling_mean_view(&signal.view(), window);
        assert_eq!(mean, mean_view);
        assert!(approx_eq(mean[0], 1.0));
        assert!(approx_eq(mean[2], 2.0));
        assert!(approx_eq(mean[4], 4.0));

        let variance = rolling::rolling_variance(&signal.view(), window);
        assert!(approx_eq(variance[2], 2.0 / 3.0));

        let mut mean_out = Array1::<f64>::zeros(signal.len());
        rolling::rolling_mean_into(&signal.view(), window, &mut mean_out).unwrap();
        assert_eq!(mean_out, mean);

        let mut variance_out = Array1::<f64>::zeros(signal.len());
        rolling::rolling_variance_into(&signal.view(), window, &mut variance_out).unwrap();
        assert_eq!(variance_out, variance);

        assert!(matches!(
            rolling::rolling_mean_into(&signal.view(), 0, &mut mean_out),
            Err(StatsError::InvalidInput(_))
        ));
        let mut bad_mean_out = Array1::<f64>::zeros(signal.len() + 1);
        assert!(matches!(
            rolling::rolling_mean_into(&signal.view(), window, &mut bad_mean_out),
            Err(StatsError::InvalidInput(_))
        ));
        assert!(matches!(
            rolling::rolling_variance_into(&signal.view(), 0, &mut variance_out),
            Err(StatsError::InvalidInput(_))
        ));
    }

    #[test]
    fn rolling_covariance_into_handles_valid_and_invalid_inputs() {
        let matrix =
            Array2::from_shape_vec((3, 2), vec![1.0_f64, 2.0, 2.0, 3.0, 3.0, 4.0]).unwrap();
        let window = 2;
        let cov = rolling::rolling_covariance(&matrix.view(), window);
        let cov_view = rolling::rolling_covariance_view(&matrix.view(), window);
        assert_eq!(cov, cov_view);
        assert!(approx_eq(cov[[0, 0]], 0.0));

        let mut output = Array2::<f64>::zeros((3, 4));
        rolling::rolling_covariance_into(&matrix.view(), window, &mut output).unwrap();
        assert_eq!(output, cov);

        let mut bad_shape = Array2::<f64>::zeros((3, 3));
        assert!(matches!(
            rolling::rolling_covariance_into(&matrix.view(), window, &mut bad_shape),
            Err(StatsError::InvalidInput(_))
        ));
        assert!(matches!(
            rolling::rolling_covariance_into(&matrix.view(), 0, &mut output),
            Err(StatsError::InvalidInput(_))
        ));
    }

    #[test]
    fn lag_view_and_shift_columns_into_cover_alignment_paths() {
        let matrix =
            Array2::from_shape_vec((3, 2), vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
        let view = matrix.view();
        let lagged = lag::lag_view(&view, 1).unwrap();
        assert_eq!(lagged.dim(), (2, 2));
        assert!(approx_eq(lagged[[0, 0]], 1.0));
        assert!(approx_eq(lagged[[1, 1]], 4.0));

        let mut shifted = Array2::<f64>::zeros((3, 2));
        lag::shift_columns_into(&view, 1, &mut shifted).unwrap();
        assert!(approx_eq(shifted[[0, 0]], 0.0));
        assert!(approx_eq(shifted[[1, 0]], 1.0));
        assert!(approx_eq(shifted[[2, 1]], 4.0));

        assert!(matches!(lag::lag_view(&view, matrix.nrows()), Err(StatsError::InvalidInput(_))));

        let mut bad_output = Array2::<f64>::zeros((2, 2));
        assert!(matches!(
            lag::shift_columns_into(&view, 1, &mut bad_output),
            Err(StatsError::InvalidInput(_))
        ));

        let mut zeroed = Array2::<f64>::ones((3, 2));
        lag::shift_columns_into(&view, matrix.nrows(), &mut zeroed).unwrap();
        assert!(zeroed.iter().all(|value| approx_eq(*value, 0.0)));
    }
}