mindmap-fascicle 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. mindmap_fascicle-0.1.0/.gitignore +19 -0
  2. mindmap_fascicle-0.1.0/LICENSE +3 -0
  3. mindmap_fascicle-0.1.0/PKG-INFO +191 -0
  4. mindmap_fascicle-0.1.0/README.md +155 -0
  5. mindmap_fascicle-0.1.0/pyproject.toml +57 -0
  6. mindmap_fascicle-0.1.0/src/fascicle/__init__.py +8 -0
  7. mindmap_fascicle-0.1.0/src/fascicle/config.py +54 -0
  8. mindmap_fascicle-0.1.0/src/fascicle/datatype.py +69 -0
  9. mindmap_fascicle-0.1.0/src/fascicle/extension.py +88 -0
  10. mindmap_fascicle-0.1.0/src/fascicle/extensions/__init__.py +7 -0
  11. mindmap_fascicle-0.1.0/src/fascicle/extensions/charm.py +100 -0
  12. mindmap_fascicle-0.1.0/src/fascicle/extensions/freesurfer.py +176 -0
  13. mindmap_fascicle-0.1.0/src/fascicle/extensions/mne.py +154 -0
  14. mindmap_fascicle-0.1.0/src/fascicle/formats.py +110 -0
  15. mindmap_fascicle-0.1.0/src/fascicle/manager.py +346 -0
  16. mindmap_fascicle-0.1.0/src/fascicle/naming.py +242 -0
  17. mindmap_fascicle-0.1.0/src/fascicle/utils.py +117 -0
  18. mindmap_fascicle-0.1.0/tests/conftest.py +91 -0
  19. mindmap_fascicle-0.1.0/tests/test_config.py +98 -0
  20. mindmap_fascicle-0.1.0/tests/test_ext_charm.py +134 -0
  21. mindmap_fascicle-0.1.0/tests/test_ext_freesurfer.py +240 -0
  22. mindmap_fascicle-0.1.0/tests/test_ext_mne.py +134 -0
  23. mindmap_fascicle-0.1.0/tests/test_extension.py +129 -0
  24. mindmap_fascicle-0.1.0/tests/test_formats.py +195 -0
  25. mindmap_fascicle-0.1.0/tests/test_manager.py +555 -0
  26. mindmap_fascicle-0.1.0/tests/test_naming.py +203 -0
  27. mindmap_fascicle-0.1.0/tests/test_pickle.py +19 -0
  28. mindmap_fascicle-0.1.0/tests/test_utils.py +109 -0
@@ -0,0 +1,19 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .ipynb_checkpoints/
6
+ dist/
7
+ build/
8
+
9
+ # Downloaded example data (fetched at runtime by the tutorial notebook,
10
+ # not tracked in the repo)
11
+ examples/data/
12
+
13
+ # editor and OS
14
+ .vscode
15
+
16
+ # Claude
17
+ CLAUDE.md
18
+ ARCHITECTURE.md
19
+ PLAN.md
@@ -0,0 +1,3 @@
1
+ MIT License
2
+
3
+ (placeholder — full license text to be added)
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.5
2
+ Name: mindmap-fascicle
3
+ Version: 0.1.0
4
+ Summary: Read and write BIDS neuroimaging datasets, with extensions for FreeSurfer, SimNIBS charm and MNE-Python derivatives.
5
+ Project-URL: Homepage, https://github.com/NinoHerve/mindmap-fascicle
6
+ Project-URL: Repository, https://github.com/NinoHerve/mindmap-fascicle
7
+ Project-URL: Issues, https://github.com/NinoHerve/mindmap-fascicle/issues
8
+ Author-email: Herve Nino <herve.nino@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: BIDS,FreeSurfer,MNE,MRI,SimNIBS,derivatives,neuroimaging
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: nibabel
20
+ Requires-Dist: numpy
21
+ Requires-Dist: pandas>=2.0
22
+ Requires-Dist: pybids
23
+ Requires-Dist: pyyaml
24
+ Provides-Extra: all
25
+ Requires-Dist: mne; extra == 'all'
26
+ Provides-Extra: examples
27
+ Requires-Dist: antspyx; extra == 'examples'
28
+ Requires-Dist: jupyter; extra == 'examples'
29
+ Requires-Dist: matplotlib; extra == 'examples'
30
+ Requires-Dist: openneuro-py; extra == 'examples'
31
+ Provides-Extra: mne
32
+ Requires-Dist: mne; extra == 'mne'
33
+ Provides-Extra: test
34
+ Requires-Dist: pytest; extra == 'test'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # fascicle
38
+
39
+ Fascicle is a Python framework for reading, writing and managing neuroscience datasets. It is built around the BIDS standard and supports outputs from FreeSurfer, MNE-Python and SimNIBS.
40
+
41
+ The core of Fascicle reads and writes raw BIDS datasets. Extensions handle common neuroimaging derivatives, such as those from FreeSurfer, MNE-Python and SimNIBS CHARM. These extensions use the same small framework that you can use to write your own extensions, and you can replace any reader or writer with your own.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install mindmap-fascicle # raw BIDS + MRI/surfaces/tractograms, FreeSurfer, SimNIBS charm
47
+ pip install "mindmap-fascicle[mne]" # + MNE-Python source-analysis derivatives
48
+ ```
49
+
50
+ The package installs as `mindmap-fascicle` but is imported as `fascicle`.
51
+
52
+ ## Quickstart
53
+
54
+ ```python
55
+ from fascicle import DatasetManager
56
+ from fascicle.extensions import freesurfer, mne
57
+
58
+ dm = DatasetManager("/data/my_study/rawdata") # no config needed
59
+ dm.get_subjects() # ['01', '02', ...]
60
+
61
+ img = dm.load("01", "T1w", session="test") # nibabel image
62
+ dm.save(img, "01", "T1w", session="retest") # writes sub-01/ses-retest/anat/sub-01_ses-retest_T1w.nii.gz
63
+
64
+ dm.add_datatype("bold", "raw", dm.bids_namer("bold")) # any other raw BIDS suffix
65
+ bold = dm.load("01", "bold", session="test", task="rest")
66
+
67
+ freesurfer.register(dm, root_path="/data/my_study/derivatives/freesurfer")
68
+ lh_coords, lh_faces = dm.load("01", "fs-pial", hemi="lh")
69
+
70
+ mne.register(dm, root_path="/data/my_study/derivatives/mne")
71
+ dm.save(cov, "01", "mne-cov", task="rest") # sub-01/cov/sub-01_task-rest_cov.fif
72
+ ```
73
+
74
+ `dm.get_path(...)` takes the same arguments as `load` and returns the path without touching the file.
75
+
76
+ ## Concepts
77
+
78
+ - **Roots**: named folders (`dm.roots`). `"raw"` is the BIDS dataset; extensions add their own (`"fs"`, `"mne"`, ...) with `add_root`.
79
+ - **Datatypes**: every key in `dm.registry` (`"T1w"`, `"fs-pial"`, `"mne-cov"`) is a `Datatype` with
80
+ - a **namer**, `namer(root, subject, **inputs) -> Path`, which only builds the path, so the same namer works for loading and saving. Inputs are BIDS entities (`session`, `task`, ...) or tool-specific ones (`hemi`);
81
+ - a **reader**, `reader(path) -> data`;
82
+ - a **writer**, `writer(data, path)`.
83
+
84
+ A missing reader or writer means "use the one registered for the file extension". `dm.describe("fs-pial")` shows all of this for one key.
85
+ - **File extensions**: `dm.ext_readers` / `dm.ext_writers` map extensions to default readers/writers: nibabel for images and tractograms (`.nii`, `.nii.gz`, `.mgh`, `.mgz`, `.gii`, `.trk`, `.tck`), the standard library for `.json` sidecars (read as dicts), numpy for `.bval`/`.bvec`, and pandas for `.tsv`/`.tsv.gz` tables (read as DataFrames, with BIDS's `n/a` as missing values).
86
+ - **References**: single files outside any subject (templates, atlases, lookup tables) loaded with `load_ref`. Each reference is read by file extension unless you give it its own reader, with `add_reference(key, path, reader=...)` or, for references from the config file, `set_ref_reader(key, reader)`. References have no writer: they're inputs, not outputs.
87
+ - **Config file** (optional): the declarative way to set up roots and references:
88
+
89
+ ```yaml
90
+ DIR_RAW: /data/my_study/rawdata # -> "raw" root (a raw_root argument wins if both are given)
91
+ DIR_TEMPLATES: /data/templates # available as dm.config["DIR_TEMPLATES"] for add_root
92
+ MRI_REF: /data/templates/MNI152.nii.gz # any key containing "REF" becomes a reference: dm.load_ref("MRI_REF")
93
+ ```
94
+
95
+ `DatasetManager(config="config.yaml")`. Reading a config with `env=True` (the `read_config` default) also exports every top-level key as an environment variable.
96
+
97
+ `save` refuses to replace an existing file unless you pass `overwrite=True`, creates missing folders, and raises `TypeError` for read-only datatypes.
98
+
99
+ ## Extensions
100
+
101
+ | extension | keys (default prefix) | extra dependency |
102
+ |---|---|---|
103
+ | `fascicle.extensions.freesurfer` | `fs-t1`, `fs-brain`, `fs-orig`, `fs-aseg`, `fs-white`/`pial`/`inflated`/`sphere`, `fs-area`/`curv`/`thickness`/`sulc`, `fs-cortex` (read-only), `fs-ras2tkras` (read-only) | none |
104
+ | `fascicle.extensions.charm` | `charm-seg`, `charm-t1` | none |
105
+ | `fascicle.extensions.mne` | `mne-src`, `mne-fwd`, `mne-ave`, `mne-i-ave`, `mne-v-ave`, `mne-cov`, `mne-stc` | `mne` |
106
+
107
+ Every extension has the same `register(dm, root_key=..., root_path=None, namespace=None, readers=None, writers=None)`. Keys are prefixed with `namespace`, which defaults to `root_key`. To compare two FreeSurfer runs, register twice: `freesurfer.register(dm, root_key="fs_run2", root_path=...)` gives `fs_run2-t1`, ...
108
+
109
+ ## Swapping a reader or writer
110
+
111
+ ```python
112
+ import ants
113
+
114
+ def ants_reader(path):
115
+ return ants.image_read(str(path))
116
+
117
+ # One datatype:
118
+ dm.set_reader("T1w", ants_reader)
119
+ freesurfer.register(dm, root_path=..., readers={"t1": ants_reader}) # at registration
120
+
121
+ # Every file of one type (raw BIDS, FreeSurfer, charm, ... alike):
122
+ dm.add_extension(".nii.gz", reader=ants_reader)
123
+ ```
124
+
125
+ `set_writer`, `writers={...}` and `add_extension(..., writer=...)` work the same way. Mark a datatype read-only with `Datatype.READ_ONLY` as its writer.
126
+
127
+ ## Writing your own extension
128
+
129
+ An extension is a table of `Datatype`s plus a `register` function. This is exactly how the built-in extensions are written. For BIDS-style names, build the namers with `derivative_namer`:
130
+
131
+ ```python
132
+ # my_lab/resection.py
133
+ from fascicle import Datatype, derivative_namer, register_extension
134
+
135
+
136
+ def read_notes(path):
137
+ return path.read_text()
138
+
139
+
140
+ def write_notes(text, path):
141
+ path.write_text(text)
142
+
143
+
144
+ DATATYPES = {
145
+ # nibabel by extension; the .json sidecar goes through the JSON reader/writer
146
+ "mask": Datatype(derivative_namer("mask", datatype="anat", extensions=(".nii.gz", ".json"))),
147
+ "notes": Datatype(
148
+ derivative_namer("notes", datatype="anat", extensions=(".txt",), entities=("session", "desc")),
149
+ read_notes,
150
+ write_notes,
151
+ ),
152
+ }
153
+
154
+
155
+ def register(dm, root_key="resec", root_path=None, namespace=None, readers=None, writers=None):
156
+ register_extension(dm, DATATYPES, root_key=root_key, root_path=root_path,
157
+ namespace=namespace, readers=readers, writers=writers)
158
+ ```
159
+
160
+ ```python
161
+ resection.register(dm, root_path="/data/my_study/derivatives/resection")
162
+ dm.save(mask_img, "01", "resec-mask", session="postop", desc="manual")
163
+ # -> derivatives/resection/sub-01/ses-postop/anat/sub-01_ses-postop_desc-manual_mask.nii.gz
164
+ mask = dm.load("01", "resec-mask", session="postop", desc="manual")
165
+ ```
166
+
167
+ ### BIDS-style names with `derivative_namer`
168
+
169
+ `derivative_namer(suffix, datatype=None, extensions=(".nii.gz",), entities=None, extra_entities=(), fixed=None)` accepts any suffix, folder and extension:
170
+
171
+ - **`datatype`** is the folder under `sub-XX[/ses-YY]/`. Pass `None` to put files directly in it.
172
+ - **`extensions`**: the first one is the default; ask for another with `extension=`, e.g. a `.json` sidecar. `None` builds extensionless stems.
173
+ - **`entities`** restricts which BIDS entities the datatype takes. By default it takes all of them, using pybids' names (`session`, `acquisition`, `desc`, ...).
174
+ - **`extra_entities=("cut",)`** adds your own entities, written as `_cut-<value>` just before `desc`.
175
+ - **`fixed={"signal": "virtual"}`** gives an entity one value for this datatype: it's always written and callers can't pass it. Use it to give variants of a file their own keys while keeping one suffix. For example, the MNE extension's `mne-i-ave` / `mne-v-ave` are `ave` files with `signal-intracranial` / `signal-virtual`.
176
+
177
+ Entities are always written in the BIDS spec's order, whatever order you pass them in. Anything the namer wasn't declared with raises `ValueError` instead of being dropped. So do values the spec forbids, such as `desc="brain-mask"`, `run="one"` or `hemi="lh"` (BIDS uses `L`/`R`). `fascicle.bids_pattern(...)` shows the pybids pattern a namer fills.
178
+
179
+ `dm.bids_namer(suffix)` is the raw-BIDS counterpart: it knows the raw spec (T1w lives in `anat/`, bold in `func/`), but only accepts raw suffixes and entities. A derivative entity such as `desc` raises and points you to `derivative_namer`.
180
+
181
+ Namers don't have to be BIDS-style: any `namer(root, subject, **inputs) -> Path` works (see `fascicle.extensions.freesurfer`). For a one-off datatype, skip the module: `dm.add_root(...)` and `dm.add_datatype(key, root_key, namer, reader, writer)`. You can also subclass `DatasetManager` and register everything in `__init__`.
182
+
183
+ ## Caveats
184
+
185
+ - **Not picklable.** `DatasetManager` wraps a `bids.BIDSLayout`, which can't be pickled. Don't pass a manager to `multiprocessing`/`joblib` workers. Resolve paths with `get_path` (or load data) in the parent process and pass those instead.
186
+ - **The BIDS index isn't refreshed after `save`.** Files you write are loadable by path straight away, but `get_subjects()` and `dm.layout` queries only see them in a new `DatasetManager`.
187
+ - **Extensions don't index their folders.** Namers build paths without looking at the disk, so they can write into folders that don't exist yet. For pybids queries on a derivatives folder, also call `dm.add_derivatives(key, path)` once it has a `dataset_description.json`. pybids doesn't parse custom entities (such as MNE's `signal`), so you can't filter on them in pybids queries; Fascicle's own `load`/`save` handle them fully.
188
+
189
+ ## Example
190
+
191
+ `examples/tutorial.ipynb` downloads one subject of OpenNeuro's `ds000114`, loads its T1w and BOLD with nibabel, then switches T1w to ANTsPy. Run `pip install -e ".[examples]"` first.
@@ -0,0 +1,155 @@
1
+ # fascicle
2
+
3
+ Fascicle is a Python framework for reading, writing and managing neuroscience datasets. It is built around the BIDS standard and supports outputs from FreeSurfer, MNE-Python and SimNIBS.
4
+
5
+ The core of Fascicle reads and writes raw BIDS datasets. Extensions handle common neuroimaging derivatives, such as those from FreeSurfer, MNE-Python and SimNIBS CHARM. These extensions use the same small framework that you can use to write your own extensions, and you can replace any reader or writer with your own.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install mindmap-fascicle # raw BIDS + MRI/surfaces/tractograms, FreeSurfer, SimNIBS charm
11
+ pip install "mindmap-fascicle[mne]" # + MNE-Python source-analysis derivatives
12
+ ```
13
+
14
+ The package installs as `mindmap-fascicle` but is imported as `fascicle`.
15
+
16
+ ## Quickstart
17
+
18
+ ```python
19
+ from fascicle import DatasetManager
20
+ from fascicle.extensions import freesurfer, mne
21
+
22
+ dm = DatasetManager("/data/my_study/rawdata") # no config needed
23
+ dm.get_subjects() # ['01', '02', ...]
24
+
25
+ img = dm.load("01", "T1w", session="test") # nibabel image
26
+ dm.save(img, "01", "T1w", session="retest") # writes sub-01/ses-retest/anat/sub-01_ses-retest_T1w.nii.gz
27
+
28
+ dm.add_datatype("bold", "raw", dm.bids_namer("bold")) # any other raw BIDS suffix
29
+ bold = dm.load("01", "bold", session="test", task="rest")
30
+
31
+ freesurfer.register(dm, root_path="/data/my_study/derivatives/freesurfer")
32
+ lh_coords, lh_faces = dm.load("01", "fs-pial", hemi="lh")
33
+
34
+ mne.register(dm, root_path="/data/my_study/derivatives/mne")
35
+ dm.save(cov, "01", "mne-cov", task="rest") # sub-01/cov/sub-01_task-rest_cov.fif
36
+ ```
37
+
38
+ `dm.get_path(...)` takes the same arguments as `load` and returns the path without touching the file.
39
+
40
+ ## Concepts
41
+
42
+ - **Roots**: named folders (`dm.roots`). `"raw"` is the BIDS dataset; extensions add their own (`"fs"`, `"mne"`, ...) with `add_root`.
43
+ - **Datatypes**: every key in `dm.registry` (`"T1w"`, `"fs-pial"`, `"mne-cov"`) is a `Datatype` with
44
+ - a **namer**, `namer(root, subject, **inputs) -> Path`, which only builds the path, so the same namer works for loading and saving. Inputs are BIDS entities (`session`, `task`, ...) or tool-specific ones (`hemi`);
45
+ - a **reader**, `reader(path) -> data`;
46
+ - a **writer**, `writer(data, path)`.
47
+
48
+ A missing reader or writer means "use the one registered for the file extension". `dm.describe("fs-pial")` shows all of this for one key.
49
+ - **File extensions**: `dm.ext_readers` / `dm.ext_writers` map extensions to default readers/writers: nibabel for images and tractograms (`.nii`, `.nii.gz`, `.mgh`, `.mgz`, `.gii`, `.trk`, `.tck`), the standard library for `.json` sidecars (read as dicts), numpy for `.bval`/`.bvec`, and pandas for `.tsv`/`.tsv.gz` tables (read as DataFrames, with BIDS's `n/a` as missing values).
50
+ - **References**: single files outside any subject (templates, atlases, lookup tables) loaded with `load_ref`. Each reference is read by file extension unless you give it its own reader, with `add_reference(key, path, reader=...)` or, for references from the config file, `set_ref_reader(key, reader)`. References have no writer: they're inputs, not outputs.
51
+ - **Config file** (optional): the declarative way to set up roots and references:
52
+
53
+ ```yaml
54
+ DIR_RAW: /data/my_study/rawdata # -> "raw" root (a raw_root argument wins if both are given)
55
+ DIR_TEMPLATES: /data/templates # available as dm.config["DIR_TEMPLATES"] for add_root
56
+ MRI_REF: /data/templates/MNI152.nii.gz # any key containing "REF" becomes a reference: dm.load_ref("MRI_REF")
57
+ ```
58
+
59
+ `DatasetManager(config="config.yaml")`. Reading a config with `env=True` (the `read_config` default) also exports every top-level key as an environment variable.
60
+
61
+ `save` refuses to replace an existing file unless you pass `overwrite=True`, creates missing folders, and raises `TypeError` for read-only datatypes.
62
+
63
+ ## Extensions
64
+
65
+ | extension | keys (default prefix) | extra dependency |
66
+ |---|---|---|
67
+ | `fascicle.extensions.freesurfer` | `fs-t1`, `fs-brain`, `fs-orig`, `fs-aseg`, `fs-white`/`pial`/`inflated`/`sphere`, `fs-area`/`curv`/`thickness`/`sulc`, `fs-cortex` (read-only), `fs-ras2tkras` (read-only) | none |
68
+ | `fascicle.extensions.charm` | `charm-seg`, `charm-t1` | none |
69
+ | `fascicle.extensions.mne` | `mne-src`, `mne-fwd`, `mne-ave`, `mne-i-ave`, `mne-v-ave`, `mne-cov`, `mne-stc` | `mne` |
70
+
71
+ Every extension has the same `register(dm, root_key=..., root_path=None, namespace=None, readers=None, writers=None)`. Keys are prefixed with `namespace`, which defaults to `root_key`. To compare two FreeSurfer runs, register twice: `freesurfer.register(dm, root_key="fs_run2", root_path=...)` gives `fs_run2-t1`, ...
72
+
73
+ ## Swapping a reader or writer
74
+
75
+ ```python
76
+ import ants
77
+
78
+ def ants_reader(path):
79
+ return ants.image_read(str(path))
80
+
81
+ # One datatype:
82
+ dm.set_reader("T1w", ants_reader)
83
+ freesurfer.register(dm, root_path=..., readers={"t1": ants_reader}) # at registration
84
+
85
+ # Every file of one type (raw BIDS, FreeSurfer, charm, ... alike):
86
+ dm.add_extension(".nii.gz", reader=ants_reader)
87
+ ```
88
+
89
+ `set_writer`, `writers={...}` and `add_extension(..., writer=...)` work the same way. Mark a datatype read-only with `Datatype.READ_ONLY` as its writer.
90
+
91
+ ## Writing your own extension
92
+
93
+ An extension is a table of `Datatype`s plus a `register` function. This is exactly how the built-in extensions are written. For BIDS-style names, build the namers with `derivative_namer`:
94
+
95
+ ```python
96
+ # my_lab/resection.py
97
+ from fascicle import Datatype, derivative_namer, register_extension
98
+
99
+
100
+ def read_notes(path):
101
+ return path.read_text()
102
+
103
+
104
+ def write_notes(text, path):
105
+ path.write_text(text)
106
+
107
+
108
+ DATATYPES = {
109
+ # nibabel by extension; the .json sidecar goes through the JSON reader/writer
110
+ "mask": Datatype(derivative_namer("mask", datatype="anat", extensions=(".nii.gz", ".json"))),
111
+ "notes": Datatype(
112
+ derivative_namer("notes", datatype="anat", extensions=(".txt",), entities=("session", "desc")),
113
+ read_notes,
114
+ write_notes,
115
+ ),
116
+ }
117
+
118
+
119
+ def register(dm, root_key="resec", root_path=None, namespace=None, readers=None, writers=None):
120
+ register_extension(dm, DATATYPES, root_key=root_key, root_path=root_path,
121
+ namespace=namespace, readers=readers, writers=writers)
122
+ ```
123
+
124
+ ```python
125
+ resection.register(dm, root_path="/data/my_study/derivatives/resection")
126
+ dm.save(mask_img, "01", "resec-mask", session="postop", desc="manual")
127
+ # -> derivatives/resection/sub-01/ses-postop/anat/sub-01_ses-postop_desc-manual_mask.nii.gz
128
+ mask = dm.load("01", "resec-mask", session="postop", desc="manual")
129
+ ```
130
+
131
+ ### BIDS-style names with `derivative_namer`
132
+
133
+ `derivative_namer(suffix, datatype=None, extensions=(".nii.gz",), entities=None, extra_entities=(), fixed=None)` accepts any suffix, folder and extension:
134
+
135
+ - **`datatype`** is the folder under `sub-XX[/ses-YY]/`. Pass `None` to put files directly in it.
136
+ - **`extensions`**: the first one is the default; ask for another with `extension=`, e.g. a `.json` sidecar. `None` builds extensionless stems.
137
+ - **`entities`** restricts which BIDS entities the datatype takes. By default it takes all of them, using pybids' names (`session`, `acquisition`, `desc`, ...).
138
+ - **`extra_entities=("cut",)`** adds your own entities, written as `_cut-<value>` just before `desc`.
139
+ - **`fixed={"signal": "virtual"}`** gives an entity one value for this datatype: it's always written and callers can't pass it. Use it to give variants of a file their own keys while keeping one suffix. For example, the MNE extension's `mne-i-ave` / `mne-v-ave` are `ave` files with `signal-intracranial` / `signal-virtual`.
140
+
141
+ Entities are always written in the BIDS spec's order, whatever order you pass them in. Anything the namer wasn't declared with raises `ValueError` instead of being dropped. So do values the spec forbids, such as `desc="brain-mask"`, `run="one"` or `hemi="lh"` (BIDS uses `L`/`R`). `fascicle.bids_pattern(...)` shows the pybids pattern a namer fills.
142
+
143
+ `dm.bids_namer(suffix)` is the raw-BIDS counterpart: it knows the raw spec (T1w lives in `anat/`, bold in `func/`), but only accepts raw suffixes and entities. A derivative entity such as `desc` raises and points you to `derivative_namer`.
144
+
145
+ Namers don't have to be BIDS-style: any `namer(root, subject, **inputs) -> Path` works (see `fascicle.extensions.freesurfer`). For a one-off datatype, skip the module: `dm.add_root(...)` and `dm.add_datatype(key, root_key, namer, reader, writer)`. You can also subclass `DatasetManager` and register everything in `__init__`.
146
+
147
+ ## Caveats
148
+
149
+ - **Not picklable.** `DatasetManager` wraps a `bids.BIDSLayout`, which can't be pickled. Don't pass a manager to `multiprocessing`/`joblib` workers. Resolve paths with `get_path` (or load data) in the parent process and pass those instead.
150
+ - **The BIDS index isn't refreshed after `save`.** Files you write are loadable by path straight away, but `get_subjects()` and `dm.layout` queries only see them in a new `DatasetManager`.
151
+ - **Extensions don't index their folders.** Namers build paths without looking at the disk, so they can write into folders that don't exist yet. For pybids queries on a derivatives folder, also call `dm.add_derivatives(key, path)` once it has a `dataset_description.json`. pybids doesn't parse custom entities (such as MNE's `signal`), so you can't filter on them in pybids queries; Fascicle's own `load`/`save` handle them fully.
152
+
153
+ ## Example
154
+
155
+ `examples/tutorial.ipynb` downloads one subject of OpenNeuro's `ds000114`, loads its T1w and BOLD with nibabel, then switches T1w to ANTsPy. Run `pip install -e ".[examples]"` first.
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ # Distribution name on PyPI ("fascicle" is taken by an unrelated project);
7
+ # the import name stays `fascicle`.
8
+ name = "mindmap-fascicle"
9
+ version = "0.1.0"
10
+ description = "Read and write BIDS neuroimaging datasets, with extensions for FreeSurfer, SimNIBS charm and MNE-Python derivatives."
11
+ readme = "README.md"
12
+ license = "MIT"
13
+ authors = [
14
+ { name = "Herve Nino", email = "herve.nino@gmail.com" },
15
+ ]
16
+ requires-python = ">=3.10"
17
+ keywords = ["BIDS", "neuroimaging", "MRI", "FreeSurfer", "MNE", "SimNIBS", "derivatives"]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Intended Audience :: Science/Research",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
25
+ ]
26
+ dependencies = [
27
+ "pybids",
28
+ "pyyaml",
29
+ "numpy",
30
+ "nibabel",
31
+ "pandas>=2.0",
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ mne = ["mne"]
36
+ all = ["mindmap-fascicle[mne]"]
37
+ test = ["pytest"]
38
+ examples = ["openneuro-py", "matplotlib", "jupyter", "antspyx"]
39
+
40
+ [project.urls]
41
+ Homepage = "https://github.com/NinoHerve/mindmap-fascicle"
42
+ Repository = "https://github.com/NinoHerve/mindmap-fascicle"
43
+ Issues = "https://github.com/NinoHerve/mindmap-fascicle/issues"
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/fascicle"]
47
+
48
+ [tool.hatch.build.targets.sdist]
49
+ # The tutorial notebook embeds plot images (~0.5 MB); it stays on GitHub.
50
+ exclude = ["examples/", ".vscode/"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ # Disable the "dash" pytest plugin some environments have autoloaded from
55
+ # user site-packages (dash.testing.plugin) — it fails to import when
56
+ # `blinker` isn't installed and has nothing to do with this project.
57
+ addopts = "-p no:dash"
@@ -0,0 +1,8 @@
1
+ """Fascicle: a BIDS-native dataset manager with pluggable extensions for derivatives."""
2
+
3
+ from .datatype import Datatype
4
+ from .extension import register_extension
5
+ from .manager import DatasetManager
6
+ from .naming import bids_pattern, derivative_namer
7
+
8
+ __all__ = ["DatasetManager", "Datatype", "bids_pattern", "derivative_namer", "register_extension"]
@@ -0,0 +1,54 @@
1
+ """Generic YAML config loading/saving.
2
+
3
+ Holds read_config/write_config, adapted from mindmap's
4
+ `mindmap/core/io.py` with mindmap-specific references stripped out.
5
+ """
6
+
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import yaml
12
+
13
+
14
+ def read_config(file: str | Path, env: bool = True) -> dict[str, Any]:
15
+ """Read a YAML configuration file.
16
+
17
+ Parameters
18
+ ----------
19
+ file: str | Path
20
+ Path to the configuration file.
21
+ env: bool
22
+ If True, also sets each top-level key as an environment variable.
23
+
24
+ Returns
25
+ -------
26
+ config: dict[str, Any]
27
+ The parsed configuration, with any string value containing "/"
28
+ converted to a Path.
29
+ """
30
+ with open(file, "r", encoding="utf-8") as f:
31
+ config = yaml.safe_load(f)
32
+
33
+ for key, value in config.items():
34
+ if env:
35
+ os.environ[key] = str(value)
36
+ if isinstance(value, str) and "/" in value:
37
+ config[key] = Path(value)
38
+
39
+ return config
40
+
41
+
42
+ def write_config(fname: str | Path, config: dict[str, Any]) -> None:
43
+ """Write a configuration dict to a YAML file.
44
+
45
+ Any Path values are converted to strings for serialization; the
46
+ original `config` dict passed in is left untouched.
47
+ """
48
+ config = {
49
+ key: (str(value) if isinstance(value, Path) else value)
50
+ for key, value in config.items()
51
+ }
52
+
53
+ with open(fname, "w", encoding="utf-8") as outfile:
54
+ yaml.dump(config, outfile, sort_keys=False, default_flow_style=False)
@@ -0,0 +1,69 @@
1
+ """The `Datatype` record: how Fascicle names, reads and writes one kind of file.
2
+
3
+ A datatype combines three parts: a *namer*, which builds the file's path,
4
+ a *reader* and a *writer*.
5
+
6
+ Namers are pure functions. A namer builds a path from a root, a subject and
7
+ any extra inputs (BIDS entities, a FreeSurfer hemisphere, ...). It never
8
+ checks whether the file exists, so `load` and `save` can share the same namer.
9
+
10
+ Readers and writers each handle exactly one file: `reader(path)` loads it,
11
+ and `writer(data, path)` saves it. Because this matches the signature of
12
+ plain library functions such as `nibabel.load` or `ants.image_read`, you can
13
+ pass those functions directly. If the reader or writer is `None`, the
14
+ manager picks one from its per-extension registries based on the file
15
+ extension.
16
+
17
+ To forbid saving a datatype, pass `writer=Datatype.READ_ONLY`. Use this when the
18
+ datatype's path ends in an extension that has a registered writer, but the
19
+ file does not hold the datatype's data. For example, a transform derived
20
+ from a T1 header points to the T1 file. Without it, `save` would
21
+ write the transform through the NIfTI writer and overwrite the T1 image.
22
+ """
23
+
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import Any, Callable
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Datatype:
31
+ """One registered kind of file.
32
+
33
+ Attributes
34
+ ----------
35
+ namer: Callable
36
+ `namer(root, subject, **inputs) -> Path`. Pure: must not check
37
+ that the file exists. Bind datatype-specific arguments with
38
+ `functools.partial` (e.g. `partial(build_fs_path, datatype="pial")`).
39
+ reader: Callable, optional
40
+ `reader(path) -> data`. None dispatches on the file extension.
41
+ writer: Callable, optional
42
+ `writer(data, path) -> None`. None dispatches on the file
43
+ extension; `Datatype.READ_ONLY` forbids saving. A datatype with no writer
44
+ and no writer for its extension is also read-only.
45
+ inputs: tuple[str, ...]
46
+ Names of the extra inputs the namer expects (e.g. `("hemi",)`).
47
+ Documentation only, surfaced by `DatasetManager.describe`.
48
+ exists: Callable, optional
49
+ `exists(path) -> bool`, used by `load`/`save` instead of
50
+ `Path.exists` -- for namers that return a stem standing for
51
+ several files (e.g. MNE's `-lh.stc`/`-rh.stc` pairs).
52
+ root_key: str, optional
53
+ Which registered root the namer resolves against, or None if the
54
+ namer finds its own way (it then receives `root=None`).
55
+ """
56
+
57
+ namer: Callable[..., Path]
58
+ reader: Callable[[Path], Any] | None = None
59
+ writer: Callable[[Any, Path], None] | None = None
60
+ inputs: tuple[str, ...] = ()
61
+ exists: Callable[[Path], bool] | None = None
62
+ root_key: str | None = None
63
+
64
+ # Not a field (no annotation): a writer sentinel, used as
65
+ # `writer=Datatype.READ_ONLY`.
66
+ @staticmethod
67
+ def READ_ONLY(data: Any, path: Path) -> None:
68
+ """Writer marking a datatype as read-only; `DatasetManager.save` refuses it."""
69
+ raise TypeError(f"Datatype at {path} is read-only.")
@@ -0,0 +1,88 @@
1
+ """The extension framework: how FreeSurfer, MNE, charm -- and yours -- plug in.
2
+
3
+ An extension is a module with a table of `Datatype`s keyed by bare name and
4
+ a `register` function that hands the table to `register_extension`:
5
+
6
+ DATATYPES = {
7
+ "t1": Datatype(partial(build_my_path, datatype="t1")),
8
+ "seg": Datatype(partial(build_my_path, datatype="seg"), reader=read_seg),
9
+ }
10
+
11
+ def register(dm, root_key="mytool", root_path=None, namespace=None,
12
+ readers=None, writers=None):
13
+ register_extension(dm, DATATYPES, root_key=root_key, root_path=root_path,
14
+ namespace=namespace, readers=readers, writers=writers)
15
+
16
+ The built-in extensions in `fascicle.extensions` are written exactly this way.
17
+ """
18
+
19
+ from dataclasses import replace
20
+ from pathlib import Path
21
+ from typing import Any, Callable
22
+
23
+ from .datatype import Datatype
24
+
25
+
26
+ def register_extension(
27
+ dm,
28
+ datatypes: dict[str, Datatype],
29
+ *,
30
+ root_key: str,
31
+ root_path: str | Path | None = None,
32
+ namespace: str | None = None,
33
+ readers: dict[str, Callable[[Any], Any]] | None = None,
34
+ writers: dict[str, Callable[[Any, Any], None]] | None = None,
35
+ ) -> None:
36
+ """Register a table of datatypes on `dm` under one root.
37
+
38
+ Parameters
39
+ ----------
40
+ dm: fascicle.DatasetManager
41
+ datatypes: dict[str, Datatype]
42
+ Bare name -> datatype. Each is registered as `f"{namespace}-{name}"`.
43
+ root_key: str
44
+ Root the datatypes resolve against.
45
+ root_path: str | Path, optional
46
+ Added as `root_key` if given; otherwise `root_key` must already
47
+ exist in `dm.roots`.
48
+ namespace: str, optional
49
+ Key prefix. Defaults to `root_key`, so registering the same
50
+ extension twice under different roots never collides.
51
+ readers, writers: dict, optional
52
+ Bare name -> function overriding that datatype's reader/writer.
53
+
54
+ Raises
55
+ ------
56
+ KeyError
57
+ If `root_path` is omitted and `root_key` isn't registered.
58
+ ValueError
59
+ If `readers`/`writers` name a datatype not in `datatypes`.
60
+ """
61
+ if root_path is not None:
62
+ dm.add_root(root_key, root_path)
63
+ elif root_key not in dm.roots:
64
+ raise KeyError(
65
+ f"Root '{root_key}' not found. Pass root_path=... to add it, "
66
+ "or call dm.add_root() yourself first."
67
+ )
68
+
69
+ readers = readers or {}
70
+ writers = writers or {}
71
+ for label, overrides in (("readers", readers), ("writers", writers)):
72
+ unknown = set(overrides) - set(datatypes)
73
+ if unknown:
74
+ raise ValueError(
75
+ f"Unknown datatype(s) in {label}=: {sorted(unknown)}. "
76
+ f"Available: {sorted(datatypes)}"
77
+ )
78
+
79
+ if namespace is None:
80
+ namespace = root_key
81
+
82
+ for name, dt in datatypes.items():
83
+ changes: dict[str, Any] = {"root_key": root_key}
84
+ if name in readers:
85
+ changes["reader"] = readers[name]
86
+ if name in writers:
87
+ changes["writer"] = writers[name]
88
+ dm.add(name, replace(dt, **changes), namespace=namespace)
@@ -0,0 +1,7 @@
1
+ """Built-in extensions for common neuroimaging derivatives.
2
+
3
+ Each submodule (`freesurfer`, `charm`, `mne`) is a table of `Datatype`s plus a
4
+ `register(dm, root_key=..., root_path=None, namespace=None, readers=None,
5
+ writers=None)` function built on `fascicle.register_extension` -- the same
6
+ framework third-party extensions use.
7
+ """