Skip to content

Add TemporaryBidsDir for runnable BIDS examples - #987

Merged
thibaultdvx merged 4 commits into
aramis-lab:devfrom
OBagnell:docs/runnable-bids-loading
Nov 20, 2026
Merged

thibaultdvx merged 4 commits into
aramis-lab:devfrom
OBagnell:docs/runnable-bids-loading

Conversation

@OBagnell

@OBagnell OBagnell commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Related issues

Partially addresses #953. Implements the TemporaryBidsDir follow-up suggested in #987 (comment).

Key changes made

  • Add clinicadl.io.bids.TemporaryBidsDir, inheriting TemporaryDirectory and returning a Path from its context.
  • Write dataset_description.json and optional metadata.tsv; optionally generate zero-valued NIfTI images for every participant/session pair and requested data type.
  • Support filename entities such as res-1x1x1_T1w and trc-18FFDG_pet, and configurable (channels, x, y, z) image shapes. Use TorchIO to preserve the channel/spatial convention when saving.
  • Reuse metadata validation, reject unsafe path components, and clean up on normal exit, exceptions, or setup failures.
  • Simplify both navigation and image-loading examples and add the helper to the API documentation.

Type of changes

  • Non-breaking changes
  • Breaking changes
  • Changes involving GPU features
  • Changes involving multi-GPU features
  • No code-related changes

Checklist

  • In-line docstrings updated
  • Unit tests added to cover the changes
  • Unit tests passed locally (make unit-tests)
  • Documentation updated and tested (cd docs && make html)
  • CI database updated (if required)

Validation

  • All 31 new helper tests pass: metadata/no-metadata, multiple participants and sessions, T1/PET filenames, scalar/multichannel shapes, real BidsDataset loading, invalid inputs, path confinement, and normal/error cleanup.
  • Focused BIDS IO, BIDS utilities and TSV utilities: 153 passed, 4 failed on Windows. The same four existing path-separator failures reproduce on unchanged commit 6f5f5e5 (three TestBidsFileType.test_3 cases and TestClinicaPipelines.test_dwi). No unrelated fixes included.
  • Both exact standalone documentation snippets ran twice using the real APIs, with expected output, temporary-directory cleanup and an unrelated sentinel preserved.
  • Ruff lint/format and git diff --check pass.

The full application test suite and Sphinx build were not run locally; upstream checks remain required. No new dependencies, patient data, downloads in the examples, training or scientific algorithm changes.

AI usage disclosure

I used OpenAI Codex assistance for:

  • Code generation
  • Test generation
  • Documentation (including examples)
  • Research and understanding

Introduce yourself

I'm a returning contributor helping make the research tooling easier to try.

@thibaultdvx

thibaultdvx commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Hey @OBagnell, thanks a lot for contributing!

What do you think of creating a TemporaryBidsDir context manager, inheriting from TemporaryDirectory, that would take care of creating the BIDS directory.

The current example would look like this:

from tempfile import TemporaryDirectory

description = {
        "Name": "Toy image-loading example",
        "BIDSVersion": "1.10.0",
        "DatasetType": "raw",
    }
metadata = pd.DataFrame(
        {
            "participant_id": ["sub-001", "sub-002"],
            "session_id": ["ses-M000", "ses-M000"],
            "age": [55.0, 62.0],
            "diagnosis": ["control", "patient"],
        }
    )
with TemporaryBidsDir(description, metadata) as bids_directory:
    for participant in metadata["participant_id"]:
        anat = bids_directory / participant / "ses-M000" / "anat"
        anat.mkdir(parents=True)
        image =  (in (np.zeros((8, 8, 8), dtype=np.float32), np.eye(4))
        nib.save(image, anat / f"{participant}_ses-M000_T1w.nii.gz")

    dataset = BidsDataset(
        bids=bids_directory,
        file_type=BidsFileType(data_type="anat", suffix="T1w"),
        data=bids_directory / "metadata.tsv",
    )

The example in #985, would look like this:

description = {
    "Name": "Toy directory navigation example",
    "BIDSVersion": "1.10.0",
    "DatasetType": "raw",
}
with TemporaryBidsDir(description, metadata=None) as bids_directory:
    (bids_directory / "sub-01" / "ses-M000").mkdir(parents=True)

    bids = Bids(bids_directory)
    print(sorted(bids.get_all_participants_sessions()))

We could go even further and implement the image creation inside this context manager:

with TemporaryBidsDir(description, metadata, with_images={"anat": "T1w"}) as bids_directory:
    dataset = BidsDataset(
        bids=bids_directory,
        file_type=BidsFileType(data_type="anat", suffix="T1w"),
        data=bids_directory / "metadata.tsv",
    )

As you can see, this makes the example cleaner, with all the setup hidden in the context manager.

The argument with_images could take as input a dictionary which keys are the datatypes of the images to save, and the values are the file suffixes. Images would be created for all the participants and sessions that are in the metadata DataFrame.

For example, in order to save T1w and PET images, I would do:

with TemporaryBidsDir(description, metadata, with_images={"anat": "res-1x1x1_T1w", "pet": "trc-18FFDG_pet"}) as bids_directory:
    ...

Which will create the following BIDS:

bids_dir
├ dataset_description.json
├ metadata.tsv
├ sub-000
| ├ ses-M000
| | ├ anat
| | | └ sub-000_ses-M000_res-1x1x1_T1w.nii.gz
| | └ pet
| |   └ sub-000_ses-M000_trc-18FFDG_pet.nii.gz
...

Finally, a last interesting feature could be to let the user define the size of the images generated. This would lead to something like this:

with TemporaryBidsDir(description, metadata, with_images={"anat": "T1w"}, image_shape=(1, 8, 8, 8)) as bids_directory:
    ...

What do you think?

@OBagnell OBagnell changed the title [DOC] Make BIDS image-loading example self-contained Add TemporaryBidsDir for runnable BIDS examples Nov 11, 2026
@OBagnell

Copy link
Copy Markdown
Contributor Author

Hey @OBagnell, thanks a lot for contributing!

What do you think of creating a TemporaryBidsDir context manager, inheriting from TemporaryDirectory, that would take care of creating the BIDS directory.

The current example would look like this:

from tempfile import TemporaryDirectory

description = {
        "Name": "Toy image-loading example",
        "BIDSVersion": "1.10.0",
        "DatasetType": "raw",
    }
metadata = pd.DataFrame(
        {
            "participant_id": ["sub-001", "sub-002"],
            "session_id": ["ses-M000", "ses-M000"],
            "age": [55.0, 62.0],
            "diagnosis": ["control", "patient"],
        }
    )
with TemporaryBidsDir(description, metadata) as bids_directory:
    for participant in metadata["participant_id"]:
        anat = bids_directory / participant / "ses-M000" / "anat"
        anat.mkdir(parents=True)
        image =  (in (np.zeros((8, 8, 8), dtype=np.float32), np.eye(4))
        nib.save(image, anat / f"{participant}_ses-M000_T1w.nii.gz")

    dataset = BidsDataset(
        bids=bids_directory,
        file_type=BidsFileType(data_type="anat", suffix="T1w"),
        data=bids_directory / "metadata.tsv",
    )

The example in #985, would look like this:

description = {
    "Name": "Toy directory navigation example",
    "BIDSVersion": "1.10.0",
    "DatasetType": "raw",
}
with TemporaryBidsDir(description, metadata=None) as bids_directory:
    (bids_directory / "sub-01" / "ses-M000").mkdir(parents=True)

    bids = Bids(bids_directory)
    print(sorted(bids.get_all_participants_sessions()))

We could go even further and implement the image creation inside this context manager:

with TemporaryBidsDir(description, metadata, with_images={"anat": "T1w"}) as bids_directory:
    dataset = BidsDataset(
        bids=bids_directory,
        file_type=BidsFileType(data_type="anat", suffix="T1w"),
        data=bids_directory / "metadata.tsv",
    )

As you can see, this makes the example cleaner, with all the setup hidden in the context manager.

The argument with_images could take as input a dictionary which keys are the datatypes of the images to save, and the values are the file suffixes. Images would be created for all the participants and sessions that are in the metadata DataFrame.

For example, in order to save T1w and PET images, I would do:

with TemporaryBidsDir(description, metadata, with_images={"anat": "res-1x1x1_T1w", "pet": "trc-18FFDG_pet"}) as bids_directory:
    ...

Which will create the following BIDS:

bids_dir
├ dataset_description.json
├ metadata.tsv
├ sub-000
| ├ ses-M000
| | ├ anat
| | | └ sub-000_ses-M000_res-1x1x1_T1w.nii.gz
| | └ pet
| |   └ sub-000_ses-M000_trc-18FFDG_pet.nii.gz
...

Finally, a last interesting feature could be to let the user define the size of the images generated. This would lead to something like this:

with TemporaryBidsDir(description, metadata, with_images={"anat": "T1w"}, image_shape=(1, 8, 8, 8)) as bids_directory:
    ...

What do you think?

@OBagnell

Copy link
Copy Markdown
Contributor Author

Thanks! Alzheimer’s research is important to me, and I’m glad to help improve the tools supporting it.

@OBagnell OBagnell closed this Nov 11, 2026
@OBagnell OBagnell reopened this Nov 11, 2026

@thibaultdvx thibaultdvx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @OBagnell, thanks for the great contribution! Here are some suggestions of improvement.

FIY, you can easily commit my suggestions by clicking on the button "Apply suggestion".

And by the way, could you please allow maintainers to edit your PR next time? It facilitates collaboration ;)

Comment thread docs/user_guide/data/datasets/bids.rst Resolved
Comment thread docs/user_guide/data/datasets/bids.rst Resolved
Comment thread clinicadl/io/bids/temporary.py Resolved
Comment thread clinicadl/io/bids/temporary.py Resolved
Comment thread clinicadl/io/bids/temporary.py Resolved
Comment thread clinicadl/io/bids/temporary.py Resolved
Comment thread clinicadl/io/bids/temporary.py Resolved
Comment thread clinicadl/io/bids/temporary.py Resolved
Comment thread clinicadl/io/bids/temporary.py Resolved
OBagnell and others added 2 commits November 17, 2026 17:09
Apply thibaultdvx's requested guide and docstring improvements. Prepared and validated with OpenAI Codex assistance.
@thibaultdvx

Copy link
Copy Markdown
Collaborator

Failing test (unittest Python 3.14 on Ubuntu) is unrelated. I merge.

@thibaultdvx
thibaultdvx merged commit b56c3e2 into aramis-lab:dev Nov 20, 2026
19 of 34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants