modewise_dataset/
spec.rs

1use std::collections::BTreeMap;
2
3use modewise_hdf5::Layout;
4
5use crate::channels::TableFormat;
6use serde::Deserialize;
7
8use crate::DatasetError;
9
10/// Where a dataset lives and how to find and read its recordings.
11#[derive(Debug, Clone, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct DatasetSpec {
14    pub root: String,
15    /// Keep only recordings whose entity takes one of the listed values.
16    #[serde(default)]
17    pub filter: BTreeMap<String, Vec<String>>,
18    /// The first input defines which recordings exist; later inputs must exist for each.
19    #[serde(rename = "input")]
20    pub inputs: Vec<InputSpec>,
21    /// What each channel is (region, hemisphere, tags), the same for every recording.
22    pub channels: Option<ChannelsSpec>,
23    /// Information about each subject, for group statistics and machine learning.
24    pub participants: Option<crate::participants::ParticipantsSpec>,
25}
26
27/// Channel tables, read once and offered to pipelines as one more input.
28#[derive(Debug, Clone, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct ChannelsSpec {
31    /// Pipeline input name for the table.
32    #[serde(default = "default_channels_name")]
33    pub name: String,
34    /// Label files in channel order, relative to the dataset spec's folder; concatenated.
35    pub tables: Vec<TableSpec>,
36    /// Signal inputs whose channels are named by the table, in order, instead of `ch0`, `ch1`, ….
37    #[serde(default)]
38    pub names_for: Vec<String>,
39}
40
41#[derive(Debug, Clone, Deserialize)]
42#[serde(deny_unknown_fields)]
43pub struct TableSpec {
44    pub path: String,
45    pub format: TableFormat,
46}
47
48fn default_channels_name() -> String {
49    "channels".into()
50}
51
52#[derive(Debug, Clone, Deserialize)]
53#[serde(deny_unknown_fields)]
54pub struct InputSpec {
55    /// Pipeline input this file feeds.
56    pub name: String,
57    pub pattern: String,
58    pub format: Format,
59    /// HDF5: path of the 2D dataset inside the file.
60    pub dataset: Option<String>,
61    #[serde(default)]
62    pub layout: LayoutName,
63    /// Fixed sampling rate. Give this or `sidecar`.
64    pub sampling_rate_hz: Option<f64>,
65    /// Pattern of a BIDS JSON sidecar holding `SamplingFrequency` or `RepetitionTime`.
66    pub sidecar: Option<String>,
67    /// Text file with one channel label per line, relative to the dataset root.
68    pub labels_file: Option<String>,
69    /// events_tsv: column holding each event's label (BIDS default: `trial_type`).
70    pub label_column: Option<String>,
71    /// timeseries_tsv: columns to read, by name or glob (`*`, `?`), for example `["trans_*", "rot_*"]`.
72    #[serde(default)]
73    pub columns: Vec<String>,
74    /// nifti: label atlases (3D NIfTI), relative to the dataset spec's folder. Each gives one
75    /// channel per label, in ascending label order; atlases are concatenated in this order.
76    #[serde(default)]
77    pub atlases: Vec<String>,
78    /// nifti: scaling of each region's signal after averaging.
79    #[serde(default)]
80    pub standardize: StandardizeName,
81}
82
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
84#[serde(rename_all = "snake_case")]
85pub enum StandardizeName {
86    #[default]
87    None,
88    /// Minus the mean, divided by the sample SD (ddof = 1), as nilearn's `zscore_sample`.
89    ZscoreSample,
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
93#[serde(rename_all = "snake_case")]
94pub enum Format {
95    Hdf5,
96    /// A 4D NIfTI run, averaged per atlas label at load time (docs/volumes.md).
97    Nifti,
98    /// BIDS `events.tsv`: tab-separated `onset`, `duration` and a label column.
99    EventsTsv,
100    /// Tab-separated series with a header, one column per series and one row per sample, such
101    /// as fMRIPrep's `*_desc-confounds_timeseries.tsv`.
102    TimeseriesTsv,
103}
104
105#[derive(Debug, Clone, Copy, Default, Deserialize)]
106#[serde(rename_all = "snake_case")]
107pub enum LayoutName {
108    #[default]
109    ChannelsByTime,
110    TimeByChannels,
111}
112
113impl From<LayoutName> for Layout {
114    fn from(name: LayoutName) -> Self {
115        match name {
116            LayoutName::ChannelsByTime => Layout::ChannelsByTime,
117            LayoutName::TimeByChannels => Layout::TimeByChannels,
118        }
119    }
120}
121
122pub(crate) enum SamplingRateSource<'a> {
123    Hz(f64),
124    Sidecar(&'a str),
125}
126
127impl InputSpec {
128    pub(crate) fn sampling_rate_source(&self) -> SamplingRateSource<'_> {
129        match (&self.sampling_rate_hz, &self.sidecar) {
130            (Some(hz), _) => SamplingRateSource::Hz(*hz),
131            (None, Some(sidecar)) => SamplingRateSource::Sidecar(sidecar),
132            (None, None) => SamplingRateSource::Hz(f64::NAN),
133        }
134    }
135
136    fn validate(&self) -> Result<(), DatasetError> {
137        let invalid = |m: &str| DatasetError::Spec(format!("input {:?}: {m}", self.name));
138        if self.format != Format::TimeseriesTsv && !self.columns.is_empty() {
139            return Err(invalid("`columns` only applies to timeseries_tsv inputs"));
140        }
141        match self.format {
142            Format::Hdf5 => {
143                if self.sampling_rate_hz.is_some() == self.sidecar.is_some() {
144                    return Err(invalid(
145                        "give exactly one of `sampling_rate_hz` or `sidecar`",
146                    ));
147                }
148                if self.dataset.is_none() {
149                    return Err(invalid(
150                        "hdf5 inputs need `dataset`, the path inside the file",
151                    ));
152                }
153                if self.label_column.is_some() {
154                    return Err(invalid("`label_column` only applies to events_tsv inputs"));
155                }
156                if !self.atlases.is_empty() || self.standardize != StandardizeName::None {
157                    return Err(invalid(
158                        "`atlases` and `standardize` only apply to nifti inputs",
159                    ));
160                }
161            }
162            Format::Nifti => {
163                if self.sampling_rate_hz.is_some() && self.sidecar.is_some() {
164                    return Err(invalid(
165                        "give at most one of `sampling_rate_hz` or `sidecar`; without either, the NIfTI header's TR is used",
166                    ));
167                }
168                if self.atlases.is_empty() {
169                    return Err(invalid(
170                        "nifti inputs need `atlases`, the label volumes to average over",
171                    ));
172                }
173                if self.dataset.is_some() || self.label_column.is_some() {
174                    return Err(invalid(
175                        "`dataset` and `label_column` do not apply to nifti inputs",
176                    ));
177                }
178            }
179            Format::TimeseriesTsv => {
180                if self.sampling_rate_hz.is_some() == self.sidecar.is_some() {
181                    return Err(invalid(
182                        "give exactly one of `sampling_rate_hz` or `sidecar`",
183                    ));
184                }
185                if self.columns.is_empty() {
186                    return Err(invalid(
187                        "timeseries_tsv inputs need `columns`, the names or globs to read",
188                    ));
189                }
190                let other = [
191                    ("dataset", self.dataset.is_some()),
192                    ("labels_file", self.labels_file.is_some()),
193                    ("label_column", self.label_column.is_some()),
194                    ("atlases", !self.atlases.is_empty()),
195                    ("standardize", self.standardize != StandardizeName::None),
196                ];
197                if let Some((field, _)) = other.iter().find(|(_, set)| *set) {
198                    return Err(invalid(&format!(
199                        "`{field}` does not apply to timeseries_tsv inputs"
200                    )));
201                }
202            }
203            Format::EventsTsv => {
204                let signal_only = [
205                    ("dataset", self.dataset.is_some()),
206                    ("sampling_rate_hz", self.sampling_rate_hz.is_some()),
207                    ("sidecar", self.sidecar.is_some()),
208                    ("labels_file", self.labels_file.is_some()),
209                    ("atlases", !self.atlases.is_empty()),
210                    ("standardize", self.standardize != StandardizeName::None),
211                ];
212                if let Some((field, _)) = signal_only.iter().find(|(_, set)| *set) {
213                    return Err(invalid(&format!(
214                        "`{field}` does not apply to events_tsv inputs"
215                    )));
216                }
217            }
218        }
219        Ok(())
220    }
221}
222
223impl DatasetSpec {
224    pub fn from_toml(text: &str) -> Result<Self, DatasetError> {
225        let spec: Self = toml::from_str(text).map_err(|e| DatasetError::Spec(e.to_string()))?;
226        if spec.inputs.is_empty() {
227            return Err(DatasetError::Spec("declare at least one [[input]]".into()));
228        }
229        for input in &spec.inputs {
230            input.validate()?;
231        }
232        if let Some(channels) = &spec.channels {
233            channels.validate(&spec.inputs)?;
234        }
235        Ok(spec)
236    }
237}
238
239impl ChannelsSpec {
240    fn validate(&self, inputs: &[InputSpec]) -> Result<(), DatasetError> {
241        let invalid = |m: String| DatasetError::Spec(format!("[channels]: {m}"));
242        if self.tables.is_empty() {
243            return Err(invalid("list at least one table".into()));
244        }
245        if inputs.iter().any(|i| i.name == self.name) {
246            return Err(invalid(format!("name {:?} is already an input", self.name)));
247        }
248        for target in &self.names_for {
249            match inputs.iter().find(|i| &i.name == target) {
250                None => return Err(invalid(format!("names_for: no input {target:?}"))),
251                Some(i) if i.format == Format::EventsTsv => {
252                    return Err(invalid(format!(
253                        "names_for: {target:?} is not a signal input"
254                    )));
255                }
256                Some(i) if i.format == Format::TimeseriesTsv => {
257                    return Err(invalid(format!(
258                        "names_for: {target:?} takes its names from its columns"
259                    )));
260                }
261                Some(i) if i.labels_file.is_some() => {
262                    return Err(invalid(format!(
263                        "names_for: {target:?} already has a labels_file"
264                    )));
265                }
266                Some(_) => {}
267            }
268        }
269        Ok(())
270    }
271}