edge-rs 0.3.1

Negative binomial differential expression for bulk and single-cell RNA-seq: the edgeR numerical stack and NEBULA mixed models.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
//! limma's `lmFit`: one weighted least squares fit per gene.
//!
//! The linear-model half of voom. Genes are fitted independently, as in
//! [`crate::glm::levenberg`].
//!
//! ### One code path
//!
//! limma splits `lmFit` across `lm.series` and `gls.series`, each with a fast
//! all-observed branch and a slow per-gene branch. They are one computation.
//! With working covariance `V = D^-1/2 R D^-1/2` (`D` the weights, `R` the
//! compound-symmetry correlation from `block`), whitening by the Cholesky
//! factor of `V` turns every case into ordinary least squares. Plain weights
//! are `R = I`, where whitening is a row scaling by `sqrt(w)`.
//!
//! The factor is computed once, not per gene: `V` factors as `L = D^-1/2 L_R`
//! (scaling a lower triangular matrix by a positive diagonal keeps it lower
//! triangular, and Cholesky factors are unique), so `L_R` depends only on
//! `block` and the correlation. Genes that keep all their observations reuse
//! it; only genes with dropped observations refactorise, on their own
//! submatrix.
//!
//! ### Missing observations
//!
//! A gene with non-finite responses or zero weights is refitted on what
//! survives, with its own residual df and rank.
//!
//! ### Rank deficiency
//!
//! The per-gene solve is a Householder QR that accepts design columns left to
//! right and rejects any whose residual norm has collapsed (LINPACK `dqrdc2`,
//! as in R's `lm.fit`). Rejected columns report `NaN` for their coefficient and
//! unscaled standard deviation, as R reports `NA`.
//! ### References
//!
//! Smyth, Statistical Applications in Genetics and Molecular Biology 3(1), 2004
//! Law, Chen, Shi and Smyth, Genome Biology 15, R29, 2014

use rayon::prelude::*;

use crate::errors::EdgeErrors;
use crate::utils::design::non_estimable;
use crate::utils::linalg::{
    cholesky_lower, cross_inverse, forward_substitute, invert_upper_triangular,
};
use crate::utils::recycled::{Recycled, RecycledRow};

/// Relative tolerance for declaring a design column linearly dependent.
/// R's `lm.fit` (LINPACK `dqrdc2`) cycles a column to the back when its
/// remaining norm falls below `1e-7` times its original norm. limma inherits the
/// threshold through `lm.fit`.
const RANK_TOL: f64 = 1e-7;

/// Weights at or below this drop the observation rather than scaling it.
///
/// limma's `gls.series` sets `M[weights < 1e-15] <- NA`; `lm.series` sets
/// `weights[weights <= 0] <- NA`. One threshold covers both: they differ only on
/// weights in `(0, 1e-15]`, which carry no information.
const MIN_WEIGHT: f64 = 1e-15;

/////////////////
// LmFitResult //
/////////////////

/// Everything `lmFit` produces, per gene.
#[derive(Clone, Debug)]
pub struct LmFitResult {
    /// Coefficients, row-major `n_genes * n_coef`.
    ///
    /// `NaN` for a coefficient that is not estimable (aliased design column, or
    /// the gene lost too many observations), where R reports `NA`.
    pub coefficients: Vec<f64>,
    /// Unscaled standard deviations, row-major `n_genes * n_coef`.
    ///
    /// The square root of the diagonal of `(X' V^-1 X)^-1`. The residual scale
    /// is kept in [`LmFitResult::sigma`] so `eBayes` can moderate it.
    pub stdev_unscaled: Vec<f64>,
    /// Residual standard deviation per gene.
    ///
    /// `sqrt(rss / df_residual)` with `rss` the whitened residual sum of
    /// squares. Zero where `df_residual` is zero, where limma reports `NA`;
    /// this is the one deliberate departure here, harmless because `squeezeVar`
    /// drops zero-df genes.
    pub sigma: Vec<f64>,
    /// Residual degrees of freedom per gene.
    ///
    /// Observations kept minus the rank achieved on them.
    pub df_residual: Vec<f64>,
    /// Fitted values, row-major `n_genes * n_samples`.
    ///
    /// `X * beta` on the original scale, aliased coefficients contributing
    /// nothing, at every sample including dropped ones. `NaN` throughout for a
    /// gene with no usable observation.
    pub fitted: Vec<f64>,
    /// Unscaled covariance of the estimable coefficients, row-major
    /// `rank * rank`.
    ///
    /// `(X' V^-1 X)^-1` for the design as a whole, in the order of
    /// [`LmFitResult::pivot`]. One matrix for all genes; see [`lm_fit`].
    /// probe weights.
    pub cov_coefficients: Vec<f64>,
    /// Design column indices, accepted ones first, then the rejected ones.
    ///
    /// Length `n_coef`, zero-based. `pivot[..rank]` names the estimable columns
    /// in the order [`LmFitResult::cov_coefficients`] uses (R's `qr()$pivot`).
    pub pivot: Vec<usize>,
    /// Rank of the design, shared by every fully observed gene.
    ///
    /// A gene that lost observations can have a lower rank of its own; that
    /// shows as extra `NaN` coefficients and a smaller
    /// [`LmFitResult::df_residual`].
    pub rank: usize,
}

///////////////////////
// Block correlation //
///////////////////////

/// The compound-symmetry correlation shared by every gene.
struct BlockCorrelation<'a> {
    /// Block label per sample. Samples sharing a label are correlated.
    block: &'a [usize],
    /// Within-block correlation.
    correlation: f64,
    /// Lower Cholesky factor of the full correlation matrix, row-major
    /// `n_samples * n_samples`. Reused by every fully observed gene.
    chol: Vec<f64>,
}

/// Writes the compound-symmetry correlation matrix for a subset of samples.
///
/// ### Params
///
/// * `out` - Destination, row-major with row stride `stride`
/// * `stride` - Row stride of `out`
/// * `obs` - Sample indices to include, in increasing order
/// * `block` - Block label per sample
/// * `correlation` - Within-block correlation
fn fill_correlation(
    out: &mut [f64],
    stride: usize,
    obs: &[usize],
    block: &[usize],
    correlation: f64,
) {
    for (i, &si) in obs.iter().enumerate() {
        for (j, &sj) in obs.iter().enumerate() {
            out[i * stride + j] = if i == j {
                1.0
            } else if block[si] == block[sj] {
                correlation
            } else {
                0.0
            };
        }
    }
}

/////////////
// Scratch //
/////////////

/// Per-thread buffers, allocated once per rayon worker.
struct Scratch {
    /// Sample indices this gene actually contributes, in increasing order.
    obs: Vec<usize>,
    /// Whitened design, column-major: column `j` starts at `j * n_samples`.
    ///
    /// Column-major: the Householder sweep reads one column at a time.
    a: Vec<f64>,
    /// Whitened response, overwritten by the Householder-transformed one. The
    /// tail below the rank is the residual, exactly R's `effects`.
    z: Vec<f64>,
    /// Householder reflectors, column-major with the same stride as `a`.
    hh: Vec<f64>,
    /// Reciprocal of `u'u / 2` for each stored reflector.
    tau: Vec<f64>,
    /// Original norm of each whitened design column, for the rank test.
    col_norm: Vec<f64>,
    /// Upper triangular factor of the accepted columns, row-major `n_coef`.
    r: Vec<f64>,
    /// Inverse of `r`, row-major `n_coef`.
    r_inv: Vec<f64>,
    /// Original indices of the accepted design columns, increasing.
    est: Vec<usize>,
    /// Solution in the accepted-column basis.
    beta: Vec<f64>,
    /// Correlation matrix for this gene's observed subset, then its Cholesky
    /// factor. Empty unless a block correlation was supplied.
    chol: Vec<f64>,
}

impl Scratch {
    /// Allocates scratch for one worker.
    ///
    /// ### Params
    ///
    /// * `n_samples` - Number of samples
    /// * `n_coef` - Number of coefficients
    /// * `blocked` - Whether a block correlation is in play, which is the only
    ///   case needing an `n_samples` by `n_samples` buffer
    ///
    /// ### Returns
    ///
    /// Buffers sized for a single gene's fit.
    fn new(n_samples: usize, n_coef: usize, blocked: bool) -> Self {
        Self {
            obs: Vec::with_capacity(n_samples),
            a: vec![0.0; n_samples * n_coef],
            z: vec![0.0; n_samples],
            hh: vec![0.0; n_samples * n_coef],
            tau: vec![0.0; n_coef],
            col_norm: vec![0.0; n_coef],
            r: vec![0.0; n_coef * n_coef],
            r_inv: vec![0.0; n_coef * n_coef],
            est: Vec::with_capacity(n_coef),
            beta: vec![0.0; n_coef],
            chol: if blocked {
                vec![0.0; n_samples * n_samples]
            } else {
                Vec::new()
            },
        }
    }
}

/// Householder QR that accepts design columns left to right and rejects any
/// whose residual norm has collapsed.
///
/// This is LINPACK's `dqrdc2` as used by R's `lm.fit`: a rejected column is set
/// aside, not cycled to the end, so `est` is an increasing subset. The per-gene
/// fit and the shared design factorisation both use it, so their ranks agree.
///
/// ### Params
///
/// * `a` - Whitened design, column-major with column stride `stride`,
///   overwritten by the transformed columns
/// * `z` - Whitened response to carry along, overwritten by `Q' z`. `None` when
///   only the factorisation itself is wanted.
/// * `hh` - Scratch for the reflectors, column-major with stride `stride`
/// * `tau` - Scratch for the reflector scales, length `n_coef`
/// * `col_norm` - Original norm of each column, read only when `pivot` is set
/// * `r` - Destination for the upper triangular factor, row-major `n_coef`
/// * `est` - Destination for the accepted column indices, cleared on entry
/// * `m` - Number of observations in play
/// * `stride` - Column stride of `a` and `hh`
/// * `n_coef` - Number of design columns
/// * `pivot` - Whether to apply the rank test. A design full rank on all
///   samples stays full rank after whitening, so a fully observed gene can skip
///   it.
///
/// ### Returns
///
/// The rank achieved, which is `est.len()`.
#[allow(clippy::too_many_arguments)]
fn rank_revealing_qr(
    a: &mut [f64],
    mut z: Option<&mut [f64]>,
    hh: &mut [f64],
    tau: &mut [f64],
    col_norm: &[f64],
    r: &mut [f64],
    est: &mut Vec<usize>,
    m: usize,
    stride: usize,
    n_coef: usize,
    pivot: bool,
) -> usize {
    est.clear();
    let mut rank = 0usize;
    for j in 0..n_coef {
        if rank == m {
            break;
        }
        let col = &a[j * stride..j * stride + m];
        let norm = col[rank..].iter().map(|v| v * v).sum::<f64>().sqrt();
        if norm == 0.0 || (pivot && norm <= RANK_TOL * col_norm[j]) {
            continue;
        }

        // Record the column of R above and on the diagonal before the column is
        // consumed by its own reflector.
        for i in 0..rank {
            r[i * n_coef + rank] = a[j * stride + i];
        }
        let head = a[j * stride + rank];
        let alpha = if head >= 0.0 { -norm } else { norm };
        r[rank * n_coef + rank] = alpha;

        // u = x - alpha e_1, so u'u = 2 * norm * (norm + |head|) > 0.
        let base = rank * stride;
        for i in rank..m {
            hh[base + i] = a[j * stride + i];
        }
        hh[base + rank] = head - alpha;
        tau[rank] = 1.0 / (norm * (norm + head.abs()));

        // Apply the reflector to every column still to come, and to the
        // response. Columns already passed over are never revisited.
        for jj in (j + 1)..n_coef {
            let cbase = jj * stride;
            let mut dot = 0.0;
            for i in rank..m {
                dot += hh[base + i] * a[cbase + i];
            }
            let factor = dot * tau[rank];
            for i in rank..m {
                a[cbase + i] -= factor * hh[base + i];
            }
        }
        if let Some(z) = z.as_deref_mut() {
            let mut dot = 0.0;
            for i in rank..m {
                dot += hh[base + i] * z[i];
            }
            let factor = dot * tau[rank];
            for i in rank..m {
                z[i] -= factor * hh[base + i];
            }
        }

        est.push(j);
        rank += 1;
    }
    rank
}

//////////////////
// Per-gene fit //
//////////////////

/// Outputs of one gene's fit, borrowed from the result buffers.
struct GeneOut<'a> {
    /// Coefficients for this gene, length `n_coef`.
    coef: &'a mut [f64],
    /// Unscaled standard deviations, length `n_coef`.
    stdev: &'a mut [f64],
    /// Fitted values, length `n_samples`.
    fitted: &'a mut [f64],
    /// Residual standard deviation.
    sigma: &'a mut f64,
    /// Residual degrees of freedom.
    df: &'a mut f64,
}

/// Fits one gene by whitening, then a rank-revealing Householder QR.
///
/// Whitening turns GLS against `V = D^-1/2 R D^-1/2` into OLS, so the rest is
/// the same for weights, block correlation, both or neither.
///
/// ### Params
///
/// * `scratch` - Per-thread buffers
/// * `y_row` - This gene's response, length `n_samples`
/// * `design` - Row-major design, `n_samples * n_coef`
/// * `n_samples` - Number of samples
/// * `n_coef` - Number of coefficients
/// * `weights` - Optional weight row for this gene
/// * `gls` - Optional block correlation
/// * `design_full_rank` - Whether the design is full rank on all samples, which
///   lets a fully observed gene skip the rank test
/// * `out` - Destination slices for this gene
#[allow(clippy::too_many_arguments)]
fn fit_gene(
    scratch: &mut Scratch,
    y_row: &[f64],
    design: &[f64],
    n_samples: usize,
    n_coef: usize,
    weights: Option<RecycledRow<'_, f64>>,
    gls: Option<&BlockCorrelation<'_>>,
    design_full_rank: bool,
    out: GeneOut<'_>,
) {
    let Scratch {
        obs,
        a,
        z,
        hh,
        tau,
        col_norm,
        r,
        r_inv,
        est,
        beta,
        chol,
    } = scratch;

    // -------------------------- //
    // which observations survive //
    // -------------------------- //
    obs.clear();
    for (sample, &value) in y_row.iter().enumerate() {
        let usable = value.is_finite()
            && match weights {
                Some(w) => {
                    let wj = w.get(sample);
                    wj.is_finite() && wj > MIN_WEIGHT
                }
                None => true,
            };
        if usable {
            obs.push(sample);
        }
    }
    let m = obs.len();

    if m == 0 {
        out.coef.fill(f64::NAN);
        out.stdev.fill(f64::NAN);
        out.fitted.fill(f64::NAN);
        *out.sigma = 0.0;
        *out.df = 0.0;
        return;
    }

    // --------------------------------------------------------------------- //
    // whiten: scale rows by sqrt(w), then apply the inverse Cholesky factor //
    // --------------------------------------------------------------------- //
    for (i, &sample) in obs.iter().enumerate() {
        let scale = match weights {
            Some(w) => w.get(sample).sqrt(),
            None => 1.0,
        };
        let row = &design[sample * n_coef..(sample + 1) * n_coef];
        for (j, &x) in row.iter().enumerate() {
            a[j * n_samples + i] = scale * x;
        }
        z[i] = scale * y_row[sample];
    }

    if let Some(g) = gls {
        // A principal submatrix of a positive definite matrix is positive
        // definite, so refactorising cannot fail once the full matrix passed.
        let factor: &[f64] = if m < n_samples {
            fill_correlation(chol, n_samples, obs, g.block, g.correlation);
            let factored = cholesky_lower(chol, m, n_samples);
            debug_assert!(factored, "principal submatrix must be positive definite");
            &chol[..]
        } else {
            &g.chol
        };
        for j in 0..n_coef {
            forward_substitute(
                factor,
                n_samples,
                m,
                &mut a[j * n_samples..j * n_samples + m],
            );
        }
        forward_substitute(factor, n_samples, m, &mut z[..m]);
    }

    // Whitening is invertible, so a full rank design stays full rank. Only a
    // gene that lost observations can lose rank and needs the reference norms.
    let pivot = !design_full_rank || m < n_samples;
    if pivot {
        for j in 0..n_coef {
            let col = &a[j * n_samples..j * n_samples + m];
            col_norm[j] = col.iter().map(|v| v * v).sum::<f64>().sqrt();
        }
    }

    // ------------------------------------------------------------- //
    // rank-revealing Householder QR, columns accepted left to right //
    // ------------------------------------------------------------- //
    let rank = rank_revealing_qr(
        a,
        Some(z.as_mut_slice()),
        hh,
        tau,
        col_norm,
        r,
        est,
        m,
        n_samples,
        n_coef,
        pivot,
    );

    // -------------- //
    // residual scale //
    // -------------- //
    let df = m - rank;
    let rss: f64 = z[rank..m].iter().map(|v| v * v).sum();
    *out.df = df as f64;
    *out.sigma = if df > 0 {
        (rss / df as f64).sqrt()
    } else {
        0.0
    };

    // ------------------------------------------------------------------- //
    // coefficients: back substitution against the leading rank block of R //
    // ------------------------------------------------------------------- //
    for i in (0..rank).rev() {
        let mut sum = z[i];
        for t in (i + 1)..rank {
            sum -= r[i * n_coef + t] * beta[t];
        }
        beta[i] = sum / r[i * n_coef + i];
    }

    out.coef.fill(f64::NAN);
    for (t, &j) in est.iter().enumerate() {
        out.coef[j] = beta[t];
    }

    // ----------------------------------------------- //
    // unscaled standard deviations: row norms of R^-1 //
    // ----------------------------------------------- //
    //
    // diag((R'R)^-1) = diag(R^-1 R^-T), so entry i is the sum of squares of row
    // i of R^-1. Inverting a tiny triangular matrix beats a solve per coefficient.
    invert_upper_triangular(r, r_inv, rank, n_coef);

    out.stdev.fill(f64::NAN);
    for (t, &j) in est.iter().enumerate() {
        let row: f64 = (t..rank).map(|s| r_inv[t * n_coef + s].powi(2)).sum();
        out.stdev[j] = row.sqrt();
    }

    // ---------------------------------------------------- //
    // fitted values on the original scale, at every sample //
    // ---------------------------------------------------- //
    for (sample, slot) in out.fitted.iter_mut().enumerate() {
        let row = &design[sample * n_coef..(sample + 1) * n_coef];
        let mut acc = 0.0;
        for (t, &j) in est.iter().enumerate() {
            acc += row[j] * beta[t];
        }
        *slot = acc;
    }
}

//////////////////////////
// Shared design factor //
//////////////////////////

/// Factors the design once for the whole fit, giving the unscaled covariance.
///
/// **This deliberately ignores per-gene weights.** limma computes
/// `cov.coefficients` from `qr(design)` on the shared design even when every
/// gene is fitted under probe weights (`R/lmfit.R:180-182`, and `R/lmfit.R:359`
/// for the blocked form, where only the correlation whitening is applied).
/// `contrasts.fit` consumes it regardless (`R/contrasts.R:5-6`), so reproducing
/// it keeps the contrast standard errors matching.
///
/// A weight row shared by every gene is folded in, as limma does when no
/// response is missing either (`R/lmfit.R:147`, `R/lmfit.R:316-318`).
///
/// ### Params
///
/// * `design` - Row-major design, `n_samples * n_coef`
/// * `n_samples` - Number of samples
/// * `n_coef` - Number of coefficients
/// * `shared_weights` - One weight per sample when every gene shares the same
///   row and no response is missing, otherwise `None`
/// * `gls` - Optional block correlation, whose Cholesky factor whitens the
///   design
///
/// ### Returns
///
/// The unscaled covariance of the estimable columns (row-major `rank * rank`),
/// the pivot with accepted columns first, and the rank.
fn design_factorisation(
    design: &[f64],
    n_samples: usize,
    n_coef: usize,
    shared_weights: Option<&[f64]>,
    gls: Option<&BlockCorrelation<'_>>,
) -> (Vec<f64>, Vec<usize>, usize) {
    let mut a = vec![0.0; n_samples * n_coef];
    for sample in 0..n_samples {
        let scale = match shared_weights {
            Some(w) => w[sample].sqrt(),
            None => 1.0,
        };
        let row = &design[sample * n_coef..(sample + 1) * n_coef];
        for (j, &x) in row.iter().enumerate() {
            a[j * n_samples + sample] = scale * x;
        }
    }

    if let Some(g) = gls {
        for j in 0..n_coef {
            forward_substitute(
                &g.chol,
                n_samples,
                n_samples,
                &mut a[j * n_samples..(j + 1) * n_samples],
            );
        }
    }

    let col_norm: Vec<f64> = (0..n_coef)
        .map(|j| {
            a[j * n_samples..(j + 1) * n_samples]
                .iter()
                .map(|v| v * v)
                .sum::<f64>()
                .sqrt()
        })
        .collect();

    let mut hh = vec![0.0; n_samples * n_coef];
    let mut tau = vec![0.0; n_coef];
    let mut r = vec![0.0; n_coef * n_coef];
    let mut est = Vec::with_capacity(n_coef);
    let rank = rank_revealing_qr(
        &mut a, None, &mut hh, &mut tau, &col_norm, &mut r, &mut est, n_samples, n_samples, n_coef,
        true,
    );

    let mut r_inv = vec![0.0; n_coef * n_coef];
    invert_upper_triangular(&r, &mut r_inv, rank, n_coef);
    let cov = cross_inverse(&r_inv, rank, n_coef);

    // Accepted columns first, then the rejected ones in their original order,
    // which is what `dqrdc2` leaves behind and what `contrasts.fit` indexes.
    let mut pivot = est.clone();
    pivot.extend((0..n_coef).filter(|j| !est.contains(j)));

    (cov, pivot, rank)
}

////////////
// lm_fit //
////////////

/// Fits a linear model to every gene by weighted or generalised least squares.
///
/// Port of limma's `lmFit`, covering the `lm.series` and `gls.series` paths.
/// Each gene is fitted on its own finite, positively weighted observations, so
/// genes with missing values get their own residual df.
///
/// `block` plus `correlation` gives the mixed-model form: samples sharing a
/// label have the stated correlation, and the fit is GLS against that
/// compound-symmetry covariance. `correlation` without `block` is ignored, as in
/// `lmFit`.
///
/// ### Params
///
/// * `y` - Response, row-major `n_genes * n_samples`. `f64` throughout (log-CPM
///   for voom). Non-finite entries are treated as missing.
/// * `n_genes` - Number of genes
/// * `n_samples` - Number of samples
/// * `design` - Design matrix, row-major `n_samples * n_coef`
/// * `n_coef` - Number of coefficients
/// * `weights` - Optional observation weights, recycled over genes and samples.
///   A weight at or below `1e-15`, or a non-finite one, drops the observation.
/// * `block` - Optional block label per sample
/// * `correlation` - Within-block correlation, required when `block` is given
///
/// ### Returns
///
/// Coefficients, unscaled standard deviations, residual standard deviations,
/// residual degrees of freedom, fitted values, and the shared design
/// factorisation `eBayes` and `contrasts.fit` need. [`EdgeErrors`] if the
/// shapes disagree, the correlation is out of range, or the implied correlation
/// matrix is not positive definite.
/// [`LmFitResult::cov_coefficients`] comes from the design as a whole, not each
/// gene's weighted fit. That is limma's choice; see `design_factorisation`.
///
/// ### References
///
/// Smyth, Michaud and Scott, Bioinformatics 21(9), 2005 (the blocked form)
#[allow(clippy::too_many_arguments)]
pub fn lm_fit(
    y: &[f64],
    n_genes: usize,
    n_samples: usize,
    design: &[f64],
    n_coef: usize,
    weights: Option<&Recycled<f64>>,
    block: Option<&[usize]>,
    correlation: Option<f64>,
) -> Result<LmFitResult, EdgeErrors> {
    if n_genes == 0 || n_samples == 0 {
        return Err(EdgeErrors::EmptyCounts { n_genes, n_samples });
    }
    if n_coef == 0 {
        return Err(EdgeErrors::MustBePositive("n_coef".to_string()));
    }
    if y.len() != n_genes * n_samples {
        return Err(EdgeErrors::LengthMismatch {
            name: "y",
            expected: n_genes * n_samples,
            got: y.len(),
        });
    }
    if design.len() != n_samples * n_coef {
        return Err(EdgeErrors::LengthMismatch {
            name: "design",
            expected: n_samples * n_coef,
            got: design.len(),
        });
    }
    if let Some(w) = weights {
        w.validate(n_genes, n_samples)?;
    }

    // ------------------------------------------------- //
    // block correlation set-up, done once for all genes //
    // ------------------------------------------------- //
    let gls = match block {
        None => None,
        Some(b) => {
            if b.len() != n_samples {
                return Err(EdgeErrors::LengthMismatch {
                    name: "block",
                    expected: n_samples,
                    got: b.len(),
                });
            }
            let rho = correlation.ok_or_else(|| {
                EdgeErrors::InvalidArgument(
                    "block requires a correlation; limma would estimate one with duplicateCorrelation"
                        .to_string(),
                )
            })?;
            if !rho.is_finite() || rho.abs() >= 1.0 {
                return Err(EdgeErrors::InvalidArgument(format!(
                    "correlation must be finite and strictly inside (-1, 1); got {rho}"
                )));
            }
            if rho == 0.0 {
                // Uncorrelated blocks give the identity; skip whitening.
                None
            } else {
                let obs: Vec<usize> = (0..n_samples).collect();
                let mut chol = vec![0.0; n_samples * n_samples];
                fill_correlation(&mut chol, n_samples, &obs, b, rho);
                if !cholesky_lower(&mut chol, n_samples, n_samples) {
                    return Err(EdgeErrors::CholeskyFailed(format!(
                        "correlation {rho} makes the block covariance indefinite; \
                         a block of size k needs correlation above -1/(k - 1)"
                    )));
                }
                Some(BlockCorrelation {
                    block: b,
                    correlation: rho,
                    chol,
                })
            }
        }
    };

    // Columns no gene can estimate. A design full rank here is full rank for
    // every gene that keeps all its observations, which skip the rank test.
    let design_full_rank = non_estimable(design, n_samples, n_coef)?.is_none();

    // limma folds weights into the shared factorisation only when one row serves
    // every gene and no response is missing, where `lm.wfit` on the shared design
    // is exact (`R/lmfit.R:142`). Otherwise it uses the bare design.
    let shared_weights: Option<Vec<f64>> = if y.par_iter().all(|v| v.is_finite()) {
        match weights {
            Some(Recycled::Scalar(w)) => Some(vec![*w; n_samples]),
            Some(Recycled::BySample(v)) => Some(v.clone()),
            _ => None,
        }
    } else {
        None
    };
    let (cov_coefficients, pivot, rank) = design_factorisation(
        design,
        n_samples,
        n_coef,
        shared_weights.as_deref(),
        gls.as_ref(),
    );

    let mut coefficients = vec![0.0; n_genes * n_coef];
    let mut stdev_unscaled = vec![0.0; n_genes * n_coef];
    let mut sigma = vec![0.0; n_genes];
    let mut df_residual = vec![0.0; n_genes];
    let mut fitted = vec![0.0; n_genes * n_samples];

    let blocked = gls.is_some();
    coefficients
        .par_chunks_mut(n_coef)
        .zip(stdev_unscaled.par_chunks_mut(n_coef))
        .zip(fitted.par_chunks_mut(n_samples))
        .zip(sigma.par_iter_mut())
        .zip(df_residual.par_iter_mut())
        .enumerate()
        .for_each_init(
            || Scratch::new(n_samples, n_coef, blocked),
            |scratch, (gene, ((((coef, stdev), fit), sig), df))| {
                let start = gene * n_samples;
                fit_gene(
                    scratch,
                    &y[start..start + n_samples],
                    design,
                    n_samples,
                    n_coef,
                    weights.map(|w| w.row(gene, n_samples)),
                    gls.as_ref(),
                    design_full_rank,
                    GeneOut {
                        coef,
                        stdev,
                        fitted: fit,
                        sigma: sig,
                        df,
                    },
                );
            },
        );

    Ok(LmFitResult {
        coefficients,
        stdev_unscaled,
        sigma,
        df_residual,
        fitted,
        cov_coefficients,
        pivot,
        rank,
    })
}

///////////
// Tests //
///////////

#[cfg(test)]
mod tests {
    // References are pasted verbatim from R's 17-digit output, including digits
    // past f64 precision and a 1/sqrt(2) clippy would like as a constant, so they
    // stay checkable against the quoted `Rscript` lines.
    #![allow(clippy::excessive_precision, clippy::approx_constant)]

    use super::*;
    use approx::assert_relative_eq;

    const N_GENES: usize = 8;
    const N_SAMPLES: usize = 5;

    /// Stand-in for R's `NA` in the embedded reference values.
    const NA: f64 = f64::NAN;

    /// Response fixture, `y[i] = ((i * 7) mod 23) / 64`, row-major 8 by 5.
    ///
    /// Dyadic rationals, so R and Rust see bit-identical inputs.
    fn fixture_y() -> Vec<f64> {
        (0..N_GENES * N_SAMPLES)
            .map(|i| ((i * 7) % 23) as f64 / 64.0)
            .collect()
    }

    /// Full weight fixture, `w[i] = (((i * 5) mod 7) + 1) / 8`, row-major 8 by 5.
    fn fixture_weights() -> Vec<f64> {
        (0..N_GENES * N_SAMPLES)
            .map(|i| (((i * 5) % 7) + 1) as f64 / 8.0)
            .collect()
    }

    /// Two-column design: intercept and a two-versus-three group indicator.
    fn design_two() -> Vec<f64> {
        vec![1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
    }

    /// Three-column design whose first column is the sum of the other two.
    fn design_aliased() -> Vec<f64> {
        vec![
            1.0, 0.0, 1.0, //
            1.0, 0.0, 1.0, //
            1.0, 1.0, 0.0, //
            1.0, 1.0, 0.0, //
            1.0, 1.0, 0.0,
        ]
    }

    /// Block labels used by every correlated fixture.
    fn blocks() -> Vec<usize> {
        vec![1, 1, 2, 2, 3]
    }

    /// Compares against R, treating `NaN` and `NA` as equal.
    fn assert_close(got: &[f64], want: &[f64]) {
        assert_eq!(got.len(), want.len(), "length");
        for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
            if w.is_nan() {
                assert!(g.is_nan(), "index {i}: expected NA, got {g}");
            } else {
                assert!(g.is_finite(), "index {i}: expected {w}, got {g}");
                assert_relative_eq!(*g, *w, max_relative = 1e-13, epsilon = 0.0);
            }
        }
    }

    //////////////////////
    // Reference values //
    //////////////////////

    // Literals come from limma 3.66 under R 4.5. Fixtures are built in R by the
    // same closed forms as `fixture_y` and `fixture_weights`:
    //
    //   library(limma)
    //   Y <- matrix(((0:39)*7) %% 23 / 64, 8, 5, byrow=TRUE)
    //   Wfull <- matrix((((0:39)*5) %% 7 + 1)/8, 8, 5, byrow=TRUE)
    //   X2 <- cbind(1, c(0,0,1,1,1))
    //   X3 <- cbind(1, c(0,0,1,1,1), c(1,1,0,0,0))
    //   wsamp <- c(1, 2, 0.5, 4, 0.25); b <- c(1,1,2,2,3)
    //   Ym <- Y; Ym[4,3] <- NA; Ym[6,] <- NA
    //   f <- lmFit(...)
    //   cat(sprintf("%.17g", as.vector(t(f$coefficients))), sep=", ")
    //   cat(sprintf("%.17g", as.vector(t(f$stdev.unscaled))), sep=", ")
    //   cat(sprintf("%.17g", f$sigma), sep=", ")
    //   cat(sprintf("%.17g", f$df.residual), sep=", ")
    //   cat(sprintf("%.17g", as.vector(t(f$coefficients %*% t(X)))), sep=", ")
    //
    // Where limma reports `sigma = NA` (zero df.residual), the literal is `0.0`:
    // this crate's one deliberate departure.

    /// `lmFit(Y, X2)`.
    const A_COEF: [f64; 16] = [
        0.054687499999999972,
        0.15364583333333334,
        0.24218749999999997,
        -0.085937499999999986,
        0.070312499999999972,
        0.15364583333333334,
        0.25781250000000011,
        -0.085937500000000042,
        0.085937499999999972,
        0.033854166666666678,
        0.27343749999999994,
        -0.085937499999999972,
        0.10156249999999997,
        0.033854166666666678,
        0.2890625,
        -0.085937499999999972,
    ];
    const A_SDU: [f64; 16] = [
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
    ];
    const A_SIGMA: [f64; 8] = [
        0.11164557869909383,
        0.099845257878545909,
        0.11164557869909383,
        0.099845257878545896,
        0.11164557869909383,
        0.099845257878545896,
        0.11164557869909383,
        0.099845257878545896,
    ];
    const A_FITTED: [f64; 40] = [
        0.054687499999999972,
        0.054687499999999972,
        0.20833333333333331,
        0.20833333333333331,
        0.20833333333333331,
        0.24218749999999997,
        0.24218749999999997,
        0.15625,
        0.15625,
        0.15625,
        0.070312499999999972,
        0.070312499999999972,
        0.22395833333333331,
        0.22395833333333331,
        0.22395833333333331,
        0.25781250000000011,
        0.25781250000000011,
        0.17187500000000006,
        0.17187500000000006,
        0.17187500000000006,
        0.085937499999999972,
        0.085937499999999972,
        0.11979166666666666,
        0.11979166666666666,
        0.11979166666666666,
        0.27343749999999994,
        0.27343749999999994,
        0.18749999999999997,
        0.18749999999999997,
        0.18749999999999997,
        0.10156249999999997,
        0.10156249999999997,
        0.13541666666666666,
        0.13541666666666666,
        0.13541666666666666,
        0.2890625,
        0.2890625,
        0.20312500000000003,
        0.20312500000000003,
        0.20312500000000003,
    ];

    /// `lmFit(Y, X2, weights = c(1, 2, 0.5, 4, 0.25))`.
    const B_COEF: [f64; 16] = [
        0.072916666666666671,
        0.23053728070175439,
        0.26041666666666663,
        -0.10992324561403506,
        0.088541666666666741,
        0.23053728070175433,
        0.27604166666666669,
        -0.10992324561403508,
        0.10416666666666669,
        -0.07209429824561403,
        0.29166666666666669,
        -0.10992324561403508,
        0.11979166666666664,
        -0.072094298245614016,
        0.30729166666666669,
        -0.10992324561403506,
    ];
    const B_SDU: [f64; 2] = [0.57735026918962584, 0.73746840550820003];
    const B_SIGMA: [f64; 8] = [
        0.094323144471374784,
        0.074810921506209174,
        0.094323144471374742,
        0.074810921506209146,
        0.11154962751509892,
        0.074810921506209146,
        0.11154962751509892,
        0.07481092150620916,
    ];

    /// `lmFit(Y, X2, weights = Wfull)`.
    const C_COEF: [f64; 16] = [
        0.093749999999999972,
        0.066105769230769246,
        0.22851562500000003,
        -0.042436079545454544,
        0.10069444444444443,
        0.15451388888888887,
        0.24687500000000015,
        -0.05156250000000008,
        0.058593750000000035,
        0.084635416666666616,
        0.26432291666666669,
        -0.044010416666666691,
        0.083333333333333343,
        0.070833333333333331,
        0.32812500000000006,
        -0.099759615384615405,
    ];
    const C_SDU: [f64; 16] = [
        1.0690449676496978,
        1.325987088263592,
        1.0,
        1.3142574813455419,
        0.94280904158206336,
        1.3333333333333333,
        0.89442719099991608,
        1.1710800875382399,
        1.4142135623730956,
        1.6329931618554525,
        0.81649658092772603,
        1.2110601416389968,
        1.1547005383792515,
        1.3662601021279464,
        1.0690449676496978,
        1.325987088263592,
    ];
    const C_SIGMA: [f64; 8] = [
        0.07289162230162545,
        0.054945826898183045,
        0.054147465881078799,
        0.066068380670931875,
        0.082088067294221856,
        0.07410330019231505,
        0.091613384135604214,
        0.074599961439633961,
    ];

    /// `lmFit(Ym, X2)`, with `Ym[4, 3]` and all of `Ym[6, ]` set to `NA`.
    const D_COEF: [f64; 16] = [
        0.054687499999999972,
        0.15364583333333334,
        0.24218749999999997,
        -0.085937499999999986,
        0.070312499999999972,
        0.15364583333333334,
        0.2578125,
        -0.031249999999999965,
        0.085937499999999972,
        0.033854166666666678,
        NA,
        NA,
        0.10156249999999997,
        0.033854166666666678,
        0.2890625,
        -0.085937499999999972,
    ];
    const D_SDU: [f64; 16] = [
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654757,
        1.0,
        0.70710678118654746,
        0.9128709291752769,
        NA,
        NA,
        0.70710678118654746,
        0.9128709291752769,
        0.70710678118654746,
        0.9128709291752769,
    ];
    const D_SIGMA: [f64; 8] = [
        0.11164557869909383,
        0.099845257878545909,
        0.11164557869909383,
        0.077339804192278636,
        0.11164557869909383,
        0.0,
        0.11164557869909383,
        0.099845257878545896,
    ];
    const D_DF: [f64; 8] = [3.0, 3.0, 3.0, 2.0, 3.0, 0.0, 3.0, 3.0];
    const D_FITTED: [f64; 40] = [
        0.054687499999999972,
        0.054687499999999972,
        0.20833333333333331,
        0.20833333333333331,
        0.20833333333333331,
        0.24218749999999997,
        0.24218749999999997,
        0.15625,
        0.15625,
        0.15625,
        0.070312499999999972,
        0.070312499999999972,
        0.22395833333333331,
        0.22395833333333331,
        0.22395833333333331,
        0.2578125,
        0.2578125,
        0.22656250000000003,
        0.22656250000000003,
        0.22656250000000003,
        0.085937499999999972,
        0.085937499999999972,
        0.11979166666666666,
        0.11979166666666666,
        0.11979166666666666,
        NA,
        NA,
        NA,
        NA,
        NA,
        0.10156249999999997,
        0.10156249999999997,
        0.13541666666666666,
        0.13541666666666666,
        0.13541666666666666,
        0.2890625,
        0.2890625,
        0.20312500000000003,
        0.20312500000000003,
        0.20312500000000003,
    ];

    /// `lmFit(Ym, X2, weights = Wfull)`.
    const E_COEF: [f64; 16] = [
        0.093749999999999972,
        0.066105769230769246,
        0.22851562500000003,
        -0.042436079545454544,
        0.10069444444444443,
        0.15451388888888887,
        0.24687499999999996,
        -0.029427083333333336,
        0.058593750000000035,
        0.084635416666666616,
        NA,
        NA,
        0.083333333333333343,
        0.070833333333333331,
        0.32812500000000006,
        -0.099759615384615405,
    ];
    const E_SDU: [f64; 16] = [
        1.0690449676496978,
        1.325987088263592,
        1.0,
        1.3142574813455419,
        0.94280904158206336,
        1.3333333333333333,
        0.89442719099991586,
        1.2110601416389966,
        1.4142135623730956,
        1.6329931618554525,
        NA,
        NA,
        1.1547005383792515,
        1.3662601021279464,
        1.0690449676496978,
        1.325987088263592,
    ];
    const E_SIGMA: [f64; 8] = [
        0.07289162230162545,
        0.054945826898183045,
        0.054147465881078799,
        0.063048940228462927,
        0.082088067294221856,
        0.0,
        0.091613384135604214,
        0.074599961439633961,
    ];

    /// `lmFit(Y, X2, block = b, correlation = 0.25)`.
    const F_COEF: [f64; 16] = [
        0.0546875,
        0.14362980769230768,
        0.24218749999999997,
        -0.077524038461538436,
        0.070312500000000042,
        0.14362980769230765,
        0.25781249999999989,
        -0.077524038461538367,
        0.085937499999999958,
        0.033052884615384658,
        0.27343749999999994,
        -0.077524038461538394,
        0.10156249999999996,
        0.033052884615384651,
        0.28906249999999983,
        -0.077524038461538325,
    ];
    const F_SDU: [f64; 2] = [0.79056941504209466, 1.0047961905856253];
    const F_SIGMA: [f64; 8] = [
        0.1146379531823081,
        0.10410655316738308,
        0.11463795318230807,
        0.10410655316738308,
        0.12883085482904671,
        0.10410655316738308,
        0.12883085482904669,
        0.10410655316738311,
    ];

    /// `lmFit(Y, X2, block = b, correlation = 0.25, weights = Wfull)`.
    const G_COEF: [f64; 16] = [
        0.1020338931741292,
        0.046620906898569577,
        0.22414926304156485,
        -0.029290377485346103,
        0.10866723833352257,
        0.1386183553847985,
        0.24332672403599037,
        -0.037918062449936007,
        0.051037727636791902,
        0.097377781866368834,
        0.2613411183871478,
        -0.035655125769476104,
        0.077711629165160057,
        0.080295409798648854,
        0.3364088931741292,
        -0.10120602688561266,
    ];
    const G_SDU: [f64; 16] = [
        1.139580592613717,
        1.4040630530325249,
        1.112163511876666,
        1.4227748106584122,
        1.0256781561509392,
        1.4571513092032287,
        0.99664956319551301,
        1.2759337202972107,
        1.5469735769439759,
        1.7857323811461194,
        0.91075033227467828,
        1.2983569545962401,
        1.2788621058650516,
        1.5060416834761272,
        1.139580592613717,
        1.4040630530325249,
    ];
    const G_SIGMA: [f64; 8] = [
        0.070104095566521502,
        0.055924276262054526,
        0.057844680310825951,
        0.067449568692666786,
        0.094410200626087654,
        0.077120443875363126,
        0.10549134470829188,
        0.07499280377972585,
    ];
    const G_FITTED_GENE0: [f64; 5] = [
        0.1020338931741292,
        0.1020338931741292,
        0.14865480007269877,
        0.14865480007269877,
        0.14865480007269877,
    ];

    /// `lmFit(Ym, X2, block = b, correlation = 0.25, weights = Wfull)`.
    const H_COEF: [f64; 16] = [
        0.1020338931741292,
        0.046620906898569577,
        0.22414926304156485,
        -0.029290377485346103,
        0.10866723833352257,
        0.1386183553847985,
        0.24332672403599037,
        -0.025878807369323673,
        0.051037727636791902,
        0.097377781866368834,
        NA,
        NA,
        0.077711629165160057,
        0.080295409798648854,
        0.3364088931741292,
        -0.10120602688561266,
    ];
    const H_SDU: [f64; 16] = [
        1.139580592613717,
        1.4040630530325249,
        1.112163511876666,
        1.4227748106584122,
        1.0256781561509392,
        1.4571513092032287,
        0.99664956319551323,
        1.288400954083966,
        1.5469735769439759,
        1.7857323811461194,
        NA,
        NA,
        1.2788621058650516,
        1.5060416834761272,
        1.139580592613717,
        1.4040630530325249,
    ];
    const H_SIGMA: [f64; 8] = [
        0.070104095566521502,
        0.055924276262054526,
        0.057844680310825951,
        0.067507835762062693,
        0.094410200626087654,
        0.0,
        0.10549134470829188,
        0.07499280377972585,
    ];

    /// `lmFit(Y, X2, weights = wsamp, block = b, correlation = 0.25)`.
    const K_COEF: [f64; 16] = [
        0.07853837083483986,
        0.23106008862949068,
        0.26603837083483994,
        -0.107400358117879,
        0.094163370834839874,
        0.23106008862949068,
        0.28166337083484,
        -0.10740035811787897,
        0.10978837083483996,
        -0.094332132363834628,
        0.29728837083484005,
        -0.107400358117879,
        0.12541337083483997,
        -0.094332132363834642,
        0.31291337083483994,
        -0.10740035811787904,
    ];
    const K_SDU: [f64; 2] = [0.63943105293252589, 0.80103691702704827];
    const K_SIGMA: [f64; 8] = [
        0.10159645906688854,
        0.081201785694141715,
        0.10159645906688854,
        0.081201785694141715,
        0.12346737328937207,
        0.081201785694141715,
        0.12346737328937207,
        0.081201785694141729,
    ];

    //////////
    // Fits //
    //////////

    #[test]
    fn test_unweighted_matches_limma() {
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            None,
            None,
            None,
        )
        .unwrap();
        assert_close(&fit.coefficients, &A_COEF);
        assert_close(&fit.stdev_unscaled, &A_SDU);
        assert_close(&fit.sigma, &A_SIGMA);
        assert_close(&fit.df_residual, &[3.0; 8]);
        assert_close(&fit.fitted, &A_FITTED);
    }

    /// `Rscript -e 'X <- matrix(c(1,0,1,0,1,1,1,1,1,1),5,2,byrow=TRUE);
    /// Q <- qr(X); chol2inv(Q$qr, size=Q$rank)'`
    const A_COV: [f64; 4] = [0.49999999999999994, -0.5, -0.5, 0.83333333333333337];

    /// Same design under `lm.wfit(X, y, c(1,2,3,4,5)/8)`.
    const A_COV_WEIGHTED: [f64; 4] = [
        2.6666666666666656,
        -2.6666666666666661,
        -2.6666666666666661,
        3.333333333333333,
    ];

    #[test]
    fn test_cov_coefficients_match_the_shared_design_qr() {
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(fit.rank, 2);
        assert_eq!(fit.pivot, vec![0, 1]);
        assert_close(&fit.cov_coefficients, &A_COV);
        // Unscaled sds are the square roots of its diagonal when no gene lost an
        // observation.
        for gene in 0..N_GENES {
            assert_relative_eq!(
                fit.stdev_unscaled[gene * 2],
                A_COV[0].sqrt(),
                epsilon = 1e-12
            );
        }
    }

    #[test]
    fn test_cov_coefficients_fold_in_a_shared_weight_row() {
        let w = Recycled::by_sample(vec![0.125, 0.25, 0.375, 0.5, 0.625]);
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            None,
            None,
        )
        .unwrap();
        assert_eq!(fit.rank, 2);
        assert_close(&fit.cov_coefficients, &A_COV_WEIGHTED);
    }

    #[test]
    fn test_cov_coefficients_ignore_per_gene_weights() {
        // limma takes `cov.coefficients` from the bare design once probe weights
        // are in play, so this must match the unweighted answer.
        let w = Recycled::full(fixture_weights(), N_GENES, N_SAMPLES).unwrap();
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            None,
            None,
        )
        .unwrap();
        assert_close(&fit.cov_coefficients, &A_COV);
    }

    #[test]
    fn test_aliased_design_reports_rank_and_pivot() {
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_aliased(),
            3,
            None,
            None,
            None,
        )
        .unwrap();
        // R rejects the third column: `qr(X)$rank` is 2 and `$pivot` is 1 2 3.
        assert_eq!(fit.rank, 2);
        assert_eq!(fit.pivot, vec![0, 1, 2]);
        assert_eq!(fit.cov_coefficients.len(), 4);
        assert_close(&fit.cov_coefficients, &A_COV);
    }

    #[test]
    fn test_sample_weights_match_limma() {
        let w = Recycled::by_sample(vec![1.0, 2.0, 0.5, 4.0, 0.25]);
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            None,
            None,
        )
        .unwrap();
        assert_close(&fit.coefficients, &B_COEF);
        assert_close(&fit.sigma, &B_SIGMA);
        // Per-sample weights are shared by every gene, so is the design metric.
        for row in fit.stdev_unscaled.chunks_exact(2) {
            assert_close(row, &B_SDU);
        }
    }

    #[test]
    fn test_full_weights_match_limma() {
        let w = Recycled::full(fixture_weights(), N_GENES, N_SAMPLES).unwrap();
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            None,
            None,
        )
        .unwrap();
        assert_close(&fit.coefficients, &C_COEF);
        assert_close(&fit.stdev_unscaled, &C_SDU);
        assert_close(&fit.sigma, &C_SIGMA);
        assert_close(&fit.df_residual, &[3.0; 8]);
    }

    #[test]
    fn test_missing_value_refits_row() {
        let mut y = fixture_y();
        y[3 * N_SAMPLES + 2] = f64::NAN;
        for s in 0..N_SAMPLES {
            y[5 * N_SAMPLES + s] = f64::NAN;
        }
        let fit = lm_fit(&y, N_GENES, N_SAMPLES, &design_two(), 2, None, None, None).unwrap();
        assert_close(&fit.coefficients, &D_COEF);
        assert_close(&fit.stdev_unscaled, &D_SDU);
        assert_close(&fit.sigma, &D_SIGMA);
        assert_close(&fit.df_residual, &D_DF);
        assert_close(&fit.fitted, &D_FITTED);
    }

    #[test]
    fn test_missing_value_with_full_weights() {
        let mut y = fixture_y();
        y[3 * N_SAMPLES + 2] = f64::NEG_INFINITY;
        for s in 0..N_SAMPLES {
            y[5 * N_SAMPLES + s] = f64::NAN;
        }
        let w = Recycled::full(fixture_weights(), N_GENES, N_SAMPLES).unwrap();
        let fit = lm_fit(
            &y,
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            None,
            None,
        )
        .unwrap();
        assert_close(&fit.coefficients, &E_COEF);
        assert_close(&fit.stdev_unscaled, &E_SDU);
        assert_close(&fit.sigma, &E_SIGMA);
        assert_close(&fit.df_residual, &D_DF);
    }

    #[test]
    fn test_zero_weight_drops_the_observation() {
        // limma sets the response to NA where the weight vanishes, so this must
        // reproduce the missing-value fit.
        let mut weights = fixture_weights();
        weights[3 * N_SAMPLES + 2] = 0.0;
        for s in 0..N_SAMPLES {
            weights[5 * N_SAMPLES + s] = 0.0;
        }
        let w = Recycled::full(weights, N_GENES, N_SAMPLES).unwrap();
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            None,
            None,
        )
        .unwrap();
        assert_close(&fit.coefficients, &E_COEF);
        assert_close(&fit.stdev_unscaled, &E_SDU);
        assert_close(&fit.sigma, &E_SIGMA);
        assert_close(&fit.df_residual, &D_DF);
    }

    #[test]
    fn test_block_correlation_matches_limma() {
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            None,
            Some(&blocks()),
            Some(0.25),
        )
        .unwrap();
        assert_close(&fit.coefficients, &F_COEF);
        assert_close(&fit.sigma, &F_SIGMA);
        assert_close(&fit.df_residual, &[3.0; 8]);
        for row in fit.stdev_unscaled.chunks_exact(2) {
            assert_close(row, &F_SDU);
        }
    }

    #[test]
    fn test_block_correlation_with_full_weights() {
        let w = Recycled::full(fixture_weights(), N_GENES, N_SAMPLES).unwrap();
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            Some(&blocks()),
            Some(0.25),
        )
        .unwrap();
        assert_close(&fit.coefficients, &G_COEF);
        assert_close(&fit.stdev_unscaled, &G_SDU);
        assert_close(&fit.sigma, &G_SIGMA);
        assert_close(&fit.fitted[..N_SAMPLES], &G_FITTED_GENE0);
    }

    #[test]
    fn test_block_correlation_with_sample_weights() {
        let w = Recycled::by_sample(vec![1.0, 2.0, 0.5, 4.0, 0.25]);
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            Some(&blocks()),
            Some(0.25),
        )
        .unwrap();
        assert_close(&fit.coefficients, &K_COEF);
        assert_close(&fit.sigma, &K_SIGMA);
        for row in fit.stdev_unscaled.chunks_exact(2) {
            assert_close(row, &K_SDU);
        }
    }

    #[test]
    fn test_block_correlation_with_missing_refits_submatrix() {
        let mut y = fixture_y();
        y[3 * N_SAMPLES + 2] = f64::NAN;
        for s in 0..N_SAMPLES {
            y[5 * N_SAMPLES + s] = f64::NAN;
        }
        let w = Recycled::full(fixture_weights(), N_GENES, N_SAMPLES).unwrap();
        let fit = lm_fit(
            &y,
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            Some(&w),
            Some(&blocks()),
            Some(0.25),
        )
        .unwrap();
        assert_close(&fit.coefficients, &H_COEF);
        assert_close(&fit.stdev_unscaled, &H_SDU);
        assert_close(&fit.sigma, &H_SIGMA);
        assert_close(&fit.df_residual, &D_DF);
    }

    #[test]
    fn test_zero_correlation_reduces_to_least_squares() {
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            None,
            Some(&blocks()),
            Some(0.0),
        )
        .unwrap();
        assert_close(&fit.coefficients, &A_COEF);
        assert_close(&fit.sigma, &A_SIGMA);
    }

    #[test]
    fn test_correlation_without_block_is_ignored() {
        // `lmFit(Y, X2, correlation = 0.25)` dispatches to `lm.series`, which
        // never sees the correlation.
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_two(),
            2,
            None,
            None,
            Some(0.25),
        )
        .unwrap();
        assert_close(&fit.coefficients, &A_COEF);
        assert_close(&fit.sigma, &A_SIGMA);
    }

    #[test]
    fn test_rank_deficient_design_aliases_the_last_column() {
        // R's `lm.fit` accepts columns left to right, so the third is dropped
        // (`lmFit` prints "Coefficients not estimable: 3").
        let fit = lm_fit(
            &fixture_y(),
            N_GENES,
            N_SAMPLES,
            &design_aliased(),
            3,
            None,
            None,
            None,
        )
        .unwrap();
        for gene in 0..N_GENES {
            let coef = &fit.coefficients[gene * 3..(gene + 1) * 3];
            let sdu = &fit.stdev_unscaled[gene * 3..(gene + 1) * 3];
            assert_close(&coef[..2], &A_COEF[gene * 2..(gene + 1) * 2]);
            assert_close(&sdu[..2], &A_SDU[gene * 2..(gene + 1) * 2]);
            assert!(coef[2].is_nan());
            assert!(sdu[2].is_nan());
        }
        assert_close(&fit.sigma, &A_SIGMA);
        assert_close(&fit.df_residual, &[3.0; 8]);
        // limma's `fitted()` would propagate the NA coefficient across the row;
        // here the aliased column contributes nothing.
        assert_close(&fit.fitted, &A_FITTED);
    }

    #[test]
    fn test_single_gene() {
        let y: Vec<f64> = fixture_y()[..N_SAMPLES].to_vec();
        let fit = lm_fit(&y, 1, N_SAMPLES, &design_two(), 2, None, None, None).unwrap();
        assert_close(&fit.coefficients, &A_COEF[..2]);
        assert_close(&fit.stdev_unscaled, &A_SDU[..2]);
        assert_close(&fit.sigma, &A_SIGMA[..1]);
        assert_close(&fit.df_residual, &[3.0]);
        assert_close(&fit.fitted, &A_FITTED[..N_SAMPLES]);
    }

    #[test]
    fn test_saturated_design_gives_zero_sigma() {
        // Five coefficients on five samples: limma would report NA, this crate
        // reports zero.
        let mut design = vec![0.0; N_SAMPLES * N_SAMPLES];
        for s in 0..N_SAMPLES {
            design[s * N_SAMPLES + s] = 1.0;
        }
        let y = fixture_y();
        let fit = lm_fit(&y, N_GENES, N_SAMPLES, &design, N_SAMPLES, None, None, None).unwrap();
        assert_close(&fit.df_residual, &[0.0; 8]);
        assert_close(&fit.sigma, &[0.0; 8]);
        assert_close(&fit.coefficients, &y);
        assert_close(&fit.fitted, &y);
    }

    ////////////////////
    // Error branches //
    ////////////////////

    #[test]
    fn test_rejects_empty_input() {
        assert!(matches!(
            lm_fit(&[], 0, N_SAMPLES, &design_two(), 2, None, None, None),
            Err(EdgeErrors::EmptyCounts { n_genes: 0, .. })
        ));
        assert!(matches!(
            lm_fit(&[], N_GENES, 0, &design_two(), 2, None, None, None),
            Err(EdgeErrors::EmptyCounts { n_samples: 0, .. })
        ));
    }

    #[test]
    fn test_rejects_zero_coefficients() {
        assert!(matches!(
            lm_fit(&fixture_y(), N_GENES, N_SAMPLES, &[], 0, None, None, None),
            Err(EdgeErrors::MustBePositive(_))
        ));
    }

    #[test]
    fn test_rejects_wrong_response_length() {
        assert!(matches!(
            lm_fit(
                &[0.0; 7],
                N_GENES,
                N_SAMPLES,
                &design_two(),
                2,
                None,
                None,
                None
            ),
            Err(EdgeErrors::LengthMismatch {
                name: "y",
                expected: 40,
                got: 7
            })
        ));
    }

    #[test]
    fn test_rejects_wrong_design_length() {
        assert!(matches!(
            lm_fit(
                &fixture_y(),
                N_GENES,
                N_SAMPLES,
                &[1.0; 8],
                2,
                None,
                None,
                None
            ),
            Err(EdgeErrors::LengthMismatch {
                name: "design",
                expected: 10,
                got: 8
            })
        ));
    }

    #[test]
    fn test_rejects_mismatched_weights() {
        let w = Recycled::by_sample(vec![1.0, 2.0]);
        assert!(matches!(
            lm_fit(
                &fixture_y(),
                N_GENES,
                N_SAMPLES,
                &design_two(),
                2,
                Some(&w),
                None,
                None
            ),
            Err(EdgeErrors::LengthMismatch {
                name: "by_sample",
                ..
            })
        ));
    }

    #[test]
    fn test_rejects_wrong_block_length() {
        assert!(matches!(
            lm_fit(
                &fixture_y(),
                N_GENES,
                N_SAMPLES,
                &design_two(),
                2,
                None,
                Some(&[1, 1, 2]),
                Some(0.25)
            ),
            Err(EdgeErrors::LengthMismatch {
                name: "block",
                expected: 5,
                got: 3
            })
        ));
    }

    #[test]
    fn test_rejects_block_without_correlation() {
        assert!(matches!(
            lm_fit(
                &fixture_y(),
                N_GENES,
                N_SAMPLES,
                &design_two(),
                2,
                None,
                Some(&blocks()),
                None
            ),
            Err(EdgeErrors::InvalidArgument(_))
        ));
    }

    #[test]
    fn test_rejects_out_of_range_correlation() {
        for rho in [1.0, -1.0, 2.5, f64::NAN] {
            assert!(matches!(
                lm_fit(
                    &fixture_y(),
                    N_GENES,
                    N_SAMPLES,
                    &design_two(),
                    2,
                    None,
                    Some(&blocks()),
                    Some(rho)
                ),
                Err(EdgeErrors::InvalidArgument(_))
            ));
        }
    }

    #[test]
    fn test_rejects_indefinite_block_covariance() {
        // One block of five needs a correlation above -1/4; limma's `chol` fails
        // at -0.5 too.
        assert!(matches!(
            lm_fit(
                &fixture_y(),
                N_GENES,
                N_SAMPLES,
                &design_two(),
                2,
                None,
                Some(&[1, 1, 1, 1, 1]),
                Some(-0.5)
            ),
            Err(EdgeErrors::CholeskyFailed(_))
        ));
    }
}