modewise_operations/
glm.rs

1use modewise_decomposition::Loadings;
2use modewise_glm::{NoiseModel, fit, task_regressors};
3use modewise_pipeline::{
4    Artifact, ArtifactKind, Inputs, Operation, OperationDescriptor, Outputs, Port, resolve_params,
5};
6use modewise_regress::{Nuisance, design};
7use ndarray::Array2;
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::input;
13
14#[derive(Serialize, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
15#[serde(rename_all = "lowercase")]
16enum Noise {
17    Ar1,
18    Ols,
19}
20
21#[derive(Serialize, Deserialize, JsonSchema)]
22#[serde(deny_unknown_fields)]
23struct Params {
24    /// Noise model: "ar1" prewhitens each channel with its own AR(1) coefficient; "ols" assumes independent samples.
25    #[serde(default = "ar1")]
26    noise: Noise,
27    /// Also model a linear trend. The mean is always modelled.
28    #[serde(default = "yes")]
29    detrend: bool,
30    /// Also model slow drifts below this frequency (Hz) with discrete cosine regressors; none by default.
31    #[serde(default)]
32    high_pass_hz: Option<f64>,
33}
34
35fn ar1() -> Noise {
36    Noise::Ar1
37}
38
39fn yes() -> bool {
40    true
41}
42
43/// Task GLM: one regressor per event condition, fitted with drift and confound regressors
44/// (docs/glm.md).
45pub struct GlmOperation;
46
47impl Operation for GlmOperation {
48    fn summary(&self) -> &'static str {
49        "Fits a task GLM to every channel: one regressor per event condition (the events convolved with the canonical haemodynamic response), with the mean, a trend, slow drifts and optional confounds; gives betas and t per condition and channel (docs/glm.md)."
50    }
51
52    fn params_schema(&self) -> Value {
53        modewise_pipeline::schema_of::<Params>()
54    }
55
56    fn descriptor(&self) -> OperationDescriptor {
57        OperationDescriptor {
58            name: "glm",
59            version: env!("CARGO_PKG_VERSION"),
60            inputs: &[
61                Port {
62                    name: "data",
63                    kinds: &[ArtifactKind::Series],
64                },
65                Port {
66                    name: "events",
67                    kinds: &[ArtifactKind::Events],
68                },
69                Port {
70                    name: "confounds",
71                    kinds: &[ArtifactKind::Series],
72                },
73            ],
74            outputs: &[
75                Port {
76                    name: "betas",
77                    kinds: &[ArtifactKind::Loadings],
78                },
79                Port {
80                    name: "t",
81                    kinds: &[ArtifactKind::Loadings],
82                },
83            ],
84        }
85    }
86
87    fn optional_inputs(&self) -> &'static [&'static str] {
88        &["confounds"]
89    }
90
91    fn resolve(&self, params: Value) -> Result<Value, String> {
92        let (typed, resolved) = resolve_params::<Params>(params)?;
93        if let Some(hz) = typed.high_pass_hz
94            && !(hz.is_finite() && hz > 0.0)
95        {
96            return Err(format!("high_pass_hz must be above 0, got {hz}"));
97        }
98        Ok(resolved)
99    }
100
101    fn run(&self, params: &Value, inputs: &Inputs) -> Result<Outputs, String> {
102        let p: Params = serde_json::from_value(params.clone()).map_err(|e| e.to_string())?;
103        let Artifact::Series(data) = input(inputs, "data")? else {
104            return Err("input \"data\" must be a series".into());
105        };
106        let Artifact::Events(events) = input(inputs, "events")? else {
107            return Err("input \"events\" must be events".into());
108        };
109        if events.is_empty() {
110            return Err("there are no events to model".into());
111        }
112        let (n, fs) = (data.n_samples(), data.sampling_rate());
113        let confounds = match inputs.get("confounds").map(|a| a.as_ref()) {
114            None => Array2::zeros((0, n)),
115            Some(Artifact::Series(c)) if c.sampling_rate() == fs => c.data().to_owned(),
116            Some(Artifact::Series(c)) => {
117                return Err(format!(
118                    "confounds are sampled at {} Hz, the data at {} Hz",
119                    c.sampling_rate().hz(),
120                    fs.hz()
121                ));
122            }
123            Some(_) => return Err("input \"confounds\" must be a series".into()),
124        };
125        let nuisance = Nuisance {
126            detrend: p.detrend,
127            high_pass_hz: p.high_pass_hz,
128        };
129        let x = design(nuisance, n, fs.hz(), confounds.view()).map_err(|e| e.to_string())?;
130        let (conditions, task) = task_regressors(events, n, fs.hz());
131        let noise = match p.noise {
132            Noise::Ar1 => NoiseModel::Ar1,
133            Noise::Ols => NoiseModel::Ols,
134        };
135        let f = fit(data.data(), task.view(), &conditions, x.view(), noise)
136            .map_err(|e| e.to_string())?;
137        let table = |values| {
138            Loadings::new(values, conditions.clone(), data.labels().to_vec())
139                .map(Artifact::Loadings)
140                .map_err(|e| e.to_string())
141        };
142        Ok(Outputs::from([
143            ("betas".into(), table(f.betas)?),
144            ("t".into(), table(f.t)?),
145        ]))
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    #![allow(clippy::unwrap_used)]
152
153    use std::sync::Arc;
154
155    use modewise_epochs::{Event, Events};
156    use modewise_signals::{MultichannelSeries, SamplingRate};
157    use serde_json::json;
158
159    use super::*;
160
161    fn series(data: Array2<f64>, hz: f64) -> Arc<Artifact> {
162        let labels = (0..data.nrows()).map(|c| format!("c{c}")).collect();
163        Arc::new(Artifact::Series(
164            MultichannelSeries::new(data, SamplingRate::new(hz).unwrap(), labels).unwrap(),
165        ))
166    }
167
168    fn events() -> Arc<Artifact> {
169        let block = |onset_s, label: &str| Event {
170            onset_s,
171            duration_s: 10.0,
172            label: label.into(),
173        };
174        Arc::new(Artifact::Events(
175            Events::new(vec![
176                block(0.0, "face"),
177                block(20.0, "shape"),
178                block(40.0, "face"),
179                block(60.0, "shape"),
180            ])
181            .unwrap(),
182        ))
183    }
184
185    fn inputs() -> Inputs {
186        let n = 100;
187        let signal = Array2::from_shape_fn((2, n), |(c, i)| ((i * (c + 3)) as f64 * 0.7).sin());
188        Inputs::from([
189            ("data".into(), series(signal, 1.0)),
190            ("events".into(), events()),
191        ])
192    }
193
194    #[test]
195    fn gives_betas_and_t_per_condition_and_channel() {
196        let params = GlmOperation.resolve(json!({})).unwrap();
197        assert_eq!(
198            params,
199            json!({"noise": "ar1", "detrend": true, "high_pass_hz": null})
200        );
201        let out = GlmOperation.run(&params, &inputs()).unwrap();
202        for port in ["betas", "t"] {
203            let Artifact::Loadings(l) = &out[port] else {
204                panic!("not loadings")
205            };
206            assert_eq!(l.latent_labels(), ["face", "shape"]);
207            assert_eq!(l.channel_labels(), ["c0", "c1"]);
208        }
209    }
210
211    #[test]
212    fn confounds_join_the_fit() {
213        let params = GlmOperation.resolve(json!({"noise": "ols"})).unwrap();
214        let mut with = inputs();
215        let Artifact::Series(data) = with["data"].as_ref() else {
216            panic!()
217        };
218        with.insert(
219            "confounds".into(),
220            series(data.data().slice(ndarray::s![0..1, ..]).to_owned(), 1.0),
221        );
222        let out = GlmOperation.run(&params, &with).unwrap();
223        let Artifact::Loadings(b) = &out["betas"] else {
224            panic!()
225        };
226        assert!(b.values().column(0).iter().all(|v| v.abs() < 1e-10));
227
228        with.insert("confounds".into(), series(Array2::zeros((1, 100)), 2.0));
229        let err = GlmOperation.run(&params, &with).unwrap_err();
230        assert!(err.contains("sampled at 2 Hz"), "{err}");
231        with.insert("confounds".into(), events());
232        assert!(GlmOperation.run(&params, &with).is_err());
233    }
234
235    #[test]
236    fn rejects_bad_parameters_and_inputs() {
237        for params in [
238            json!({"high_pass_hz": 0.0}),
239            json!({"high_pass_hz": -0.1}),
240            json!({"noise": "ar2"}),
241        ] {
242            assert!(GlmOperation.resolve(params).is_err());
243        }
244        let params = GlmOperation.resolve(json!({})).unwrap();
245        let mut bad = inputs();
246        bad.insert(
247            "events".into(),
248            Arc::new(Artifact::Events(Events::new(vec![]).unwrap())),
249        );
250        let err = GlmOperation.run(&params, &bad).unwrap_err();
251        assert!(err.contains("no events"), "{err}");
252        let mut bad = inputs();
253        bad.insert("events".into(), series(Array2::zeros((1, 100)), 1.0));
254        assert!(GlmOperation.run(&params, &bad).is_err());
255        let mut bad = inputs();
256        bad.insert("data".into(), events());
257        assert!(GlmOperation.run(&params, &bad).is_err());
258    }
259}