modewise_dataset/
lib.rs

1//! Finds recordings on disk by file patterns and loads them as pipeline inputs.
2//!
3//! Patterns use `{entity}` placeholders, for example
4//! `sub-{subject}/func/sub-{subject}_task-{task}_run-{run}_bold.h5`, so BIDS and
5//! BIDS-like layouts of any modality are described the same way.
6
7mod channels;
8mod events_tsv;
9mod participants;
10mod pattern;
11mod spec;
12mod timeseries_tsv;
13
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16
17use modewise_brain::ChannelTable;
18use modewise_hdf5::read_series;
19use modewise_pipeline::{Artifact, InputSource};
20use modewise_signals::{MultichannelSeries, SamplingRate};
21use thiserror::Error;
22
23pub use channels::{TableFormat, read_table, schaefer_channel, tian_channel};
24pub use events_tsv::read as read_events_tsv;
25pub use participants::{ParticipantTable, ParticipantsSpec, read_participants};
26pub use pattern::Pattern;
27pub use spec::{ChannelsSpec, DatasetSpec, Format, InputSpec, LayoutName, TableSpec};
28
29use spec::SamplingRateSource;
30
31#[derive(Debug, Error)]
32pub enum DatasetError {
33    #[error("cannot read dataset spec: {0}")]
34    Spec(String),
35    #[error("invalid pattern {pattern:?}: {message}")]
36    Pattern { pattern: String, message: String },
37    #[error("cannot list {path}: {message}")]
38    Io { path: String, message: String },
39    #[error("filter on {0:?}, which the first input's pattern does not contain")]
40    UnknownFilterEntity(String),
41}
42
43/// One matched set of entity values, with the file for each input.
44#[derive(Debug, Clone, PartialEq)]
45pub struct Recording {
46    /// Entity values in the order they appear in the first input's pattern.
47    pub entities: Vec<(String, String)>,
48    pub paths: BTreeMap<String, PathBuf>,
49}
50
51impl Recording {
52    /// Stable name such as `subject-01_task-rest_run-1`.
53    pub fn id(&self) -> String {
54        let parts: Vec<String> = self
55            .entities
56            .iter()
57            .map(|(k, v)| format!("{k}-{v}"))
58            .collect();
59        parts.join("_")
60    }
61
62    fn entity_map(&self) -> BTreeMap<String, String> {
63        self.entities.iter().cloned().collect()
64    }
65}
66
67/// A dataset spec with its recordings discovered.
68pub struct Dataset {
69    spec: DatasetSpec,
70    /// The spec's folder, which atlas and channel-table paths are relative to.
71    base: PathBuf,
72    root: PathBuf,
73    recordings: Vec<Recording>,
74    channels: Option<ChannelTable>,
75    participants: Option<modewise_study::Participants>,
76}
77
78impl Dataset {
79    /// Reads a dataset TOML file. A relative `root` is resolved against the file's folder.
80    pub fn from_file(path: &Path) -> Result<Self, DatasetError> {
81        let text = std::fs::read_to_string(path).map_err(|e| DatasetError::Io {
82            path: path.display().to_string(),
83            message: e.to_string(),
84        })?;
85        let base = path.parent().unwrap_or(Path::new("."));
86        Self::discover(DatasetSpec::from_toml(&text)?, base)
87    }
88
89    pub fn discover(spec: DatasetSpec, base: &Path) -> Result<Self, DatasetError> {
90        let root = base.join(&spec.root);
91        let Some(first) = spec.inputs.first() else {
92            return Err(DatasetError::Spec("declare at least one [[input]]".into()));
93        };
94
95        let primary = Pattern::parse(&first.pattern)?;
96        if let Some(unknown) = spec.filter.keys().find(|k| !primary.entities().contains(k)) {
97            return Err(DatasetError::UnknownFilterEntity(unknown.clone()));
98        }
99        let others = spec.inputs[1..]
100            .iter()
101            .map(|i| Ok((i.name.clone(), Pattern::parse(&i.pattern)?)))
102            .collect::<Result<Vec<_>, DatasetError>>()?;
103
104        let mut recordings = Vec::new();
105        for (path, entities) in primary.find(&root)? {
106            let keep = spec.filter.iter().all(|(entity, allowed)| {
107                entities
108                    .iter()
109                    .any(|(k, v)| k == entity && allowed.contains(v))
110            });
111            if !keep {
112                continue;
113            }
114            let values: BTreeMap<String, String> = entities.iter().cloned().collect();
115            let mut paths = BTreeMap::from([(first.name.clone(), path)]);
116            for (name, pattern) in &others {
117                paths.insert(name.clone(), root.join(pattern.fill(&values)?));
118            }
119            recordings.push(Recording { entities, paths });
120        }
121        let channels = match &spec.channels {
122            Some(c) => {
123                let tables = c
124                    .tables
125                    .iter()
126                    .map(|t| read_table(&base.join(&t.path), t.format))
127                    .collect::<Result<Vec<_>, _>>()
128                    .map_err(DatasetError::Spec)?;
129                Some(ChannelTable::concat(tables).map_err(|e| DatasetError::Spec(e.to_string()))?)
130            }
131            None => None,
132        };
133        let participants = match &spec.participants {
134            Some(p) => Some(read_participants(&root, p).map_err(DatasetError::Spec)?),
135            None => None,
136        };
137        Ok(Self {
138            spec,
139            base: base.to_path_buf(),
140            root,
141            recordings,
142            channels,
143            participants,
144        })
145    }
146
147    /// Participant information from `[participants]`, if the spec has one.
148    pub fn participants(&self) -> Option<&modewise_study::Participants> {
149        self.participants.as_ref()
150    }
151
152    /// The channel table from `[channels]`, if the spec has one.
153    pub fn channels(&self) -> Option<&ChannelTable> {
154        self.channels.as_ref()
155    }
156
157    pub fn recordings(&self) -> &[Recording] {
158        &self.recordings
159    }
160
161    pub fn recording(&self, id: &str) -> Option<&Recording> {
162        self.recordings.iter().find(|r| r.id() == id)
163    }
164
165    fn load_input(&self, input: &InputSpec, recording: &Recording) -> Result<Artifact, String> {
166        let path = &recording.paths[&input.name];
167        match input.format {
168            Format::Hdf5 => self.load_series(input, recording).map(Artifact::Series),
169            Format::Nifti => self.load_nifti(input, recording).map(Artifact::Series),
170            Format::EventsTsv => {
171                let column = input.label_column.as_deref().unwrap_or("trial_type");
172                events_tsv::read(path, column).map(Artifact::Events)
173            }
174            Format::TimeseriesTsv => {
175                let hz = self.sampling_rate(input, recording)?.unwrap_or(f64::NAN);
176                let fs = SamplingRate::new(hz).map_err(|e| e.to_string())?;
177                timeseries_tsv::read(path, &input.columns, fs).map(Artifact::Series)
178            }
179        }
180    }
181
182    /// Channel names: a labels file, or the channel table when `names_for` lists this input.
183    fn channel_names(&self, input: &InputSpec) -> Result<Option<Vec<String>>, String> {
184        let named = self
185            .spec
186            .channels
187            .as_ref()
188            .is_some_and(|c| c.names_for.contains(&input.name));
189        Ok(match (&input.labels_file, &self.channels) {
190            (Some(file), _) => Some(read_labels(&self.root.join(file))?),
191            (None, Some(table)) if named => Some(table.names()),
192            _ => None,
193        })
194    }
195
196    fn sampling_rate(
197        &self,
198        input: &InputSpec,
199        recording: &Recording,
200    ) -> Result<Option<f64>, String> {
201        Ok(match input.sampling_rate_source() {
202            SamplingRateSource::Hz(hz) if hz.is_nan() => None,
203            SamplingRateSource::Hz(hz) => Some(hz),
204            SamplingRateSource::Sidecar(sidecar) => {
205                let relative = Pattern::parse(sidecar)
206                    .and_then(|p| p.fill(&recording.entity_map()))
207                    .map_err(|e| e.to_string())?;
208                Some(sidecar_rate(&self.root.join(relative))?)
209            }
210        })
211    }
212
213    fn load_nifti(
214        &self,
215        input: &InputSpec,
216        recording: &Recording,
217    ) -> Result<MultichannelSeries, String> {
218        let bold =
219            modewise_nifti::read_bold(&recording.paths[&input.name]).map_err(|e| e.to_string())?;
220        let hz =
221            match self.sampling_rate(input, recording)? {
222                Some(hz) => hz,
223                None => 1.0 / bold.repetition_time_s.ok_or(
224                    "the NIfTI header has no repetition time; give `sampling_rate_hz` or `sidecar`",
225                )?,
226            };
227        let standardize = match input.standardize {
228            spec::StandardizeName::None => modewise_parcellate::Standardize::None,
229            spec::StandardizeName::ZscoreSample => modewise_parcellate::Standardize::ZscoreSample,
230        };
231        let mut rows = Vec::new();
232        for atlas in &input.atlases {
233            let path = self.base.join(atlas);
234            let labels = modewise_nifti::read_labels(&path).map_err(|e| e.to_string())?;
235            let (signals, _) = modewise_parcellate::parcellate(
236                bold.data.view(),
237                &bold.affine,
238                labels.data.view(),
239                &labels.affine,
240                standardize,
241            )
242            .map_err(|e| format!("{}: {e}", path.display()))?;
243            rows.push(signals);
244        }
245        let views: Vec<_> = rows.iter().map(|r| r.view()).collect();
246        let data = ndarray::concatenate(ndarray::Axis(0), &views).map_err(|e| e.to_string())?;
247        let labels = self
248            .channel_names(input)?
249            .unwrap_or_else(|| (0..data.nrows()).map(|c| format!("ch{c}")).collect());
250        let fs = SamplingRate::new(hz).map_err(|e| e.to_string())?;
251        MultichannelSeries::new(data, fs, labels).map_err(|e| e.to_string())
252    }
253
254    fn load_series(
255        &self,
256        input: &InputSpec,
257        recording: &Recording,
258    ) -> Result<MultichannelSeries, String> {
259        let hz = self.sampling_rate(input, recording)?.unwrap_or(f64::NAN);
260        let fs = SamplingRate::new(hz).map_err(|e| e.to_string())?;
261        let labels = self.channel_names(input)?;
262        let dataset = input.dataset.as_deref().unwrap_or_default();
263        read_series(
264            &recording.paths[&input.name],
265            dataset,
266            input.layout.into(),
267            fs,
268            labels,
269        )
270        .map_err(|e| e.to_string())
271    }
272}
273
274impl InputSource for Dataset {
275    fn input_names(&self) -> Vec<String> {
276        let mut names: Vec<String> = self.spec.inputs.iter().map(|i| i.name.clone()).collect();
277        names.extend(self.spec.channels.as_ref().map(|c| c.name.clone()));
278        names
279    }
280
281    fn recording_ids(&self) -> Vec<String> {
282        self.recordings.iter().map(Recording::id).collect()
283    }
284
285    fn load(&self, id: &str) -> Result<BTreeMap<String, Artifact>, String> {
286        let recording = self
287            .recording(id)
288            .ok_or_else(|| format!("no recording {id:?}"))?;
289        let mut loaded = self
290            .spec
291            .inputs
292            .iter()
293            .map(|input| {
294                let series = self
295                    .load_input(input, recording)
296                    .map_err(|e| format!("input {:?}: {e}", input.name))?;
297                Ok((input.name.clone(), series))
298            })
299            .collect::<Result<BTreeMap<_, _>, String>>()?;
300        if let (Some(spec), Some(table)) = (&self.spec.channels, &self.channels) {
301            loaded.insert(spec.name.clone(), Artifact::Channels(table.clone()));
302        }
303        Ok(loaded)
304    }
305}
306
307/// Reads `SamplingFrequency` (Hz) or `RepetitionTime` (s) from a BIDS JSON sidecar.
308fn sidecar_rate(path: &Path) -> Result<f64, String> {
309    let text =
310        std::fs::read_to_string(path).map_err(|e| format!("sidecar {}: {e}", path.display()))?;
311    let json: serde_json::Value =
312        serde_json::from_str(&text).map_err(|e| format!("sidecar {}: {e}", path.display()))?;
313    if let Some(hz) = json.get("SamplingFrequency").and_then(|v| v.as_f64()) {
314        return Ok(hz);
315    }
316    if let Some(tr) = json.get("RepetitionTime").and_then(|v| v.as_f64()) {
317        return Ok(1.0 / tr);
318    }
319    Err(format!(
320        "sidecar {} has neither SamplingFrequency nor RepetitionTime",
321        path.display()
322    ))
323}
324
325/// One channel label per non-empty line.
326fn read_labels(path: &Path) -> Result<Vec<String>, String> {
327    let text = std::fs::read_to_string(path)
328        .map_err(|e| format!("labels file {}: {e}", path.display()))?;
329    Ok(text
330        .lines()
331        .map(str::trim)
332        .filter(|l| !l.is_empty())
333        .map(String::from)
334        .collect())
335}