1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//! # exg — EEG/ECG/EMG preprocessing in pure Rust
//!
//! [](https://crates.io/crates/exg)
//! [](https://docs.rs/exg)
//!
//! `exg` is a pure-Rust library for EEG preprocessing with 100% numerical
//! parity against [MNE-Python](https://mne.tools). Every DSP step is ported
//! from MNE and verified against ground-truth test vectors (200+ tests).
//!
//! _No Python, no BLAS, no C libraries — pure Rust + [RustFFT](https://crates.io/crates/rustfft)._
//!
//! ## Workspace
//!
//! | Crate | Description |
//! |-------|-------------|
//! | **`exg`** | Core DSP, file I/O, generic preprocessing pipeline |
//! | **[`exg-luna`](https://crates.io/crates/exg-luna)** | LUNA seizure-detection pipeline |
//! | **[`exg-source`](https://crates.io/crates/exg-source)** | Source localisation (eLORETA, MNE/dSPM/sLORETA) |
//!
//! ## Features
//!
//! | Category | Capabilities |
//! |----------|-------------|
//! | **File I/O** | FIF, EDF/EDF+, CSV readers; HDF5 (feature-gated); safetensors export |
//! | **Filters** | Highpass, lowpass, bandpass, notch — all MNE-parity `_firwin_design` |
//! | **DSP** | FFT polyphase resampling, average reference, overlap-add convolution |
//! | **Normalisation** | Global z-score, channel-wise z-score, per-epoch baseline correction |
//! | **Montages** | TCP bipolar (22-ch), Siena unipolar (29-ch), SEED-V unipolar (62-ch) |
//! | **Pipelines** | Generic `preprocess()`, LUNA-specific via `exg-luna` crate |
//! | **Source localisation** | eLORETA, MNE/dSPM/sLORETA (via `exg-source` crate) |
//!
//! ## Quick start — generic pipeline
//!
//! ```no_run
//! use exg::{preprocess, PipelineConfig, fiff::open_raw};
//! use ndarray::Array2;
//!
//! let raw = open_raw("data/sample1_raw.fif").unwrap();
//! let data = raw.read_all_data().unwrap();
//! let chan_pos: Array2<f32> = Array2::zeros((raw.info.n_chan, 3));
//! let cfg = PipelineConfig::default(); // 256 Hz · 0.5 Hz HP · 5 s epochs
//! let epochs = preprocess(data.mapv(|v| v as f32), chan_pos, raw.info.sfreq as f32, &cfg).unwrap();
//! ```
//!
//! ## Quick start — LUNA seizure-detection pipeline
//!
//! The LUNA pipeline lives in the separate [`exg-luna`](https://crates.io/crates/exg-luna) crate:
//!
//! ```ignore
//! use exg::edf::open_raw_edf;
//! use exg_luna::{preprocess_luna, LunaPipelineConfig};
//!
//! let raw = open_raw_edf("recording.edf").unwrap();
//! let data = raw.read_all_data().unwrap();
//! let ch_names = raw.channel_names();
//! let cfg = LunaPipelineConfig::default(); // 0.1–75 Hz BP · 60 Hz notch · TCP montage
//! let epochs = preprocess_luna(data, &ch_names, raw.header.sample_rate, &cfg).unwrap();
//! ```
//!
//! ## Individual DSP steps
//!
//! ```no_run
//! use exg::{resample::resample, filter::*, reference::*, normalize::*, epoch::*};
//! use ndarray::Array2;
//!
//! let mut data: Array2<f32> = Array2::zeros((22, 7680));
//!
//! // Resample 512 → 256 Hz
//! let mut data = resample(&data, 512.0, 256.0).unwrap();
//!
//! // Bandpass 0.1–75 Hz
//! let h = design_bandpass(0.1, 75.0, 256.0);
//! apply_fir_zero_phase(&mut data, &h).unwrap();
//!
//! // Notch 60 Hz
//! let h = design_notch(60.0, 256.0, None, None);
//! apply_fir_zero_phase(&mut data, &h).unwrap();
//!
//! // Average reference → channel-wise z-score → epoch
//! average_reference_inplace(&mut data);
//! zscore_channelwise_inplace(&mut data);
//! let epochs = epoch(&data, 1280); // [E, 22, 1280]
//! ```
/// EEG source localization (MNE / dSPM / sLORETA / eLORETA).
///
/// This module re-exports the [`exg_source`] crate. It is available when
/// the **`source`** feature is enabled (on by default).
///
/// Disable it with `default-features = false` if you only need preprocessing:
///
/// ```toml
/// [dependencies]
/// exg = { version = "0.0.3", default-features = false }
/// ```
pub use exg_source as source_localization;
use Result;
use Array2;
// ── Crate-root re-exports ─────────────────────────────────────────────────
//
// Everything a downstream user is likely to need is available directly as
// `exg::Foo` without having to know the internal module layout.
// config
pub use PipelineConfig;
// csv
pub use read_eeg;
// edf
pub use ;
// epoch
pub use ;
// fiff — measurement info, raw reader, tag I/O, tree, constants
pub use ;
// filter — design helpers + convolution
pub use ;
// hdf5 — HDF5 dataset reader (feature-gated)
pub use ;
// io — safetensors helpers
pub use ;
// montage
pub use ;
// normalize
pub use ;
// reference
pub use average_reference_inplace;
// resample — resampler + supporting math
pub use ;
// source_localization — inverse modeling (MNE / dSPM / sLORETA / eLORETA)
pub use ;
/// Run the **full EEG preprocessing pipeline** on a single continuous recording.
///
/// This is the main entry point for the `exg` library. It chains all
/// preprocessing steps in the exact order used to train the model and
/// matches the MNE-Python reference implementation to within floating-point
/// rounding error (< 4 × 10⁻⁶ on typical EEG data).
///
/// # Pipeline steps
///
/// 1. Zero-fill channels listed in [`PipelineConfig::bad_channels`].
/// 2. Resample from `src_sfreq` to [`PipelineConfig::target_sfreq`] (FFT polyphase).
/// 3. Apply a zero-phase highpass FIR filter at [`PipelineConfig::hp_freq`].
/// 4. Subtract the per-timepoint channel mean (average reference).
/// 5. Apply global z-score normalisation (`ddof = 0`).
/// 6. Split into non-overlapping epochs of [`PipelineConfig::epoch_samples()`] samples
/// and apply per-epoch per-channel baseline correction.
/// 7. Divide each epoch by [`PipelineConfig::data_norm`].
///
/// # Arguments
///
/// * `data` – Raw EEG signal, shape `[C, T]`, in original units (volts).
/// Must have at least `cfg.epoch_samples()` columns; shorter recordings
/// produce zero epochs.
/// * `chan_pos` – Channel positions in **metres**, shape `[C, 3]`.
/// Returned unchanged alongside each epoch so downstream code
/// has direct access to spatial layout.
/// * `src_sfreq` – Sampling rate of `data` in Hz.
/// * `cfg` – Pipeline configuration (see [`PipelineConfig`]).
///
/// # Returns
///
/// A `Vec` of `(epoch_data, chan_pos)` tuples:
/// * `epoch_data` — shape `[C, cfg.epoch_samples()]`, `f32`.
/// * `chan_pos` — the original `chan_pos` argument (cloned, `f32`).
///
/// The length of the `Vec` is `floor(T_resampled / cfg.epoch_samples())`.
/// Trailing samples that do not fill a complete epoch are discarded.
///
/// # Errors
///
/// Returns an error if:
/// * The resampler fails (e.g. zero-length input).
/// * The FIR convolution fails (internal FFT planner error, extremely rare).
///
/// # Examples
///
/// ```no_run
/// use exg::{preprocess, PipelineConfig};
/// use ndarray::Array2;
///
/// // 12-channel, 15-second recording at 256 Hz
/// let data: Array2<f32> = Array2::zeros((12, 3840));
/// let chan_pos: Array2<f32> = Array2::zeros((12, 3));
///
/// let cfg = PipelineConfig::default();
/// let epochs = preprocess(data, chan_pos, 256.0, &cfg).unwrap();
/// assert_eq!(epochs.len(), 2); // floor(3840 / 1280) = 2 (baseline uses 1 epoch's worth)
/// ```
/// Zero-fill channels whose normalised name appears in `bad`.
///
/// Name normalisation: lowercase + strip spaces.
/// Silently skips names not found in `ch_names`.