1use modewise_pipeline::{
2 Artifact, ArtifactKind, Inputs, Operation, OperationDescriptor, Outputs, Port, resolve_params,
3};
4use modewise_regress::{Nuisance, design, residuals};
5use modewise_signals::MultichannelSeries;
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use crate::input;
11
12#[derive(Serialize, Deserialize, JsonSchema)]
13#[serde(deny_unknown_fields)]
14struct Params {
15 #[serde(default = "yes")]
17 detrend: bool,
18 #[serde(default)]
20 high_pass_hz: Option<f64>,
21}
22
23fn yes() -> bool {
24 true
25}
26
27impl Params {
28 fn nuisance(&self) -> Nuisance {
29 Nuisance {
30 detrend: self.detrend,
31 high_pass_hz: self.high_pass_hz,
32 }
33 }
34}
35
36pub struct RegressOperation;
38
39impl Operation for RegressOperation {
40 fn summary(&self) -> &'static str {
41 "Removes confound regressors, the mean, a linear trend and slow cosine drifts from every channel in one least-squares fit (docs/regression.md)."
42 }
43
44 fn params_schema(&self) -> serde_json::Value {
45 modewise_pipeline::schema_of::<Params>()
46 }
47
48 fn descriptor(&self) -> OperationDescriptor {
49 OperationDescriptor {
50 name: "regress",
51 version: env!("CARGO_PKG_VERSION"),
52 inputs: &[
53 Port {
54 name: "data",
55 kinds: &[ArtifactKind::Series],
56 },
57 Port {
58 name: "regressors",
59 kinds: &[ArtifactKind::Series],
60 },
61 ],
62 outputs: &[Port {
63 name: "signal",
64 kinds: &[ArtifactKind::Series],
65 }],
66 }
67 }
68
69 fn resolve(&self, params: Value) -> Result<Value, String> {
70 let (typed, resolved) = resolve_params::<Params>(params)?;
71 if let Some(hz) = typed.high_pass_hz
72 && !(hz.is_finite() && hz > 0.0)
73 {
74 return Err(format!("high_pass_hz must be above 0, got {hz}"));
75 }
76 Ok(resolved)
77 }
78
79 fn run(&self, params: &Value, inputs: &Inputs) -> Result<Outputs, String> {
80 let p: Params = serde_json::from_value(params.clone()).map_err(|e| e.to_string())?;
81 let Artifact::Series(data) = input(inputs, "data")? else {
82 return Err("input \"data\" must be a series".into());
83 };
84 let Artifact::Series(regressors) = input(inputs, "regressors")? else {
85 return Err("input \"regressors\" must be a series".into());
86 };
87 let fs = data.sampling_rate();
88 if regressors.sampling_rate() != fs {
89 return Err(format!(
90 "regressors are sampled at {} Hz, the data at {} Hz",
91 regressors.sampling_rate().hz(),
92 fs.hz()
93 ));
94 }
95 let x = design(p.nuisance(), data.n_samples(), fs.hz(), regressors.data())
96 .map_err(|e| e.to_string())?;
97 let clean = residuals(data.data(), x.view()).map_err(|e| e.to_string())?;
98 let signal = MultichannelSeries::new(clean, fs, data.labels().to_vec())
99 .map_err(|e| e.to_string())?;
100 Ok(Outputs::from([("signal".into(), Artifact::Series(signal))]))
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 #![allow(clippy::unwrap_used)]
107
108 use std::sync::Arc;
109
110 use modewise_signals::SamplingRate;
111 use ndarray::{Array2, array};
112 use serde_json::json;
113
114 use super::*;
115
116 fn series(data: Array2<f64>, hz: f64) -> Arc<Artifact> {
117 let labels = (0..data.nrows()).map(|c| format!("c{c}")).collect();
118 Arc::new(Artifact::Series(
119 MultichannelSeries::new(data, SamplingRate::new(hz).unwrap(), labels).unwrap(),
120 ))
121 }
122
123 fn inputs(data_hz: f64, regressors_hz: f64) -> Inputs {
124 Inputs::from([
125 (
126 "data".into(),
127 series(array![[1.0, 3.0, 2.0, 6.0, 4.0, 5.0]], data_hz),
128 ),
129 (
130 "regressors".into(),
131 series(array![[0.0, 1.0, 0.0, 2.0, 0.0, 1.0]], regressors_hz),
132 ),
133 ])
134 }
135
136 #[test]
137 fn keeps_labels_and_rate_and_removes_the_mean() {
138 let params = RegressOperation.resolve(json!({})).unwrap();
139 assert_eq!(params, json!({"detrend": true, "high_pass_hz": null}));
140 let out = RegressOperation.run(¶ms, &inputs(1.0, 1.0)).unwrap();
141 let Artifact::Series(s) = &out["signal"] else {
142 panic!("not a series")
143 };
144 assert_eq!(s.labels(), ["c0"]);
145 assert_eq!(s.sampling_rate().hz(), 1.0);
146 assert!(s.data().sum().abs() < 1e-12);
147 }
148
149 #[test]
150 fn rejects_other_rates_and_bad_cutoffs() {
151 let params = RegressOperation.resolve(json!({})).unwrap();
152 let err = RegressOperation
153 .run(¶ms, &inputs(1.0, 2.0))
154 .unwrap_err();
155 assert!(err.contains("sampled at 2 Hz"), "{err}");
156 for hz in [0.0, -0.1] {
157 assert!(
158 RegressOperation
159 .resolve(json!({"high_pass_hz": hz}))
160 .is_err()
161 );
162 }
163 let params = RegressOperation
164 .resolve(json!({"high_pass_hz": 0.6}))
165 .unwrap();
166 let err = RegressOperation
167 .run(¶ms, &inputs(1.0, 1.0))
168 .unwrap_err();
169 assert!(err.contains("Nyquist"), "{err}");
170 }
171
172 #[test]
173 fn rejects_other_kinds() {
174 let params = RegressOperation.resolve(json!({})).unwrap();
175 let mut bad = inputs(1.0, 1.0);
176 bad.insert(
177 "regressors".into(),
178 Arc::new(Artifact::Events(
179 modewise_epochs::Events::new(vec![]).unwrap(),
180 )),
181 );
182 assert!(RegressOperation.run(¶ms, &bad).is_err());
183 let mut bad = inputs(1.0, 1.0);
184 bad.insert(
185 "data".into(),
186 Arc::new(Artifact::Events(
187 modewise_epochs::Events::new(vec![]).unwrap(),
188 )),
189 );
190 assert!(RegressOperation.run(¶ms, &bad).is_err());
191 }
192}