Metadata-Version: 2.4
Name: optopro
Version: 0.1.0
Summary: fNIRS and EEG analysis for OptoHive recordings: responses, statistics and brain maps.
Author: OptoHive
License-Expression: BSD-3-Clause AND MIT
Project-URL: Repository, https://github.com/optohive/optopro
Project-URL: Documentation, https://github.com/optohive/optopro#readme
Project-URL: Issues, https://github.com/optohive/optopro/issues
Project-URL: Changelog, https://github.com/optohive/optopro/blob/main/CHANGELOG.md
Keywords: fNIRS,EEG,neuroimaging,haemodynamic response,OptoHive,cedalion,MNE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.13
Requires-Dist: pandas>=2.2
Requires-Dist: xarray>=2024.7
Requires-Dist: matplotlib>=3.9
Requires-Dist: h5py>=3.11
Requires-Dist: mne>=1.8
Requires-Dist: antio
Requires-Dist: scikit-learn>=1.5
Requires-Dist: statsmodels>=0.14.2
Requires-Dist: joblib
Requires-Dist: threadpoolctl
Requires-Dist: tqdm
Requires-Dist: pooch
Requires-Dist: snirf>=0.8
Requires-Dist: pint
Requires-Dist: pint-xarray<0.5,>=0.4
Requires-Dist: pywavelets>=1.6
Requires-Dist: scikit-image>=0.24
Requires-Dist: networkx
Requires-Dist: nibabel>=5.2
Requires-Dist: strenum
Requires-Dist: pyvista>=0.44
Requires-Dist: trimesh>=4.4
Requires-Dist: rtree
Requires-Dist: nest_asyncio
Requires-Dist: pmcxcl>=0.3.1
Requires-Dist: ipykernel
Requires-Dist: pytest
Requires-Dist: nbformat
Requires-Dist: nbclient
Dynamic: license-file

# OptoPro

fNIRS and EEG analysis for OptoHive recordings, from the raw recording to responses,
statistics and brain maps. fNIRS is built on [cedalion](https://github.com/ibs-lab/cedalion)
(the parts used come with the library), EEG on [MNE](https://mne.tools):

- **`fNIRSPro`** takes a SNIRF recording from raw light intensity to the haemodynamic
  response (HbO / HbR) per task;
- **`EEGPro`** takes an EEG recording (any format MNE reads, ANT Neuro's `.cnt` included)
  to band power per task, or to event-related potentials;
- **`GroupPro`** and **`Multimodal`** compare many subjects, and fNIRS with EEG.

Every step is one call that can be switched on or off, inspected and plotted before and
after, and every result records how it was made.

> **License:** BSD 3-Clause, see [LICENSE](https://github.com/optohive/optopro/blob/main/LICENSE); code adapted from other projects
> keeps its own, see [THIRD_PARTY_NOTICES.md](https://github.com/optohive/optopro/blob/main/THIRD_PARTY_NOTICES.md). The test data:
> OptoHive's recordings CC BY 4.0, the public EEG data ODC-By (see `data/`).

## Install

```bash
pip install optopro
```

That is all, on Python 3.11 or newer. It also works in an environment that already has
numpy, SciPy, MNE and the like: the library only needs recent versions of them and leaves
newer ones as they are.

The tutorials and test data are in the repository: clone it and run `pip install -e .`
inside, which installs the library from the clone. Step by step from a blank machine:
[SETUP.md](https://github.com/optohive/optopro/blob/main/SETUP.md).

## Quick start

**fNIRS:**

```python
from optopro import fNIRSPro, Params, read_snirf

rec = read_snirf("data/fnirs/finger_tapping_hair_tool.snirf")[0]   # its blocks in rec.stim (see Your own recordings)
o = fNIRSPro(rec, Params(subject_age=30)).interpolate().snr().cv().cardiac().sci().psp()   # the quality checks
tasks = ["left tapping", "right tapping"]
both = o.copy().filter("conc", (0.01, 0)).scr().glm(trial_types=tasks)   # remove the scalp signal: SCR, then the GLM
glm = o.copy().filter("conc", (0.01, 0)).glm(trial_types=tasks)          # or the GLM alone
scr = o.copy().filter("conc", (0.01, 0.5)).scr()                         # or SCR alone, a quick look

both.plot_response("SL16DL15", "right tapping")   # one channel's response beside the brain map
both.statistics("right tapping")                  # per channel: does it respond?
```

**EEG:**

```python
from optopro import EEGPro, EEGParams, read_eeg

e = EEGPro(read_eeg("session.cnt"), params=EEGParams(line_freq=50.0))
e.filter((1, 45)).bad_channels().notch().reference()
e.ica()                                         # eye, muscle and heart components
e.plot_response("O1", "focus", band="alpha", baseline="rest")
e.statistics("focus", compare="rest", band="alpha")
```

## Tutorials

On the test data in `data/`; open one, pick the environment's kernel, *Run All*.

1. **[tutorial_fNIRSPro.ipynb](https://github.com/optohive/optopro/blob/main/tutorial/tutorial_fNIRSPro.ipynb)**, start here: the whole
   fNIRS pipeline on a finger-tapping recording, what every step changes, and the responses.
2. **[tutorial_EEGPro.ipynb](https://github.com/optohive/optopro/blob/main/tutorial/tutorial_EEGPro.ipynb):** the EEG pipeline on public
   data, eyes open against eyes closed, to the alpha rhythm it ends with.
3. **[tutorial_Statistics.ipynb](https://github.com/optohive/optopro/blob/main/tutorial/tutorial_Statistics.ipynb):** the statistics on
   two finger-tapping recordings of one head (`data/fnirs`): one recording
   across its blocks, two against each other, and the two as a small group; which test
   each call runs, and what t, p and q say.
4. **[experimental/tutorial_GroundTruth.ipynb](https://github.com/optohive/optopro/blob/main/tutorial/experimental/tutorial_GroundTruth.ipynb):** testing a
   pipeline against a known answer: the Monte Carlo simulation and its sensitivity map, a
   response added to a real recording, and how each setting does on it (experimental; about
   10 minutes).
5. **[experimental/tutorial_LayoutDesign.ipynb](https://github.com/optohive/optopro/blob/main/tutorial/experimental/tutorial_LayoutDesign.ipynb):** where to
   put the optodes for a brain region: candidate positions over the whole head simulated once,
   layouts chosen and scored by how well DOT places known responses, the cap's positions in the
   region against designed ones, and where each optode goes in 10-10 terms (experimental).
6. **[experimental/tutorial_DOT.ipynb](https://github.com/optohive/optopro/blob/main/tutorial/experimental/tutorial_DOT.ipynb):**
   DOT, an image of where a response lies, on the real tapping and against a known response
   (experimental).

## fNIRS: fNIRSPro

`fNIRSPro` holds the recording as three stages, each computed from the one before when
first used:

| Stage | What it is | Steps that apply to it |
|---|---|---|
| `o.amp` | light intensity | `interpolate()`, `snr()`, `sci()`, `psp()`; `backlight_correction()`, not by default |
| `o.od` | optical density | `tddr()` |
| `o.conc` | HbO / HbR concentration | `scr()` then `glm()`; or either alone |
| any stage | | `filter(stage, (fmin, fmax))` |

| Step | What it does |
|---|---|
| `backlight_correction()` | subtracts the device's backlight reading (`amp_02`) on every channel; not settled yet, since it reads negative on about a third of the channels |
| `interpolate()` | interpolates missing samples and samples at or below zero, which optical density (a logarithm) cannot take; drops a channel where one stretch lasts longer than 1 s or they are more than 5% of it |
| `snr(threshold=20)` | drops channels whose signal-to-noise ratio (mean over standard deviation, per 10 s window) is below 20 in more than 30% of the windows, at any wavelength |
| `cv(threshold=0.15)` | drops channels with an unstable baseline, a coefficient of variation above 15% in more than 30% of 30 s windows, or a flat one (below 0.1%), at any wavelength |
| `cardiac(threshold=0.1)` | drops channels with less than 10% of their power in the heartbeat band, 0.5-2.5 Hz, at any wavelength |
| `sci(threshold=0.7)` | drops channels whose scalp coupling index (the mean over all wavelength pairs) is at or below 0.7 in more than 30% of the 5 s windows |
| `psp(threshold=0.05)` | drops channels whose peak spectral power (cedalion's scale, where Pollonini's 0.1 is 0.05; the mean over all wavelength pairs) is below 0.05 in more than 30% of the 5 s windows |
| `tddr()` | corrects abrupt motion: spikes and steps (temporal derivative distribution repair) |
| `filter(stage, band)` | Butterworth, forwards and backwards; `band = (fmin, fmax)` in Hz, `fmax = 0` high-pass only, `fmin = 0` low-pass only. `amp` takes only a low-pass |
| `scr()` | subtracts the short channels from each long channel (non-negative least squares); after `filter("conc", (0.01, 0.5))` |
| `glm(trial_types)` | fits response, drift and scalp regressors and keeps the modelled response, whose shape it learns from the data (Gaussian bumps after each onset; `basis=` sets another); after `filter("conc", (0.01, 0))`. Name the task conditions (a list, or one as a string): the rest is the baseline. The response is modelled to 12 s after each block, the drift up to half the design's high-pass, min(0.01 Hz, 1/(2T)) with T one block and its rest |

- **A step runs when called**, prints what it did, and applies once. `o.copy()` gives an
  independent fork, so one preprocessing can branch into several analyses.
- **Changing a stage recomputes the ones after it**, so apply the steps in stage order;
  every error names the step or call that fixes it.
- **SCI and PSP compare two wavelengths**, so `pairs=` says which: `"mean"` of the three
  pairs (default), the worst (`"min"`), the best (`"max"`), or one, e.g. `(810, 850)`.
- **Optional, for recordings with much movement:** `blissard()` (continuous motion, on
  `od`) and `glm(..., tcca=True)` (scalp and motion regressors from the IMU), both slow:
  see [EXTRAS.md](https://github.com/optohive/optopro/blob/main/EXTRAS.md).

### Every step is yours

No step runs unless you call it; the defaults are where to start. The same steps and
parameters for every recording keep differences between recordings from being differences
in processing, and `GroupPro` refuses subjects processed differently. Two steps are left out
of the examples on purpose: `backlight_correction()`, since the device's reference reads
negative on about a third of the channels, which light cannot, so what it holds is not
settled yet; and `tddr()`, which repairs abrupt motion but also shrinks every slow response.

```python
o = fNIRSPro(rec, Params(subject_age=30)).interpolate().snr().cv().cardiac().sci().psp()
o.steps()                          # each step: its stage, function, library version, parameters
both.recipe                        # the calls that built both, with every argument
fNIRSPro(other, both.params).run(both.recipe)     # the same, on another recording
```

A recipe of your own is a list of `(step, arguments)` pairs, e.g.
`[("interpolate", {}), ("snr", dict(threshold=3)), ("tddr", {})]`.

### Removing the scalp signal: SCR then GLM, by default

SCR removes the scalp, then the GLM fits the responses to what is left, without a scalp
regressor of its own. This is the default; the GLM alone and SCR alone are the alternatives,
each on its own copy. High-pass only before the GLM, since its noise model needs the fast
fluctuations:

```python
tasks = ["left tapping", "right tapping"]
both = o.copy().filter("conc", (0.01, 0)).scr().glm(trial_types=tasks)   # SCR, then the GLM: the default
glm = o.copy().filter("conc", (0.01, 0)).glm(trial_types=tasks)          # the GLM alone, with its own scalp regressor
scr = o.copy().filter("conc", (0.01, 0.5)).scr()                         # SCR alone: seconds, a quick look
```

Which correction suits a study is your decision; [tutorial_GroundTruth.ipynb](https://github.com/optohive/optopro/blob/main/tutorial/experimental/tutorial_GroundTruth.ipynb)
tests them on known responses added to a real recording.

To compare two of them, all from the same `conc`:

```python
scr.plot_response("SL16DL15", "right tapping", compare=glm)   # both curves and both maps in one figure
```

### Looking at the result

| Call | Shows |
|---|---|
| `o.plot_stage("od")` | a few channels of a stage as it is now |
| `o.plot_compare(before)` | one channel before and after the steps applied since `before = o.copy()` |
| `o.plot_compare([scr, glm, both])` | one channel in several pipelines, all on one graph |
| `o.quality()` | per channel: SNR, CV, cardiac share, SCI and PSP; `o.quality("sci")` one measure per window |
| `o.plot_montage()` | the optodes and channels on the head: in use, dropped by a step (red), outside the distance bands (blue) |
| `o.activation(task)` | each channel's block value: its mean response from 3 s after the onset to 3 s after the block, minus up to 5 s before, in µM |
| `o.statistics(task, compare=)` | per channel, whether it responds: on the GLM's contrast after a block-design `glm()`, across the blocks otherwise (see [Statistics](#statistics)) |
| `o.statistics(task, compare=, beta=False)` | across the blocks even after `glm()`; `beta=True` asks for the GLM's contrast (see [STATISTICS.md](STATISTICS.md)) |
| `o.plot_response(channel, task)` | the block-averaged HbO and HbR beside a map of every channel's response on the cortex, the channel in green. `compare=` adds another task, another analysis (`compare=glm`) or another recording; `head=` picks the views, from "front", "top", "back", "left", "right" |
| `o.export_responses(path, task)` | `plot_response` for every channel, as a PDF |

Each step is also a plain function in `optopro/fnirs/processing.py`, usable without
the class.

## EEG: EEGPro

`EEGPro` is `fNIRSPro`'s counterpart for EEG: it holds an MNE `Raw`, uses MNE's own
methods for its steps, and shares `steps()`, `recipe` and `run()`.

| Step | What it does |
|---|---|
| `filter((1, 45))` | band-pass, in Hz |
| `bad_channels()` | interpolates flat channels and outliers among their neighbours; after `filter()`, or the blinks flag the frontal channels |
| `notch()` | removes the mains frequency (`EEGParams(line_freq=50.0)` in Europe) |
| `reference()` | the average reference |
| `ica()` | removes eye, muscle and heart components (MNE's ICA and its detectors) |
| `csd()` | optional: current source density, sharper maps; after the ICA |
| `rejection()` | drops segments with outlying amplitudes |

**Reading.** `read_eeg(path)` reads every format MNE reads and ANT Neuro's `.cnt`, and
says which companion files it found (ANT's `.evt` and `.seg`, BrainVision's `.vmrk`).
For a whole session with several tasks:

| | |
|---|---|
| `inspect_eeg(path)` | what the files hold, without loading the signal: the recording, its segments, the triggers per task |
| `eeg_triggers(raw)` | the named triggers as a table: event and stream (the task that sent it) |
| `split_tasks(raw, blocks=)` | cuts the session into one `Raw` per task, and turns each task's triggers into blocks |

```python
parts = split_tasks(read_eeg("session.cnt"), sfreq=250,
                    blocks={"N0_BLOCK_START": ("0-back", 60.0),    # start event: (block,
                            "RS_START": ("rest", "RS_END")})       #   seconds or end event)
e = EEGPro(parts["N-back Triggers"])
```

**Block design or event-related.** Annotations with a duration are blocks, those
without are events:

| | block design | event-related |
|---|---|---|
| annotations | blocks with a duration (`0-back`, 60 s) | events, points in time (`TIMER_ONSET`) |
| unit | a 2 s segment of a block (`e.epochs`) | a trial around each event (`e.trials`) |
| measure | band power, in dB against another task | voltage, against the trial's own time before the event |
| plot | `plot_response(channel, task, band=)` | `plot_erp(channel, event)` |
| statistics | `statistics(task, compare=, band=)` | `statistics(event, compare=, window=(0.15, 0.25))` |

A method given a name of the other design stops and says which to use instead. Events get
their conditions with `label_events`, e.g. from a behavioural log:
`e.label_events("TIMER_ONSET", beh["delay_type"])`, then `e.plot_erp("Cz", "long",
compare="short")`. The MNE objects are at hand: `e.raw`, `e.epochs`, `e.trials`,
`e.spectrum`, `e.ica_fit`.

## Groups: GroupPro

`GroupPro` takes many subjects' pipelines, all `fNIRSPro` or all `EEGPro`, processed
alike: each subject reduces a task to one value per channel, and the statistics run
across subjects.

```python
from optopro import GroupPro

subjects = {sub: fNIRSPro(rec, PARAMS, name=sub).interpolate().snr().cv().cardiac().sci().psp()
                 .copy().filter("conc", (0.01, 0)).scr().glm(trial_types=["task", "control"])
            for sub, rec in recordings.items()}
controls = GroupPro(subjects, name="controls")

controls.statistics("task")                      # per channel, against 0
controls.statistics("task", compare="control")   # two tasks, paired within subjects
controls.statistics("task", compare=patients)    # two groups, Welch's t-test
controls.plot_response("S3D2", "task", compare="control")   # group mean ± SE, group map
```

- **The same processing for everyone:** the subjects' `recipe` must match.
- **Channels are matched by name** and analysed where at least `min_subjects` kept them
  (half the group, at least 2); `coverage()` shows who kept what.
- **Caps:** the OptoHive cap comes in several sizes, on which the same optode name sits
  in different places. `caps` says which cap each subject wears; per-channel analyses
  need one cap, regions (below) work across caps.
- **EEG groups** work the same way, on band power per electrode, or with `window=` on
  event-related potentials; `plot_erp` draws the group's.

## fNIRS and EEG together: Multimodal

`Multimodal` takes one group's fNIRS and EEG, a `GroupPro` of each, and compares the
subjects both have:

```python
from optopro import Multimodal

both = Multimodal(fnirs=controls_fnirs, eeg=controls_eeg)
both.statistics("task", compare="control", band="theta")        # both tables, in t
both.correlation("task", compare="control", band="theta")       # across subjects
both.plot_correlation("task", compare="control", band="theta")  # r on the brain
```

µM and dB cannot be compared, t can. The correlation asks whether a subject with a
stronger HbO change also shows a stronger band-power change: per fNIRS channel with the
electrode nearest to it, or per region.

## Regions

Every `statistics`, `activation` and `plot_response`, and `Multimodal.correlation`, takes
`regions=`: the channels are averaged per region first, and the tests run per region.
Fewer tests, so the correction for them costs less.

```python
from optopro import REGIONS

both.statistics("left tapping", compare="right tapping", regions=REGIONS)
both.plot_response("left central", "left tapping", regions=REGIONS)
both.plot_montage(regions=REGIONS)           # the montage, the cortex coloured by region
both.channel_regions(REGIONS)                # which channel belongs to which region
```

**A region is a list of 10-10 electrodes**, so fNIRS and EEG share one definition.
`REGIONS` is a coarse default, lobe and side (e.g. `"left central": ["C5", "C3", "C1",
"CP5", "CP3", "CP1"]`); a study defines the regions of its hypothesis, e.g.
`{"left DLPFC": ["F3", "F5", "AF3"]}`. An electrode belongs to the region that lists it;
an fNIRS channel to the region of the listed electrode nearest to its midpoint, within
30 mm. In `Multimodal`, `pairs=` pairs an fNIRS region with another EEG region, for an EEG
that does not cover it, e.g. `pairs={"left frontal": "midline frontal"}`.

## Statistics

Every `statistics()` tests each channel, electrode or region on one value per block,
segment, trial or subject: a one-sample t-test against 0, a paired t-test within
subjects, or Welch's t-test between independent sets, then corrects across channels for
the false-discovery rate (q). Which call runs which test, the formulas and what each
assumes: [STATISTICS.md](https://github.com/optohive/optopro/blob/main/STATISTICS.md). One recording's blocks are not independent
subjects: for a study, test across subjects with `GroupPro`.

## Your own recordings

- **fNIRS:** any SNIRF file, `read_snirf(path)[0]`. **EEG:** any file MNE reads, or ANT
  Neuro's `.cnt`, `read_eeg(path)`.
- **Settings:** `Params(subject_age=30)` (for the differential pathlength factor; also
  the short and long distance bands, 5–10 and 20–40 mm), `EEGParams(line_freq=50.0)`.
- **The blocks**, one table for responses, maps and the GLM: `rec.stim` for `fNIRSPro`,
  `stim=` (or the file's own annotations) for `EEGPro`, in exactly this form:

```
       onset  duration  value   trial_type
0     44.020      15.0    1.0  TempCompOff
1     79.020      15.0    1.0  TempCompOff
2    638.195      15.0    1.0   TempCompOn
```

| column | meaning |
|---|---|
| `onset` | when the block starts, in seconds from the recording's start |
| `duration` | how long it lasts, in seconds |
| `value` | the block's height in the GLM's regressor, normally `1.0` |
| `trial_type` | the condition |

The library does not guess how your markers make blocks: that depends on the protocol.
Both pipelines check the table and say what is wrong. Where it comes from:

- **Already in this form:** `read_snirf` puts it in `rec.stim`.
- **Event markers**, e.g. one `N0_BLOCK_START` per block: keep the starts and give each
  its length from the protocol (`duration = 60.0`), the condition from the marker's name.
- **A trigger log:** `read_trigger_log(path, rec, blocks)` reads a NIRx/LSL log, e.g.
  `blocks={"CALIB_BLOCK": "letters", "CALIB_REST": "rest_calib"}`.
- **A BIDS events file:** `pd.read_csv(path, sep="\t")`, adding `value` (1.0).

## Things to know

- **The first brain map downloads the standard head** (ICBM152, 15 MB, 150 MB unpacked, cached).
- **The GLM is the slow step:** about 10 s on the 9-minute test recording, about 2 minutes on
  a 20-minute recording with 100 channels. It fits every channel with an
  autocorrelation-corrected model.
- **The quality checks let 30% of the windows fail** by default (`max_fraction=0.3`);
  `max_fraction=0` drops a channel at its first bad window. They judge every wavelength
  (pair), 735 nm included, so they keep fewer channels than checks on 810 and 850 nm alone.
- **SCR and GLM can disagree:** they use different filters, scalp models and response
  shapes.
- **Plan enough blocks per condition:** the tests run across the blocks, so a few blocks
  can only show large responses. `tutorial_GroundTruth.ipynb` tests it with 10.
- **HbR is harder to find than HbO:** its change is a few times smaller, so with 10
  blocks it rarely reaches significance where HbO does.
