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