[MAINT]: Regular repository maintenance #337

Merged
synchon merged 13 commits from chore/repo-maint into main 2024-06-03 13:37:46 +00:00
126 changed files with 720 additions and 186 deletions

View file

@ -4,7 +4,7 @@ ci:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v4.6.0
hooks:
- id: check-ast
- id: check-docstring-first
@ -20,14 +20,14 @@ repos:
rev: v0.16
hooks:
- id: validate-pyproject
- repo: https://github.com/psf/black
rev: 24.1.1
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.4.2
hooks:
- id: black
exclude: ^(docs/|examples/|tools/)
args: [--check]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.15
rev: v0.4.2
hooks:
- id: ruff
types_or: [python, jupyter]
@ -38,7 +38,7 @@ repos:
hooks:
- id: codespell
exclude: ^(.github/|docs/)
args: [--config, tox.ini]
args: [--toml, pyproject.toml]
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
@ -47,3 +47,10 @@ repos:
- id: rst-backticks
- id: rst-directive-colons
- id: rst-inline-touching-normal
- repo: https://github.com/adamchainz/blacken-docs
rev: "1.16.0"
hooks:
- id: blacken-docs
additional_dependencies:
- black==24.4.2
args: [-l 79]

View file

@ -0,0 +1 @@
Update ``pre-commit`` dependency versions, add ``blacken-docs`` to ``pre-commit``, add ``__all__`` for modules, sub-packages and package, update ``ruff`` and ``pytest`` configs in ``pyproject.toml`` by `Synchon Mandal`_

View file

@ -70,10 +70,7 @@ with the DMN. Here, we use the DMN coordinates used in a
.. code-block:: python
dmn_coords = np.array(
[[0, -52, 18],
[-46, -68, 32],
[46, -68, 32],
[1, 50, -5]]
[[0, -52, 18], [-46, -68, 32], [46, -68, 32], [1, 50, -5]]
)
voi_names = [
"Posterior Cingulate Cortex",
@ -90,10 +87,7 @@ simply use this to register our coordinates:
.. code-block:: python
register_coordinates(
name="DMNCustom",
coordinates=dmn_coords,
voi_names=voi_names,
space="MNI"
name="DMNCustom", coordinates=dmn_coords, voi_names=voi_names, space="MNI"
)
Now, when we run this script, ``junifer`` registers these coordinates and we can

View file

@ -115,14 +115,14 @@ For example, in our BIDS example, the variables will be:
types = ["T1w", "BOLD"]
patterns = {
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
replacements = ["subject", "session"]
@ -144,25 +144,24 @@ With the variables defined above, we can create our DataGrabber and name it
class ExampleBIDSDataGrabber(PatternDataGrabber):
def __init__(self, datadir: str | Path) -> None:
types = ["T1w", "BOLD"]
patterns = {
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
replacements = ["subject", "session"]
super().__init__(
datadir=datadir,
types=types,
patterns=patterns,
replacements=replacements,
datadir=datadir,
types=types,
patterns=patterns,
replacements=replacements,
)
Our DataGrabber is ready to be used by ``junifer``. However, it is still unknown
@ -180,25 +179,24 @@ use the :func:`.register_datagrabber` decorator.
@register_datagrabber
class ExampleBIDSDataGrabber(PatternDataGrabber):
def __init__(self, datadir: str | Path) -> None:
types = ["T1w", "BOLD"]
patterns = {
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
replacements = ["subject", "session"]
super().__init__(
datadir=datadir,
types=types,
patterns=patterns,
replacements=replacements,
datadir=datadir,
types=types,
patterns=patterns,
replacements=replacements,
)
@ -267,29 +265,28 @@ And we can create our DataGrabber:
@register_datagrabber
class ExampleBIDSDataGrabber(PatternDataladDataGrabber):
def __init__(self) -> None:
types = ["T1w", "BOLD"]
patterns = {
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
"T1w": {
"pattern": "{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"pattern": "{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
replacements = ["subject", "session"]
uri = "https://gin.g-node.org/juaml/datalad-example-bids"
rootdir = "example_bids_ses"
super().__init__(
datadir=None,
uri=uri,
rootdir=rootdir,
types=types,
patterns=patterns,
replacements=replacements,
datadir=None,
uri=uri,
rootdir=rootdir,
types=types,
patterns=patterns,
replacements=replacements,
)
This approach can be used directly from the YAML, like so:
@ -391,17 +388,17 @@ and ``session``, we will use them as parameters of ``get_item``:
.. code-block:: python
def get_item(self, subject: str, session: str) -> dict[str, dict[str, str]]:
out = {
"T1w": {
"path": f"{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"path": f"{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
return out
out = {
"T1w": {
"path": f"{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"path": f"{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
return out
The second method, ``get_elements``, needs to return a list of all the elements
@ -415,16 +412,16 @@ need to remember that for session *ses-03* there is no BOLD data.
def get_elements(self) -> list[str]:
subjects = ["sub-01", "sub-02", "sub-03"]
sessions = ["ses-01", "ses-02"]
subjects = ["sub-01", "sub-02", "sub-03"]
sessions = ["ses-01", "ses-02"]
# If we are not working on BOLD data, we can add "ses-03"
if "BOLD" not in self.types:
sessions.append("ses-03")
elements = []
for subject, element in product(subjects, sessions):
elements.append({"subject": subject, "session": session})
return elements
# If we are not working on BOLD data, we can add "ses-03"
if "BOLD" not in self.types:
sessions.append("ses-03")
elements = []
for subject, element in product(subjects, sessions):
elements.append({"subject": subject, "session": session})
return elements
And finally, we can implement the ``get_element_keys`` method. This method needs
@ -435,7 +432,7 @@ method, in the same order.
.. code-block:: python
def get_element_keys(self) -> list[str]:
return ["subject", "session"]
return ["subject", "session"]
So, to summarise, our DataGrabber will look like this:
@ -448,35 +445,36 @@ So, to summarise, our DataGrabber will look like this:
@register_datagrabber
class ExampleBIDSDataGrabber(BaseDataGrabber):
def get_item(
self, subject: str, session: str
) -> dict[str, dict[str, str]]:
out = {
"T1w": {
"path": f"{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"path": f"{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
return out
def get_item(self, subject: str, session: str) -> dict[str, dict[str, str]]:
out = {
"T1w": {
"path": f"{subject}/{session}/anat/{subject}_{session}_T1w.nii.gz",
"space": "native",
},
"BOLD": {
"path": f"{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
},
}
return out
def get_elements(self) -> list[str]:
subjects = ["sub-01", "sub-02", "sub-03"]
sessions = ["ses-01", "ses-02"]
def get_elements(self) -> list[str]:
subjects = ["sub-01", "sub-02", "sub-03"]
sessions = ["ses-01", "ses-02"]
# If we are not working on BOLD data, we can add "ses-03"
if "BOLD" not in self.types:
sessions.append("ses-03")
elements = []
for subject in subjects:
for session in sessions:
elements.append({"subject": subject, "session": session})
return elements
# If we are not working on BOLD data, we can add "ses-03"
if "BOLD" not in self.types:
sessions.append("ses-03")
elements = []
for subject in subjects:
for session in sessions:
elements.append({"subject": subject, "session": session})
return elements
def get_element_keys(self) -> list[str]:
return ["subject", "session"]
def get_element_keys(self) -> list[str]:
return ["subject", "session"]
Optional: Using datalad
~~~~~~~~~~~~~~~~~~~~~~~
@ -522,26 +520,24 @@ this:
.. code-block:: python
def get_item(
self, subject: str, session: str
) -> dict:
out = {
"BOLD": {
"path": f"{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
"confounds": {
"path": f"{subject}/{session}/func/{subject}_{session}_confounds.tsv",
"format": "adhoc",
"mappings": {
"fmriprep": {
"variable1": "rot_x",
"variable2": "rot_z",
"variable3": "rot_y",
},
},
},
},
}
def get_item(self, subject: str, session: str) -> dict:
out = {
"BOLD": {
"path": f"{subject}/{session}/func/{subject}_{session}_task-rest_bold.nii.gz",
"space": "MNI152NLin6Asym",
"confounds": {
"path": f"{subject}/{session}/func/{subject}_{session}_confounds.tsv",
"format": "adhoc",
"mappings": {
"fmriprep": {
"variable1": "rot_x",
"variable2": "rot_z",
"variable3": "rot_y",
},
},
},
},
}
.. note::

View file

@ -93,6 +93,7 @@ that it shows the problem a bit better and how we solve it:
self, using: str, reference: str, on: Union[List[str], str]
) -> None:
# validation and setting up
...
Here, you see a new class attribute ``_CONDITIONAL_DEPENDENCIES`` which is a
@ -129,6 +130,7 @@ similar. ``FSLWarper`` looks like this (only the relevant part is shown here):
extra_input: Dict[str, Any],
) -> Dict[str, Any]:
# implementation
...
Here you can see the familiar ``_DEPENDENCIES`` and ``_EXT_DEPENDENCIES`` class
attributes. The validation process starts by looking up the ``using`` value of

View file

@ -82,10 +82,10 @@ parcellation to use. Thus, we can define the ``__init__`` method as follows:
.. code-block:: python
def __init__(
self,
parcellation: str,
on: str | list[str] | None = None,
name: str | None = None,
self,
parcellation: str,
on: str | list[str] | None = None,
name: str | None = None,
) -> None:
self.parcellation = parcellation
super().__init__(on=on, name=name)
@ -137,9 +137,9 @@ the ``store`` method.
def compute(
self,
input: dict[str, Any],
extra_input: dict[str, Any] | None = None,
self,
input: dict[str, Any],
extra_input: dict[str, Any] | None = None,
) -> dict[str, Any]:
# Get the data
data = input["data"]
@ -207,10 +207,10 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
_DEPENDENCIES = {"nilearn", "numpy"}
def __init__(
self,
parcellation: str,
on: str | list[str] | None = None,
name: str | None = None,
self,
parcellation: str,
on: str | list[str] | None = None,
name: str | None = None,
) -> None:
self.parcellation = parcellation
super().__init__(on=on, name=name)
@ -225,9 +225,9 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
return "vector"
def compute(
self,
input: dict[str, Any],
extra_input: dict[str, Any] | None = None,
self,
input: dict[str, Any],
extra_input: dict[str, Any] | None = None,
) -> dict[str, Any]:
# Get the data
data = input["data"]
@ -269,7 +269,6 @@ Template for a custom Marker
@register_marker
class TemplateMarker(BaseMarker):
def __init__(self, on=None, name=None):
# TODO: add marker-specific parameters
super().__init__(on=on, name=name)

View file

@ -83,7 +83,7 @@ look like this:
name="my_custom_parcellation",
parcellation_path=path_to_parcellation,
parcels_labels=my_labels,
space="MNI152NLin2009cAsym"
space="MNI152NLin2009cAsym",
)
We can run this code and it seems to work, however, how can we actually

View file

@ -43,9 +43,11 @@ For input we can accept ``T1w``, ``T2w`` and ``BOLD``
...
def get_valid_inputs(self) -> list[str]:
return ["T1w", "T2w", "BOLD"]
...
The output definition of the Preprocessor is unused now but is kept for
@ -55,9 +57,11 @@ completeness.
...
def get_output_type(self, input_type: str) -> str:
return input_type
...
.. _extending_preprocessors_init:
@ -90,6 +94,7 @@ you configure it. Our class will have the following arguments:
...
def __init__(
self,
fwhm: int | float | ArrayLike | Literal["fast"] | None,
@ -98,6 +103,7 @@ you configure it. Our class will have the following arguments:
self.fwhm = fwhm
super().__init__(on=on)
...
.. caution::
@ -147,15 +153,18 @@ and it has two return values:
...
def preprocess(
self,
input: dict[str, Any],
extra_input: dict[str, Any] | None = None,
) -> tuple[dict[str, Any], dict[str, Any] | None]:
input["data"] = nimg.smooth_img(imgs=input["data"], fwhm=self.fwhm)
return input, None
input["data"] = nimg.smooth_img(imgs=input["data"], fwhm=self.fwhm)
return input, None
...
...
Step 4: Finalise the Preprocessor
---------------------------------

View file

@ -12,7 +12,7 @@ This is the *object* that traverses the steps of the pipeline. It is indeed a
dictionary of dictionaries. The first level of keys are the :ref:`data types <data_types>`
and the values are the corresponding information as dictionaries.
.. code-block:: python
.. code-block::
{'BOLD': {...}, 'T1w': {...}}
@ -24,7 +24,7 @@ The :ref:`Data Grabber <datagrabber>` step adds the ``path`` second-level key
which gives the path to the file containing the data. The ``meta`` key in this
step only contains information about the DataGrabber used.
.. code-block:: python
.. code-block::
{'BOLD': {'meta': {'datagrabber': {'class': 'SPMAuditoryTestingDataGrabber',
'types': ['BOLD', 'T1w']},
@ -41,7 +41,7 @@ The :ref:`Data Reader <datareader>` step adds the ``data`` second-level key
which is the actual data loaded into memory. The ``meta`` key in this step
adds information about the DataReader used to read the data.
.. code-block:: python
.. code-block::
{'BOLD': {'data': <nibabel.nifti1.Nifti1Image object at 0x16b5d8910>,
'meta': {'datagrabber': {'class': 'SPMAuditoryTestingDataGrabber',
@ -58,6 +58,7 @@ adds information about the DataReader used to read the data.
'element': {'subject': 'sub001'}},
'path': PosixPath('/var/folders/dv/2lbr8f8j0q12zrx3mz3ll5m40000gp/T/tmpe49321ce/sub001_T1w.nii.gz')}}
The :ref:`Preprocess <preprocess>` step, if used, modifies the ``data``
second-level key's value and appends the ``meta`` key with information about
the preprocessor.
@ -66,7 +67,7 @@ The :ref:`Marker <marker>` step removes the ``path`` second-level key,
replaces the ``data`` second-level key's value with the marker's computed value
and adds further keys needed for the storage, for example, ``col_names``.
.. code-block:: python
.. code-block::
{'BOLD': {'col_names': ['root_sum_of_squares_ets'],
'data': ...,

View file

@ -69,7 +69,7 @@ Example in python format:
strategy = {
"motion": "basic",
"wm_csf": "full",
"global_signal": "derivatives"
"global_signal": "derivatives",
}
or in YAML format:
@ -85,11 +85,7 @@ The default value is to use all the *noise components* with the ``full`` *confou
.. code-block:: python
strategy = {
"motion": "full",
"wm_csf": "full",
"global_signal": "full"
}
strategy = {"motion": "full", "wm_csf": "full", "global_signal": "full"}
Other Parameters
~~~~~~~~~~~~~~~~

View file

@ -20,3 +20,20 @@ from . import (
onthefly,
)
from ._version import __version__
__all__ = [
"api",
"configs",
"data",
"datagrabber",
"datareader",
"markers",
"pipeline",
"preprocess",
"stats",
"storage",
"utils",
"external",
"onthefly",
]

View file

@ -7,3 +7,6 @@
from . import decorators
from .cli import cli
from .functions import collect, queue, run
__all__ = ["decorators", "cli", "collect", "queue", "run"]

View file

@ -10,6 +10,15 @@ from typing import Type
from ..pipeline.registry import register
__all__ = [
"register_datagrabber",
"register_datareader",
"register_preprocessor",
"register_marker",
"register_storage",
]
def register_datagrabber(klass: Type) -> Type:
"""Register DataGrabber.

View file

@ -23,6 +23,9 @@ from .queue_context import GnuParallelLocalAdapter, HTCondorAdapter
from .utils import yaml
__all__ = ["run", "collect", "queue", "reset", "list_elements"]
def _get_datagrabber(datagrabber_config: Dict) -> BaseDataGrabber:
"""Get DataGrabber.
@ -92,7 +95,7 @@ def run(
datagrabber : dict
DataGrabber to use. Must have a key ``kind`` with the kind of
DataGrabber to use. All other keys are passed to the DataGrabber
init function.
constructor.
markers : list of dict
List of markers to extract. Each marker is a dict with at least two
keys: ``name`` and ``kind``. The ``name`` key is used to name the
@ -102,11 +105,11 @@ def run(
storage : dict
Storage to use. Must have a key ``kind`` with the kind of
storage to use. All other keys are passed to the storage
init function.
constructor.
preprocessors : list of dict, optional
List of preprocessors to use. Each preprocessor is a dict with at
least a key ``kind`` specifying the preprocessor to use. All other keys
are passed to the preprocessor init function (default None).
are passed to the preprocessor constructor (default None).
elements : str or tuple or list of str or tuple, optional
Element(s) to process. Will be used to index the DataGrabber
(default None).
@ -188,7 +191,7 @@ def collect(storage: Dict) -> None:
storage : dict
Storage to use. Must have a key ``kind`` with the kind of
storage to use. All other keys are passed to the storage
init function.
constructor.
"""
storage_params = storage.copy()

View file

@ -14,6 +14,9 @@ from ..utils.logging import logger, raise_error
from .utils import yaml
__all__ = ["parse_yaml"]
def parse_yaml(filepath: Union[str, Path]) -> Dict:
"""Parse YAML.

View file

@ -6,3 +6,6 @@
from .queue_context_adapter import QueueContextAdapter
from .htcondor_adapter import HTCondorAdapter
from .gnu_parallel_local_adapter import GnuParallelLocalAdapter
__all__ = ["QueueContextAdapter", "HTCondorAdapter", "GnuParallelLocalAdapter"]

View file

@ -31,7 +31,7 @@ if [ -d "${var}" ]; then
done
echo "Docker args: ${docker_args[*]}" >&2
echo "Corrected args for afni: ${corrected_args[*]}" >&2
echo "Corrected args for AFNI: ${corrected_args[*]}" >&2
cwd=$(pwd)
cmd="docker run --rm ${docker_args[*]} -v ${cwd}:${cwd} -w ${cwd} afni/afni_make_build ${corrected_args[*]}"

View file

@ -31,7 +31,7 @@ if [ -d "${var}" ]; then
done
echo "Docker args: ${docker_args[*]}" >&2
echo "Corrected args for fsl: ${corrected_args[*]}" >&2
echo "Corrected args for ANTs: ${corrected_args[*]}" >&2
cwd=$(pwd)
cmd="docker run --rm ${docker_args[*]} -v ${cwd}:${cwd} -w ${cwd} antsx/ants ${corrected_args[*]}"

View file

@ -31,7 +31,7 @@ if [ -d "${var}" ]; then
done
echo "Docker args: ${docker_args[*]}" >&2
echo "Corrected args for fsl: ${corrected_args[*]}" >&2
echo "Corrected args for FSL: ${corrected_args[*]}" >&2
cwd=$(pwd)
cmd="docker run --rm ${docker_args[*]} -v ${cwd}:${cwd} -w ${cwd} brainlife/fsl ${corrected_args[*]}"

View file

@ -4,3 +4,6 @@
# License: AGPL
from . import datagrabbers
__all__ = ["datagrabbers"]

Some files were not shown because too many files have changed in this diff Show more