[ENH]: Update Warp datatype schema and logic #390

Merged
synchon merged 20 commits from refactor/warp-dtype into main 2024-11-13 11:55:48 +00:00
31 changed files with 750 additions and 339 deletions

View file

@ -0,0 +1 @@
:class:`.SpaceWarper`'s ``using`` now supports ``"auto"`` allowing auto tool selection based on DataGrabber specification by `Synchon Mandal`_

View file

@ -0,0 +1 @@
Update ``Warp`` data type to be a list of dictionaries and adapt to allow multiple transforms to be specified by `Synchon Mandal`_

View file

@ -39,7 +39,7 @@ and others who use it will thank you.
Handling external dependencies from toolboxes Handling external dependencies from toolboxes
--------------------------------------------- ---------------------------------------------
You can also specify dependencies of external toolboxes like AFIN, FSL and ANTs, You can also specify dependencies of external toolboxes like AFNI, FSL and ANTs,
by having a class attribute like so: by having a class attribute like so:
.. code-block:: python .. code-block:: python
@ -87,6 +87,10 @@ that it shows the problem a bit better and how we solve it:
"using": "ants", "using": "ants",
"depends_on": ANTsWarper, "depends_on": ANTsWarper,
}, },
{
"using": "auto",
"depends_on": [FSLWarper, ANTsWarper],
},
] ]
def __init__( def __init__(
@ -100,13 +104,20 @@ 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) : a class which implements the particular tool's use * ``depends_on`` (object or list of objects) : a class or list of classes which \
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
this case as the validation starts with this and moves further. It is also this case as the validation starts with this and moves further. It is also
mandatory to only allow the value of ``using`` argument to be one of them mandatory to only allow the value of ``using`` argument to be one of them
specified in the ``using`` key of ``_CONDITIONAL_DEPENDENCIES`` entries. specified in the ``using`` key of ``_CONDITIONAL_DEPENDENCIES`` entries.
For some cases, like we have here, it might be worth to have ``"auto"`` for
``"using"`` which eases the choice of a particular tool by the user and
instead lets ``junifer`` do it automatically. In that case, ``"depends_on"``
needs to be a list of the tool implementation classes. This also requires the
user to have all the tools in the ``PATH``.
For brevity, we only show the ``FSLWarper`` here but ``ANTsWarper`` looks very For brevity, we only show the ``FSLWarper`` here but ``ANTsWarper`` looks very
similar. ``FSLWarper`` looks like this (only the relevant part is shown here): similar. ``FSLWarper`` looks like this (only the relevant part is shown here):

View file

@ -146,14 +146,23 @@ Warping to subject's native space
To warp to subject's native space, the dataset needs to provide ``T1w`` and To warp to subject's native space, the dataset needs to provide ``T1w`` and
fraimondo commented 2024-11-08 15:52:55 +00:00 (Migrated from github.com)

There's no "preferred", but the one that suits the datagrabber's warp file format.

There's no "preferred", but the one that suits the datagrabber's warp file format.
``Warp`` data types and the DataGrabber needs to at least have ``Warp`` data types and the DataGrabber needs to at least have
``["BOLD", "T1w", "Warp"]`` (if you are warping ``BOLD``) as the ``types`` ``["BOLD", "T1w", "Warp"]`` (if you are warping ``BOLD``) as the ``types``
parameter's value. The :class:`.SpaceWarper`'s ``reference`` parameter needs parameter's value.
The :class:`.SpaceWarper`'s ``reference`` parameter needs
to be set to ``T1w``, which means that the ``BOLD`` data will be transformed to be set to ``T1w``, which means that the ``BOLD`` data will be transformed
using the ``T1w`` as reference (it's resampled internally to match the using the ``T1w`` as reference (it's resampled internally to match the
resolution of the ``BOLD``). The ``Warp`` data type is new and it's only purpose resolution of the ``BOLD``).
is to provide the warp or transformation file (can be linear, non-linear or
linear + non-linear transform) for the purpose. For ``using`` parameter, you can The ``Warp`` data type provides the warp or transformation file (can be linear,
pass either ``"fsl"`` or ``"ants"`` depending on the warp or transformation file non-linear or linear + non-linear transform) for the purpose. For ``using``
format. parameter, you can pass either ``fsl`` or ``ants`` depending on the warp or
transformation file format. You can also provide ``auto`` to ``using`` in which
case either ``FSL`` or ``ANTs`` will be used based on the file format provided
by the DataGrabber. This also requires that both the tools are in the ``PATH``.
And finally, you would need to set the ``on`` parameter to ``BOLD`` to make it
clear which data type you intend to warp, as the :class:`.SpaceWarper` is also
capable of warping ``T1w``.
An example YAML might look like this: An example YAML might look like this:
@ -163,6 +172,7 @@ An example YAML might look like this:
- kind: SpaceWarper - kind: SpaceWarper
using: fsl using: fsl
reference: T1w reference: T1w
on: BOLD
.. _preprocess_warping_template: .. _preprocess_warping_template:
@ -174,8 +184,8 @@ data type that you want to work on) in ``MNI152NLin6Asym`` template space but
you would like to compute features in ``MNI152NLin2009cAsym`` template space, you would like to compute features in ``MNI152NLin2009cAsym`` template space,
you can also use the :class:`.SpaceWarper` by setting the ``reference`` you can also use the :class:`.SpaceWarper` by setting the ``reference``
parameter to the template space's name, in this case, parameter to the template space's name, in this case,
``reference="MNI152NLin2009cAsym"``. The ``using`` parameter needs to be set ``reference: MNI152NLin2009cAsym``. The ``using`` parameter needs to be set
to ``"ants"`` as we need it to warp the data. to ``ants`` as we need it to warp the data.
.. note:: .. note::
@ -190,3 +200,4 @@ For an YAML example:
- kind: SpaceWarper - kind: SpaceWarper
using: ants using: ants
reference: MNI152NLin2009cAsym reference: MNI152NLin2009cAsym
on: BOLD

View file

@ -26,7 +26,7 @@ class ANTsCoordinatesWarper:
self, self,
seeds: ArrayLike, seeds: ArrayLike,
target_data: Dict[str, Any], target_data: Dict[str, Any],
extra_input: Dict[str, Any], warp_data: Dict[str, Any],
) -> ArrayLike: ) -> ArrayLike:
"""Warp ``seeds`` to correct space. """Warp ``seeds`` to correct space.
@ -37,10 +37,8 @@ class ANTsCoordinatesWarper:
target_data : dict target_data : dict
The corresponding item of the data object to which the coordinates The corresponding item of the data object to which the coordinates
will be applied. will be applied.
fraimondo commented 2024-11-08 15:55:14 +00:00 (Migrated from github.com)

Don't we also need to check that the "warper" is "ants"?

Don't we also need to check that the "warper" is "ants"?
extra_input : dict, optional warp_data : dict or None
The other fields in the data object. Useful for accessing other The warp data item of the data object.
data kinds that needs to be used in the computation of coordinates
(default None).
Returns Returns
------- -------
@ -79,7 +77,7 @@ class ANTsCoordinatesWarper:
"-f 0", "-f 0",
f"-i {pretransform_coordinates_path.resolve()}", f"-i {pretransform_coordinates_path.resolve()}",
f"-o {transformed_coords_path.resolve()}", f"-o {transformed_coords_path.resolve()}",
f"-t {extra_input['Warp']['path'].resolve()};", f"-t {warp_data['path'].resolve()}",
] ]
# Call antsApplyTransformsToPoints # Call antsApplyTransformsToPoints
run_ext_cmd( run_ext_cmd(

View file

@ -14,6 +14,7 @@ from numpy.typing import ArrayLike
from ...utils import logger, raise_error from ...utils import logger, raise_error
from ...utils.singleton import Singleton from ...utils.singleton import Singleton
from ..pipeline_data_registry_base import BasePipelineDataRegistry from ..pipeline_data_registry_base import BasePipelineDataRegistry
from ..utils import get_native_warper
from ._ants_coordinates_warper import ANTsCoordinatesWarper from ._ants_coordinates_warper import ANTsCoordinatesWarper
from ._fsl_coordinates_warper import FSLCoordinatesWarper from ._fsl_coordinates_warper import FSLCoordinatesWarper
@ -311,7 +312,8 @@ class CoordinatesRegistry(BasePipelineDataRegistry, metaclass=Singleton):
Raises Raises
------ ------
RuntimeError RuntimeError
If warp / transformation file extension is not ".mat" or ".h5". If warping specification required for warping using ANTs, is not
found.
ValueError ValueError
If ``extra_input`` is None when ``target_data``'s space is native. If ``extra_input`` is None when ``target_data``'s space is native.
@ -329,27 +331,38 @@ class CoordinatesRegistry(BasePipelineDataRegistry, metaclass=Singleton):
f"{target_data['space']} space for further computation." f"{target_data['space']} space for further computation."
) )
# Check for warp file type to use correct tool # Get native space warper spec
warp_file_ext = extra_input["Warp"]["path"].suffix warper_spec = get_native_warper(
if warp_file_ext == ".mat": target_data=target_data,
other_data=extra_input,
)
# Conditional for warping tool implementation
if warper_spec["warper"] == "fsl":
seeds = FSLCoordinatesWarper().warp( seeds = FSLCoordinatesWarper().warp(
seeds=seeds, seeds=seeds,
target_data=target_data, target_data=target_data,
extra_input=extra_input, warp_data=warper_spec,
)
elif warper_spec["warper"] == "ants":
# Requires the inverse warp
inverse_warper_spec = get_native_warper(
target_data=target_data,
other_data=extra_input,
inverse=True,
)
# Check warper
if inverse_warper_spec["warper"] != "ants":
raise_error(
klass=RuntimeError,
msg=(
"Warping specification mismatch for native space "
"warping of coordinates using ANTs."
),
) )
elif warp_file_ext == ".h5":
seeds = ANTsCoordinatesWarper().warp( seeds = ANTsCoordinatesWarper().warp(
seeds=seeds, seeds=seeds,
target_data=target_data, target_data=target_data,
extra_input=extra_input, warp_data=warper_spec,
)
else:
raise_error(
msg=(
"Unknown warp / transformation file extension: "
f"{warp_file_ext}"
),
klass=RuntimeError,
) )
return seeds, labels return seeds, labels

View file

@ -26,7 +26,7 @@ class FSLCoordinatesWarper:
self, self,
seeds: ArrayLike, seeds: ArrayLike,
target_data: Dict[str, Any], target_data: Dict[str, Any],
extra_input: Dict[str, Any], warp_data: Dict[str, Any],
) -> ArrayLike: ) -> ArrayLike:
"""Warp ``seeds`` to correct space. """Warp ``seeds`` to correct space.
@ -37,10 +37,8 @@ class FSLCoordinatesWarper:
target_data : dict target_data : dict
The corresponding item of the data object to which the coordinates The corresponding item of the data object to which the coordinates
will be applied. will be applied.
fraimondo commented 2024-11-08 16:00:25 +00:00 (Migrated from github.com)

Same as before.

Same as before.
extra_input : dict, optional warp_data : dict
The other fields in the data object. Useful for accessing other The warp data item of the data object.
data kinds that needs to be used in the computation of coordinates
(default None).
Returns Returns
------- -------
@ -72,7 +70,7 @@ class FSLCoordinatesWarper:
"| img2imgcoord -mm", "| img2imgcoord -mm",
f"-src {target_data['path'].resolve()}", f"-src {target_data['path'].resolve()}",
f"-dest {target_data['reference_path'].resolve()}", f"-dest {target_data['reference_path'].resolve()}",
f"-warp {extra_input['Warp']['path'].resolve()}", f"-warp {warp_data['path'].resolve()}",
f"> {transformed_coords_path.resolve()};", f"> {transformed_coords_path.resolve()};",
f"sed -i 1d {transformed_coords_path.resolve()}", f"sed -i 1d {transformed_coords_path.resolve()}",
] ]

View file

@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional
import nibabel as nib import nibabel as nib
from ...pipeline import WorkDirManager from ...pipeline import WorkDirManager
from ...utils import logger, run_ext_cmd from ...utils import logger, raise_error, run_ext_cmd
from ..template_spaces import get_template, get_xfm from ..template_spaces import get_template, get_xfm
@ -34,7 +34,7 @@ class ANTsMaskWarper:
src: str, src: str,
dst: str, dst: str,
target_data: Dict[str, Any], target_data: Dict[str, Any],
extra_input: Optional[Dict[str, Any]] = None, warp_data: Optional[Dict[str, Any]],
) -> "Nifti1Image": ) -> "Nifti1Image":
"""Warp ``mask_img`` to correct space. """Warp ``mask_img`` to correct space.
@ -55,17 +55,20 @@ class ANTsMaskWarper:
target_data : dict target_data : dict
The corresponding item of the data object to which the mask The corresponding item of the data object to which the mask
will be applied. will be applied.
extra_input : dict, optional warp_data : dict or None
The other fields in the data object. Useful for accessing other The warp data item of the data object. The value is unused if
data kinds that needs to be used in the computation of mask ``dst!="T1w"``.
(default None).
Returns Returns
------- -------
nibabel.nifti1.Nifti1Image nibabel.nifti1.Nifti1Image
The transformed mask image. The transformed mask image.
Raises
------
RuntimeError
If ``warp_data`` is None when ``dst="T1w"``.
""" """
# Create element-scoped tempdir so that warped mask is # Create element-scoped tempdir so that warped mask is
# available later as nibabel stores file path reference for # available later as nibabel stores file path reference for
@ -80,7 +83,11 @@ class ANTsMaskWarper:
) )
# Native space warping # Native space warping
if dst == "T1w": if dst == "native":
# Warp data check
if warp_data is None:
fraimondo commented 2024-11-08 16:00:34 +00:00 (Migrated from github.com)

Same as before

Same as before
fraimondo commented 2024-11-08 16:01:18 +00:00 (Migrated from github.com)

why is this T1w here?

why is this T1w here?
synchon commented 2024-11-12 15:19:42 +00:00 (Migrated from github.com)
Because that's provided here: https://github.com/juaml/junifer/blob/2d974e1f1c9c569e5f55f2d7e61460f526d931f0/junifer/data/masks/_masks.py#L536
fraimondo commented 2024-11-13 10:37:32 +00:00 (Migrated from github.com)

I meant that it does not make any sense to asume that T1w is native space.

The comment says "native space warping" and then check if dst = "T1w". This would be true if the space of the T1w is native.

I meant that it does not make any sense to asume that T1w is native space. The comment says "native space warping" and then check if `dst = "T1w"`. This would be true if the space of the T1w is native.
synchon commented 2024-11-13 11:06:57 +00:00 (Migrated from github.com)

Fair enough.

Fair enough.
raise_error("No `warp_data` provided")
logger.debug("Using ANTs for mask transformation") logger.debug("Using ANTs for mask transformation")
# Save existing mask image to a tempfile # Save existing mask image to a tempfile
@ -98,7 +105,7 @@ class ANTsMaskWarper:
f"-i {prewarp_mask_path.resolve()}", f"-i {prewarp_mask_path.resolve()}",
# use resampled reference # use resampled reference
f"-r {target_data['reference_path'].resolve()}", f"-r {target_data['reference_path'].resolve()}",
f"-t {extra_input['Warp']['path'].resolve()}", f"-t {warp_data['path'].resolve()}",
f"-o {warped_mask_path.resolve()}", f"-o {warped_mask_path.resolve()}",
] ]
# Call antsApplyTransforms # Call antsApplyTransforms

View file

@ -31,7 +31,7 @@ class FSLMaskWarper:
mask_name: str, mask_name: str,
mask_img: "Nifti1Image", mask_img: "Nifti1Image",
target_data: Dict[str, Any], target_data: Dict[str, Any],
extra_input: Dict[str, Any], warp_data: Dict[str, Any],
) -> "Nifti1Image": ) -> "Nifti1Image":
"""Warp ``mask_img`` to correct space. """Warp ``mask_img`` to correct space.
@ -44,10 +44,8 @@ class FSLMaskWarper:
target_data : dict target_data : dict
The corresponding item of the data object to which the mask The corresponding item of the data object to which the mask
will be applied. will be applied.
extra_input : dict, optional warp_data : dict
The other fields in the data object. Useful for accessing other The warp data item of the data object.
data kinds that needs to be used in the computation of mask
(default None).
Returns Returns
------- -------
@ -77,7 +75,7 @@ class FSLMaskWarper:
f"-i {prewarp_mask_path.resolve()}", f"-i {prewarp_mask_path.resolve()}",
# use resampled reference # use resampled reference
f"-r {target_data['reference_path'].resolve()}", f"-r {target_data['reference_path'].resolve()}",
f"-w {extra_input['Warp']['path'].resolve()}", f"-w {warp_data['path'].resolve()}",
f"-o {warped_mask_path.resolve()}", f"-o {warped_mask_path.resolve()}",
] ]
# Call applywarp # Call applywarp

View file

@ -29,7 +29,7 @@ from ...utils import logger, raise_error
from ...utils.singleton import Singleton from ...utils.singleton import Singleton
from ..pipeline_data_registry_base import BasePipelineDataRegistry from ..pipeline_data_registry_base import BasePipelineDataRegistry
from ..template_spaces import get_template from ..template_spaces import get_template
from ..utils import closest_resolution from ..utils import closest_resolution, get_native_warper
from ._ants_mask_warper import ANTsMaskWarper from ._ants_mask_warper import ANTsMaskWarper
from ._fsl_mask_warper import FSLMaskWarper from ._fsl_mask_warper import FSLMaskWarper
@ -105,14 +105,16 @@ def compute_brain_mask(
"data type to infer target template space." "data type to infer target template space."
) )
# Set target standard space to warp file space source # Set target standard space to warp file space source
target_std_space = extra_input["Warp"]["src"] for entry in extra_input["Warp"]:
if entry["dst"] == "native":
target_std_space = entry["src"]
# Fetch template in closest resolution # Fetch template in closest resolution
template = get_template( template = get_template(
space=target_std_space, space=target_std_space,
target_data=target_data, target_data=target_data,
extra_input=extra_input, extra_input=extra_input,
template_type=mask_type if mask_type in ["gm", "wm"] else "T1w", template_type=mask_type,
) )
# Resample template to target image # Resample template to target image
target_img = target_data["data"] target_img = target_data["data"]
@ -357,8 +359,6 @@ class MaskRegistry(BasePipelineDataRegistry, metaclass=Singleton):
Raises Raises
------ ------
RuntimeError
If warp / transformation file extension is not ".mat" or ".h5".
ValueError ValueError
If extra key is provided in addition to mask name in ``masks`` or If extra key is provided in addition to mask name in ``masks`` or
if no mask is provided or if no mask is provided or
@ -372,8 +372,6 @@ class MaskRegistry(BasePipelineDataRegistry, metaclass=Singleton):
""" """
# Check pre-requirements for space manipulation # Check pre-requirements for space manipulation
target_space = target_data["space"] target_space = target_data["space"]
# Set target standard space to target space
target_std_space = target_space
# Extra data type requirement check if target space is native # Extra data type requirement check if target space is native
if target_space == "native": if target_space == "native":
# Check for extra inputs # Check for extra inputs
@ -383,8 +381,16 @@ class MaskRegistry(BasePipelineDataRegistry, metaclass=Singleton):
"data types in particular for transformation to " "data types in particular for transformation to "
f"{target_data['space']} space for further computation." f"{target_data['space']} space for further computation."
) )
# Get native space warper spec
warper_spec = get_native_warper(
target_data=target_data,
other_data=extra_input,
)
# Set target standard space to warp file space source # Set target standard space to warp file space source
target_std_space = extra_input["Warp"]["src"] target_std_space = warper_spec["src"]
else:
# Set target standard space to target space
target_std_space = target_space
# Get the min of the voxels sizes and use it as the resolution # Get the min of the voxels sizes and use it as the resolution
target_img = target_data["data"] target_img = target_data["data"]
@ -489,7 +495,7 @@ class MaskRegistry(BasePipelineDataRegistry, metaclass=Singleton):
src=mask_space, src=mask_space,
dst=target_std_space, dst=target_std_space,
target_data=target_data, target_data=target_data,
extra_input=None, warp_data=None,
) )
all_masks.append(mask_img) all_masks.append(mask_img)
@ -510,32 +516,22 @@ class MaskRegistry(BasePipelineDataRegistry, metaclass=Singleton):
# Warp mask if target data is native # Warp mask if target data is native
if target_space == "native": if target_space == "native":
# extra_input check done earlier # extra_input check done earlier and warper_spec exists
# Check for warp file type to use correct tool if warper_spec["warper"] == "fsl":
warp_file_ext = extra_input["Warp"]["path"].suffix
if warp_file_ext == ".mat":
mask_img = FSLMaskWarper().warp( mask_img = FSLMaskWarper().warp(
mask_name="native", mask_name="native",
mask_img=mask_img, mask_img=mask_img,
target_data=target_data, target_data=target_data,
extra_input=extra_input, warp_data=warper_spec,
) )
elif warp_file_ext == ".h5": elif warper_spec["warper"] == "ants":
mask_img = ANTsMaskWarper().warp( mask_img = ANTsMaskWarper().warp(
mask_name="native", mask_name="native",
mask_img=mask_img, mask_img=mask_img,
src="", src="",
dst="T1w", dst="native",
target_data=target_data, target_data=target_data,
extra_input=extra_input, warp_data=warper_spec,
)
else:
raise_error(
msg=(
"Unknown warp / transformation file extension: "
f"{warp_file_ext}"
),
klass=RuntimeError,
) )
return mask_img return mask_img

View file

@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional
import nibabel as nib import nibabel as nib
from ...pipeline import WorkDirManager from ...pipeline import WorkDirManager
from ...utils import logger, run_ext_cmd from ...utils import logger, raise_error, run_ext_cmd
from ..template_spaces import get_template, get_xfm from ..template_spaces import get_template, get_xfm
@ -34,7 +34,7 @@ class ANTsParcellationWarper:
src: str, src: str,
dst: str, dst: str,
target_data: Dict[str, Any], target_data: Dict[str, Any],
extra_input: Optional[Dict[str, Any]] = None, warp_data: Optional[Dict[str, Any]],
) -> "Nifti1Image": ) -> "Nifti1Image":
"""Warp ``parcellation_img`` to correct space. """Warp ``parcellation_img`` to correct space.
@ -55,17 +55,20 @@ class ANTsParcellationWarper:
target_data : dict target_data : dict
The corresponding item of the data object to which the parcellation The corresponding item of the data object to which the parcellation
will be applied. will be applied.
extra_input : dict, optional warp_data : dict or None
The other fields in the data object. Useful for accessing other The warp data item of the data object. The value is unused if
data kinds that needs to be used in the computation of parcellation ``dst!="T1w"``.
(default None).
Returns Returns
------- -------
nibabel.nifti1.Nifti1Image nibabel.nifti1.Nifti1Image
The transformed parcellation image. The transformed parcellation image.
Raises
------
ValueError
If ``warp_data`` is None when ``dst="T1w"``.
""" """
# Create element-scoped tempdir so that warped parcellation is # Create element-scoped tempdir so that warped parcellation is
# available later as nibabel stores file path reference for # available later as nibabel stores file path reference for
@ -80,7 +83,11 @@ class ANTsParcellationWarper:
) )
# Native space warping # Native space warping
if dst == "T1w": if dst == "native":
# Warp data check
if warp_data is None:
raise_error("No `warp_data` provided")
logger.debug("Using ANTs for parcellation transformation") logger.debug("Using ANTs for parcellation transformation")
# Save existing parcellation image to a tempfile # Save existing parcellation image to a tempfile
@ -102,7 +109,7 @@ class ANTsParcellationWarper:
f"-i {prewarp_parcellation_path.resolve()}", f"-i {prewarp_parcellation_path.resolve()}",
# use resampled reference # use resampled reference
f"-r {target_data['reference_path'].resolve()}", f"-r {target_data['reference_path'].resolve()}",
f"-t {extra_input['Warp']['path'].resolve()}", f"-t {warp_data['path'].resolve()}",
f"-o {warped_parcellation_path.resolve()}", f"-o {warped_parcellation_path.resolve()}",
] ]
# Call antsApplyTransforms # Call antsApplyTransforms

View file

@ -31,7 +31,7 @@ class FSLParcellationWarper:
parcellation_name: str, parcellation_name: str,
parcellation_img: "Nifti1Image", parcellation_img: "Nifti1Image",
target_data: Dict[str, Any], target_data: Dict[str, Any],
extra_input: Dict[str, Any], warp_data: Dict[str, Any],
) -> "Nifti1Image": ) -> "Nifti1Image":
"""Warp ``parcellation_img`` to correct space. """Warp ``parcellation_img`` to correct space.
@ -44,10 +44,8 @@ class FSLParcellationWarper:
target_data : dict target_data : dict
The corresponding item of the data object to which the parcellation The corresponding item of the data object to which the parcellation
will be applied. will be applied.
extra_input : dict, optional warp_data : dict
The other fields in the data object. Useful for accessing other The warp data item of the data object.
data kinds that needs to be used in the computation of parcellation
(default None).
Returns Returns
------- -------
@ -81,7 +79,7 @@ class FSLParcellationWarper:
f"-i {prewarp_parcellation_path.resolve()}", f"-i {prewarp_parcellation_path.resolve()}",
# use resampled reference # use resampled reference
f"-r {target_data['reference_path'].resolve()}", f"-r {target_data['reference_path'].resolve()}",
f"-w {extra_input['Warp']['path'].resolve()}", f"-w {warp_data['path'].resolve()}",
f"-o {warped_parcellation_path.resolve()}", f"-o {warped_parcellation_path.resolve()}",
] ]
# Call applywarp # Call applywarp

View file

@ -23,7 +23,7 @@ from nilearn import datasets, image
from ...utils import logger, raise_error, warn_with_log from ...utils import logger, raise_error, warn_with_log
from ...utils.singleton import Singleton from ...utils.singleton import Singleton
from ..pipeline_data_registry_base import BasePipelineDataRegistry from ..pipeline_data_registry_base import BasePipelineDataRegistry
from ..utils import closest_resolution from ..utils import closest_resolution, get_native_warper
from ._ants_parcellation_warper import ANTsParcellationWarper from ._ants_parcellation_warper import ANTsParcellationWarper
from ._fsl_parcellation_warper import FSLParcellationWarper from ._fsl_parcellation_warper import FSLParcellationWarper
@ -394,16 +394,12 @@ class ParcellationRegistry(BasePipelineDataRegistry, metaclass=Singleton):
Raises Raises
------ ------
RuntimeError
If warp / transformation file extension is not ".mat" or ".h5".
ValueError ValueError
If ``extra_input`` is None when ``target_data``'s space is native. If ``extra_input`` is None when ``target_data``'s space is native.
""" """
# Check pre-requirements for space manipulation # Check pre-requirements for space manipulation
target_space = target_data["space"] target_space = target_data["space"]
# Set target standard space to target space
target_std_space = target_space
# Extra data type requirement check if target space is native # Extra data type requirement check if target space is native
if target_space == "native": if target_space == "native":
# Check for extra inputs # Check for extra inputs
@ -413,8 +409,16 @@ class ParcellationRegistry(BasePipelineDataRegistry, metaclass=Singleton):
"data types in particular for transformation to " "data types in particular for transformation to "
f"{target_data['space']} space for further computation." f"{target_data['space']} space for further computation."
) )
# Get native space warper spec
warper_spec = get_native_warper(
target_data=target_data,
other_data=extra_input,
)
# Set target standard space to warp file space source # Set target standard space to warp file space source
target_std_space = extra_input["Warp"]["src"] target_std_space = warper_spec["src"]
else:
# Set target standard space to target space
target_std_space = target_space
# Get the min of the voxels sizes and use it as the resolution # Get the min of the voxels sizes and use it as the resolution
target_img = target_data["data"] target_img = target_data["data"]
@ -428,12 +432,14 @@ class ParcellationRegistry(BasePipelineDataRegistry, metaclass=Singleton):
all_parcellations = [] all_parcellations = []
all_labels = [] all_labels = []
for name in parcellations: for name in parcellations:
# Load parcellation
img, labels, _, space = self.load( img, labels, _, space = self.load(
name=name, name=name,
resolution=resolution, resolution=resolution,
) )
# Convert parcellation spaces if required # Convert parcellation spaces if required;
# cannot be "native" due to earlier check
if space != target_std_space: if space != target_std_space:
raw_img = ANTsParcellationWarper().warp( raw_img = ANTsParcellationWarper().warp(
parcellation_name=name, parcellation_name=name,
@ -441,7 +447,7 @@ class ParcellationRegistry(BasePipelineDataRegistry, metaclass=Singleton):
src=space, src=space,
dst=target_std_space, dst=target_std_space,
target_data=target_data, target_data=target_data,
extra_input=None, warp_data=None,
) )
# Remove extra dimension added by ANTs # Remove extra dimension added by ANTs
img = image.math_img("np.squeeze(img)", img=raw_img) img = image.math_img("np.squeeze(img)", img=raw_img)
@ -471,32 +477,22 @@ class ParcellationRegistry(BasePipelineDataRegistry, metaclass=Singleton):
# Warp parcellation if target space is native # Warp parcellation if target space is native
if target_space == "native": if target_space == "native":
# extra_input check done earlier # extra_input check done earlier and warper_spec exists
# Check for warp file type to use correct tool if warper_spec["warper"] == "fsl":
warp_file_ext = extra_input["Warp"]["path"].suffix
if warp_file_ext == ".mat":
resampled_parcellation_img = FSLParcellationWarper().warp( resampled_parcellation_img = FSLParcellationWarper().warp(
parcellation_name="native", parcellation_name="native",
parcellation_img=resampled_parcellation_img, parcellation_img=resampled_parcellation_img,
target_data=target_data, target_data=target_data,
extra_input=extra_input, warp_data=warper_spec,
) )
elif warp_file_ext == ".h5": elif warper_spec["warper"] == "ants":
resampled_parcellation_img = ANTsParcellationWarper().warp( resampled_parcellation_img = ANTsParcellationWarper().warp(
parcellation_name="native", parcellation_name="native",
parcellation_img=resampled_parcellation_img, parcellation_img=resampled_parcellation_img,
src="", src="",
dst="T1w", dst="native",
target_data=target_data, target_data=target_data,
extra_input=extra_input, warp_data=warper_spec,
)
else:
raise_error(
msg=(
"Unknown warp / transformation file extension: "
f"{warp_file_ext}"
),
klass=RuntimeError,
) )
return resampled_parcellation_img, labels return resampled_parcellation_img, labels

View file

@ -4,14 +4,14 @@
# Synchon Mandal <s.mandal@fz-juelich.de> # Synchon Mandal <s.mandal@fz-juelich.de>
# License: AGPL # License: AGPL
from typing import List, Optional, Union from typing import Dict, List, MutableMapping, Optional, Union
import numpy as np import numpy as np
from ..utils.logging import logger from ..utils import logger, raise_error
__all__ = ["closest_resolution"] __all__ = ["closest_resolution", "get_native_warper"]
def closest_resolution( def closest_resolution(
@ -49,3 +49,67 @@ def closest_resolution(
closest = np.min(valid_resolution) closest = np.min(valid_resolution)
return closest return closest
def get_native_warper(
target_data: MutableMapping,
other_data: MutableMapping,
inverse: bool = False,
) -> Dict:
"""Get correct warping specification for native space.
Parameters
----------
target_data : dict
The target data from the pipeline data object.
other_data : dict
The other data in the pipeline data object.
inverse : bool, optional
Whether to get the inverse warping specification (default False).
Returns
-------
dict
The correct warping specification.
Raises
------
RuntimeError
If no warper or multiple possible warpers are found.
"""
# Get possible warpers
possible_warpers = []
for entry in other_data["Warp"]:
if not inverse:
if (
entry["src"] == target_data["prewarp_space"]
and entry["dst"] == "native"
):
possible_warpers.append(entry)
else:
if (
entry["dst"] == target_data["prewarp_space"]
and entry["src"] == "native"
):
possible_warpers.append(entry)
# Check for no warper
if not possible_warpers:
raise_error(
klass=RuntimeError,
msg="Could not find correct warping specification",
)
# Check for multiple possible warpers
if len(possible_warpers) > 1:
raise_error(
klass=RuntimeError,
msg=(
"Cannot proceed as multiple warping specification found, "
"adjust either the DataGrabber or the working space: "
f"{possible_warpers}"
),
)
return possible_warpers[0]

View file

@ -169,7 +169,8 @@ class DataladAOMICID1000(PatternDataladDataGrabber):
"space": "native", "space": "native",
}, },
}, },
"Warp": { "Warp": [
{
"pattern": ( "pattern": (
"derivatives/fmriprep/{subject}/anat/" "derivatives/fmriprep/{subject}/anat/"
"{subject}_from-MNI152NLin2009cAsym_to-T1w_" "{subject}_from-MNI152NLin2009cAsym_to-T1w_"
@ -177,7 +178,19 @@ class DataladAOMICID1000(PatternDataladDataGrabber):
), ),
"src": "MNI152NLin2009cAsym", "src": "MNI152NLin2009cAsym",
"dst": "native", "dst": "native",
"warper": "ants",
}, },
{
"pattern": (
"derivatives/fmriprep/{subject}/anat/"
"{subject}_from-T1w_to-MNI152NLin2009cAsym_"
"mode-image_xfm.h5"
),
"src": "native",
"dst": "MNI152NLin2009cAsym",
"warper": "ants",
},
],
} }
) )
# Set default types # Set default types

View file

@ -204,7 +204,8 @@ class DataladAOMICPIOP1(PatternDataladDataGrabber):
"space": "native", "space": "native",
}, },
}, },
"Warp": { "Warp": [
{
"pattern": ( "pattern": (
"derivatives/fmriprep/{subject}/anat/" "derivatives/fmriprep/{subject}/anat/"
"{subject}_from-MNI152NLin2009cAsym_to-T1w_" "{subject}_from-MNI152NLin2009cAsym_to-T1w_"
@ -212,7 +213,19 @@ class DataladAOMICPIOP1(PatternDataladDataGrabber):
), ),
"src": "MNI152NLin2009cAsym", "src": "MNI152NLin2009cAsym",
"dst": "native", "dst": "native",
"warper": "ants",
}, },
{
"pattern": (
"derivatives/fmriprep/{subject}/anat/"
"{subject}_from-T1w_to-MNI152NLin2009cAsym_"
"mode-image_xfm.h5"
),
"src": "native",
"dst": "MNI152NLin2009cAsym",
"warper": "ants",
},
],
} }
) )
# Set default types # Set default types

View file

@ -202,7 +202,8 @@ class DataladAOMICPIOP2(PatternDataladDataGrabber):
"space": "native", "space": "native",
}, },
}, },
"Warp": { "Warp": [
{
"pattern": ( "pattern": (
"derivatives/fmriprep/{subject}/anat/" "derivatives/fmriprep/{subject}/anat/"
"{subject}_from-MNI152NLin2009cAsym_to-T1w_" "{subject}_from-MNI152NLin2009cAsym_to-T1w_"
@ -210,7 +211,19 @@ class DataladAOMICPIOP2(PatternDataladDataGrabber):
), ),
"src": "MNI152NLin2009cAsym", "src": "MNI152NLin2009cAsym",
"dst": "native", "dst": "native",
"warper": "ants",
}, },
{
"pattern": (
"derivatives/fmriprep/{subject}/anat/"
"{subject}_from-T1w_to-MNI152NLin2009cAsym_"
"mode-image_xfm.h5"
),
"src": "native",
"dst": "MNI152NLin2009cAsym",
"warper": "ants",
},
],
} }
) )
# Set default types # Set default types

View file

@ -96,6 +96,11 @@ class BaseDataGrabber(ABC, UpdateMetaMixin):
# Update metadata # Update metadata
for _, t_val in out.items(): for _, t_val in out.items():
self.update_meta(t_val, "datagrabber") self.update_meta(t_val, "datagrabber")
# Conditional for list dtype vals like Warp
if isinstance(t_val, list):
for entry in t_val:
entry["meta"]["element"] = named_element
else:
t_val["meta"]["element"] = named_element t_val["meta"]["element"] = named_element
return out return out

View file

@ -181,6 +181,13 @@ class DataladDataGrabber(BaseDataGrabber):
""" """
to_get = [] to_get = []
for type_val in out.values(): for type_val in out.values():
# Conditional for list dtype vals like Warp
if isinstance(type_val, list):
for entry in type_val:
for k, v in entry.items():
if k == "path":
to_get.append(v)
else:
# Iterate to check for nested "types" like mask # Iterate to check for nested "types" like mask
for k, v in type_val.items(): for k, v in type_val.items():
# Add base data type path # Add base data type path

View file

@ -150,7 +150,7 @@ class DMCC13Benchmark(PatternDataladDataGrabber):
"mask": { "mask": {
"pattern": ( "pattern": (
"derivatives/fmriprep-1.3.2/{subject}/{session}/" "derivatives/fmriprep-1.3.2/{subject}/{session}/"
"/func/{subject}_{session}_task-{task}_acq-mb4" "func/{subject}_{session}_task-{task}_acq-mb4"
"{phase_encoding}_run-{run}_" "{phase_encoding}_run-{run}_"
"space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz" "space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz"
), ),
@ -221,7 +221,8 @@ class DMCC13Benchmark(PatternDataladDataGrabber):
"space": "native", "space": "native",
}, },
}, },
"Warp": { "Warp": [
{
"pattern": ( "pattern": (
"derivatives/fmriprep-1.3.2/{subject}/anat/" "derivatives/fmriprep-1.3.2/{subject}/anat/"
"{subject}_from-MNI152NLin2009cAsym_to-T1w_" "{subject}_from-MNI152NLin2009cAsym_to-T1w_"
@ -229,7 +230,19 @@ class DMCC13Benchmark(PatternDataladDataGrabber):
), ),
"src": "MNI152NLin2009cAsym", "src": "MNI152NLin2009cAsym",
"dst": "native", "dst": "native",
"warper": "ants",
}, },
{
"pattern": (
"derivatives/fmriprep-1.3.2/{subject}/anat/"
"{subject}_from-T1w_to-MNI152NLin2009cAsym_"
"mode-image_xfm.h5"
),
"src": "native",
"dst": "MNI152NLin2009cAsym",
"warper": "ants",
},
],
} }
) )
# Set default types # Set default types

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