1use crate::error::FdarError;
14use crate::iter_maybe_parallel;
15use crate::linalg::{
16 cholesky_factor as linalg_cholesky_factor,
17 cholesky_forward_back as linalg_cholesky_forward_back,
18};
19use crate::matrix::FdMatrix;
20use crate::regression::fdata_to_pc_1d;
21#[cfg(feature = "parallel")]
22use rayon::iter::ParallelIterator;
23
24#[derive(Debug, Clone, PartialEq)]
26#[non_exhaustive]
27pub struct FmmResult {
28 pub mean_function: Vec<f64>,
30 pub beta_functions: FdMatrix,
32 pub random_effects: FdMatrix,
34 pub fitted: FdMatrix,
36 pub residuals: FdMatrix,
38 pub random_variance: Vec<f64>,
40 pub sigma2_eps: f64,
42 pub sigma2_u: Vec<f64>,
44 pub ncomp: usize,
46 pub n_subjects: usize,
48 pub eigenvalues: Vec<f64>,
50}
51
52#[derive(Debug, Clone, PartialEq)]
54#[non_exhaustive]
55pub struct FmmTestResult {
56 pub f_statistics: Vec<f64>,
58 pub p_values: Vec<f64>,
60}
61
62#[must_use = "expensive computation whose result should not be discarded"]
88pub fn fmm(
89 data: &FdMatrix,
90 subject_ids: &[usize],
91 covariates: Option<&FdMatrix>,
92 ncomp: usize,
93) -> Result<FmmResult, FdarError> {
94 let n_total = data.nrows();
95 let m = data.ncols();
96 if n_total == 0 || m == 0 {
97 return Err(FdarError::InvalidDimension {
98 parameter: "data",
99 expected: "non-empty matrix".to_string(),
100 actual: format!("{n_total} x {m}"),
101 });
102 }
103 if subject_ids.len() != n_total {
104 return Err(FdarError::InvalidDimension {
105 parameter: "subject_ids",
106 expected: format!("length {n_total}"),
107 actual: format!("length {}", subject_ids.len()),
108 });
109 }
110 if ncomp == 0 {
111 return Err(FdarError::InvalidParameter {
112 parameter: "ncomp",
113 message: "must be >= 1".to_string(),
114 });
115 }
116
117 let (subject_map, n_subjects) = build_subject_map(subject_ids);
119
120 let argvals: Vec<f64> = (0..m).map(|j| j as f64 / (m - 1).max(1) as f64).collect();
122 let fpca = fdata_to_pc_1d(data, ncomp, &argvals)?;
123 let k = fpca.scores.ncols(); let p = covariates.map_or(0, super::matrix::FdMatrix::ncols);
127 let ComponentResults {
128 gamma,
129 u_hat,
130 sigma2_u,
131 sigma2_eps,
132 } = fit_all_components(
133 &fpca.scores,
134 &subject_map,
135 n_subjects,
136 covariates,
137 p,
138 k,
139 n_total,
140 m,
141 );
142
143 let beta_functions = recover_beta_functions(&gamma, &fpca.rotation, p, m, k);
145 let random_effects = recover_random_effects(&u_hat, &fpca.rotation, n_subjects, m, k);
146
147 let random_variance = compute_random_variance(&random_effects, n_subjects, m);
149
150 let (fitted, residuals) = compute_fitted_residuals(
152 data,
153 &fpca.mean,
154 &beta_functions,
155 &random_effects,
156 covariates,
157 &subject_map,
158 n_total,
159 m,
160 p,
161 );
162
163 let eigenvalues: Vec<f64> = fpca
164 .singular_values
165 .iter()
166 .map(|&sv| sv * sv / n_total as f64)
167 .collect();
168
169 Ok(FmmResult {
170 mean_function: fpca.mean,
171 beta_functions,
172 random_effects,
173 fitted,
174 residuals,
175 random_variance,
176 sigma2_eps,
177 sigma2_u,
178 ncomp: k,
179 n_subjects,
180 eigenvalues,
181 })
182}
183
184pub(crate) fn build_subject_map(subject_ids: &[usize]) -> (Vec<usize>, usize) {
186 let mut unique_ids: Vec<usize> = subject_ids.to_vec();
187 unique_ids.sort_unstable();
188 unique_ids.dedup();
189 let n_subjects = unique_ids.len();
190
191 let map: Vec<usize> = subject_ids
192 .iter()
193 .map(|id| unique_ids.iter().position(|u| u == id).unwrap_or(0))
194 .collect();
195
196 (map, n_subjects)
197}
198
199struct ComponentResults {
201 gamma: Vec<Vec<f64>>, u_hat: Vec<Vec<f64>>, sigma2_u: Vec<f64>, sigma2_eps: f64, }
206
207#[allow(clippy::too_many_arguments)]
212fn fit_all_components(
213 scores: &FdMatrix,
214 subject_map: &[usize],
215 n_subjects: usize,
216 covariates: Option<&FdMatrix>,
217 p: usize,
218 k: usize,
219 n_total: usize,
220 m: usize,
221) -> ComponentResults {
222 let h = if m > 1 { 1.0 / (m - 1) as f64 } else { 1.0 };
225 let score_scale = h.sqrt();
226
227 let per_comp: Vec<ScalarMixedResult> = iter_maybe_parallel!(0..k)
229 .map(|comp| {
230 let comp_scores: Vec<f64> = (0..n_total)
231 .map(|i| scores[(i, comp)] * score_scale)
232 .collect();
233 fit_scalar_mixed_model(&comp_scores, subject_map, n_subjects, covariates, p)
234 })
235 .collect();
236
237 let mut gamma = vec![vec![0.0; k]; p];
239 let mut u_hat = vec![vec![0.0; k]; n_subjects];
240 let mut sigma2_u = vec![0.0; k];
241 let mut sigma2_eps_total = 0.0;
242
243 for (comp, result) in per_comp.iter().enumerate() {
244 for j in 0..p {
245 gamma[j][comp] = result.gamma[j] / score_scale;
246 }
247 for s in 0..n_subjects {
248 u_hat[s][comp] = result.u_hat[s] / score_scale;
249 }
250 sigma2_u[comp] = result.sigma2_u;
251 sigma2_eps_total += result.sigma2_eps;
252 }
253 let sigma2_eps = sigma2_eps_total / k as f64;
254
255 ComponentResults {
256 gamma,
257 u_hat,
258 sigma2_u,
259 sigma2_eps,
260 }
261}
262
263pub(crate) struct ScalarMixedResult {
265 pub(crate) gamma: Vec<f64>, pub(crate) u_hat: Vec<f64>, pub(crate) sigma2_u: f64, pub(crate) sigma2_eps: f64, }
270
271pub(crate) struct SubjectStructure {
273 pub(crate) counts: Vec<usize>,
274 pub(crate) obs: Vec<Vec<usize>>,
275}
276
277impl SubjectStructure {
278 pub(crate) fn new(subject_map: &[usize], n_subjects: usize, n: usize) -> Self {
279 let mut counts = vec![0usize; n_subjects];
280 let mut obs: Vec<Vec<usize>> = vec![Vec::new(); n_subjects];
281 for i in 0..n {
282 let s = subject_map[i];
283 counts[s] += 1;
284 obs[s].push(i);
285 }
286 Self { counts, obs }
287 }
288}
289
290fn shrinkage_weights(ss: &SubjectStructure, sigma2_u: f64, sigma2_e: f64) -> Vec<f64> {
292 ss.counts
293 .iter()
294 .map(|&c| {
295 let ns = c as f64;
296 if ns < 1.0 {
297 0.0
298 } else {
299 sigma2_u / (sigma2_u + sigma2_e / ns)
300 }
301 })
302 .collect()
303}
304
305fn gls_update_gamma(
309 cov: &FdMatrix,
310 p: usize,
311 ss: &SubjectStructure,
312 weights: &[f64],
313 y: &[f64],
314 sigma2_e: f64,
315) -> Option<Vec<f64>> {
316 let n_subjects = ss.counts.len();
317 let mut xtvinvx = vec![0.0; p * p];
318 let mut xtvinvy = vec![0.0; p];
319 let inv_e = 1.0 / sigma2_e;
320
321 for s in 0..n_subjects {
322 let ns = ss.counts[s] as f64;
323 if ns < 1.0 {
324 continue;
325 }
326 let (x_sum, y_sum) = subject_sums(cov, y, &ss.obs[s], p);
327 accumulate_gls_terms(
328 cov,
329 y,
330 &ss.obs[s],
331 &x_sum,
332 y_sum,
333 weights[s],
334 ns,
335 inv_e,
336 p,
337 &mut xtvinvx,
338 &mut xtvinvy,
339 );
340 }
341
342 for j in 0..p {
343 xtvinvx[j * p + j] += 1e-10;
344 }
345 cholesky_solve(&xtvinvx, &xtvinvy, p)
346}
347
348fn subject_sums(cov: &FdMatrix, y: &[f64], obs: &[usize], p: usize) -> (Vec<f64>, f64) {
350 let mut x_sum = vec![0.0; p];
351 let mut y_sum = 0.0;
352 for &i in obs {
353 for r in 0..p {
354 x_sum[r] += cov[(i, r)];
355 }
356 y_sum += y[i];
357 }
358 (x_sum, y_sum)
359}
360
361fn accumulate_gls_terms(
363 cov: &FdMatrix,
364 y: &[f64],
365 obs: &[usize],
366 x_sum: &[f64],
367 y_sum: f64,
368 w_s: f64,
369 ns: f64,
370 inv_e: f64,
371 p: usize,
372 xtvinvx: &mut [f64],
373 xtvinvy: &mut [f64],
374) {
375 for &i in obs {
376 let vinv_y = inv_e * (y[i] - w_s * y_sum / ns);
377 for r in 0..p {
378 xtvinvy[r] += cov[(i, r)] * vinv_y;
379 for c in r..p {
380 let vinv_xc = inv_e * (cov[(i, c)] - w_s * x_sum[c] / ns);
381 let val = cov[(i, r)] * vinv_xc;
382 xtvinvx[r * p + c] += val;
383 if r != c {
384 xtvinvx[c * p + r] += val;
385 }
386 }
387 }
388 }
389}
390
391fn reml_variance_update(
396 residuals: &[f64],
397 ss: &SubjectStructure,
398 weights: &[f64],
399 sigma2_u: f64,
400 p: usize,
401) -> (f64, f64) {
402 let n_subjects = ss.counts.len();
403 let n: usize = ss.counts.iter().sum();
404 let mut sigma2_u_new = 0.0;
405 let mut sigma2_e_new = 0.0;
406
407 for s in 0..n_subjects {
408 let ns = ss.counts[s] as f64;
409 if ns < 1.0 {
410 continue;
411 }
412 let w_s = weights[s];
413 let mean_r_s: f64 = ss.obs[s].iter().map(|&i| residuals[i]).sum::<f64>() / ns;
414 let u_hat_s = w_s * mean_r_s;
415 let cond_var_s = sigma2_u * (1.0 - w_s);
416
417 sigma2_u_new += u_hat_s * u_hat_s + cond_var_s;
418 for &i in &ss.obs[s] {
419 sigma2_e_new += (residuals[i] - u_hat_s).powi(2);
420 }
421 sigma2_e_new += ns * cond_var_s;
422 }
423
424 let denom_e = (n.saturating_sub(p)).max(1) as f64;
426
427 (
428 (sigma2_u_new / n_subjects as f64).max(1e-15),
429 (sigma2_e_new / denom_e).max(1e-15),
430 )
431}
432
433pub(crate) fn fit_scalar_mixed_model(
439 y: &[f64],
440 subject_map: &[usize],
441 n_subjects: usize,
442 covariates: Option<&FdMatrix>,
443 p: usize,
444) -> ScalarMixedResult {
445 let n = y.len();
446 let ss = SubjectStructure::new(subject_map, n_subjects, n);
447
448 let gamma_init = estimate_fixed_effects(y, covariates, p, n);
450 let residuals_init = compute_ols_residuals(y, covariates, &gamma_init, p, n);
451 let (mut sigma2_u, mut sigma2_e) =
452 estimate_variance_components(&residuals_init, subject_map, n_subjects, n);
453
454 if sigma2_e < 1e-15 {
455 sigma2_e = 1e-6;
456 }
457 if sigma2_u < 1e-15 {
458 sigma2_u = sigma2_e * 0.1;
459 }
460
461 let mut gamma = gamma_init;
462
463 for _iter in 0..50 {
464 let sigma2_u_old = sigma2_u;
465 let sigma2_e_old = sigma2_e;
466
467 let weights = shrinkage_weights(&ss, sigma2_u, sigma2_e);
468
469 if let Some(cov) = covariates.filter(|_| p > 0) {
470 if let Some(g) = gls_update_gamma(cov, p, &ss, &weights, y, sigma2_e) {
471 gamma = g;
472 }
473 }
474
475 let r = compute_ols_residuals(y, covariates, &gamma, p, n);
476 (sigma2_u, sigma2_e) = reml_variance_update(&r, &ss, &weights, sigma2_u, p);
477
478 let delta = (sigma2_u - sigma2_u_old).abs() + (sigma2_e - sigma2_e_old).abs();
479 if delta < 1e-10 * (sigma2_u_old + sigma2_e_old) {
480 break;
481 }
482 }
483
484 let final_residuals = compute_ols_residuals(y, covariates, &gamma, p, n);
485 let u_hat = compute_blup(
486 &final_residuals,
487 subject_map,
488 n_subjects,
489 sigma2_u,
490 sigma2_e,
491 );
492
493 ScalarMixedResult {
494 gamma,
495 u_hat,
496 sigma2_u,
497 sigma2_eps: sigma2_e,
498 }
499}
500
501fn estimate_fixed_effects(
503 y: &[f64],
504 covariates: Option<&FdMatrix>,
505 p: usize,
506 n: usize,
507) -> Vec<f64> {
508 if p == 0 || covariates.is_none() {
509 return Vec::new();
510 }
511 let cov = covariates.expect("checked: covariates is Some");
512
513 let mut xtx = vec![0.0; p * p];
515 let mut xty = vec![0.0; p];
516 for i in 0..n {
517 for r in 0..p {
518 xty[r] += cov[(i, r)] * y[i];
519 for s in r..p {
520 let val = cov[(i, r)] * cov[(i, s)];
521 xtx[r * p + s] += val;
522 if r != s {
523 xtx[s * p + r] += val;
524 }
525 }
526 }
527 }
528 for j in 0..p {
530 xtx[j * p + j] += 1e-8;
531 }
532
533 cholesky_solve(&xtx, &xty, p).unwrap_or(vec![0.0; p])
534}
535
536fn cholesky_solve(a: &[f64], b: &[f64], p: usize) -> Option<Vec<f64>> {
539 let l = linalg_cholesky_factor(a, p).ok()?;
540 Some(linalg_cholesky_forward_back(&l, b, p))
541}
542
543fn compute_ols_residuals(
545 y: &[f64],
546 covariates: Option<&FdMatrix>,
547 gamma: &[f64],
548 p: usize,
549 n: usize,
550) -> Vec<f64> {
551 let mut residuals = y.to_vec();
552 if p > 0 {
553 if let Some(cov) = covariates {
554 for i in 0..n {
555 for j in 0..p {
556 residuals[i] -= cov[(i, j)] * gamma[j];
557 }
558 }
559 }
560 }
561 residuals
562}
563
564fn estimate_variance_components(
568 residuals: &[f64],
569 subject_map: &[usize],
570 n_subjects: usize,
571 n: usize,
572) -> (f64, f64) {
573 let mut subject_sums = vec![0.0; n_subjects];
575 let mut subject_counts = vec![0usize; n_subjects];
576 for i in 0..n {
577 let s = subject_map[i];
578 subject_sums[s] += residuals[i];
579 subject_counts[s] += 1;
580 }
581 let subject_means: Vec<f64> = subject_sums
582 .iter()
583 .zip(&subject_counts)
584 .map(|(&s, &c)| if c > 0 { s / c as f64 } else { 0.0 })
585 .collect();
586
587 let mut ss_within = 0.0;
589 for i in 0..n {
590 let s = subject_map[i];
591 ss_within += (residuals[i] - subject_means[s]).powi(2);
592 }
593 let df_within = n.saturating_sub(n_subjects);
594
595 let grand_mean = residuals.iter().sum::<f64>() / n as f64;
597 let mut ss_between = 0.0;
598 for s in 0..n_subjects {
599 ss_between += subject_counts[s] as f64 * (subject_means[s] - grand_mean).powi(2);
600 }
601
602 let sigma2_eps = if df_within > 0 {
603 ss_within / df_within as f64
604 } else {
605 1e-6
606 };
607
608 let n_bar = n as f64 / n_subjects.max(1) as f64;
610 let df_between = n_subjects.saturating_sub(1).max(1);
611 let ms_between = ss_between / df_between as f64;
612 let sigma2_u = ((ms_between - sigma2_eps) / n_bar).max(0.0);
613
614 (sigma2_u, sigma2_eps)
615}
616
617fn compute_blup(
621 residuals: &[f64],
622 subject_map: &[usize],
623 n_subjects: usize,
624 sigma2_u: f64,
625 sigma2_eps: f64,
626) -> Vec<f64> {
627 let mut subject_sums = vec![0.0; n_subjects];
628 let mut subject_counts = vec![0usize; n_subjects];
629 for (i, &r) in residuals.iter().enumerate() {
630 let s = subject_map[i];
631 subject_sums[s] += r;
632 subject_counts[s] += 1;
633 }
634
635 (0..n_subjects)
636 .map(|s| {
637 let ni = subject_counts[s] as f64;
638 if ni < 1.0 {
639 return 0.0;
640 }
641 let mean_r = subject_sums[s] / ni;
642 let shrinkage = sigma2_u / (sigma2_u + sigma2_eps / ni).max(1e-15);
643 shrinkage * mean_r
644 })
645 .collect()
646}
647
648fn recover_beta_functions(
654 gamma: &[Vec<f64>],
655 rotation: &FdMatrix,
656 p: usize,
657 m: usize,
658 k: usize,
659) -> FdMatrix {
660 let mut beta = FdMatrix::zeros(p, m);
661 for j in 0..p {
662 for t in 0..m {
663 let mut val = 0.0;
664 for comp in 0..k {
665 val += gamma[j][comp] * rotation[(t, comp)];
666 }
667 beta[(j, t)] = val;
668 }
669 }
670 beta
671}
672
673pub(crate) fn recover_random_effects(
675 u_hat: &[Vec<f64>],
676 rotation: &FdMatrix,
677 n_subjects: usize,
678 m: usize,
679 k: usize,
680) -> FdMatrix {
681 let mut re = FdMatrix::zeros(n_subjects, m);
682 for s in 0..n_subjects {
683 for t in 0..m {
684 let mut val = 0.0;
685 for comp in 0..k {
686 val += u_hat[s][comp] * rotation[(t, comp)];
687 }
688 re[(s, t)] = val;
689 }
690 }
691 re
692}
693
694fn compute_random_variance(random_effects: &FdMatrix, n_subjects: usize, m: usize) -> Vec<f64> {
696 (0..m)
697 .map(|t| {
698 let mean: f64 =
699 (0..n_subjects).map(|s| random_effects[(s, t)]).sum::<f64>() / n_subjects as f64;
700 let var: f64 = (0..n_subjects)
701 .map(|s| (random_effects[(s, t)] - mean).powi(2))
702 .sum::<f64>()
703 / n_subjects.max(1) as f64;
704 var
705 })
706 .collect()
707}
708
709fn compute_fitted_residuals(
711 data: &FdMatrix,
712 mean_function: &[f64],
713 beta_functions: &FdMatrix,
714 random_effects: &FdMatrix,
715 covariates: Option<&FdMatrix>,
716 subject_map: &[usize],
717 n_total: usize,
718 m: usize,
719 p: usize,
720) -> (FdMatrix, FdMatrix) {
721 let mut fitted = FdMatrix::zeros(n_total, m);
722 let mut residuals = FdMatrix::zeros(n_total, m);
723
724 for i in 0..n_total {
725 let s = subject_map[i];
726 for t in 0..m {
727 let mut val = mean_function[t] + random_effects[(s, t)];
728 if p > 0 {
729 if let Some(cov) = covariates {
730 for j in 0..p {
731 val += cov[(i, j)] * beta_functions[(j, t)];
732 }
733 }
734 }
735 fitted[(i, t)] = val;
736 residuals[(i, t)] = data[(i, t)] - val;
737 }
738 }
739
740 (fitted, residuals)
741}
742
743#[must_use = "prediction result should not be discarded"]
755pub fn fmm_predict(result: &FmmResult, new_covariates: Option<&FdMatrix>) -> FdMatrix {
756 let m = result.mean_function.len();
757 let n_new = new_covariates.map_or(1, super::matrix::FdMatrix::nrows);
758 let p = result.beta_functions.nrows();
759
760 let mut predicted = FdMatrix::zeros(n_new, m);
761 for i in 0..n_new {
762 for t in 0..m {
763 let mut val = result.mean_function[t];
764 if let Some(cov) = new_covariates {
765 for j in 0..p {
766 val += cov[(i, j)] * result.beta_functions[(j, t)];
767 }
768 }
769 predicted[(i, t)] = val;
770 }
771 }
772 predicted
773}
774
775#[must_use = "expensive computation whose result should not be discarded"]
798pub fn fmm_test_fixed(
799 data: &FdMatrix,
800 subject_ids: &[usize],
801 covariates: &FdMatrix,
802 ncomp: usize,
803 n_perm: usize,
804 seed: u64,
805) -> Result<FmmTestResult, FdarError> {
806 let n_total = data.nrows();
807 let m = data.ncols();
808 let p = covariates.ncols();
809 if n_total == 0 {
810 return Err(FdarError::InvalidDimension {
811 parameter: "data",
812 expected: "non-empty matrix".to_string(),
813 actual: format!("{n_total} rows"),
814 });
815 }
816 if p == 0 {
817 return Err(FdarError::InvalidDimension {
818 parameter: "covariates",
819 expected: "at least 1 column".to_string(),
820 actual: "0 columns".to_string(),
821 });
822 }
823
824 let result = fmm(data, subject_ids, Some(covariates), ncomp)?;
826
827 let observed_stats = compute_integrated_beta_sq(&result.beta_functions, p, m);
829
830 let (f_statistics, p_values) = permutation_test(
832 data,
833 subject_ids,
834 covariates,
835 ncomp,
836 n_perm,
837 seed,
838 &observed_stats,
839 p,
840 m,
841 );
842
843 Ok(FmmTestResult {
844 f_statistics,
845 p_values,
846 })
847}
848
849fn compute_integrated_beta_sq(beta: &FdMatrix, p: usize, m: usize) -> Vec<f64> {
851 let h = if m > 1 { 1.0 / (m - 1) as f64 } else { 1.0 };
852 (0..p)
853 .map(|j| {
854 let ss: f64 = (0..m).map(|t| beta[(j, t)].powi(2)).sum();
855 ss * h
856 })
857 .collect()
858}
859
860fn permutation_test(
862 data: &FdMatrix,
863 subject_ids: &[usize],
864 covariates: &FdMatrix,
865 ncomp: usize,
866 n_perm: usize,
867 seed: u64,
868 observed_stats: &[f64],
869 p: usize,
870 m: usize,
871) -> (Vec<f64>, Vec<f64>) {
872 use rand::prelude::*;
873 let n_total = data.nrows();
874 let mut rng = StdRng::seed_from_u64(seed);
875 let mut n_ge = vec![0usize; p];
876
877 for _ in 0..n_perm {
878 let mut perm_indices: Vec<usize> = (0..n_total).collect();
880 perm_indices.shuffle(&mut rng);
881 let perm_cov = permute_rows(covariates, &perm_indices);
882
883 if let Ok(perm_result) = fmm(data, subject_ids, Some(&perm_cov), ncomp) {
884 let perm_stats = compute_integrated_beta_sq(&perm_result.beta_functions, p, m);
885 for j in 0..p {
886 if perm_stats[j] >= observed_stats[j] {
887 n_ge[j] += 1;
888 }
889 }
890 }
891 }
892
893 let p_values: Vec<f64> = n_ge
894 .iter()
895 .map(|&count| (count + 1) as f64 / (n_perm + 1) as f64)
896 .collect();
897 let f_statistics = observed_stats.to_vec();
898
899 (f_statistics, p_values)
900}
901
902fn permute_rows(mat: &FdMatrix, indices: &[usize]) -> FdMatrix {
904 let n = indices.len();
905 let m = mat.ncols();
906 let mut result = FdMatrix::zeros(n, m);
907 for (new_i, &old_i) in indices.iter().enumerate() {
908 for j in 0..m {
909 result[(new_i, j)] = mat[(old_i, j)];
910 }
911 }
912 result
913}
914
915#[derive(Debug, Clone, PartialEq)]
923#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
924pub struct DenseFlmmConfig {
925 pub ncomp: usize,
927 pub max_iter: usize,
929 pub tol: f64,
931 pub random_slopes: bool,
938}
939
940impl Default for DenseFlmmConfig {
941 fn default() -> Self {
942 Self {
943 ncomp: 3,
944 max_iter: 50,
945 tol: 1e-10,
946 random_slopes: false,
947 }
948 }
949}
950
951#[derive(Debug, Clone, PartialEq)]
963#[non_exhaustive]
964#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
965pub struct DenseFlmmResult {
966 pub mean_function: Vec<f64>,
968 pub beta_functions: FdMatrix,
970 pub random_effects: FdMatrix,
972 pub fitted: FdMatrix,
974 pub residuals: FdMatrix,
976 pub random_variance: Vec<f64>,
978 pub sigma2_eps: f64,
985 pub sigma2_u: Vec<f64>,
987 pub sigma2_slope: Vec<f64>,
989 pub ncomp: usize,
991 pub n_subjects: usize,
993 pub eigenvalues: Vec<f64>,
995 pub n_iter: usize,
997 pub converged: bool,
999}
1000
1001#[must_use = "expensive computation whose result should not be discarded"]
1036pub fn dense_flmm(
1037 data: &FdMatrix,
1038 subject_ids: &[usize],
1039 covariates: Option<&FdMatrix>,
1040 config: &DenseFlmmConfig,
1041) -> Result<DenseFlmmResult, FdarError> {
1042 let n_total = data.nrows();
1043 let m = data.ncols();
1044 if n_total == 0 || m == 0 {
1045 return Err(FdarError::InvalidDimension {
1046 parameter: "data",
1047 expected: "non-empty matrix".to_string(),
1048 actual: format!("{n_total} x {m}"),
1049 });
1050 }
1051 if subject_ids.len() != n_total {
1052 return Err(FdarError::InvalidDimension {
1053 parameter: "subject_ids",
1054 expected: format!("length {n_total}"),
1055 actual: format!("length {}", subject_ids.len()),
1056 });
1057 }
1058 if config.ncomp == 0 {
1059 return Err(FdarError::InvalidParameter {
1060 parameter: "ncomp",
1061 message: "must be >= 1".to_string(),
1062 });
1063 }
1064 if config.max_iter == 0 {
1065 return Err(FdarError::InvalidParameter {
1066 parameter: "max_iter",
1067 message: "must be >= 1".to_string(),
1068 });
1069 }
1070 if config.random_slopes {
1071 return Err(FdarError::InvalidParameter {
1072 parameter: "random_slopes",
1073 message: "random slope estimation is not yet implemented; \
1074 use random_slopes: false"
1075 .to_string(),
1076 });
1077 }
1078
1079 let (subject_map, n_subjects) = build_subject_map(subject_ids);
1080
1081 let argvals: Vec<f64> = (0..m).map(|j| j as f64 / (m - 1).max(1) as f64).collect();
1082 let fpca = fdata_to_pc_1d(data, config.ncomp, &argvals)?;
1083 let k = fpca.scores.ncols();
1084
1085 let p = covariates.map_or(0, super::matrix::FdMatrix::ncols);
1086
1087 let h = if m > 1 { 1.0 / (m - 1) as f64 } else { 1.0 };
1089 let score_scale = h.sqrt();
1090
1091 let per_comp: Vec<ScalarMixedResultWithMeta> = iter_maybe_parallel!(0..k)
1093 .map(|comp| {
1094 let comp_scores: Vec<f64> = (0..n_total)
1095 .map(|i| fpca.scores[(i, comp)] * score_scale)
1096 .collect();
1097 fit_scalar_mixed_model_tracked(
1098 &comp_scores,
1099 &subject_map,
1100 n_subjects,
1101 covariates,
1102 p,
1103 config.max_iter,
1104 config.tol,
1105 )
1106 })
1107 .collect();
1108
1109 let mut gamma = vec![vec![0.0; k]; p];
1111 let mut u_hat = vec![vec![0.0; k]; n_subjects];
1112 let mut sigma2_u = vec![0.0; k];
1113 let mut sigma2_eps_total = 0.0;
1114 let mut all_converged = true;
1115 let mut max_n_iter = 0usize;
1116
1117 for (comp, r) in per_comp.iter().enumerate() {
1118 for j in 0..p {
1119 gamma[j][comp] = r.result.gamma[j] / score_scale;
1120 }
1121 for s in 0..n_subjects {
1122 u_hat[s][comp] = r.result.u_hat[s] / score_scale;
1123 }
1124 sigma2_u[comp] = r.result.sigma2_u;
1125 sigma2_eps_total += r.result.sigma2_eps;
1126 if !r.converged {
1127 all_converged = false;
1128 }
1129 if r.n_iter > max_n_iter {
1130 max_n_iter = r.n_iter;
1131 }
1132 }
1133 let sigma2_eps = if k > 0 {
1134 sigma2_eps_total / k as f64
1135 } else {
1136 0.0
1137 };
1138
1139 let beta_functions = recover_beta_functions(&gamma, &fpca.rotation, p, m, k);
1140 let random_effects = recover_random_effects(&u_hat, &fpca.rotation, n_subjects, m, k);
1141 let random_variance = compute_random_variance(&random_effects, n_subjects, m);
1142
1143 let (fitted, residuals) = compute_fitted_residuals(
1144 data,
1145 &fpca.mean,
1146 &beta_functions,
1147 &random_effects,
1148 covariates,
1149 &subject_map,
1150 n_total,
1151 m,
1152 p,
1153 );
1154
1155 let eigenvalues: Vec<f64> = fpca
1156 .singular_values
1157 .iter()
1158 .map(|&sv| sv * sv / n_total as f64)
1159 .collect();
1160
1161 let sigma2_slope = vec![0.0; k];
1163
1164 Ok(DenseFlmmResult {
1165 mean_function: fpca.mean,
1166 beta_functions,
1167 random_effects,
1168 fitted,
1169 residuals,
1170 random_variance,
1171 sigma2_eps,
1172 sigma2_u,
1173 sigma2_slope,
1174 ncomp: k,
1175 n_subjects,
1176 eigenvalues,
1177 n_iter: max_n_iter,
1178 converged: all_converged,
1179 })
1180}
1181
1182struct ScalarMixedResultWithMeta {
1184 result: ScalarMixedResult,
1185 n_iter: usize,
1186 converged: bool,
1187}
1188
1189fn fit_scalar_mixed_model_tracked(
1191 y: &[f64],
1192 subject_map: &[usize],
1193 n_subjects: usize,
1194 covariates: Option<&FdMatrix>,
1195 p: usize,
1196 max_iter: usize,
1197 tol: f64,
1198) -> ScalarMixedResultWithMeta {
1199 let n = y.len();
1200 let ss = SubjectStructure::new(subject_map, n_subjects, n);
1201
1202 let gamma_init = estimate_fixed_effects(y, covariates, p, n);
1203 let residuals_init = compute_ols_residuals(y, covariates, &gamma_init, p, n);
1204 let (mut sigma2_u, mut sigma2_e) =
1205 estimate_variance_components(&residuals_init, subject_map, n_subjects, n);
1206
1207 if sigma2_e < 1e-15 {
1208 sigma2_e = 1e-6;
1209 }
1210 if sigma2_u < 1e-15 {
1211 sigma2_u = sigma2_e * 0.1;
1212 }
1213
1214 let mut gamma = gamma_init;
1215 let mut converged = false;
1216 let mut n_iter = 0usize;
1217
1218 for _iter in 0..max_iter {
1219 n_iter += 1;
1220 let sigma2_u_old = sigma2_u;
1221 let sigma2_e_old = sigma2_e;
1222
1223 let weights = shrinkage_weights(&ss, sigma2_u, sigma2_e);
1224
1225 if let Some(cov) = covariates.filter(|_| p > 0) {
1226 if let Some(g) = gls_update_gamma(cov, p, &ss, &weights, y, sigma2_e) {
1227 gamma = g;
1228 }
1229 }
1230
1231 let r = compute_ols_residuals(y, covariates, &gamma, p, n);
1232 (sigma2_u, sigma2_e) = reml_variance_update(&r, &ss, &weights, sigma2_u, p);
1233
1234 let delta = (sigma2_u - sigma2_u_old).abs() + (sigma2_e - sigma2_e_old).abs();
1235 if delta < tol * (sigma2_u_old + sigma2_e_old) {
1236 converged = true;
1237 break;
1238 }
1239 }
1240
1241 let final_residuals = compute_ols_residuals(y, covariates, &gamma, p, n);
1242 let u_hat = compute_blup(
1243 &final_residuals,
1244 subject_map,
1245 n_subjects,
1246 sigma2_u,
1247 sigma2_e,
1248 );
1249
1250 ScalarMixedResultWithMeta {
1251 result: ScalarMixedResult {
1252 gamma,
1253 u_hat,
1254 sigma2_u,
1255 sigma2_eps: sigma2_e,
1256 },
1257 n_iter,
1258 converged,
1259 }
1260}
1261
1262#[derive(Debug, Clone, PartialEq)]
1270#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1271pub struct MultiFammConfig {
1272 pub ncomp: usize,
1274 pub max_iter: usize,
1276 pub tol: f64,
1278}
1279
1280impl Default for MultiFammConfig {
1281 fn default() -> Self {
1282 Self {
1283 ncomp: 3,
1284 max_iter: 50,
1285 tol: 1e-10,
1286 }
1287 }
1288}
1289
1290#[derive(Debug, Clone, PartialEq)]
1301#[non_exhaustive]
1302#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1303pub struct MultiFammResult {
1304 pub components: Vec<DenseFlmmResult>,
1306 pub stacked_fitted: FdMatrix,
1308 pub stacked_residuals: FdMatrix,
1310 pub n_dims: usize,
1312}
1313
1314#[must_use = "expensive computation whose result should not be discarded"]
1337pub fn multi_famm(
1338 data: &[FdMatrix],
1339 subject_ids: &[usize],
1340 covariates: Option<&FdMatrix>,
1341 config: &MultiFammConfig,
1342) -> Result<MultiFammResult, FdarError> {
1343 let n_dims = data.len();
1344 if n_dims == 0 {
1345 return Err(FdarError::InvalidDimension {
1346 parameter: "data",
1347 expected: "at least one response dimension".to_string(),
1348 actual: "0 dimensions".to_string(),
1349 });
1350 }
1351
1352 let n_total = data[0].nrows();
1353 let m = data[0].ncols();
1354
1355 if n_total == 0 || m == 0 {
1356 return Err(FdarError::InvalidDimension {
1357 parameter: "data",
1358 expected: "non-empty matrix".to_string(),
1359 actual: format!("{n_total} x {m}"),
1360 });
1361 }
1362
1363 for (d, dim) in data.iter().enumerate().skip(1) {
1365 if dim.ncols() != m {
1366 return Err(FdarError::InvalidDimension {
1367 parameter: "data",
1368 expected: format!("all dimensions share ncols = {m}"),
1369 actual: format!("dimension {d} has ncols = {}", dim.ncols()),
1370 });
1371 }
1372 if dim.nrows() != n_total {
1373 return Err(FdarError::InvalidDimension {
1374 parameter: "data",
1375 expected: format!("all dimensions share nrows = {n_total}"),
1376 actual: format!("dimension {d} has nrows = {}", dim.nrows()),
1377 });
1378 }
1379 }
1380
1381 let dense_cfg = DenseFlmmConfig {
1383 ncomp: config.ncomp,
1384 max_iter: config.max_iter,
1385 tol: config.tol,
1386 random_slopes: false,
1387 };
1388
1389 let mut components: Vec<DenseFlmmResult> = Vec::with_capacity(n_dims);
1391 for dim_data in data.iter() {
1392 let result = dense_flmm(dim_data, subject_ids, covariates, &dense_cfg)?;
1393 components.push(result);
1394 }
1395
1396 let stacked_rows = n_total * n_dims;
1398 let mut stacked_fitted_data = vec![0.0; stacked_rows * m];
1399 let mut stacked_residuals_data = vec![0.0; stacked_rows * m];
1400
1401 for (d, comp) in components.iter().enumerate() {
1402 for i in 0..n_total {
1403 let row = d * n_total + i;
1404 for t in 0..m {
1405 stacked_fitted_data[row + t * stacked_rows] = comp.fitted[(i, t)];
1407 stacked_residuals_data[row + t * stacked_rows] = comp.residuals[(i, t)];
1408 }
1409 }
1410 }
1411
1412 let stacked_fitted = FdMatrix::from_column_major(stacked_fitted_data, stacked_rows, m)
1413 .map_err(|_| FdarError::ComputationFailed {
1414 operation: "multi_famm stacking",
1415 detail: "failed to build stacked_fitted matrix".to_string(),
1416 })?;
1417 let stacked_residuals = FdMatrix::from_column_major(stacked_residuals_data, stacked_rows, m)
1418 .map_err(|_| FdarError::ComputationFailed {
1419 operation: "multi_famm stacking",
1420 detail: "failed to build stacked_residuals matrix".to_string(),
1421 })?;
1422
1423 Ok(MultiFammResult {
1424 components,
1425 stacked_fitted,
1426 stacked_residuals,
1427 n_dims,
1428 })
1429}
1430
1431#[derive(Debug, Clone, PartialEq)]
1439#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1440pub struct FastFmmConfig {
1441 pub smooth_window: usize,
1449 pub max_iter: usize,
1451 pub tol: f64,
1453 pub compute_inference: bool,
1462}
1463
1464impl Default for FastFmmConfig {
1465 fn default() -> Self {
1466 Self {
1467 smooth_window: 3,
1468 max_iter: 30,
1469 tol: 1e-8,
1470 compute_inference: true,
1471 }
1472 }
1473}
1474
1475#[derive(Debug, Clone, PartialEq)]
1484#[non_exhaustive]
1485#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1486pub struct FastFmmResult {
1487 pub beta_matrix: FdMatrix,
1489 pub t_stats: FdMatrix,
1491 pub p_values: FdMatrix,
1493 pub sigma2_eps: Vec<f64>,
1495 pub sigma2_u: Vec<f64>,
1497 pub n_grid: usize,
1499}
1500
1501#[must_use = "expensive computation whose result should not be discarded"]
1521pub fn fast_fmm(
1522 data: &FdMatrix,
1523 subject_ids: &[usize],
1524 covariates: Option<&FdMatrix>,
1525 config: &FastFmmConfig,
1526) -> Result<FastFmmResult, FdarError> {
1527 let n_total = data.nrows();
1528 let m = data.ncols();
1529 if n_total == 0 || m == 0 {
1530 return Err(FdarError::InvalidDimension {
1531 parameter: "data",
1532 expected: "non-empty matrix".to_string(),
1533 actual: format!("{n_total} x {m}"),
1534 });
1535 }
1536 if subject_ids.len() != n_total {
1537 return Err(FdarError::InvalidDimension {
1538 parameter: "subject_ids",
1539 expected: format!("length {n_total}"),
1540 actual: format!("length {}", subject_ids.len()),
1541 });
1542 }
1543 if config.smooth_window == 0 {
1544 return Err(FdarError::InvalidParameter {
1545 parameter: "smooth_window",
1546 message: "must be >= 1 (use 1 for no smoothing)".to_string(),
1547 });
1548 }
1549 if config.max_iter == 0 {
1550 return Err(FdarError::InvalidParameter {
1551 parameter: "max_iter",
1552 message: "must be >= 1".to_string(),
1553 });
1554 }
1555
1556 let (subject_map, n_subjects) = build_subject_map(subject_ids);
1557 let p = covariates.map_or(0, super::matrix::FdMatrix::ncols);
1558
1559 struct PointwiseResult {
1561 gamma: Vec<f64>, sigma2_u: f64, sigma2_eps: f64, }
1565
1566 let per_point: Vec<PointwiseResult> = iter_maybe_parallel!(0..m)
1569 .map(|t| {
1570 let y_t: Vec<f64> = data.column(t).to_vec();
1571 let r = fit_scalar_mixed_model_tracked(
1572 &y_t,
1573 &subject_map,
1574 n_subjects,
1575 covariates,
1576 p,
1577 config.max_iter,
1578 config.tol,
1579 );
1580 PointwiseResult {
1581 gamma: r.result.gamma,
1582 sigma2_u: r.result.sigma2_u,
1583 sigma2_eps: r.result.sigma2_eps,
1584 }
1585 })
1586 .collect();
1587
1588 let mut raw_beta_data = vec![0.0; p * m]; let mut sigma2_eps_vec = vec![0.0; m];
1591 let mut sigma2_u_vec = vec![0.0; m];
1592
1593 for (t, pt) in per_point.iter().enumerate() {
1594 for j in 0..p {
1596 raw_beta_data[j + t * p] = pt.gamma.get(j).copied().unwrap_or(0.0);
1597 }
1598 sigma2_eps_vec[t] = pt.sigma2_eps;
1599 sigma2_u_vec[t] = pt.sigma2_u;
1600 }
1601
1602 let w = if config.smooth_window % 2 == 0 {
1607 config.smooth_window + 1
1608 } else {
1609 config.smooth_window
1610 };
1611 let mut smoothed_beta_data = raw_beta_data.clone();
1612 if w > 1 && m > 1 {
1613 let half = w / 2;
1614 for j in 0..p {
1615 for t in 0..m {
1616 let lo = t.saturating_sub(half);
1617 let hi = (t + half + 1).min(m);
1618 let count = (hi - lo) as f64;
1619 let sum: f64 = (lo..hi).map(|tt| raw_beta_data[j + tt * p]).sum();
1620 smoothed_beta_data[j + t * p] = sum / count;
1621 }
1622 }
1623 }
1624
1625 let beta_matrix = if p > 0 {
1627 FdMatrix::from_column_major(smoothed_beta_data, p, m).map_err(|_| {
1628 FdarError::ComputationFailed {
1629 operation: "fast_fmm",
1630 detail: "failed to build beta_matrix".to_string(),
1631 }
1632 })?
1633 } else {
1634 FdMatrix::zeros(0, m)
1635 };
1636
1637 let (t_stats, p_values) = if config.compute_inference && p > 0 {
1639 let xtx_inv_diag = compute_xtx_inv_diag(covariates, p, n_total);
1643
1644 let mut t_data = vec![0.0f64; p * m];
1645 let mut pv_data = vec![1.0f64; p * m];
1646
1647 for j in 0..p {
1648 for t in 0..m {
1649 let beta_jt = beta_matrix[(j, t)];
1650 let se_sq = sigma2_eps_vec[t] * xtx_inv_diag.get(j).copied().unwrap_or(1.0);
1651 let se = se_sq.sqrt().max(1e-15);
1652 let t_stat = beta_jt / se;
1653 let pval = 2.0 * normal_sf(t_stat.abs());
1654 t_data[j + t * p] = t_stat;
1655 pv_data[j + t * p] = pval.clamp(0.0, 1.0);
1656 }
1657 }
1658
1659 let ts = FdMatrix::from_column_major(t_data, p, m).map_err(|_| {
1660 FdarError::ComputationFailed {
1661 operation: "fast_fmm",
1662 detail: "failed to build t_stats".to_string(),
1663 }
1664 })?;
1665 let pv = FdMatrix::from_column_major(pv_data, p, m).map_err(|_| {
1666 FdarError::ComputationFailed {
1667 operation: "fast_fmm",
1668 detail: "failed to build p_values".to_string(),
1669 }
1670 })?;
1671 (ts, pv)
1672 } else {
1673 (FdMatrix::zeros(p, m), ones_fdmatrix(p, m))
1675 };
1676
1677 Ok(FastFmmResult {
1678 beta_matrix,
1679 t_stats,
1680 p_values,
1681 sigma2_eps: sigma2_eps_vec,
1682 sigma2_u: sigma2_u_vec,
1683 n_grid: m,
1684 })
1685}
1686
1687fn compute_xtx_inv_diag(covariates: Option<&FdMatrix>, p: usize, n: usize) -> Vec<f64> {
1689 let Some(cov) = covariates else {
1690 return vec![1.0; p];
1691 };
1692 let mut xtx = vec![0.0; p * p];
1693 for i in 0..n {
1694 for r in 0..p {
1695 for s in r..p {
1696 let val = cov[(i, r)] * cov[(i, s)];
1697 xtx[r * p + s] += val;
1698 if r != s {
1699 xtx[s * p + r] += val;
1700 }
1701 }
1702 }
1703 }
1704 for j in 0..p {
1705 xtx[j * p + j] += 1e-8;
1706 }
1707 if let Some(inv) = cholesky_invert(&xtx, p) {
1709 (0..p).map(|j| inv[j * p + j].max(1e-15)).collect()
1710 } else {
1711 (0..p)
1713 .map(|j| {
1714 let d = xtx[j * p + j];
1715 if d > 1e-15 {
1716 1.0 / d
1717 } else {
1718 1.0
1719 }
1720 })
1721 .collect()
1722 }
1723}
1724
1725fn cholesky_invert(a: &[f64], p: usize) -> Option<Vec<f64>> {
1727 let l = linalg_cholesky_factor(a, p).ok()?;
1728 let mut inv = vec![0.0; p * p];
1730 let mut e = vec![0.0; p];
1731 for j in 0..p {
1732 e.fill(0.0);
1733 e[j] = 1.0;
1734 let col = linalg_cholesky_forward_back(&l, &e, p);
1735 for i in 0..p {
1736 inv[i * p + j] = col[i];
1737 }
1738 }
1739 Some(inv)
1740}
1741
1742fn normal_sf(x: f64) -> f64 {
1744 0.5 * erfc(x / core::f64::consts::SQRT_2)
1746}
1747
1748fn erfc(x: f64) -> f64 {
1750 if x < 0.0 {
1752 return 2.0 - erfc(-x);
1753 }
1754 let t = 1.0 / (1.0 + 0.3275911 * x);
1756 let poly = t
1757 * (0.254_829_592
1758 + t * (-0.284_496_736
1759 + t * (1.421_413_741 + t * (-1.453_152_027 + t * 1.061_405_429))));
1760 poly * (-x * x).exp()
1761}
1762
1763fn ones_fdmatrix(p: usize, m: usize) -> FdMatrix {
1765 if p == 0 || m == 0 {
1766 return FdMatrix::zeros(p, m);
1767 }
1768 let data = vec![1.0f64; p * m];
1769 FdMatrix::from_column_major(data, p, m).unwrap_or_else(|_| FdMatrix::zeros(p, m))
1770}
1771
1772#[cfg(test)]
1777mod tests {
1778 use super::*;
1779 use crate::test_helpers::uniform_grid;
1780 use std::f64::consts::PI;
1781
1782 fn generate_fmm_data(
1785 n_subjects: usize,
1786 n_visits: usize,
1787 m: usize,
1788 ) -> (FdMatrix, Vec<usize>, FdMatrix, Vec<f64>) {
1789 let t = uniform_grid(m);
1790 let n_total = n_subjects * n_visits;
1791 let mut col_major = vec![0.0; n_total * m];
1792 let mut subject_ids = vec![0usize; n_total];
1793 let mut cov_data = vec![0.0; n_total];
1794
1795 for s in 0..n_subjects {
1796 let z = s as f64 / n_subjects as f64; let subject_effect = 0.5 * (s as f64 - n_subjects as f64 / 2.0); for v in 0..n_visits {
1800 let obs = s * n_visits + v;
1801 subject_ids[obs] = s;
1802 cov_data[obs] = z;
1803 let noise_scale = 0.05;
1804
1805 for (j, &tj) in t.iter().enumerate() {
1806 let mu = (2.0 * PI * tj).sin();
1808 let fixed = z * tj * 3.0;
1809 let random = subject_effect * (2.0 * PI * tj).cos() * 0.3;
1810 let noise = noise_scale * ((obs * 7 + j * 3) % 100) as f64 / 100.0;
1811 col_major[obs + j * n_total] = mu + fixed + random + noise;
1812 }
1813 }
1814 }
1815
1816 let data = FdMatrix::from_column_major(col_major, n_total, m).unwrap();
1817 let covariates = FdMatrix::from_column_major(cov_data, n_total, 1).unwrap();
1818 (data, subject_ids, covariates, t)
1819 }
1820
1821 #[test]
1822 fn test_fmm_basic() {
1823 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 50);
1824 let result = fmm(&data, &subject_ids, Some(&covariates), 3).unwrap();
1825
1826 assert_eq!(result.mean_function.len(), 50);
1827 assert_eq!(result.beta_functions.nrows(), 1); assert_eq!(result.beta_functions.ncols(), 50);
1829 assert_eq!(result.random_effects.nrows(), 10);
1830 assert_eq!(result.fitted.nrows(), 30);
1831 assert_eq!(result.residuals.nrows(), 30);
1832 assert_eq!(result.n_subjects, 10);
1833 }
1834
1835 #[test]
1836 fn test_fmm_fitted_plus_residuals_equals_data() {
1837 let (data, subject_ids, covariates, _t) = generate_fmm_data(8, 3, 40);
1838 let result = fmm(&data, &subject_ids, Some(&covariates), 3).unwrap();
1839
1840 let n = data.nrows();
1841 let m = data.ncols();
1842 for i in 0..n {
1843 for t in 0..m {
1844 let reconstructed = result.fitted[(i, t)] + result.residuals[(i, t)];
1845 assert!(
1846 (reconstructed - data[(i, t)]).abs() < 1e-8,
1847 "Fitted + residual should equal data at ({}, {}): {} vs {}",
1848 i,
1849 t,
1850 reconstructed,
1851 data[(i, t)]
1852 );
1853 }
1854 }
1855 }
1856
1857 #[test]
1858 fn test_fmm_random_variance_positive() {
1859 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 50);
1860 let result = fmm(&data, &subject_ids, Some(&covariates), 3).unwrap();
1861
1862 for &v in &result.random_variance {
1863 assert!(v >= 0.0, "Random variance should be non-negative");
1864 }
1865 }
1866
1867 #[test]
1868 fn test_fmm_no_covariates() {
1869 let (data, subject_ids, _cov, _t) = generate_fmm_data(8, 3, 40);
1870 let result = fmm(&data, &subject_ids, None, 3).unwrap();
1871
1872 assert_eq!(result.beta_functions.nrows(), 0);
1873 assert_eq!(result.n_subjects, 8);
1874 assert_eq!(result.fitted.nrows(), 24);
1875 }
1876
1877 #[test]
1878 fn test_fmm_predict() {
1879 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 50);
1880 let result = fmm(&data, &subject_ids, Some(&covariates), 3).unwrap();
1881
1882 let new_cov = FdMatrix::from_column_major(vec![0.5], 1, 1).unwrap();
1884 let predicted = fmm_predict(&result, Some(&new_cov));
1885
1886 assert_eq!(predicted.nrows(), 1);
1887 assert_eq!(predicted.ncols(), 50);
1888
1889 for t in 0..50 {
1891 assert!(predicted[(0, t)].is_finite());
1892 assert!(
1893 predicted[(0, t)].abs() < 20.0,
1894 "Predicted value too extreme at t={}: {}",
1895 t,
1896 predicted[(0, t)]
1897 );
1898 }
1899 }
1900
1901 #[test]
1902 fn test_fmm_test_fixed_detects_effect() {
1903 let (data, subject_ids, covariates, _t) = generate_fmm_data(15, 3, 40);
1904
1905 let result = fmm_test_fixed(&data, &subject_ids, &covariates, 3, 99, 42).unwrap();
1906
1907 assert_eq!(result.f_statistics.len(), 1);
1908 assert_eq!(result.p_values.len(), 1);
1909 assert!(
1910 result.p_values[0] < 0.1,
1911 "Should detect covariate effect, got p={}",
1912 result.p_values[0]
1913 );
1914 }
1915
1916 #[test]
1917 fn test_fmm_test_fixed_no_effect() {
1918 let n_subjects = 10;
1919 let n_visits = 3;
1920 let m = 40;
1921 let t = uniform_grid(m);
1922 let n_total = n_subjects * n_visits;
1923
1924 let mut col_major = vec![0.0; n_total * m];
1926 let mut subject_ids = vec![0usize; n_total];
1927 let mut cov_data = vec![0.0; n_total];
1928
1929 for s in 0..n_subjects {
1930 for v in 0..n_visits {
1931 let obs = s * n_visits + v;
1932 subject_ids[obs] = s;
1933 cov_data[obs] = s as f64 / n_subjects as f64;
1934 for (j, &tj) in t.iter().enumerate() {
1935 col_major[obs + j * n_total] =
1936 (2.0 * PI * tj).sin() + 0.1 * ((obs * 7 + j * 3) % 100) as f64 / 100.0;
1937 }
1938 }
1939 }
1940
1941 let data = FdMatrix::from_column_major(col_major, n_total, m).unwrap();
1942 let covariates = FdMatrix::from_column_major(cov_data, n_total, 1).unwrap();
1943
1944 let result = fmm_test_fixed(&data, &subject_ids, &covariates, 3, 99, 42).unwrap();
1945 assert!(
1946 result.p_values[0] > 0.05,
1947 "Should not detect effect, got p={}",
1948 result.p_values[0]
1949 );
1950 }
1951
1952 #[test]
1953 fn test_fmm_invalid_input() {
1954 let data = FdMatrix::zeros(0, 0);
1955 assert!(fmm(&data, &[], None, 1).is_err());
1956
1957 let data = FdMatrix::zeros(10, 50);
1958 let ids = vec![0; 5]; assert!(fmm(&data, &ids, None, 1).is_err());
1960 }
1961
1962 #[test]
1963 fn test_fmm_single_visit_per_subject() {
1964 let n = 10;
1965 let m = 40;
1966 let t = uniform_grid(m);
1967 let mut col_major = vec![0.0; n * m];
1968 let subject_ids: Vec<usize> = (0..n).collect();
1969
1970 for i in 0..n {
1971 for (j, &tj) in t.iter().enumerate() {
1972 col_major[i + j * n] = (2.0 * PI * tj).sin();
1973 }
1974 }
1975 let data = FdMatrix::from_column_major(col_major, n, m).unwrap();
1976
1977 let result = fmm(&data, &subject_ids, None, 2).unwrap();
1979 assert_eq!(result.n_subjects, n);
1980 assert_eq!(result.fitted.nrows(), n);
1981 }
1982
1983 #[test]
1984 fn test_build_subject_map() {
1985 let (map, n) = build_subject_map(&[5, 5, 10, 10, 20]);
1986 assert_eq!(n, 3);
1987 assert_eq!(map, vec![0, 0, 1, 1, 2]);
1988 }
1989
1990 #[test]
1991 fn test_variance_components_positive() {
1992 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 50);
1993 let result = fmm(&data, &subject_ids, Some(&covariates), 3).unwrap();
1994
1995 assert!(result.sigma2_eps >= 0.0);
1996 for &s in &result.sigma2_u {
1997 assert!(s >= 0.0);
1998 }
1999 }
2000
2001 #[test]
2006 fn test_fmm_ncomp_zero_returns_error() {
2007 let (data, subject_ids, _cov, _t) = generate_fmm_data(5, 2, 20);
2008 let err = fmm(&data, &subject_ids, None, 0).unwrap_err();
2009 match err {
2010 FdarError::InvalidParameter { parameter, .. } => {
2011 assert_eq!(parameter, "ncomp");
2012 }
2013 other => panic!("Expected InvalidParameter, got {:?}", other),
2014 }
2015 }
2016
2017 #[test]
2018 fn test_fmm_single_component() {
2019 let (data, subject_ids, covariates, _t) = generate_fmm_data(8, 3, 30);
2021 let result = fmm(&data, &subject_ids, Some(&covariates), 1).unwrap();
2022
2023 assert_eq!(result.ncomp, 1);
2024 assert_eq!(result.sigma2_u.len(), 1);
2025 assert_eq!(result.eigenvalues.len(), 1);
2026 assert_eq!(result.mean_function.len(), 30);
2027 for i in 0..data.nrows() {
2029 for t in 0..data.ncols() {
2030 let diff = (result.fitted[(i, t)] + result.residuals[(i, t)] - data[(i, t)]).abs();
2031 assert!(diff < 1e-8);
2032 }
2033 }
2034 }
2035
2036 #[test]
2037 fn test_fmm_two_subjects() {
2038 let n_subjects = 2;
2040 let n_visits = 5;
2041 let m = 20;
2042 let t = uniform_grid(m);
2043 let n_total = n_subjects * n_visits;
2044 let mut col_major = vec![0.0; n_total * m];
2045 let mut subject_ids = vec![0usize; n_total];
2046
2047 for s in 0..n_subjects {
2048 for v in 0..n_visits {
2049 let obs = s * n_visits + v;
2050 subject_ids[obs] = s;
2051 for (j, &tj) in t.iter().enumerate() {
2052 col_major[obs + j * n_total] =
2053 (2.0 * PI * tj).sin() + (s as f64) * 0.5 + 0.01 * v as f64;
2054 }
2055 }
2056 }
2057 let data = FdMatrix::from_column_major(col_major, n_total, m).unwrap();
2058 let result = fmm(&data, &subject_ids, None, 2).unwrap();
2059
2060 assert_eq!(result.n_subjects, 2);
2061 assert_eq!(result.random_effects.nrows(), 2);
2062 assert_eq!(result.fitted.nrows(), n_total);
2063 }
2064
2065 #[test]
2066 fn test_fmm_predict_no_covariates() {
2067 let (data, subject_ids, _cov, _t) = generate_fmm_data(6, 3, 30);
2068 let result = fmm(&data, &subject_ids, None, 2).unwrap();
2069
2070 let predicted = fmm_predict(&result, None);
2072 assert_eq!(predicted.nrows(), 1);
2073 assert_eq!(predicted.ncols(), 30);
2074 for t in 0..30 {
2075 let diff = (predicted[(0, t)] - result.mean_function[t]).abs();
2076 assert!(
2077 diff < 1e-12,
2078 "Without covariates, prediction should equal mean"
2079 );
2080 }
2081 }
2082
2083 #[test]
2084 fn test_fmm_predict_multiple_new_subjects() {
2085 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 40);
2086 let result = fmm(&data, &subject_ids, Some(&covariates), 3).unwrap();
2087
2088 let new_cov = FdMatrix::from_column_major(vec![0.1, 0.5, 0.9], 3, 1).unwrap();
2090 let predicted = fmm_predict(&result, Some(&new_cov));
2091
2092 assert_eq!(predicted.nrows(), 3);
2093 assert_eq!(predicted.ncols(), 40);
2094
2095 for i in 0..3 {
2097 for t in 0..40 {
2098 assert!(predicted[(i, t)].is_finite());
2099 }
2100 }
2101
2102 let diff_01: f64 = (0..40)
2104 .map(|t| (predicted[(0, t)] - predicted[(1, t)]).powi(2))
2105 .sum();
2106 assert!(
2107 diff_01 > 1e-10,
2108 "Different covariates should yield different predictions"
2109 );
2110 }
2111
2112 #[test]
2113 fn test_fmm_eigenvalues_decreasing() {
2114 let (data, subject_ids, _cov, _t) = generate_fmm_data(10, 3, 50);
2115 let result = fmm(&data, &subject_ids, None, 5).unwrap();
2116
2117 for i in 1..result.eigenvalues.len() {
2119 assert!(
2120 result.eigenvalues[i] <= result.eigenvalues[i - 1] + 1e-10,
2121 "Eigenvalues should be non-increasing: {} > {}",
2122 result.eigenvalues[i],
2123 result.eigenvalues[i - 1]
2124 );
2125 }
2126 }
2127
2128 #[test]
2129 fn test_fmm_random_effects_sum_near_zero() {
2130 let (data, subject_ids, covariates, _t) = generate_fmm_data(20, 3, 40);
2132 let result = fmm(&data, &subject_ids, Some(&covariates), 3).unwrap();
2133
2134 let m = result.mean_function.len();
2135 for t in 0..m {
2136 let sum: f64 = (0..result.n_subjects)
2137 .map(|s| result.random_effects[(s, t)])
2138 .sum();
2139 let mean_abs: f64 = (0..result.n_subjects)
2140 .map(|s| result.random_effects[(s, t)].abs())
2141 .sum::<f64>()
2142 / result.n_subjects as f64;
2143 if mean_abs > 1e-10 {
2145 assert!(
2146 (sum / result.n_subjects as f64).abs() < mean_abs * 2.0,
2147 "Random effects should roughly center around zero at t={}: sum={}, mean_abs={}",
2148 t,
2149 sum,
2150 mean_abs
2151 );
2152 }
2153 }
2154 }
2155
2156 #[test]
2157 fn test_fmm_subject_ids_mismatch_error() {
2158 let data = FdMatrix::zeros(10, 20);
2159 let ids = vec![0; 7]; let err = fmm(&data, &ids, None, 1).unwrap_err();
2161 match err {
2162 FdarError::InvalidDimension { parameter, .. } => {
2163 assert_eq!(parameter, "subject_ids");
2164 }
2165 other => panic!("Expected InvalidDimension, got {:?}", other),
2166 }
2167 }
2168
2169 #[test]
2170 fn test_fmm_test_fixed_empty_data_error() {
2171 let data = FdMatrix::zeros(0, 0);
2172 let covariates = FdMatrix::zeros(0, 1);
2173 let err = fmm_test_fixed(&data, &[], &covariates, 1, 10, 42).unwrap_err();
2174 match err {
2175 FdarError::InvalidDimension { parameter, .. } => {
2176 assert_eq!(parameter, "data");
2177 }
2178 other => panic!("Expected InvalidDimension for data, got {:?}", other),
2179 }
2180 }
2181
2182 #[test]
2183 fn test_fmm_test_fixed_zero_covariates_error() {
2184 let data = FdMatrix::zeros(10, 20);
2185 let ids = vec![0; 10];
2186 let covariates = FdMatrix::zeros(10, 0);
2187 let err = fmm_test_fixed(&data, &ids, &covariates, 1, 10, 42).unwrap_err();
2188 match err {
2189 FdarError::InvalidDimension { parameter, .. } => {
2190 assert_eq!(parameter, "covariates");
2191 }
2192 other => panic!("Expected InvalidDimension for covariates, got {:?}", other),
2193 }
2194 }
2195
2196 #[test]
2197 fn test_build_subject_map_single_subject() {
2198 let (map, n) = build_subject_map(&[42, 42, 42]);
2199 assert_eq!(n, 1);
2200 assert_eq!(map, vec![0, 0, 0]);
2201 }
2202
2203 #[test]
2204 fn test_build_subject_map_non_contiguous_ids() {
2205 let (map, n) = build_subject_map(&[100, 200, 100, 300, 200]);
2206 assert_eq!(n, 3);
2207 assert_eq!(map, vec![0, 1, 0, 2, 1]);
2209 }
2210
2211 #[test]
2212 fn test_fmm_many_components_clamped() {
2213 let (data, subject_ids, _cov, _t) = generate_fmm_data(5, 3, 20);
2215 let n_total = data.nrows();
2216 let result = fmm(&data, &subject_ids, None, 100).unwrap();
2218 assert!(
2219 result.ncomp <= n_total.min(20),
2220 "ncomp should be clamped: got {}",
2221 result.ncomp
2222 );
2223 assert!(result.ncomp >= 1);
2224 }
2225
2226 #[test]
2227 fn test_fmm_residuals_small_with_enough_components() {
2228 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 30);
2230 let result = fmm(&data, &subject_ids, Some(&covariates), 5).unwrap();
2231
2232 let n = data.nrows();
2233 let m = data.ncols();
2234 let mut data_ss = 0.0_f64;
2235 let mut resid_ss = 0.0_f64;
2236 for i in 0..n {
2237 for t in 0..m {
2238 data_ss += data[(i, t)].powi(2);
2239 resid_ss += result.residuals[(i, t)].powi(2);
2240 }
2241 }
2242
2243 let r_squared = 1.0 - resid_ss / data_ss;
2245 assert!(
2246 r_squared > 0.5,
2247 "R-squared should be high with enough components: {}",
2248 r_squared
2249 );
2250 }
2251
2252 #[test]
2257 fn test_dense_flmm_basic() {
2258 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 30);
2259 let cfg = DenseFlmmConfig::default();
2260 let result = dense_flmm(&data, &subject_ids, Some(&covariates), &cfg).unwrap();
2261 assert_eq!(result.ncomp, cfg.ncomp);
2262 assert_eq!(result.n_subjects, 10);
2263 assert_eq!(result.mean_function.len(), 30);
2264 assert_eq!(result.beta_functions.ncols(), 30);
2265 assert_eq!(result.random_variance.len(), 30);
2266 assert_eq!(result.sigma2_u.len(), cfg.ncomp);
2267 assert_eq!(result.sigma2_slope.len(), cfg.ncomp);
2269 assert!(result.sigma2_slope.iter().all(|&v| v == 0.0));
2270 }
2271
2272 #[test]
2273 fn test_dense_flmm_fitted_plus_residuals_equals_data() {
2274 let (data, subject_ids, covariates, _t) = generate_fmm_data(8, 3, 24);
2275 let cfg = DenseFlmmConfig::default();
2276 let result = dense_flmm(&data, &subject_ids, Some(&covariates), &cfg).unwrap();
2277 let n = data.nrows();
2278 let m = data.ncols();
2279 for i in 0..n {
2280 for j in 0..m {
2281 let recon = result.fitted[(i, j)] + result.residuals[(i, j)];
2282 assert!(
2283 (recon - data[(i, j)]).abs() < 1e-6,
2284 "fitted+residuals must equal data at ({i},{j})"
2285 );
2286 }
2287 }
2288 }
2289
2290 #[test]
2291 fn test_dense_flmm_recovers_signal_and_positive_variance() {
2292 let (data, subject_ids, covariates, _t) = generate_fmm_data(12, 4, 30);
2293 let cfg = DenseFlmmConfig {
2294 ncomp: 4,
2295 ..Default::default()
2296 };
2297 let result = dense_flmm(&data, &subject_ids, Some(&covariates), &cfg).unwrap();
2298 let n = data.nrows();
2300 let m = data.ncols();
2301 let mut col_means = vec![0.0; m];
2302 for j in 0..m {
2303 for i in 0..n {
2304 col_means[j] += data[(i, j)];
2305 }
2306 col_means[j] /= n as f64;
2307 }
2308 let (mut base_ss, mut resid_ss) = (0.0_f64, 0.0_f64);
2309 for i in 0..n {
2310 for j in 0..m {
2311 base_ss += (data[(i, j)] - col_means[j]).powi(2);
2312 resid_ss += result.residuals[(i, j)].powi(2);
2313 }
2314 }
2315 assert!(
2316 resid_ss < 0.5 * base_ss,
2317 "mixed model should explain most variance: resid={resid_ss}, base={base_ss}"
2318 );
2319 assert!(result.sigma2_u.iter().any(|&v| v > 0.0));
2321 }
2322
2323 #[test]
2324 fn test_dense_flmm_invalid_inputs() {
2325 let cfg = DenseFlmmConfig::default();
2326 let empty = FdMatrix::from_column_major(vec![], 0, 0).unwrap();
2327 assert!(dense_flmm(&empty, &[], None, &cfg).is_err());
2328
2329 let (data, subject_ids, _cov, _t) = generate_fmm_data(4, 2, 10);
2330 let bad_ids = vec![0usize; subject_ids.len() + 1];
2332 assert!(dense_flmm(&data, &bad_ids, None, &cfg).is_err());
2333
2334 let bad_cfg = DenseFlmmConfig {
2336 ncomp: 0,
2337 ..Default::default()
2338 };
2339 assert!(dense_flmm(&data, &subject_ids, None, &bad_cfg).is_err());
2340 }
2341
2342 #[test]
2347 fn test_multi_famm_basic() {
2348 let (d0, subject_ids, cov, _t) = generate_fmm_data(10, 3, 20);
2349 let (d1, _s1, _c1, _t1) = generate_fmm_data(10, 3, 20);
2350 let cfg = MultiFammConfig {
2351 ncomp: 3,
2352 max_iter: 50,
2353 tol: 1e-10,
2354 };
2355 let result = multi_famm(&[d0, d1], &subject_ids, Some(&cov), &cfg).unwrap();
2356 assert_eq!(result.n_dims, 2);
2357 assert_eq!(result.components.len(), 2);
2358 assert_eq!(result.stacked_fitted.nrows(), 2 * subject_ids.len());
2360 assert_eq!(result.stacked_residuals.nrows(), 2 * subject_ids.len());
2361 }
2362
2363 #[test]
2364 fn test_multi_famm_invalid_inputs() {
2365 let cfg = MultiFammConfig {
2366 ncomp: 3,
2367 max_iter: 50,
2368 tol: 1e-10,
2369 };
2370 assert!(multi_famm(&[], &[], None, &cfg).is_err());
2372
2373 let (d0, subject_ids, cov, _t) = generate_fmm_data(6, 2, 20);
2375 let (d1, _s1, _c1, _t1) = generate_fmm_data(6, 2, 25);
2376 assert!(multi_famm(&[d0, d1], &subject_ids, Some(&cov), &cfg).is_err());
2377 }
2378
2379 #[test]
2384 fn test_fast_fmm_basic() {
2385 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 20);
2386 let cfg = FastFmmConfig::default();
2387 let result = fast_fmm(&data, &subject_ids, Some(&covariates), &cfg).unwrap();
2388 assert_eq!(result.n_grid, 20);
2389 assert_eq!(result.beta_matrix.ncols(), 20);
2390 assert_eq!(result.p_values.ncols(), 20);
2391 assert_eq!(result.sigma2_eps.len(), 20);
2392 for i in 0..result.p_values.nrows() {
2394 for j in 0..result.p_values.ncols() {
2395 let p = result.p_values[(i, j)];
2396 assert!((0.0..=1.0).contains(&p), "p-value out of range: {p}");
2397 assert!(result.t_stats[(i, j)].is_finite());
2398 }
2399 }
2400 }
2401
2402 #[test]
2403 fn test_fast_fmm_invalid_inputs() {
2404 let (data, subject_ids, _cov, _t) = generate_fmm_data(4, 2, 10);
2405 let bad_cfg = FastFmmConfig {
2407 smooth_window: 0,
2408 ..Default::default()
2409 };
2410 assert!(fast_fmm(&data, &subject_ids, None, &bad_cfg).is_err());
2411
2412 let cfg = FastFmmConfig::default();
2414 let bad_ids = vec![0usize; subject_ids.len() + 1];
2415 assert!(fast_fmm(&data, &bad_ids, None, &cfg).is_err());
2416 }
2417
2418 #[test]
2423 fn test_dense_flmm_converged() {
2424 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 20);
2425 let cfg = DenseFlmmConfig {
2427 max_iter: 100,
2428 ..Default::default()
2429 };
2430 let result = dense_flmm(&data, &subject_ids, Some(&covariates), &cfg).unwrap();
2431 assert!(result.converged, "should converge with 100 iterations");
2432
2433 let tight_cfg = DenseFlmmConfig {
2436 max_iter: 1,
2437 tol: 1e-30,
2438 ..Default::default()
2439 };
2440 let result2 = dense_flmm(&data, &subject_ids, Some(&covariates), &tight_cfg).unwrap();
2441 assert_eq!(result2.n_iter, 1, "expected exactly 1 iteration");
2442 }
2446
2447 #[test]
2452 fn test_fast_fmm_detects_effect() {
2453 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 20);
2454 let cfg = FastFmmConfig {
2455 compute_inference: true,
2456 ..Default::default()
2457 };
2458 let result = fast_fmm(&data, &subject_ids, Some(&covariates), &cfg).unwrap();
2459 let norm_sq: f64 = (0..result.beta_matrix.ncols())
2462 .map(|t| result.beta_matrix[(0, t)].powi(2))
2463 .sum();
2464 assert!(
2465 norm_sq > 0.0,
2466 "beta_matrix row 0 should be non-zero for data with a real covariate effect"
2467 );
2468 let max_abs_t: f64 = (0..result.t_stats.ncols())
2470 .map(|t| result.t_stats[(0, t)].abs())
2471 .fold(0.0_f64, f64::max);
2472 assert!(
2473 max_abs_t > 0.5,
2474 "expected a noticeable t-stat somewhere on the grid, got max |t|={max_abs_t}"
2475 );
2476 }
2477
2478 #[test]
2483 fn test_fast_fmm_empty_data_error() {
2484 let empty = FdMatrix::zeros(0, 0);
2485 let cfg = FastFmmConfig::default();
2486 let err = fast_fmm(&empty, &[], None, &cfg).unwrap_err();
2487 match err {
2488 FdarError::InvalidDimension { parameter, .. } => {
2489 assert_eq!(parameter, "data");
2490 }
2491 other => panic!("Expected InvalidDimension for data, got {:?}", other),
2492 }
2493 }
2494
2495 #[test]
2500 fn test_fast_fmm_max_iter_takes_effect() {
2501 let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 20);
2502 let cfg_tight = FastFmmConfig {
2505 max_iter: 1,
2506 tol: 1e-30,
2507 compute_inference: false,
2508 ..Default::default()
2509 };
2510 let cfg_full = FastFmmConfig {
2511 max_iter: 100,
2512 tol: 1e-10,
2513 compute_inference: false,
2514 ..Default::default()
2515 };
2516 let r1 = fast_fmm(&data, &subject_ids, Some(&covariates), &cfg_tight).unwrap();
2517 let r2 = fast_fmm(&data, &subject_ids, Some(&covariates), &cfg_full).unwrap();
2518 let same = r1
2520 .sigma2_eps
2521 .iter()
2522 .zip(&r2.sigma2_eps)
2523 .all(|(a, b)| (a - b).abs() < 1e-12);
2524 assert!(
2525 !same,
2526 "1-iter and 100-iter fast_fmm should produce different sigma2_eps (max_iter is now wired)"
2527 );
2528 }
2529
2530 #[test]
2535 fn test_fast_fmm_even_smooth_window() {
2536 let (data, subject_ids, covariates, _t) = generate_fmm_data(6, 3, 15);
2537 let cfg_even = FastFmmConfig {
2539 smooth_window: 4,
2540 compute_inference: false,
2541 ..Default::default()
2542 };
2543 let result = fast_fmm(&data, &subject_ids, Some(&covariates), &cfg_even).unwrap();
2544 assert_eq!(result.n_grid, 15);
2545 for j in 0..result.beta_matrix.nrows() {
2546 for t in 0..result.beta_matrix.ncols() {
2547 assert!(result.beta_matrix[(j, t)].is_finite());
2548 }
2549 }
2550 let cfg_odd = FastFmmConfig {
2552 smooth_window: 5,
2553 compute_inference: false,
2554 ..Default::default()
2555 };
2556 let result_odd = fast_fmm(&data, &subject_ids, Some(&covariates), &cfg_odd).unwrap();
2557 for j in 0..result.beta_matrix.nrows() {
2558 for t in 0..result.beta_matrix.ncols() {
2559 assert!(
2560 (result.beta_matrix[(j, t)] - result_odd.beta_matrix[(j, t)]).abs() < 1e-12,
2561 "even window 4 should produce identical output to odd window 5 (rounded up)"
2562 );
2563 }
2564 }
2565 }
2566
2567 #[test]
2572 fn test_dense_flmm_random_slopes_errors() {
2573 let (data, subject_ids, covariates, _t) = generate_fmm_data(6, 2, 15);
2574 let cfg = DenseFlmmConfig {
2575 random_slopes: true,
2576 ..Default::default()
2577 };
2578 let err = dense_flmm(&data, &subject_ids, Some(&covariates), &cfg).unwrap_err();
2579 match err {
2580 FdarError::InvalidParameter { parameter, .. } => {
2581 assert_eq!(parameter, "random_slopes");
2582 }
2583 other => panic!(
2584 "Expected InvalidParameter for random_slopes, got {:?}",
2585 other
2586 ),
2587 }
2588 }
2589
2590 #[test]
2595 fn test_dense_flmm_max_iter_zero_errors() {
2596 let (data, subject_ids, _cov, _t) = generate_fmm_data(4, 2, 10);
2597 let cfg = DenseFlmmConfig {
2598 max_iter: 0,
2599 ..Default::default()
2600 };
2601 let err = dense_flmm(&data, &subject_ids, None, &cfg).unwrap_err();
2602 match err {
2603 FdarError::InvalidParameter { parameter, .. } => {
2604 assert_eq!(parameter, "max_iter");
2605 }
2606 other => panic!("Expected InvalidParameter for max_iter, got {:?}", other),
2607 }
2608 }
2609
2610 #[test]
2611 fn test_fast_fmm_max_iter_zero_errors() {
2612 let (data, subject_ids, _cov, _t) = generate_fmm_data(4, 2, 10);
2613 let cfg = FastFmmConfig {
2614 max_iter: 0,
2615 ..Default::default()
2616 };
2617 let err = fast_fmm(&data, &subject_ids, None, &cfg).unwrap_err();
2618 match err {
2619 FdarError::InvalidParameter { parameter, .. } => {
2620 assert_eq!(parameter, "max_iter");
2621 }
2622 other => panic!("Expected InvalidParameter for max_iter, got {:?}", other),
2623 }
2624 }
2625}