Skip to main content

fdars_core/
famm.rs

1//! Functional Additive Mixed Models (FAMM).
2//!
3//! Implements functional mixed effects models for repeated functional
4//! measurements with subject-level covariates.
5//!
6//! Model: `Y_ij(t) = μ(t) + X_i'β(t) + b_i(t) + ε_ij(t)`
7//!
8//! Key functions:
9//! - [`fmm`] — Fit a functional mixed model via FPC decomposition
10//! - [`fmm_predict`] — Predict curves for new subjects
11//! - [`fmm_test_fixed`] — Hypothesis test on fixed effects
12
13use 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/// Result of a functional mixed model fit.
25#[derive(Debug, Clone, PartialEq)]
26#[non_exhaustive]
27pub struct FmmResult {
28    /// Overall mean function μ̂(t) (length m)
29    pub mean_function: Vec<f64>,
30    /// Fixed effect coefficient functions β̂_j(t) (p × m matrix, one row per covariate)
31    pub beta_functions: FdMatrix,
32    /// Random effect functions b̂_i(t) per subject (n_subjects × m)
33    pub random_effects: FdMatrix,
34    /// Fitted values for all observations (n_total × m)
35    pub fitted: FdMatrix,
36    /// Residuals (n_total × m)
37    pub residuals: FdMatrix,
38    /// Variance of random effects at each time point (length m)
39    pub random_variance: Vec<f64>,
40    /// Residual variance estimate
41    pub sigma2_eps: f64,
42    /// Random effect variance estimate (per-component)
43    pub sigma2_u: Vec<f64>,
44    /// Number of FPC components used
45    pub ncomp: usize,
46    /// Number of subjects
47    pub n_subjects: usize,
48    /// FPC eigenvalues (singular values squared / n)
49    pub eigenvalues: Vec<f64>,
50}
51
52/// Result of fixed effect hypothesis test.
53#[derive(Debug, Clone, PartialEq)]
54#[non_exhaustive]
55pub struct FmmTestResult {
56    /// F-statistic per covariate (length p)
57    pub f_statistics: Vec<f64>,
58    /// P-values per covariate (via permutation, length p)
59    pub p_values: Vec<f64>,
60}
61
62// ---------------------------------------------------------------------------
63// Core FMM algorithm
64// ---------------------------------------------------------------------------
65
66/// Fit a functional mixed model via FPC decomposition.
67///
68/// # Arguments
69/// * `data` — All observed curves (n_total × m), stacked across subjects and visits
70/// * `subject_ids` — Subject identifier for each curve (length n_total)
71/// * `covariates` — Subject-level covariates (n_total × p).
72///   Each row corresponds to the same curve in `data`.
73///   If a covariate is subject-level, its value should be repeated across visits.
74/// * `ncomp` — Number of FPC components
75///
76/// # Algorithm
77/// 1. Pool curves, compute FPCA
78/// 2. For each FPC score, fit scalar mixed model: ξ_ijk = x_i'γ_k + u_ik + e_ijk
79/// 3. Recover β̂(t) and b̂_i(t) from component coefficients
80///
81/// # Errors
82///
83/// Returns [`FdarError::InvalidDimension`] if `data` is empty (zero rows or
84/// columns), or if `subject_ids.len()` does not match the number of rows.
85/// Returns [`FdarError::InvalidParameter`] if `ncomp` is zero.
86/// Returns [`FdarError::ComputationFailed`] if the underlying FPCA fails.
87#[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    // Determine unique subjects
118    let (subject_map, n_subjects) = build_subject_map(subject_ids);
119
120    // Step 1: FPCA on pooled data
121    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(); // actual number of components
124
125    // Step 2: For each FPC score, fit scalar mixed model (parallelized)
126    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    // Step 3: Recover functional coefficients (using gamma in original scale)
144    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    // Compute random variance function: Var(b_i(t)) across subjects
148    let random_variance = compute_random_variance(&random_effects, n_subjects, m);
149
150    // Compute fitted and residuals
151    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
184/// Build mapping from observation index to subject index (0..n_subjects-1).
185pub(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
199/// Aggregated results from fitting all FPC components.
200struct ComponentResults {
201    gamma: Vec<Vec<f64>>, // gamma[j][k] = fixed effect coeff j for component k
202    u_hat: Vec<Vec<f64>>, // u_hat[i][k] = random effect for subject i, component k
203    sigma2_u: Vec<f64>,   // per-component random effect variance
204    sigma2_eps: f64,      // average residual variance across components
205}
206
207/// Fit scalar mixed models for all FPC components (parallelized across components).
208///
209/// For each component k, scales FPC scores to L²-normalized space, fits a scalar
210/// mixed model, then scales coefficients back to the original score space.
211#[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    // Normalize scores by sqrt(h) to match R's L²-weighted FPCA convention.
223    // This ensures variance components are on the same scale as R's lmer().
224    let h = if m > 1 { 1.0 / (m - 1) as f64 } else { 1.0 };
225    let score_scale = h.sqrt();
226
227    // Fit each component independently — parallelized when the feature is enabled
228    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    // Unpack per-component results into the aggregate structure
238    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
263/// Scalar mixed model result for one FPC component.
264pub(crate) struct ScalarMixedResult {
265    pub(crate) gamma: Vec<f64>, // fixed effects (length p)
266    pub(crate) u_hat: Vec<f64>, // random effects per subject (length n_subjects)
267    pub(crate) sigma2_u: f64,   // random effect variance
268    pub(crate) sigma2_eps: f64, // residual variance
269}
270
271/// Precomputed subject structure for the mixed model.
272pub(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
290/// Compute shrinkage weights: w_s = σ²_u / (σ²_u + σ²_e / n_s).
291fn 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
305/// GLS fixed effect update using block-diagonal V^{-1}.
306///
307/// Computes γ = (X'V⁻¹X)⁻¹ X'V⁻¹y exploiting the balanced random intercept structure.
308fn 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
348/// Compute subject-level covariate sums and response sum.
349fn 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
361/// Accumulate X'V^{-1}X and X'V^{-1}y for one subject.
362fn 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
391/// REML EM update for variance components.
392///
393/// Returns (σ²_u_new, σ²_e_new) from the conditional expectations.
394/// Uses n - p divisor for σ²_e (REML correction where p = number of fixed effects).
395fn 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    // REML divisor: n - p for residual variance (matches R's lmer)
425    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
433/// Fit scalar mixed model: y_ij = x_i'γ + u_i + e_ij.
434///
435/// Uses iterative GLS for fixed effects + REML EM for variance components,
436/// matching R's lmer() behavior. Initializes from Henderson's ANOVA, then
437/// iterates until convergence.
438pub(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    // Initialize from OLS + Henderson's ANOVA
449    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
501/// OLS estimation of fixed effects.
502fn 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    // Solve (X'X)γ = X'y via Cholesky
514    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    // Regularize
529    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
536/// Cholesky solve: A x = b where A is p-by-p symmetric positive definite.
537/// Returns `None` if the matrix is singular.
538fn 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
543/// Compute OLS residuals: r = y - X*gamma.
544fn 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
564/// Estimate variance components via method of moments.
565///
566/// σ²_u and σ²_ε from one-way random effects ANOVA.
567fn estimate_variance_components(
568    residuals: &[f64],
569    subject_map: &[usize],
570    n_subjects: usize,
571    n: usize,
572) -> (f64, f64) {
573    // Compute subject means and within-subject SS
574    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    // Within-subject SS
588    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    // Between-subject SS
596    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    // Mean number of observations per subject
609    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
617/// Compute BLUP (Best Linear Unbiased Prediction) for random effects.
618///
619/// û_i = σ²_u / (σ²_u + σ²_ε/n_i) * (ȳ_i - x̄_i'γ)
620fn 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
648// ---------------------------------------------------------------------------
649// Recovery of functional coefficients
650// ---------------------------------------------------------------------------
651
652/// Recover β̂(t) = Σ_k γ̂_jk φ_k(t) for each covariate j.
653fn 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
673/// Recover b̂_i(t) = Σ_k û_ik φ_k(t) for each subject i.
674pub(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
694/// Compute random effect variance function: Var_i(b̂_i(t)).
695fn 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
709/// Compute fitted values and residuals.
710fn 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// ---------------------------------------------------------------------------
744// Prediction
745// ---------------------------------------------------------------------------
746
747/// Predict curves for new subjects.
748///
749/// # Arguments
750/// * `result` — Fitted FMM result
751/// * `new_covariates` — Covariates for new subjects (n_new × p)
752///
753/// Returns predicted curves (n_new × m) using only fixed effects (no random effects for new subjects).
754#[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// ---------------------------------------------------------------------------
776// Hypothesis testing
777// ---------------------------------------------------------------------------
778
779/// Permutation test for fixed effects in functional mixed model.
780///
781/// Tests H₀: β_j(t) = 0 for each covariate j.
782/// Uses integrated squared norm as test statistic: T_j = ∫ β̂_j(t)² dt.
783///
784/// # Arguments
785/// * `data` — All observed curves (n_total × m)
786/// * `subject_ids` — Subject identifiers
787/// * `covariates` — Subject-level covariates (n_total × p)
788/// * `ncomp` — Number of FPC components
789/// * `n_perm` — Number of permutations
790/// * `seed` — Random seed
791///
792/// # Errors
793///
794/// Returns [`FdarError::InvalidDimension`] if `data` has zero rows, or
795/// `covariates` has zero columns.
796/// Propagates errors from [`fmm`] (e.g., dimension mismatches or FPCA failure).
797#[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    // Fit observed model
825    let result = fmm(data, subject_ids, Some(covariates), ncomp)?;
826
827    // Observed test statistics: ∫ β̂_j(t)² dt for each covariate
828    let observed_stats = compute_integrated_beta_sq(&result.beta_functions, p, m);
829
830    // Permutation test
831    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
849/// Compute ∫ β̂_j(t)² dt for each covariate.
850fn 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
860/// Run permutation test for fixed effects.
861fn 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        // Permute covariates across subjects
879        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
902/// Permute rows of a matrix according to given indices.
903fn 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// ---------------------------------------------------------------------------
916// denseFLMM — dense functional linear mixed model
917// ---------------------------------------------------------------------------
918
919/// Configuration for [`dense_flmm`].
920///
921/// No `#[non_exhaustive]` — callers may use struct-literal construction.
922#[derive(Debug, Clone, PartialEq)]
923#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
924pub struct DenseFlmmConfig {
925    /// Number of FPC components (default: 3)
926    pub ncomp: usize,
927    /// Maximum REML EM iterations per component model (default: 50)
928    pub max_iter: usize,
929    /// Relative convergence tolerance for variance components (default: 1e-10)
930    pub tol: f64,
931    /// Include random slopes in addition to random intercepts (default: false).
932    ///
933    /// When `false`, only random intercepts are estimated.
934    /// Random-slope estimation is **not yet implemented**; setting this to `true`
935    /// returns [`FdarError::InvalidParameter`] until the feature ships.
936    /// `sigma2_slope` is always zero-filled in this release.
937    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/// Result of a dense functional linear mixed model fit.
952///
953/// # Parametrization note
954///
955/// fdars formulates the model over FPC scores (reusing `fdata_to_pc_1d`) rather than
956/// over spline/basis coefficients as in R's `denseFLMM` package. Consequently
957/// variance components are per FPC component, not smoothed over the argument domain.
958///
959/// Random-slope estimation is not implemented in this release; `sigma2_slope` is
960/// always zero-filled (one entry per FPC component). Future releases may add
961/// two-random-effect scalar LMM support via a dedicated helper.
962#[derive(Debug, Clone, PartialEq)]
963#[non_exhaustive]
964#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
965pub struct DenseFlmmResult {
966    /// Overall mean function μ̂(t) (length m)
967    pub mean_function: Vec<f64>,
968    /// Fixed effect coefficient functions β̂_j(t) (p × m matrix, one row per covariate)
969    pub beta_functions: FdMatrix,
970    /// Random effect functions b̂_i(t) per subject (n_subjects × m)
971    pub random_effects: FdMatrix,
972    /// Fitted values for all observations (n_total × m)
973    pub fitted: FdMatrix,
974    /// Residuals (n_total × m)
975    pub residuals: FdMatrix,
976    /// Variance of random effects at each time point Var_i(b̂_i(t)) (length m)
977    pub random_variance: Vec<f64>,
978    /// Mean residual variance averaged across FPC-score component models.
979    ///
980    /// Each per-component model operates on L²-normalized scores; this average
981    /// is on the normalized scale and is not directly comparable to the marginal
982    /// residual variance `σ²_ε` from R's `lmer()`. See the struct-level
983    /// parametrization note.
984    pub sigma2_eps: f64,
985    /// Random-intercept variance per FPC component (length k)
986    pub sigma2_u: Vec<f64>,
987    /// Random-slope variance per FPC component (zero-filled when `random_slopes = false`)
988    pub sigma2_slope: Vec<f64>,
989    /// Number of FPC components actually used
990    pub ncomp: usize,
991    /// Number of unique subjects
992    pub n_subjects: usize,
993    /// FPC eigenvalues (singular values squared / n_total), length k
994    pub eigenvalues: Vec<f64>,
995    /// Maximum number of REML EM iterations reached across components
996    pub n_iter: usize,
997    /// `true` if all component models converged before `config.max_iter`
998    pub converged: bool,
999}
1000
1001/// Fit a dense functional linear mixed model via FPC score decomposition.
1002///
1003/// Extends [`fmm`] with REML convergence metadata and the `DenseFlmmConfig`
1004/// struct interface.
1005///
1006/// # Parametrization divergence from R's `denseFLMM`
1007///
1008/// R's `denseFLMM` estimates eigenfunctions from raw covariance smoothing
1009/// (gamm/bam REML over basis coefficients). fdars decomposes curves into
1010/// FPC scores via `fdata_to_pc_1d`, then fits a per-component scalar mixed
1011/// model — producing equivalent fixed-effect and random-effect functions but
1012/// without the covariance-smoothing regularization step.
1013///
1014/// # Arguments
1015///
1016/// * `data` — All observed curves (n_total × m)
1017/// * `subject_ids` — Subject identifier for each curve (length n_total)
1018/// * `covariates` — Subject-level covariates (n_total × p), or `None`
1019/// * `config` — Algorithm configuration
1020///
1021/// # Errors
1022///
1023/// Returns [`FdarError::InvalidDimension`] if `data` is empty or `subject_ids`
1024/// length mismatches `data.nrows()`.
1025/// Returns [`FdarError::InvalidParameter`] if `config.ncomp` is zero.
1026/// Returns [`FdarError::ComputationFailed`] if the underlying FPCA fails.
1027///
1028/// # Example
1029///
1030/// ```rust
1031/// use fdars_core::famm::{DenseFlmmConfig, dense_flmm};
1032/// let mut cfg = DenseFlmmConfig::default();
1033/// cfg.ncomp = 2;
1034/// ```
1035#[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    // Scale scores as in fit_all_components
1088    let h = if m > 1 { 1.0 / (m - 1) as f64 } else { 1.0 };
1089    let score_scale = h.sqrt();
1090
1091    // Fit each component with convergence tracking
1092    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    // Unpack per-component results
1110    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    // sigma2_slope is always zero-filled (random-slope estimation not yet implemented)
1162    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
1182/// Internal: scalar mixed model result with convergence metadata.
1183struct ScalarMixedResultWithMeta {
1184    result: ScalarMixedResult,
1185    n_iter: usize,
1186    converged: bool,
1187}
1188
1189/// Fit scalar mixed model, tracking convergence and iteration count.
1190fn 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// ---------------------------------------------------------------------------
1263// multiFAMM — multivariate stacked extension
1264// ---------------------------------------------------------------------------
1265
1266/// Configuration for [`multi_famm`].
1267///
1268/// No `#[non_exhaustive]` — callers may use struct-literal construction.
1269#[derive(Debug, Clone, PartialEq)]
1270#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1271pub struct MultiFammConfig {
1272    /// Number of FPC components per response dimension (default: 3)
1273    pub ncomp: usize,
1274    /// Maximum REML EM iterations per component model (default: 50)
1275    pub max_iter: usize,
1276    /// Convergence tolerance (default: 1e-10)
1277    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/// Result of a multivariate FAMM fit.
1291///
1292/// # Divergence from R's `multiFAMM`
1293///
1294/// R's `multiFAMM` (Volkmann et al. 2021) uses joint multivariate FPCA so that
1295/// cross-dimension covariance kernels K_g(d,e)(t,t') are modelled. fdars instead
1296/// runs D independent univariate FPCAs (one per response dimension via
1297/// [`dense_flmm`]), capturing within-dimension structure but **not**
1298/// cross-dimension covariances. This is a documented capability divergence;
1299/// users requiring cross-dimension random effects should consider the R package.
1300#[derive(Debug, Clone, PartialEq)]
1301#[non_exhaustive]
1302#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1303pub struct MultiFammResult {
1304    /// Per-dimension FLMM results (length D)
1305    pub components: Vec<DenseFlmmResult>,
1306    /// Fitted values stacked row-wise across all dimensions: (n_total × D) × m
1307    pub stacked_fitted: FdMatrix,
1308    /// Residuals stacked row-wise across all dimensions: (n_total × D) × m
1309    pub stacked_residuals: FdMatrix,
1310    /// Number of response dimensions D
1311    pub n_dims: usize,
1312}
1313
1314/// Fit a multivariate functional additive mixed model.
1315///
1316/// Calls [`dense_flmm`] independently for each response dimension and stacks
1317/// the fitted curves and residuals row-wise.
1318///
1319/// All dimensions must share the same number of evaluation points (`ncols`).
1320///
1321/// # Divergence from R's `multiFAMM`
1322///
1323/// Cross-dimension covariance kernels are not modelled; see [`MultiFammResult`]
1324/// for details.
1325///
1326/// # Errors
1327///
1328/// Returns [`FdarError::InvalidDimension`] if:
1329/// - `data` is empty (zero dimensions),
1330/// - any dimension has zero rows or columns,
1331/// - dimensions differ in grid size (`ncols`), or
1332/// - `subject_ids` length mismatches `data[0].nrows()`.
1333///
1334/// Returns [`FdarError::InvalidParameter`] if `config.ncomp` is zero.
1335/// Propagates errors from [`dense_flmm`].
1336#[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    // Validate all dimensions share the same grid and row count
1364    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    // Build per-dimension DenseFlmmConfig from MultiFammConfig
1382    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    // Fit each dimension independently
1390    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    // Stack fitted and residuals row-wise: (n_total * n_dims) × m
1397    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                // column-major: element (row, col) at index row + col * nrows
1406                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// ---------------------------------------------------------------------------
1432// fastFMM — massively-univariate per-gridpoint inference
1433// ---------------------------------------------------------------------------
1434
1435/// Configuration for [`fast_fmm`].
1436///
1437/// No `#[non_exhaustive]` — callers may use struct-literal construction.
1438#[derive(Debug, Clone, PartialEq)]
1439#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1440pub struct FastFmmConfig {
1441    /// Running-mean smoother window width along the grid axis (default: 3; 1 = no smoothing).
1442    ///
1443    /// # Divergence from R's `fastFMM`
1444    ///
1445    /// R's `fastFMM` uses mgcv thin-plate splines for post-smoothing. fdars uses
1446    /// a running-mean smoother configured by this window width. Savitzky-Golay
1447    /// smoothing (better peak preservation) is a planned future improvement.
1448    pub smooth_window: usize,
1449    /// Maximum iterations for each per-gridpoint scalar mixed model (default: 30)
1450    pub max_iter: usize,
1451    /// Convergence tolerance (default: 1e-8)
1452    pub tol: f64,
1453    /// Compute Wald t-statistics and pointwise p-values (default: true).
1454    ///
1455    /// When `false`, `t_stats` is zero-filled and `p_values` is one-filled.
1456    ///
1457    /// # Divergence from R's `fastFMM`
1458    ///
1459    /// R uses a bootstrap for non-Gaussian inference. fdars provides Wald-only
1460    /// (standard-normal approximation) inference.
1461    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/// Result of a fast massively-univariate functional mixed model fit.
1476///
1477/// # Divergence from R's `fastFMM`
1478///
1479/// R's `fastFMM` (Cui et al. 2022, JCGS 31(1):219–230) fits per-gridpoint
1480/// GLMMs via `lme4` and smooths via mgcv. fdars fits per-gridpoint scalar mixed
1481/// models via the existing REML-EM solver, smooths via running-mean, and
1482/// computes Wald-only inference — no bootstrap.
1483#[derive(Debug, Clone, PartialEq)]
1484#[non_exhaustive]
1485#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1486pub struct FastFmmResult {
1487    /// Smoothed fixed-effect functions: p × m matrix (one row per covariate)
1488    pub beta_matrix: FdMatrix,
1489    /// Wald t-statistics: p × m (zero-filled when `compute_inference = false`)
1490    pub t_stats: FdMatrix,
1491    /// Pointwise two-sided p-values: p × m (one-filled when `compute_inference = false`)
1492    pub p_values: FdMatrix,
1493    /// Per-gridpoint residual variance estimate (length m)
1494    pub sigma2_eps: Vec<f64>,
1495    /// Per-gridpoint random-intercept variance estimate (length m)
1496    pub sigma2_u: Vec<f64>,
1497    /// Number of grid points m
1498    pub n_grid: usize,
1499}
1500
1501/// Fit a fast massively-univariate functional mixed model.
1502///
1503/// Fits a scalar mixed model at each grid point independently, then
1504/// applies a running-mean smoother along the grid axis.
1505///
1506/// # Algorithm
1507///
1508/// 1. For each grid point t in 0..m: fit a scalar mixed model on `data.column(t)`
1509///    via REML-EM, producing raw (β̂(t), û_i(t), σ̂²_u(t), σ̂²_ε(t)).
1510/// 2. Smooth the raw p × m coefficient matrix with a running-mean window of
1511///    width `config.smooth_window` (window 1 = identity / no smoothing).
1512/// 3. When `config.compute_inference`: compute Wald t-statistics
1513///    `t_jt = β̂_j(t) / se_j(t)` using a standard-normal two-sided p-value.
1514///
1515/// # Errors
1516///
1517/// Returns [`FdarError::InvalidDimension`] if `data` is empty or `subject_ids`
1518/// length mismatches `data.nrows()`.
1519/// Returns [`FdarError::InvalidParameter`] if `config.smooth_window` is zero.
1520#[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    // Per-gridpoint result container (immutable per-item for safe parallel collect)
1560    struct PointwiseResult {
1561        gamma: Vec<f64>, // length p (fixed effects at this grid point)
1562        sigma2_u: f64,   // random-intercept variance at this grid point
1563        sigma2_eps: f64, // residual variance at this grid point
1564    }
1565
1566    // Step 1: Fit per-gridpoint scalar mixed models
1567    // Use column-major zero-copy access: data.column(t) is a contiguous &[f64]
1568    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    // Unpack into raw p × m beta matrix and per-gridpoint variances
1589    let mut raw_beta_data = vec![0.0; p * m]; // row-by-row in column-major: row=j, col=t
1590    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        // Fill column-major beta: element (j, t) at index j + t * p
1595        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    // Step 2: Running-mean smoothing along the grid axis (per covariate row)
1603    // Force smooth_window to an odd value so the half-width formula `half = w / 2`
1604    // produces a symmetric window of exactly `w` elements (for even w the range
1605    // [t-half, t+half+1) would be w+1 elements wide — one too many).
1606    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    // Build the smoothed beta FdMatrix (p × m, column-major)
1626    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    // Step 3: Wald inference
1638    let (t_stats, p_values) = if config.compute_inference && p > 0 {
1639        // Compute X'X for standard errors using the first non-zero observation
1640        // SE²_j(t) = sigma2_eps(t) * (X'X)^{-1}_{jj}
1641        // We accumulate X'X once (same design for all t) then invert
1642        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        // No inference or no covariates: zeros / ones
1674        (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
1687/// Compute diagonal of (X'X)^{-1} for Wald standard errors.
1688fn 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    // Invert via Cholesky; fall back to reciprocal diagonal if singular
1708    if let Some(inv) = cholesky_invert(&xtx, p) {
1709        (0..p).map(|j| inv[j * p + j].max(1e-15)).collect()
1710    } else {
1711        // Fallback: diagonal only
1712        (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
1725/// Invert a p×p symmetric positive definite matrix via Cholesky.
1726fn cholesky_invert(a: &[f64], p: usize) -> Option<Vec<f64>> {
1727    let l = linalg_cholesky_factor(a, p).ok()?;
1728    // Solve A * X = I column by column
1729    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
1742/// Standard normal survival function: P(Z > x) using erf approximation.
1743fn normal_sf(x: f64) -> f64 {
1744    // 0.5 * erfc(x / sqrt(2))
1745    0.5 * erfc(x / core::f64::consts::SQRT_2)
1746}
1747
1748/// Complementary error function approximation (Abramowitz & Stegun 7.1.26).
1749fn erfc(x: f64) -> f64 {
1750    // Handle negative x via symmetry: erfc(-x) = 2 - erfc(x)
1751    if x < 0.0 {
1752        return 2.0 - erfc(-x);
1753    }
1754    // Rational approximation valid for x >= 0, max |error| < 1.5e-7
1755    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
1763/// Create an FdMatrix filled with ones (p × m).
1764fn 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// ---------------------------------------------------------------------------
1773// Tests
1774// ---------------------------------------------------------------------------
1775
1776#[cfg(test)]
1777mod tests {
1778    use super::*;
1779    use crate::test_helpers::uniform_grid;
1780    use std::f64::consts::PI;
1781
1782    /// Generate repeated measurements: n_subjects × n_visits curves.
1783    /// Subject-level covariate z affects the curve amplitude.
1784    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; // covariate in [0, 1)
1797            let subject_effect = 0.5 * (s as f64 - n_subjects as f64 / 2.0); // random-like effect
1798
1799            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                    // Y_sv(t) = sin(2πt) + z * t + subject_effect * cos(2πt) + noise
1807                    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); // 1 covariate
1828        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        // Predict for new subjects with covariate = 0.5
1883        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        // Predicted curve should be reasonable (not NaN or extreme)
1890        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        // No covariate effect: Y = sin(2πt) + noise
1925        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]; // wrong length
1959        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        // Should still work with 1 visit per subject
1978        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    // -------------------------------------------------------------------
2002    // Additional tests
2003    // -------------------------------------------------------------------
2004
2005    #[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        // Fit with only 1 FPC component
2020        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        // Fitted + residuals = data
2028        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        // Minimal number of subjects (2) with multiple visits
2039        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        // Predict without covariates — should return mean function
2071        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        // Predict for 3 new subjects with different covariate values
2089        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        // All predictions should be finite
2096        for i in 0..3 {
2097            for t in 0..40 {
2098                assert!(predicted[(i, t)].is_finite());
2099            }
2100        }
2101
2102        // Predictions for different covariates should differ
2103        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        // Eigenvalues should be in decreasing order (from FPCA)
2118        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        // Random effects should approximately sum to zero across subjects
2131        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            // Relative to the scale of random effects, the sum should be small
2144            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]; // wrong length
2160        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        // sorted unique: [100, 200, 300] -> indices [0, 1, 2]
2208        assert_eq!(map, vec![0, 1, 0, 2, 1]);
2209    }
2210
2211    #[test]
2212    fn test_fmm_many_components_clamped() {
2213        // Request more components than available; FPCA should clamp
2214        let (data, subject_ids, _cov, _t) = generate_fmm_data(5, 3, 20);
2215        let n_total = data.nrows();
2216        // Request 100 components — should be clamped to min(n_total, m) - 1
2217        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        // With enough components, residuals should be small relative to data
2229        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        // R-squared should be reasonably high for structured data
2244        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    // -----------------------------------------------------------------------
2253    // dense_flmm tests
2254    // -----------------------------------------------------------------------
2255
2256    #[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        // Random-slope variance is always present, zero-filled this release.
2268        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        // Residuals shrink relative to a mean-only baseline (fit tracks the truth).
2299        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        // At least one FPC component has positive random-intercept variance.
2320        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        // Mismatched subject_ids length.
2331        let bad_ids = vec![0usize; subject_ids.len() + 1];
2332        assert!(dense_flmm(&data, &bad_ids, None, &cfg).is_err());
2333
2334        // ncomp == 0.
2335        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    // -----------------------------------------------------------------------
2343    // multi_famm tests
2344    // -----------------------------------------------------------------------
2345
2346    #[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        // Stacked matrices carry D * n_total rows.
2359        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        // Empty dimension list.
2371        assert!(multi_famm(&[], &[], None, &cfg).is_err());
2372
2373        // Grid-size mismatch between dimensions.
2374        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    // -----------------------------------------------------------------------
2380    // fast_fmm tests
2381    // -----------------------------------------------------------------------
2382
2383    #[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        // p-values must be valid probabilities, t-stats finite.
2393        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        // smooth_window == 0.
2406        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        // Mismatched subject_ids length.
2413        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    // -----------------------------------------------------------------------
2419    // REG-05-G: dense_flmm converged field is exercised (WR-04)
2420    // -----------------------------------------------------------------------
2421
2422    #[test]
2423    fn test_dense_flmm_converged() {
2424        let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 20);
2425        // With plenty of iterations, well-conditioned data should converge.
2426        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        // With max_iter=1 and a very tight tol, convergence should fail to be
2434        // reported (n_iter reported is exactly 1).
2435        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        // With 1 iteration and a near-impossible tolerance, converged is likely false.
2443        // We do not assert it is false (could converge in 1 step on degenerate data),
2444        // but we do verify n_iter is tracked correctly.
2445    }
2446
2447    // -----------------------------------------------------------------------
2448    // REG-05-K: fast_fmm detects a real fixed effect (WR-04)
2449    // -----------------------------------------------------------------------
2450
2451    #[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        // beta_matrix row 0 (the covariate effect) should be non-zero since the
2460        // data-generating process includes a fixed covariate term z * t * 3.
2461        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        // At least some grid points should show a meaningful t-statistic.
2469        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    // -----------------------------------------------------------------------
2479    // REG-05-L: fast_fmm empty-data error path (WR-04)
2480    // -----------------------------------------------------------------------
2481
2482    #[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    // -----------------------------------------------------------------------
2496    // CR-01: fast_fmm max_iter actually takes effect
2497    // -----------------------------------------------------------------------
2498
2499    #[test]
2500    fn test_fast_fmm_max_iter_takes_effect() {
2501        let (data, subject_ids, covariates, _t) = generate_fmm_data(10, 3, 20);
2502        // A very tight 1-iteration run should yield different variance estimates
2503        // than a well-converged 100-iteration run.
2504        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        // sigma2_eps at some grid points should differ between 1-iter and 100-iter.
2519        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    // -----------------------------------------------------------------------
2531    // WR-01: even smooth_window is rounded up to nearest odd
2532    // -----------------------------------------------------------------------
2533
2534    #[test]
2535    fn test_fast_fmm_even_smooth_window() {
2536        let (data, subject_ids, covariates, _t) = generate_fmm_data(6, 3, 15);
2537        // Even window (4) — should not error, and produces finite results.
2538        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        // Odd window (5) should produce the same result as even 4 (rounded up to 5).
2551        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    // -----------------------------------------------------------------------
2568    // WR-02: random_slopes = true returns InvalidParameter
2569    // -----------------------------------------------------------------------
2570
2571    #[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    // -----------------------------------------------------------------------
2591    // WR-03: max_iter == 0 returns InvalidParameter for dense_flmm and fast_fmm
2592    // -----------------------------------------------------------------------
2593
2594    #[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}