Coverage for nilearn/interfaces/bids/utils.py: 9%
27 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-20 10:58 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-20 10:58 +0200
1"""Public Utility functions for the nilearn.interfaces.bids module."""
3from __future__ import annotations
6def bids_entities():
7 """Return a dictionary of BIDS entities.
9 Entities are listed in the order they should appear in a filename.
11 https://bids-specification.readthedocs.io/en/stable/appendices/entities.html
13 Note that:
15 - this only contains the entities for functional data
17 https://github.com/bids-standard/bids-specification/blob/master/src/schema/rules/files/raw/func.yaml#L13
18 https://github.com/bids-standard/bids-specification/blob/master/src/schema/rules/files/deriv/imaging.yaml#L29
20 Returns
21 -------
22 Dictionary of raw and derivatives entities : dict[str, list[str]]
24 """
25 return {
26 "raw": [
27 "sub",
28 "ses",
29 "task",
30 "acq",
31 "ce",
32 "rec",
33 "dir",
34 "run",
35 "echo",
36 "part",
37 ],
38 "derivatives": ["hemi", "space", "res", "den", "desc"],
39 }
42def check_bids_label(label):
43 """Validate a BIDS label.
45 https://bids-specification.readthedocs.io/en/stable/glossary.html#label-formats
47 Parameters
48 ----------
49 label : Any
50 Label to validate
52 """
53 if not isinstance(label, str):
54 raise TypeError(
55 f"All bids labels must be string. "
56 f"Got '{type(label)}' for {label} instead."
57 )
58 if not all(char.isalnum() for char in label):
59 raise ValueError(
60 f"All bids labels must be alphanumeric. Got '{label}' instead."
61 )
64def create_bids_filename(fields, entities_to_include=None):
65 """Create BIDS filename from dictionary of entity-label pairs.
67 Parameters
68 ----------
69 fields : :obj:`dict` of :obj:`str`
70 Dictionary of entity-label pairs, for example:
72 {
73 "prefix": None, # can be useful to easily prefix filenames
74 "suffix": "T1w",
75 "extension": "nii.gz",
76 "entities": {"acq": "ap",
77 "desc": "preproc"}
78 }.
80 Returns
81 -------
82 BIDS filename : :obj:`str`
84 """
85 if entities_to_include is None:
86 entities_to_include = bids_entities()["raw"]
88 filename = ""
90 for key in entities_to_include:
91 if value := fields["entities"].get(key):
92 filename += f"{key}-{value}_"
93 if "suffix" in fields:
94 filename += f"{fields['suffix']}"
95 if "extension" in fields:
96 filename += f".{fields['extension']}"
97 if "prefix" in fields:
98 prefix = fields["prefix"]
99 if prefix is None:
100 prefix = ""
101 if prefix and prefix != "" and not prefix.endswith("_"):
102 prefix += "_"
103 filename = f"{prefix}{filename}"
105 return filename