[ENH]: Adopt Pydantic for schema validation #364
196 changed files with 5115 additions and 5268 deletions
|
|
@ -5,5 +5,5 @@ On-the-fly
|
|||
:members:
|
||||
:imported-members:
|
||||
|
||||
.. automodule:: junifer.onthefly.brainprint
|
||||
.. automodule:: junifer.onthefly._brainprint
|
||||
:members:
|
||||
|
|
|
|||
|
|
@ -158,16 +158,16 @@ Available
|
|||
| (subject-native or other template spaces)
|
||||
- Done
|
||||
- 0.0.4
|
||||
* - ``Smoothing``
|
||||
* - :class:`.Smoothing`
|
||||
- | Apply smoothing to data, particularly useful when dealing with
|
||||
| ``fMRIPrep``-ed data
|
||||
- In Progress
|
||||
- :gh:`161`
|
||||
* - ``TemporalSlicer``
|
||||
* - :class:`.TemporalSlicer`
|
||||
- Slice ``BOLD`` data temporally
|
||||
- | Done
|
||||
- :gh:`443`
|
||||
* - ``TemporalFilter``
|
||||
* - :class:`.TemporalFilter`
|
||||
- Filter (clean) ``BOLD`` data temporally
|
||||
- | Done
|
||||
- :gh:`432`
|
||||
|
|
|
|||
1
docs/changes/newsfragments/364.doc
Normal file
1
docs/changes/newsfragments/364.doc
Normal file
|
|
@ -0,0 +1 @@
|
|||
Add documentation on adding confounds format by `Synchon Mandal`_
|
||||
1
docs/changes/newsfragments/364.enh
Normal file
1
docs/changes/newsfragments/364.enh
Normal file
|
|
@ -0,0 +1 @@
|
|||
Adopt Pydantic for user-facing core objects to perform automatic validation using typing annotations by `Synchon Mandal`_
|
||||
1
docs/changes/newsfragments/364.feature
Normal file
1
docs/changes/newsfragments/364.feature
Normal file
|
|
@ -0,0 +1 @@
|
|||
Enable confounds format to be added by introducing :func:`.register_confounds_format` by `Synchon Mandal`_
|
||||
12
docs/conf.py
12
docs/conf.py
|
|
@ -65,6 +65,8 @@ extensions = [
|
|||
"sphinx_copybutton", # copy button for code blocks
|
||||
"sphinxcontrib.mermaid", # mermaid support
|
||||
"sphinxcontrib.towncrier.ext", # towncrier fragment support
|
||||
"sphinxcontrib.autodoc_pydantic", # autodoc support for pydantic models
|
||||
"enum_tools.autoenum", # enum support
|
||||
]
|
||||
|
||||
if use_multiversion:
|
||||
|
|
@ -97,6 +99,15 @@ nitpick_ignore_regex = [
|
|||
("py:class", "pipeline.Pipeline"), # nilearn
|
||||
("py:obj", "neurokit2.*"), # ignore neurokit2
|
||||
("py:obj", "datalad.*"), # ignore datalad
|
||||
("py:obj", "junifer.*"), # ignore junifer internal
|
||||
("py:class", "annotated_types.*"), # ignore pydantic annotated types
|
||||
("py:obj", "variants"), # ignore variants
|
||||
("py:obj", "them"), # ignore them
|
||||
("py:class", "junifer.utils.helpers.ensure_list"), # ignore ensure_list
|
||||
("py:class", "junifer.utils.helpers.ensure_list_or_none"), # ignore ensure_list_or_none
|
||||
("py:class", "PydanticUndefined"), # ignore PydanticUndefined
|
||||
("py:class", "FieldInfo"), # ignore FieldInfo
|
||||
("py:class", "NoneType"), # ignore NoneType
|
||||
]
|
||||
|
||||
# -- Options for HTML output -------------------------------------------------
|
||||
|
|
@ -154,6 +165,7 @@ intersphinx_mapping = {
|
|||
"pandas": ("https://pandas.pydata.org/pandas-docs/dev", None),
|
||||
# "sqlalchemy": ("https://docs.sqlalchemy.org/en/20/", None),
|
||||
"scipy": ("https://docs.scipy.org/doc/scipy/", None),
|
||||
"pydantic": ("https://docs.pydantic.dev/latest/", None),
|
||||
}
|
||||
|
||||
# -- sphinx.ext.extlinks configuration ---------------------------------------
|
||||
|
|
|
|||
22
docs/extending/confounds_format.rst
Normal file
22
docs/extending/confounds_format.rst
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
.. include:: ../links.inc
|
||||
|
||||
.. _adding_confounds_format:
|
||||
|
||||
Adding Confounds Format
|
||||
=======================
|
||||
|
||||
#. Check :ref:`extending junifer <extending_extension>` on how to create a
|
||||
*junifer extension* if you have not done so.
|
||||
#. Register the confounds format before defining / using a DataGrabber like so:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from junifer.datagrabber import register_confounds_format
|
||||
...
|
||||
|
||||
|
||||
# registers the confounds format as "confounds" and accessible as
|
||||
# ``ConfoundsFormat.Confounds``
|
||||
register_confounds_format(name="Confounds", alias="confounds")
|
||||
|
||||
...
|
||||
|
|
@ -140,29 +140,24 @@ With the variables defined above, we can create our DataGrabber and name it
|
|||
|
||||
from pathlib import Path
|
||||
|
||||
from junifer.datagrabber import PatternDataGrabber
|
||||
from junifer.datagrabber import PatternDataGrabber, DataType
|
||||
from junifer.typing import DataGrabberPatterns
|
||||
|
||||
|
||||
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",
|
||||
},
|
||||
}
|
||||
replacements = ["subject", "session"]
|
||||
super().__init__(
|
||||
datadir=datadir,
|
||||
types=types,
|
||||
patterns=patterns,
|
||||
replacements=replacements,
|
||||
)
|
||||
|
||||
types: list[DataType] = [DataType.T1w, DataType.BOLD]
|
||||
patterns: DataGrabberPatterns = {
|
||||
"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: list[str] = ["subject", "session"]
|
||||
|
||||
Our DataGrabber is ready to be used by ``junifer``. However, it is still unknown
|
||||
to the library. We need to register it in the library. To do so, we need to
|
||||
|
|
@ -175,29 +170,24 @@ use the :func:`.register_datagrabber` decorator.
|
|||
|
||||
from junifer.api.decorators import register_datagrabber
|
||||
from junifer.datagrabber import PatternDataGrabber
|
||||
from junifer.typing import DataGrabberPatterns
|
||||
|
||||
|
||||
@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",
|
||||
},
|
||||
}
|
||||
replacements = ["subject", "session"]
|
||||
super().__init__(
|
||||
datadir=datadir,
|
||||
types=types,
|
||||
patterns=patterns,
|
||||
replacements=replacements,
|
||||
)
|
||||
|
||||
types: list[DataType] = [DataType.T1w, DataType.BOLD]
|
||||
patterns: DataGrabberPatterns = {
|
||||
"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: list[str] = ["subject", "session"]
|
||||
|
||||
|
||||
Now, we can use our DataGrabber in ``junifer``, by setting the ``datagrabber``
|
||||
|
|
@ -259,35 +249,30 @@ And we can create our DataGrabber:
|
|||
|
||||
.. code-block:: python
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from junifer.api.decorators import register_datagrabber
|
||||
from junifer.datagrabber import PatternDataladDataGrabber
|
||||
from pydantic import AnyUrl
|
||||
|
||||
|
||||
@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",
|
||||
},
|
||||
}
|
||||
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,
|
||||
)
|
||||
|
||||
uri: AnyUrl = "https://gin.g-node.org/juaml/datalad-example-bids"
|
||||
types: list[DataType] = ["T1w", "BOLD"]
|
||||
patterns: DataGrabberPatterns = {
|
||||
"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: list[str] = ["subject", "session"]
|
||||
rootdir: Path = "example_bids_ses"
|
||||
|
||||
This approach can be used directly from the YAML, like so:
|
||||
|
||||
|
|
@ -376,8 +361,8 @@ need to implement the following methods:
|
|||
|
||||
.. note::
|
||||
|
||||
The ``__init__`` method could also be implemented, but it is not mandatory.
|
||||
This is required if the DataGrabber requires any extra parameter.
|
||||
If the DataGrabber requires any extra parameter, they could be defined as
|
||||
class attributes.
|
||||
|
||||
We will now implement our BIDS example with this method.
|
||||
|
||||
|
|
@ -494,8 +479,8 @@ more information about the format of the confounds file. Thus, the
|
|||
``BOLD.confounds`` element is a dictionary with the following keys:
|
||||
|
||||
- ``path``: the path to the confounds file.
|
||||
- ``format``: the format of the confounds file. Currently, this can be either
|
||||
``fmriprep`` or ``adhoc``.
|
||||
- ``format``: the format of the confounds file. Check :enum:`.ConfoundsFormat`
|
||||
for options.
|
||||
|
||||
The ``fmriprep`` format corresponds to the format of the confounds files
|
||||
generated by `fMRIPrep`_. The ``adhoc`` format corresponds to a format that is
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ by having a class attribute like so:
|
|||
|
||||
_EXT_DEPENDENCIES: ClassVar[ExternalDependencies] = [
|
||||
{
|
||||
"name": "afni",
|
||||
"name": ExtDep.AFNI,
|
||||
"commands": ["3dReHo", "3dAFNItoNIFTI"],
|
||||
},
|
||||
]
|
||||
|
|
@ -55,7 +55,7 @@ The above example is taken from the class which computes regional homogeneity
|
|||
(ReHo) using AFNI. The general pattern is that you need to have the value of
|
||||
``_EXT_DEPENDENCIES`` as a list of dictionary with two keys:
|
||||
|
||||
* ``name`` (str) : lowercased name of the toolbox
|
||||
* ``name`` (:enum:`.ExtDep`) : name of the toolbox
|
||||
* ``commands`` (list of str) : actual names of the commands you need to use
|
||||
|
||||
This is simple but powerful as we will see in the following sub-sections.
|
||||
|
|
@ -81,11 +81,11 @@ that it shows the problem a bit better and how we solve it:
|
|||
_CONDITIONAL_DEPENDENCIES: ClassVar[ConditionalDependencies] = [
|
||||
{
|
||||
"using": "fsl",
|
||||
"depends_on": FSLWarper,
|
||||
"depends_on": [FSLWarper],
|
||||
},
|
||||
{
|
||||
"using": "ants",
|
||||
"depends_on": ANTsWarper,
|
||||
"depends_on": [ANTSWarper],
|
||||
},
|
||||
{
|
||||
"using": "auto",
|
||||
|
|
@ -93,18 +93,16 @@ that it shows the problem a bit better and how we solve it:
|
|||
},
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self, using: str, reference: str, on: Union[List[str], str]
|
||||
) -> None:
|
||||
# validation and setting up
|
||||
...
|
||||
using: str
|
||||
reference: str
|
||||
on: List[DataType]
|
||||
|
||||
|
||||
Here, you see a new class attribute ``_CONDITIONAL_DEPENDENCIES`` which is a
|
||||
list of dictionaries with two keys:
|
||||
|
||||
* ``using`` (str) : lowercased name of the toolbox
|
||||
* ``depends_on`` (object or list of objects) : a class or list of classes which \
|
||||
* ``depends_on`` (list of objects) : list of classes which \
|
||||
implements the particular tool's use
|
||||
|
||||
It is mandatory to have the ``using`` positional argument in the constructor in
|
||||
|
|
@ -128,7 +126,7 @@ similar. ``FSLWarper`` looks like this (only the relevant part is shown here):
|
|||
|
||||
_EXT_DEPENDENCIES: ClassVar[ExternalDependencies] = [
|
||||
{
|
||||
"name": "fsl",
|
||||
"name": ExtDep.FSL,
|
||||
"commands": ["flirt", "applywarp"],
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -34,4 +34,5 @@ DataGrabbers, Preprocessors, Markers, etc., following the *junifer* way.
|
|||
plugins
|
||||
data_registries
|
||||
data_types
|
||||
confounds_format
|
||||
data_dump_asset
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ Most of the functionality of a ``junifer`` Marker has been taken care by the
|
|||
:class:`.BaseMarker` class. Thus, only a few methods and class attributes are
|
||||
required:
|
||||
|
||||
#. ``__init__``: The initialisation method, where the Marker is configured.
|
||||
#. (optional) ``validate_marker_params``: The method to perform logical validation of parameters (if required).
|
||||
#. ``compute``: The method that given the data, computes the Marker.
|
||||
|
||||
As an example, we will develop a ``ParcelMean`` Marker, a Marker that first
|
||||
|
|
@ -29,8 +29,8 @@ Step 1: Configure input and output
|
|||
This step is quite simple: we need to define the input and output of the Marker.
|
||||
Based on the current :ref:`data types <data_types>`, we can have ``BOLD``,
|
||||
``VBM_WM`` and ``VBM_GM`` as valid inputs. The output of the Marker depends on
|
||||
the input. For ``BOLD``, it will be ``timeseries``, while for the rest of the
|
||||
inputs, it will be ``vector``. Thus, we have a class attribute like so:
|
||||
the input. For ``BOLD``, it will be ``Timeseries``, while for the rest of the
|
||||
inputs, it will be ``Vector``. Thus, we have a class attribute like so:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
|
@ -38,14 +38,14 @@ inputs, it will be ``vector``. Thus, we have a class attribute like so:
|
|||
# You can have multiple features for one data type,
|
||||
# each feature having same or different storage type
|
||||
_MARKER_INOUT_MAPPINGS = {
|
||||
"BOLD": {
|
||||
"parcel_mean": "timeseries",
|
||||
DataType.BOLD: {
|
||||
"parcel_mean": StorageType.Timeseries,
|
||||
},
|
||||
"VBM_WM": {
|
||||
"parcel_mean": "vector",
|
||||
DataType.VBM_WM: {
|
||||
"parcel_mean": StorageType.Vector,
|
||||
},
|
||||
"VBM_GM": {
|
||||
"parcel_mean": "vector",
|
||||
DataType.VBM_GM: {
|
||||
"parcel_mean": StorageType.Vector,
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -57,13 +57,11 @@ Step 2: Initialise the Marker
|
|||
In this step we need to define the parameters of the Marker the user can provide
|
||||
to configure how the Marker will behave.
|
||||
|
||||
The parameters of the Marker are defined in the ``__init__`` method. The
|
||||
:class:`.BaseMarker` class requires two optional parameters:
|
||||
The parameters of the Marker are defined as class attributes. The
|
||||
:class:`.BaseMarker` class defines two optional parameters:
|
||||
|
||||
1. ``name``: the name of the Marker. This is used to identify the Marker in the
|
||||
configuration file.
|
||||
2. ``on``: a list or string with the data types that the Marker will be applied
|
||||
to.
|
||||
1. ``name``: the name of the Marker. This is used to identify the Marker in the configuration file.
|
||||
2. ``on``: a list of :enum:`.DataType` with the data types that the Marker will be applied to.
|
||||
|
||||
.. attention::
|
||||
|
||||
|
|
@ -72,18 +70,11 @@ The parameters of the Marker are defined in the ``__init__`` method. The
|
|||
JSON format, and JSON only supports these types.
|
||||
|
||||
In this example, only parameter required for the computation is the name of the
|
||||
parcellation to use. Thus, we can define the ``__init__`` method as follows:
|
||||
parcellation to use. Thus, we can define as follows:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parcellation: str,
|
||||
on: str | list[str] | None = None,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
self.parcellation = parcellation
|
||||
super().__init__(on=on, name=name)
|
||||
parcellation: str
|
||||
|
||||
.. caution::
|
||||
|
||||
|
|
@ -121,14 +112,14 @@ and the values would be a dictionary of storage type specific key-value pairs.
|
|||
|
||||
To simplify the ``store`` method, define keys of the dictionary based on the
|
||||
corresponding store functions in the :ref:`storage types <storage_types>`.
|
||||
For example, if the output is a ``vector``, the keys of the dictionary should
|
||||
For example, if the output is a ``Vector``, the keys of the dictionary should
|
||||
be ``data`` and ``col_names``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from typing import Any
|
||||
|
||||
from junifer.data import get_parcellation
|
||||
from junifer.data import get_data
|
||||
from nilearn.maskers import NiftiLabelsMasker
|
||||
|
||||
|
||||
|
|
@ -141,8 +132,9 @@ and the values would be a dictionary of storage type specific key-value pairs.
|
|||
data = input["data"]
|
||||
|
||||
# Get the parcellation tailored for the target
|
||||
t_parcellation, t_labels, _ = get_parcellation(
|
||||
name=self.parcellation_name,
|
||||
t_parcellation, t_labels, _ = get_data(
|
||||
kind="parcellation",
|
||||
name=[self.parcellation],
|
||||
target_data=input,
|
||||
extra_input=extra_input,
|
||||
)
|
||||
|
|
@ -194,8 +186,10 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
|
|||
from typing import Any, ClassVar
|
||||
|
||||
from junifer.api.decorators import register_marker
|
||||
from junifer.data import get_parcellation
|
||||
from junifer.data import get_data
|
||||
from junifer.datagrabber import DataType
|
||||
from junifer.markers import BaseMarker
|
||||
from junifer.storage import StorageType
|
||||
from junifer.typing import Dependencies, MarkerInOutMappings
|
||||
from nilearn.maskers import NiftiLabelsMasker
|
||||
|
||||
|
|
@ -206,25 +200,18 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
|
|||
_DEPENDENCIES: ClassVar[Dependencies] = {"nilearn", "numpy"}
|
||||
|
||||
_MARKER_INOUT_MAPPINGS: ClassVar[MarkerInOutMappings] = {
|
||||
"BOLD": {
|
||||
"parcel_mean": "timeseries",
|
||||
DataType.BOLD: {
|
||||
"parcel_mean": StorageType.Timeseries,
|
||||
},
|
||||
"VBM_WM": {
|
||||
"parcel_mean": "vector",
|
||||
DataType.VBM_WM: {
|
||||
"parcel_mean": StorageType.Vector,
|
||||
},
|
||||
"VBM_GM": {
|
||||
"parcel_mean": "vector",
|
||||
DataType.VBM_GM: {
|
||||
"parcel_mean": StorageType.Vector,
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parcellation: str,
|
||||
on: str | list[str] | None = None,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
self.parcellation = parcellation
|
||||
super().__init__(on=on, name=name)
|
||||
parcellation: str
|
||||
|
||||
def compute(
|
||||
self,
|
||||
|
|
@ -235,8 +222,9 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
|
|||
data = input["data"]
|
||||
|
||||
# Get the parcellation tailored for the target
|
||||
t_parcellation, t_labels, _ = get_parcellation(
|
||||
name=self.parcellation_name,
|
||||
t_parcellation, t_labels, _ = get_data(
|
||||
kind="parcellation",
|
||||
name=[self.parcellation],
|
||||
target_data=input,
|
||||
extra_input=extra_input,
|
||||
)
|
||||
|
|
@ -280,9 +268,13 @@ Template for a custom Marker
|
|||
# TODO: add the input-output mappings
|
||||
_MARKER_INOUT_MAPPINGS = {}
|
||||
|
||||
def __init__(self, on=None, name=None):
|
||||
# TODO: add marker-specific parameters
|
||||
super().__init__(on=on, name=name)
|
||||
# TODO: define marker-specific parameters
|
||||
|
||||
# optional
|
||||
def validate_marker_params(self):
|
||||
# TODO: add validation logic for marker parameters
|
||||
pass
|
||||
|
||||
def compute(self, input, extra_input):
|
||||
# TODO: compute the marker and create the output dictionary
|
||||
return {}
|
||||
|
|
|
|||
|
|
@ -124,7 +124,7 @@ parcellation when registering it. For example, we can add a
|
|||
markers:
|
||||
|
|
||||
- name: CustomParcellation_mean
|
||||
kind: ParcelAggregation
|
||||
parcellation: my_custom_parcellation
|
||||
parcellation: <my_custom_parcellation>
|
||||
method: mean
|
||||
|
||||
Now, you can simply use this YAML file to run your pipeline.
|
||||
|
|
|
|||
|
|
@ -16,8 +16,7 @@ own Preprocessor.
|
|||
While implementing your own Preprocessor, you need to always inherit from
|
||||
:class:`.BasePreprocessor` and implement a few methods and class attributes:
|
||||
|
||||
#. ``__init__``: The initialisation method, where the Preprocessor is
|
||||
configured.
|
||||
#. (optional) ``validate_preprocessor_params``: The method to perform logical validation of parameters (if required).
|
||||
#. ``preprocess``: The method that given the data, preprocesses the data.
|
||||
|
||||
As an example, we will develop a ``NilearnSmoothing`` Preprocessor, which
|
||||
|
|
@ -43,8 +42,8 @@ For input we can accept ``T1w``, ``T2w`` and ``BOLD``
|
|||
Step 2: Initialise the Preprocessor
|
||||
-----------------------------------
|
||||
|
||||
Now we need to define our Preprocessor class' constructor which is also how
|
||||
you configure it. Our class will have the following arguments:
|
||||
Now we need to define our Preprocessor class' parameters as class attributes.
|
||||
Our class will have the following:
|
||||
|
||||
1. ``fwhm``: The smoothing strength as a full-width at half maximum
|
||||
(in millimetres). Since we depend on :func:`nilearn.image.smooth_img`, we
|
||||
|
|
@ -59,6 +58,8 @@ you configure it. Our class will have the following arguments:
|
|||
are allowed as parameters. This is because the parameters are stored in
|
||||
JSON format, and JSON only supports these types.
|
||||
|
||||
As :class:`.BasePreprocessor` already defines ``on``, we can define the other:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from typing import Literal
|
||||
|
|
@ -68,15 +69,7 @@ you configure it. Our class will have the following arguments:
|
|||
|
||||
...
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
fwhm: int | float | ArrayLike | Literal["fast"] | None,
|
||||
on: str | list[str] | None = None,
|
||||
) -> None:
|
||||
self.fwhm = fwhm
|
||||
super().__init__(on=on)
|
||||
|
||||
fwhm: int | float | ArrayLike | Literal["fast"] | None
|
||||
|
||||
...
|
||||
|
||||
|
|
@ -165,15 +158,9 @@ decorator and our final code should look like this:
|
|||
|
||||
_DEPENDENCIES = {"nilearn"}
|
||||
|
||||
_VALID_DATA_TYPES: ClassVar[Sequence[str]] = ["T1w", "T2w", "BOLD"]
|
||||
_VALID_DATA_TYPES: ClassVar[Sequence[DataType]] = ["T1w", "T2w", "BOLD"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
fwhm: int | float | ArrayLike | Literal["fast"] | None,
|
||||
on: str | list[str] | None = None,
|
||||
) -> None:
|
||||
self.fwhm = fwhm
|
||||
super().__init__(on=on)
|
||||
fwhm: int | float | ArrayLike | Literal["fast"] | None
|
||||
|
||||
def preprocess(
|
||||
self,
|
||||
|
|
@ -191,7 +178,11 @@ Template for a custom Preprocessor
|
|||
|
||||
.. code-block:: python
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import ClassVar
|
||||
|
||||
from junifer.api.decorators import register_preprocessor
|
||||
from junifer.datagrabber import DataType
|
||||
from junifer.preprocess import BasePreprocessor
|
||||
|
||||
|
||||
|
|
@ -202,11 +193,14 @@ Template for a custom Preprocessor
|
|||
_DEPENDENCIES = {}
|
||||
|
||||
# TODO: add the inputs
|
||||
|
We can already leave the typing in the template here We can already leave the typing in the template here
What do you mean? What do you mean?
This is supposed to be a template to create your own preprocessor:
This is supposed to be a template to create your own preprocessor:
```
_VALID_DATA_TYPES: ClassVar[Sequence[DataType]] = []
```
Addressed in latest commit. Addressed in latest commit.
|
||||
_VALID_DATA_TYPES = []
|
||||
_VALID_DATA_TYPES: ClassVar[Sequence[DataType]] = []
|
||||
|
||||
def __init__(self, on=None):
|
||||
# TODO: add preprocessor-specific parameters
|
||||
super().__init__(on=on)
|
||||
# TODO: define preprocessor-specific parameters
|
||||
|
||||
# optional
|
||||
def validate_preprocessor_params(self):
|
||||
# TODO: add validation logic for preprocessor parameters
|
||||
pass
|
||||
|
||||
def preprocess(self, input, extra_input):
|
||||
# TODO: add the preprocessor logic
|
||||
|
|
|
|||
|
|
@ -265,7 +265,7 @@ Features
|
|||
^^^^^^^^
|
||||
|
||||
- Introduce :func:`.normalize` and :func:`.reweight` functions for downstream
|
||||
BrainPrint analysis in :mod:`.onthefly.brainprint` by `Synchon Mandal`_
|
||||
BrainPrint analysis in :mod:`.onthefly._brainprint` by `Synchon Mandal`_
|
||||
(:gh:`354`)
|
||||
- Introduce :class:`junifer.pipeline.PipelineComponentRegistry` to centralise
|
||||
pipeline component management by `Synchon Mandal`_ (:gh:`362`)
|
||||
|
|
|
|||
|
|
@ -15,8 +15,10 @@ from junifer.testing.datagrabbers import (
|
|||
OasisVBMTestingDataGrabber,
|
||||
SPMAuditoryTestingDataGrabber,
|
||||
)
|
||||
from junifer.datagrabber import DataType
|
||||
from junifer.datareader import DefaultDataReader
|
||||
from junifer.markers import ParcelAggregation
|
||||
from junifer.stats import AggFunc
|
||||
from junifer.utils import configure_logging
|
||||
|
||||
|
||||
|
|
@ -32,7 +34,10 @@ with OasisVBMTestingDataGrabber() as dg:
|
|||
# Read the element
|
||||
element_data = DefaultDataReader().fit_transform(dg[element])
|
||||
# Initialize marker
|
||||
marker = ParcelAggregation(parcellation="Schaefer100x7", method="mean")
|
||||
marker = ParcelAggregation(
|
||||
parcellation="Schaefer100x7",
|
||||
method=AggFunc.Mean,
|
||||
)
|
||||
# Compute feature
|
||||
feature = marker.fit_transform(element_data)
|
||||
# Print the output
|
||||
|
|
@ -48,7 +53,9 @@ with SPMAuditoryTestingDataGrabber() as dg:
|
|||
element_data = DefaultDataReader().fit_transform(dg[element])
|
||||
# Initialize marker
|
||||
marker = ParcelAggregation(
|
||||
parcellation="Schaefer100x7", method="mean", on="BOLD"
|
||||
parcellation="Schaefer100x7",
|
||||
method=AggFunc.Mean,
|
||||
on=[DataType.BOLD],
|
||||
)
|
||||
# Compute feature
|
||||
feature = marker.fit_transform(element_data)
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ Authors: Federico Raimondo
|
|||
License: BSD 3 clause
|
||||
"""
|
||||
|
||||
from junifer.datagrabber import PatternDataladDataGrabber
|
||||
from junifer.datagrabber import DataType, PatternDataladDataGrabber
|
||||
from junifer.utils import configure_logging
|
||||
|
||||
|
||||
|
|
@ -23,7 +23,7 @@ configure_logging(level="INFO")
|
|||
# The BIDS DataGrabber requires three parameters: the types of data we want,
|
||||
# the specific pattern that matches each type, and the variables that will be
|
||||
# replaced in the patterns.
|
||||
types = ["T1w", "BOLD"]
|
||||
types = [DataType.T1w, DataType.BOLD]
|
||||
patterns = {
|
||||
"T1w": {
|
||||
"pattern": "{subject}/anat/{subject}_T1w.nii.gz",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ from julearn import run_cross_validation, PipelineCreator
|
|||
|
||||
import junifer.testing.registry # noqa: F401
|
||||
from junifer.api import collect, run
|
||||
from junifer.storage.sqlite import SQLiteFeatureStorage
|
||||
from junifer.storage import SQLiteFeatureStorage
|
||||
from junifer.utils import configure_logging
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
# Synchon Mandal <s.mandal@fz-juelich.de>
|
||||
# License: AGPL
|
||||
|
||||
import atexit
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
|
@ -182,6 +183,7 @@ def run(
|
|||
"elements will be processed"
|
||||
)
|
||||
WorkDirManager(**workdir)
|
||||
atexit.register(WorkDirManager()._cleanup)
|
||||
|
||||
# Get datagrabber to use
|
||||
datagrabber_object = _get_datagrabber(datagrabber.copy())
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
__all__ = ["QueueContextAdapter", "HTCondorAdapter", "GnuParallelLocalAdapter"]
|
||||
__all__ = [
|
||||
"QueueContextAdapter",
|
||||
"EnvKind",
|
||||
"EnvShell",
|
||||
"QueueContextEnv",
|
||||
"HTCondorAdapter",
|
||||
"HTCondorCollect",
|
||||
"GnuParallelLocalAdapter",
|
||||
]
|
||||
|
||||
from .queue_context_adapter import QueueContextAdapter
|
||||
from .htcondor_adapter import HTCondorAdapter
|
||||
from .queue_context_adapter import QueueContextAdapter, EnvKind, EnvShell, QueueContextEnv
|
||||
from .htcondor_adapter import HTCondorAdapter, HTCondorCollect
|
||||
from .gnu_parallel_local_adapter import GnuParallelLocalAdapter
|
||||
|
|
|
|||
|
|
@ -6,10 +6,16 @@
|
|||
import shutil
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from ...typing import Elements
|
||||
from ...utils import logger, make_executable, raise_error, run_ext_cmd
|
||||
from .queue_context_adapter import QueueContextAdapter
|
||||
from .queue_context_adapter import (
|
||||
EnvKind,
|
||||
EnvShell,
|
||||
QueueContextAdapter,
|
||||
QueueContextEnv,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["GnuParallelLocalAdapter"]
|
||||
|
|
@ -26,14 +32,14 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
The path to the job directory.
|
||||
yaml_config_path : pathlib.Path
|
||||
The path to the YAML config file.
|
||||
elements : list of str or tuple
|
||||
elements : ``Elements``
|
||||
Element(s) to process. Will be used to index the DataGrabber.
|
||||
pre_run : str or None, optional
|
||||
pre_run_cmds : str or None, optional
|
||||
Extra shell commands to source before the run (default None).
|
||||
pre_collect : str or None, optional
|
||||
Extra bash commands to source before the collect (default None).
|
||||
env : dict, optional
|
||||
The Python environment configuration. If None, will run without a
|
||||
pre_collect_cmds : str or None, optional
|
||||
Extra shell commands to source before the collect (default None).
|
||||
env : :class:`.QueueContextEnv` or None, optional
|
||||
The environment configuration. If None, will run without a
|
||||
virtual environment of any kind (default None).
|
||||
verbose : str, optional
|
||||
The level of verbosity (default "info").
|
||||
|
|
@ -43,12 +49,6 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
submit : bool, optional
|
||||
Whether to submit the jobs (default False).
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If ``env.kind`` is invalid or
|
||||
if ``env.shell`` is invalid.
|
||||
|
||||
See Also
|
||||
--------
|
||||
QueueContextAdapter :
|
||||
|
|
@ -58,87 +58,44 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
job_name: str,
|
||||
job_dir: Path,
|
||||
yaml_config_path: Path,
|
||||
elements: Elements,
|
||||
pre_run: str | None = None,
|
||||
pre_collect: str | None = None,
|
||||
env: dict[str, str] | None = None,
|
||||
verbose: str = "info",
|
||||
verbose_datalad: str | None = None,
|
||||
submit: bool = False,
|
||||
) -> None:
|
||||
"""Initialize the class."""
|
||||
self._job_name = job_name
|
||||
self._job_dir = job_dir
|
||||
self._yaml_config_path = yaml_config_path
|
||||
self._elements = elements
|
||||
self._pre_run = pre_run
|
||||
self._pre_collect = pre_collect
|
||||
self._check_env(env)
|
||||
self._verbose = verbose
|
||||
self._verbose_datalad = verbose_datalad
|
||||
self._submit = submit
|
||||
job_name: str
|
||||
job_dir: Path
|
||||
yaml_config_path: Path
|
||||
elements: Elements
|
||||
pre_run_cmds: str | None = None
|
||||
pre_collect_cmds: str | None = None
|
||||
env: QueueContextEnv | None = None
|
||||
verbose: str = "info"
|
||||
verbose_datalad: str | None = None
|
||||
submit: bool = False
|
||||
|
||||
self._log_dir = self._job_dir / "logs"
|
||||
self._pre_run_path = self._job_dir / "pre_run.sh"
|
||||
self._pre_collect_path = self._job_dir / "pre_collect.sh"
|
||||
self._run_path = self._job_dir / f"run_{self._job_name}.sh"
|
||||
self._collect_path = self._job_dir / f"collect_{self._job_name}.sh"
|
||||
self._run_joblog_path = self._job_dir / f"run_{self._job_name}_joblog"
|
||||
self._elements_file_path = self._job_dir / "elements"
|
||||
|
||||
def _check_env(self, env: dict[str, str] | None) -> None:
|
||||
"""Check value of env parameter on init.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
env : dict or None
|
||||
The value of env parameter.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If ``env.kind`` is invalid.
|
||||
|
||||
"""
|
||||
# Set env related variables
|
||||
if env is None:
|
||||
env = {"kind": "local"}
|
||||
# Check env kind
|
||||
valid_env_kinds = ["conda", "venv", "local"]
|
||||
if env["kind"] not in valid_env_kinds:
|
||||
raise_error(
|
||||
f"Invalid value for `env.kind`: {env['kind']}, "
|
||||
f"must be one of {valid_env_kinds}"
|
||||
def model_post_init(self, context: Any): # noqa: D102
|
||||
if self.env is None:
|
||||
self.env = QueueContextEnv(
|
||||
kind=EnvKind.Local, shell=EnvShell.Bash, name=""
|
||||
)
|
||||
if self.env["kind"] == EnvKind.Local:
|
||||
# No virtual environment
|
||||
self._executable = "junifer"
|
||||
self._arguments = ""
|
||||
else:
|
||||
# Check shell
|
||||
shell = env.get("shell", "bash")
|
||||
valid_shells = ["bash", "zsh"]
|
||||
if shell not in valid_shells:
|
||||
raise_error(
|
||||
f"Invalid value for `env.shell`: {shell}, "
|
||||
f"must be one of {valid_shells}"
|
||||
)
|
||||
self._shell = shell
|
||||
# Set variables
|
||||
if env["kind"] == "local":
|
||||
# No virtual environment
|
||||
self._executable = "junifer"
|
||||
self._arguments = ""
|
||||
else:
|
||||
self._executable = f"run_{env['kind']}.{self._shell}"
|
||||
self._arguments = f"{env['name']} junifer"
|
||||
self._exec_path = self._job_dir / self._executable
|
||||
if self.env["name"] is None:
|
||||
raise_error("`env.name` is required")
|
||||
self._executable = f"run_{self.env['kind']}.{self.env['shell']}"
|
||||
self._arguments = f"{self.env['name']} junifer"
|
||||
self._exec_path = self.job_dir / self._executable
|
||||
self._log_dir = self.job_dir / "logs"
|
||||
self._pre_run_path = self.job_dir / "pre_run.sh"
|
||||
self._pre_collect_path = self.job_dir / "pre_collect.sh"
|
||||
self._run_path = self.job_dir / f"run_{self.job_name}.sh"
|
||||
self._collect_path = self.job_dir / f"collect_{self.job_name}.sh"
|
||||
self._run_joblog_path = self.job_dir / f"run_{self.job_name}_joblog"
|
||||
self._elements_file_path = self.job_dir / "elements"
|
||||
|
||||
def elements(self) -> str:
|
||||
def elements_to_run(self) -> str:
|
||||
"""Return elements to run."""
|
||||
elements_to_run = []
|
||||
for element in self._elements:
|
||||
for element in self.elements:
|
||||
# Stringify elements if tuple for operation
|
||||
str_element = (
|
||||
",".join(element) if isinstance(element, tuple) else element
|
||||
|
|
@ -150,23 +107,23 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
def pre_run(self) -> str:
|
||||
"""Return pre-run commands."""
|
||||
fixed = (
|
||||
f"#!/usr/bin/env {self._shell}\n\n"
|
||||
f"#!/usr/bin/env {self.env['shell']}\n\n"
|
||||
"# This script is auto-generated by junifer.\n\n"
|
||||
"# Force datalad to run in non-interactive mode\n"
|
||||
"DATALAD_UI_INTERACTIVE=false\n"
|
||||
)
|
||||
var = self._pre_run or ""
|
||||
var = self.pre_run_cmds or ""
|
||||
return fixed + "\n" + var
|
||||
|
||||
def run(self) -> str:
|
||||
"""Return run commands."""
|
||||
verbose_args = f"--verbose {self._verbose}"
|
||||
if self._verbose_datalad:
|
||||
verbose_args = f"--verbose {self.verbose}"
|
||||
if self.verbose_datalad:
|
||||
verbose_args = (
|
||||
f"{verbose_args} --verbose-datalad {self._verbose_datalad}"
|
||||
f"{verbose_args} --verbose-datalad {self.verbose_datalad}"
|
||||
)
|
||||
return (
|
||||
f"#!/usr/bin/env {self._shell}\n\n"
|
||||
f"#!/usr/bin/env {self.env['shell']}\n\n"
|
||||
"# This script is auto-generated by junifer.\n\n"
|
||||
"# Run pre_run.sh\n"
|
||||
f"sh {self._pre_run_path.resolve()!s}\n\n"
|
||||
|
|
@ -176,9 +133,9 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
"--delay 60 " # wait 1 min before next job is spawned
|
||||
f"--results {self._log_dir} "
|
||||
f"--arg-file {self._elements_file_path.resolve()!s} "
|
||||
f"{self._job_dir.resolve()!s}/{self._executable} "
|
||||
f"{self.job_dir.resolve()!s}/{self._executable} "
|
||||
f"{self._arguments} run "
|
||||
f"{self._yaml_config_path.resolve()!s} "
|
||||
f"{self.yaml_config_path.resolve()!s} "
|
||||
f"{verbose_args} "
|
||||
f"--element"
|
||||
)
|
||||
|
|
@ -186,28 +143,28 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
def pre_collect(self) -> str:
|
||||
"""Return pre-collect commands."""
|
||||
fixed = (
|
||||
f"#!/usr/bin/env {self._shell}\n\n"
|
||||
f"#!/usr/bin/env {self.env['shell']}\n\n"
|
||||
"# This script is auto-generated by junifer.\n"
|
||||
)
|
||||
var = self._pre_collect or ""
|
||||
var = self.pre_collect_cmds or ""
|
||||
return fixed + "\n" + var
|
||||
|
||||
def collect(self) -> str:
|
||||
"""Return collect commands."""
|
||||
verbose_args = f"--verbose {self._verbose}"
|
||||
if self._verbose_datalad:
|
||||
verbose_args = f"--verbose {self.verbose}"
|
||||
if self.verbose_datalad:
|
||||
verbose_args = (
|
||||
f"{verbose_args} --verbose-datalad {self._verbose_datalad}"
|
||||
f"{verbose_args} --verbose-datalad {self.verbose_datalad}"
|
||||
)
|
||||
return (
|
||||
f"#!/usr/bin/env {self._shell}\n\n"
|
||||
f"#!/usr/bin/env {self.env['shell']}\n\n"
|
||||
"# This script is auto-generated by junifer.\n\n"
|
||||
"# Run pre_collect.sh\n"
|
||||
f"sh {self._pre_collect_path.resolve()!s}\n\n"
|
||||
"# Run `junifer collect`\n"
|
||||
f"{self._job_dir.resolve()!s}/{self._executable} "
|
||||
f"{self.job_dir.resolve()!s}/{self._executable} "
|
||||
f"{self._arguments} collect "
|
||||
f"{self._yaml_config_path.resolve()!s} "
|
||||
f"{self.yaml_config_path.resolve()!s} "
|
||||
f"{verbose_args}"
|
||||
)
|
||||
|
||||
|
|
@ -230,17 +187,19 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
f"{self._elements_file_path.resolve()!s}"
|
||||
)
|
||||
self._elements_file_path.touch()
|
||||
self._elements_file_path.write_text(textwrap.dedent(self.elements()))
|
||||
self._elements_file_path.write_text(
|
||||
textwrap.dedent(self.elements_to_run())
|
||||
)
|
||||
# Create pre run
|
||||
logger.info(
|
||||
f"Writing {self._pre_run_path.name} to {self._job_dir.resolve()!s}"
|
||||
f"Writing {self._pre_run_path.name} to {self.job_dir.resolve()!s}"
|
||||
)
|
||||
self._pre_run_path.touch()
|
||||
self._pre_run_path.write_text(textwrap.dedent(self.pre_run()))
|
||||
make_executable(self._pre_run_path)
|
||||
# Create run
|
||||
logger.info(
|
||||
f"Writing {self._run_path.name} to {self._job_dir.resolve()!s}"
|
||||
f"Writing {self._run_path.name} to {self.job_dir.resolve()!s}"
|
||||
)
|
||||
self._run_path.touch()
|
||||
self._run_path.write_text(textwrap.dedent(self.run()))
|
||||
|
|
@ -248,14 +207,14 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
# Create pre collect
|
||||
logger.info(
|
||||
f"Writing {self._pre_collect_path.name} to "
|
||||
f"{self._job_dir.resolve()!s}"
|
||||
f"{self.job_dir.resolve()!s}"
|
||||
)
|
||||
self._pre_collect_path.touch()
|
||||
self._pre_collect_path.write_text(textwrap.dedent(self.pre_collect()))
|
||||
make_executable(self._pre_collect_path)
|
||||
# Create collect
|
||||
logger.info(
|
||||
f"Writing {self._collect_path.name} to {self._job_dir.resolve()!s}"
|
||||
f"Writing {self._collect_path.name} to {self.job_dir.resolve()!s}"
|
||||
)
|
||||
self._collect_path.touch()
|
||||
self._collect_path.write_text(textwrap.dedent(self.collect()))
|
||||
|
|
@ -263,7 +222,7 @@ class GnuParallelLocalAdapter(QueueContextAdapter):
|
|||
# Submit if required
|
||||
run_cmd = f"sh {self._run_path.resolve()!s}"
|
||||
collect_cmd = f"sh {self._collect_path.resolve()!s}"
|
||||
if self._submit:
|
||||
if self.submit:
|
||||
logger.info(
|
||||
"Shell scripts created, the following will be run:\n"
|
||||
f"{run_cmd}\n"
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue
Same here: str or list[str]