[ENH]: Enable Markers to extract multiple features #349
53 changed files with 1026 additions and 1088 deletions
1
docs/changes/newsfragments/349.change
Normal file
1
docs/changes/newsfragments/349.change
Normal file
|
|
@ -0,0 +1 @@
|
|||
``fractional`` parameter for ``ALFFBase``, :class:`.ALFFParcels` and :class:`.ALFFSpheres` have been removed in favour of returning both ALFF and fALFF by `Synchon Mandal`_
|
||||
1
docs/changes/newsfragments/349.enh
Normal file
1
docs/changes/newsfragments/349.enh
Normal file
|
|
@ -0,0 +1 @@
|
|||
Enable Markers to output multiple features by `Synchon Mandal`_
|
||||
|
|
@ -5,24 +5,17 @@
|
|||
Creating Markers
|
||||
================
|
||||
|
||||
Computing a marker (a.k.a. *feature*) is the main goal of ``junifer``. While we
|
||||
aim to provide as many Markers as possible, it might be the case that the Marker
|
||||
you are looking for is not available. In this case, you can create your own Marker
|
||||
by following this tutorial.
|
||||
Computing a marker (a.k.a. *feature(s)*) is the main goal of ``junifer``. While
|
||||
we aim to provide as many Markers as possible, it might be the case that the
|
||||
Marker you are looking for is not available. In this case, you can create your
|
||||
own Marker by following this tutorial.
|
||||
|
||||
Most of the functionality of a ``junifer`` Marker has been taken care by the
|
||||
:class:`.BaseMarker` class. Thus, only a few methods are required:
|
||||
:class:`.BaseMarker` class. Thus, only a few methods and class attributes are
|
||||
required:
|
||||
|
||||
#. ``get_valid_inputs``: The method to obtain the list of valid inputs for the
|
||||
Marker. This is used to check that the inputs provided by the user are
|
||||
valid. This method should return a list of strings, representing
|
||||
:ref:`data types <data_types>`.
|
||||
#. ``get_output_type``: The method to obtain the output type of the Marker.
|
||||
This is used to check that the output of the Marker is compatible with the
|
||||
storage. This method should return a string, representing
|
||||
:ref:`storage types <storage_types>`.
|
||||
#. ``compute``: The method that given the data, computes the Marker.
|
||||
#. ``__init__``: The initialisation method, where the Marker is configured.
|
||||
#. ``compute``: The method that given the data, computes the Marker.
|
||||
|
||||
As an example, we will develop a ``ParcelMean`` Marker, a Marker that first
|
||||
applies a parcellation and then computes the mean of the data in each parcel.
|
||||
|
|
@ -35,24 +28,26 @@ 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.
|
||||
``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:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_valid_inputs(self) -> list[str]:
|
||||
return ["BOLD", "VBM_WM", "VBM_GM"]
|
||||
|
||||
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 can define the output as:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_output_type(self, input_type: str) -> str:
|
||||
if input_type == "BOLD":
|
||||
return "timeseries"
|
||||
else:
|
||||
return "vector"
|
||||
# NOTE: data type -> feature -> storage type
|
||||
# You can have multiple features for one data type,
|
||||
# each feature having same or different storage type
|
||||
_MARKER_INOUT_MAPPINGS = {
|
||||
"BOLD": {
|
||||
"parcel_mean": "timeseries",
|
||||
},
|
||||
"VBM_WM": {
|
||||
"parcel_mean": "vector",
|
||||
},
|
||||
"VBM_GM": {
|
||||
"parcel_mean": "vector",
|
||||
},
|
||||
}
|
||||
|
||||
.. _extending_markers_init:
|
||||
|
||||
|
|
@ -119,7 +114,8 @@ arguments:
|
|||
Following the example, we will compute the mean of the data in each parcel using
|
||||
:class:`nilearn.maskers.NiftiLabelsMasker`. Importantly, the output of the
|
||||
compute function must be a dictionary. This dictionary will later be passed onto
|
||||
the ``store`` method.
|
||||
the ``store`` method. The dictionary's first level of keys would the feature name
|
||||
and the values would be a dictionary of storage type specific key-value pairs.
|
||||
|
||||
.. hint::
|
||||
|
||||
|
|
@ -162,11 +158,13 @@ the ``store`` method.
|
|||
# mask the data
|
||||
out_values = masker.fit_transform([data])
|
||||
|
||||
# Create the output dictionary
|
||||
out = {"data": out_values, "col_names": t_labels}
|
||||
|
||||
return out
|
||||
|
||||
# Create and return the output dictionary
|
||||
return {
|
||||
"parcel_mean": {
|
||||
"data": out_values,
|
||||
"col_names": t_labels,
|
||||
},
|
||||
}
|
||||
|
||||
.. _extending_markers_finalize:
|
||||
|
||||
|
|
@ -193,11 +191,11 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
|
|||
|
||||
.. code-block:: python
|
||||
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from junifer.api.decorators import register_marker
|
||||
from junifer.data import get_parcellation
|
||||
from junifer.markers.base import BaseMarker
|
||||
from junifer.markers import BaseMarker
|
||||
from nilearn.maskers import NiftiLabelsMasker
|
||||
|
||||
|
||||
|
|
@ -206,6 +204,18 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
|
|||
|
||||
_DEPENDENCIES = {"nilearn", "numpy"}
|
||||
|
||||
_MARKER_INOUT_MAPPINGS: ClassVar[dict[str, dict[str, str]]] = {
|
||||
"BOLD": {
|
||||
"parcel_mean": "timeseries",
|
||||
},
|
||||
"VBM_WM": {
|
||||
"parcel_mean": "vector",
|
||||
},
|
||||
"VBM_GM": {
|
||||
"parcel_mean": "vector",
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parcellation: str,
|
||||
|
|
@ -215,15 +225,6 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
|
|||
self.parcellation = parcellation
|
||||
super().__init__(on=on, name=name)
|
||||
|
||||
def get_valid_inputs(self) -> list[str]:
|
||||
return ["BOLD", "VBM_WM", "VBM_GM"]
|
||||
|
||||
def get_output_type(self, input_type: str) -> str:
|
||||
if input_type == "BOLD":
|
||||
return "timeseries"
|
||||
else:
|
||||
return "vector"
|
||||
|
||||
def compute(
|
||||
self,
|
||||
input: dict[str, Any],
|
||||
|
|
@ -250,11 +251,13 @@ Finally, we need to register the Marker using the ``@register_marker`` decorator
|
|||
# mask the data
|
||||
out_values = masker.fit_transform([data])
|
||||
|
||||
# Create the output dictionary
|
||||
out = {"data": out_values, "col_names": t_labels}
|
||||
|
||||
return out
|
||||
|
||||
# Create and return the output dictionary
|
||||
return {
|
||||
"parcel_mean": {
|
||||
"data": out_values,
|
||||
"col_names": t_labels,
|
||||
},
|
||||
}
|
||||
|
||||
.. _extending_markers_template:
|
||||
|
||||
|
|
@ -269,22 +272,16 @@ Template for a custom Marker
|
|||
|
||||
@register_marker
|
||||
class TemplateMarker(BaseMarker):
|
||||
|
||||
# TODO: add the dependencies
|
||||
_DEPENDENCIES = {}
|
||||
|
||||
# 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)
|
||||
|
||||
def get_valid_inputs(self):
|
||||
# TODO: Complete with the valid inputs
|
||||
valid = []
|
||||
return valid
|
||||
|
||||
def get_output_type(self, input_type):
|
||||
# TODO: Return the valid output type for each input type
|
||||
pass
|
||||
|
||||
def compute(self, input, extra_input):
|
||||
# TODO: compute the marker and create the output dictionary
|
||||
|
||||
# Create the output dictionary
|
||||
out = {"data": None, "col_names": None}
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -26,7 +26,5 @@ on them outside the context as long as the actual data is in the memory and the
|
|||
Python runtime has not garbage-collected it.
|
||||
|
||||
If you are interested in using already provided Markers, please go to
|
||||
:doc:`../builtin`. And, if you want to implement your own Marker, you need to
|
||||
provide concrete implementation of :class:`.BaseMarker`. Specifically, you
|
||||
need to override ``get_valid_inputs``, ``get_output_type`` and ``compute``
|
||||
methods.
|
||||
:doc:`../builtin`. And, if you want to implement your own Marker, please check
|
||||
out :doc:`../extending/marker`.
|
||||
|
|
|
|||
|
|
@ -15,13 +15,13 @@ from junifer.datagrabber import DataladDataGrabber
|
|||
_testing_dataset = {
|
||||
"example_bids": {
|
||||
"uri": "https://gin.g-node.org/juaml/datalad-example-bids",
|
||||
"commit": "522dfb203afcd2cd55799bf347f9b211919a7338",
|
||||
"id": "fec92475-d9c0-4409-92ba-f041b6a12c40",
|
||||
"commit": "b87897cbe51bf0ee5514becaa5c7dd76491db5ad",
|
||||
"id": "8fddff30-6993-420a-9d1e-b5b028c59468",
|
||||
},
|
||||
"example_bids_ses": {
|
||||
"uri": "https://gin.g-node.org/juaml/datalad-example-bids-ses",
|
||||
"commit": "3d08d55d1faad4f12ab64ac9497544a0d924d47a",
|
||||
"id": "c83500d0-532f-45be-baf1-0dab703bdc2a",
|
||||
"commit": "6b163aa98af76a9eac0272273c27e14127850181",
|
||||
"id": "715c17cf-a1b9-42d6-9af8-9f74c1a4a724",
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,13 +15,13 @@ from junifer.datagrabber import PatternDataladDataGrabber
|
|||
_testing_dataset = {
|
||||
"example_bids": {
|
||||
"uri": "https://gin.g-node.org/juaml/datalad-example-bids",
|
||||
"commit": "522dfb203afcd2cd55799bf347f9b211919a7338",
|
||||
"id": "fec92475-d9c0-4409-92ba-f041b6a12c40",
|
||||
"commit": "b87897cbe51bf0ee5514becaa5c7dd76491db5ad",
|
||||
"id": "8fddff30-6993-420a-9d1e-b5b028c59468",
|
||||
},
|
||||
"example_bids_ses": {
|
||||
"uri": "https://gin.g-node.org/juaml/datalad-example-bids-ses",
|
||||
"commit": "3d08d55d1faad4f12ab64ac9497544a0d924d47a",
|
||||
"id": "c83500d0-532f-45be-baf1-0dab703bdc2a",
|
||||
"commit": "6b163aa98af76a9eac0272273c27e14127850181",
|
||||
"id": "715c17cf-a1b9-42d6-9af8-9f74c1a4a724",
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
# License: AGPL
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from copy import deepcopy
|
||||
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
||||
|
||||
from ..pipeline import PipelineStepMixin, UpdateMetaMixin
|
||||
|
|
@ -35,6 +36,8 @@ class BaseMarker(ABC, PipelineStepMixin, UpdateMetaMixin):
|
|||
|
||||
Raises
|
||||
------
|
||||
AttributeError
|
||||
If the marker does not have `_MARKER_INOUT_MAPPINGS` attribute.
|
||||
ValueError
|
||||
If required input data type(s) is(are) not found.
|
||||
|
||||
|
|
@ -45,6 +48,12 @@ class BaseMarker(ABC, PipelineStepMixin, UpdateMetaMixin):
|
|||
on: Optional[Union[List[str], str]] = None,
|
||||
name: Optional[str] = None,
|
||||
) -> None:
|
||||
# Check for missing mapping attribute
|
||||
if not hasattr(self, "_MARKER_INOUT_MAPPINGS"):
|
||||
raise_error(
|
||||
msg=("Missing `_MARKER_INOUT_MAPPINGS` for the marker"),
|
||||
klass=AttributeError,
|
||||
)
|
||||
# Use all data types if not provided
|
||||
if on is None:
|
||||
on = self.get_valid_inputs()
|
||||
|
|
@ -88,7 +97,6 @@ class BaseMarker(ABC, PipelineStepMixin, UpdateMetaMixin):
|
|||
)
|
||||
return [x for x in self._on if x in input]
|
||||
|
||||
@abstractmethod
|
||||
def get_valid_inputs(self) -> List[str]:
|
||||
"""Get valid data types for input.
|
||||
|
||||
|
|
@ -98,30 +106,25 @@ class BaseMarker(ABC, PipelineStepMixin, UpdateMetaMixin):
|
|||
The list of data types that can be used as input for this marker.
|
||||
|
||||
"""
|
||||
raise_error(
|
||||
msg="Concrete classes need to implement get_valid_inputs().",
|
||||
klass=NotImplementedError,
|
||||
)
|
||||
return list(self._MARKER_INOUT_MAPPINGS.keys())
|
||||
|
||||
@abstractmethod
|
||||
def get_output_type(self, input_type: str) -> str:
|
||||
def get_output_type(self, input_type: str, output_feature: str) -> str:
|
||||
"""Get output type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_type : str
|
||||
The data type input to the marker.
|
||||
output_feature : str
|
||||
The feature output of the marker.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The storage type output by the marker.
|
||||
The storage type output of the marker.
|
||||
|
||||
"""
|
||||
raise_error(
|
||||
msg="Concrete classes need to implement get_output_type().",
|
||||
klass=NotImplementedError,
|
||||
)
|
||||
return self._MARKER_INOUT_MAPPINGS[input_type][output_feature]
|
||||
|
||||
@abstractmethod
|
||||
def compute(self, input: Dict, extra_input: Optional[Dict] = None) -> Dict:
|
||||
|
|
@ -154,6 +157,7 @@ class BaseMarker(ABC, PipelineStepMixin, UpdateMetaMixin):
|
|||
def store(
|
||||
self,
|
||||
type_: str,
|
||||
feature: str,
|
||||
out: Dict[str, Any],
|
||||
storage: "BaseFeatureStorage",
|
||||
) -> None:
|
||||
|
|
@ -163,13 +167,15 @@ class BaseMarker(ABC, PipelineStepMixin, UpdateMetaMixin):
|
|||
----------
|
||||
type_ : str
|
||||
The data type to store.
|
||||
feature : str
|
||||
The feature to store.
|
||||
out : dict
|
||||
The computed result as a dictionary to store.
|
||||
storage : storage-like
|
||||
The storage class, for example, SQLiteFeatureStorage.
|
||||
|
||||
"""
|
||||
output_type_ = self.get_output_type(type_)
|
||||
output_type_ = self.get_output_type(type_, feature)
|
||||
logger.debug(f"Storing {output_type_} in {storage}")
|
||||
storage.store(kind=output_type_, **out)
|
||||
|
||||
|
|
@ -213,15 +219,35 @@ class BaseMarker(ABC, PipelineStepMixin, UpdateMetaMixin):
|
|||
t_meta["type"] = type_
|
||||
# Compute marker
|
||||
t_out = self.compute(input=t_input, extra_input=extra_input)
|
||||
t_out["meta"] = t_meta
|
||||
# Update metadata for step
|
||||
self.update_meta(t_out, "marker")
|
||||
# Check storage
|
||||
if storage is not None:
|
||||
logger.info(f"Storing in {storage}")
|
||||
self.store(type_=type_, out=t_out, storage=storage)
|
||||
else:
|
||||
logger.info("No storage specified, returning dictionary")
|
||||
out[type_] = t_out
|
||||
# Initialize empty dictionary if no storage object is provided
|
||||
if storage is None:
|
||||
out[type_] = {}
|
||||
# Store individual features
|
||||
for feature_name, feature_data in t_out.items():
|
||||
# Make deep copy of the feature data for manipulation
|
||||
feature_data_copy = deepcopy(feature_data)
|
||||
# Make deep copy of metadata and add to feature data
|
||||
feature_data_copy["meta"] = deepcopy(t_meta)
|
||||
# Update metadata for the feature,
|
||||
# feature data is not manipulated, only meta
|
||||
self.update_meta(feature_data_copy, "marker")
|
||||
# Update marker feature's metadata name
|
||||
feature_data_copy["meta"]["marker"][
|
||||
"name"
|
||||
] += f"_{feature_name}"
|
||||
|
||||
if storage is not None:
|
||||
logger.info(f"Storing in {storage}")
|
||||
self.store(
|
||||
type_=type_,
|
||||
feature=feature_name,
|
||||
out=feature_data_copy,
|
||||
storage=storage,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"No storage specified, returning dictionary"
|
||||
)
|
||||
out[type_][feature_name] = feature_data_copy
|
||||
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -3,21 +3,9 @@
|
|||
# Authors: Synchon Mandal <s.mandal@fz-juelich.de>
|
||||
# License: AGPL
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
if sys.version_info < (3, 11): # pragma: no cover
|
||||
from importlib_metadata import packages_distributions
|
||||
else:
|
||||
from importlib.metadata import packages_distributions
|
||||
|
||||
import uuid
|
||||
from copy import deepcopy
|
||||
from importlib.util import find_spec
|
||||
from itertools import chain
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
ClassVar,
|
||||
Dict,
|
||||
|
|
@ -37,15 +25,10 @@ from ..external.BrainPrint.brainprint.brainprint import (
|
|||
)
|
||||
from ..external.BrainPrint.brainprint.surfaces import surf_to_vtk
|
||||
from ..pipeline import WorkDirManager
|
||||
from ..pipeline.utils import check_ext_dependencies
|
||||
from ..utils import logger, raise_error, run_ext_cmd
|
||||
from ..utils import logger, run_ext_cmd
|
||||
from .base import BaseMarker
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from junifer.storage import BaseFeatureStorage
|
||||
|
||||
|
||||
__all__ = ["BrainPrint"]
|
||||
|
||||
|
||||
|
|
@ -99,6 +82,15 @@ class BrainPrint(BaseMarker):
|
|||
|
||||
_DEPENDENCIES: ClassVar[Set[str]] = {"lapy", "numpy"}
|
||||
|
||||
_MARKER_INOUT_MAPPINGS: ClassVar[Dict[str, Dict[str, str]]] = {
|
||||
"FreeSurfer": {
|
||||
"eigenvalues": "scalar_table",
|
||||
"areas": "vector",
|
||||
"volumes": "vector",
|
||||
"distances": "vector",
|
||||
}
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num: int = 50,
|
||||
|
|
@ -121,117 +113,6 @@ class BrainPrint(BaseMarker):
|
|||
self.use_cholmod = use_cholmod
|
||||
super().__init__(name=name, on="FreeSurfer")
|
||||
|
||||
def get_valid_inputs(self) -> List[str]:
|
||||
"""Get valid data types for input.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list of str
|
||||
The list of data types that can be used as input for this marker.
|
||||
|
||||
"""
|
||||
return ["FreeSurfer"]
|
||||
|
||||
# TODO: kept for making this class concrete; should be removed later
|
||||
def get_output_type(self, input_type: str) -> str:
|
||||
"""Get output type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_type : str
|
||||
The data type input to the marker.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The storage type output by the marker.
|
||||
|
||||
"""
|
||||
return "vector"
|
||||
|
||||
# TODO: overridden to allow multiple outputs from single data type; should
|
||||
# be removed later
|
||||
def validate(self, input: List[str]) -> List[str]:
|
||||
"""Validate the the pipeline step.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input : list of str
|
||||
The input to the pipeline step.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list of str
|
||||
The output of the pipeline step.
|
||||
|
||||
"""
|
||||
|
||||
def _check_dependencies(obj) -> None:
|
||||
"""Check obj._DEPENDENCIES.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
obj : object
|
||||
Object to check _DEPENDENCIES of.
|
||||
|
||||
Raises
|
||||
------
|
||||
ImportError
|
||||
If the pipeline step object is missing dependencies required
|
||||
for its working.
|
||||
|
||||
"""
|
||||
# Check if _DEPENDENCIES attribute is found;
|
||||
# (markers and preprocessors will have them but not datareaders
|
||||
# as of now)
|
||||
dependencies_not_found = []
|
||||
if hasattr(obj, "_DEPENDENCIES"):
|
||||
# Check if dependencies are importable
|
||||
for dependency in obj._DEPENDENCIES:
|
||||
# First perform an easy check
|
||||
if find_spec(dependency) is None:
|
||||
# Then check mapped names
|
||||
if dependency not in list(
|
||||
chain.from_iterable(
|
||||
packages_distributions().values()
|
||||
)
|
||||
):
|
||||
dependencies_not_found.append(dependency)
|
||||
# Raise error if any dependency is not found
|
||||
if dependencies_not_found:
|
||||
raise_error(
|
||||
msg=(
|
||||
f"{dependencies_not_found} are not installed but are "
|
||||
f"required for using {obj.__class__.__name__}."
|
||||
),
|
||||
klass=ImportError,
|
||||
)
|
||||
|
||||
def _check_ext_dependencies(obj) -> None:
|
||||
"""Check obj._EXT_DEPENDENCIES.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
obj : object
|
||||
Object to check _EXT_DEPENDENCIES of.
|
||||
|
||||
"""
|
||||
# Check if _EXT_DEPENDENCIES attribute is found;
|
||||
# (some markers and preprocessors might have them)
|
||||
if hasattr(obj, "_EXT_DEPENDENCIES"):
|
||||
for dependency in obj._EXT_DEPENDENCIES:
|
||||
check_ext_dependencies(**dependency)
|
||||
|
||||
# Check dependencies
|
||||
_check_dependencies(self)
|
||||
# Check external dependencies
|
||||
# _check_ext_dependencies(self)
|
||||
# Validate input
|
||||
_ = self.validate_input(input=input)
|
||||
# Validate output type
|
||||
outputs = ["scalar_table", "vector"]
|
||||
return outputs
|
||||
|
||||
def _create_aseg_surface(
|
||||
self,
|
||||
aseg_path: Path,
|
||||
|
|
@ -426,6 +307,27 @@ class BrainPrint(BaseMarker):
|
|||
),
|
||||
}
|
||||
|
||||
def _fix_nan(
|
||||
self,
|
||||
input_data: List[Union[float, str, npt.ArrayLike]],
|
||||
) -> np.ndarray:
|
||||
"""Convert BrainPrint output with string NaN to ``numpy.nan``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_data : list of str, float or numpy.ndarray-like
|
||||
The data to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
np.ndarray
|
||||
The converted data as ``numpy.ndarray``.
|
||||
|
||||
"""
|
||||
arr = np.asarray(input_data)
|
||||
arr[arr == "NaN"] = np.nan
|
||||
return arr.astype(np.float64)
|
||||
|
||||
def compute(
|
||||
self,
|
||||
input: Dict[str, Any],
|
||||
|
|
@ -443,16 +345,32 @@ class BrainPrint(BaseMarker):
|
|||
Returns
|
||||
-------
|
||||
dict
|
||||
The computed result as dictionary. The dictionary has the following
|
||||
keys:
|
||||
The computed result as dictionary. This will be either returned
|
||||
to the user or stored in the storage by calling the store method
|
||||
with this as a parameter. The dictionary has the following keys:
|
||||
|
||||
* ``eigenvalues`` : dict of surface labels (str) and eigenvalues
|
||||
(``np.ndarray``)
|
||||
* ``eigenvectors`` : dict of surface labels (str) and eigenvectors
|
||||
(``np.ndarray``) if ``keep_eigenvectors=True``
|
||||
else None
|
||||
* ``distances`` : dict of ``{left_label}_{right_label}`` (str) and
|
||||
distance (float) if ``asymmetry=True`` else None
|
||||
* ``eigenvalues`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : eigenvalues as ``np.ndarray``
|
||||
- ``col_names`` : surface labels as list of str
|
||||
- ``row_names`` : eigenvalue count labels as list of str
|
||||
- ``row_header_col_name`` : "eigenvalue"
|
||||
()
|
||||
* ``areas`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : areas as ``np.ndarray``
|
||||
- ``col_names`` : surface labels as list of str
|
||||
|
||||
* ``volumes`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : volumes as ``np.ndarray``
|
||||
- ``col_names`` : surface labels as list of str
|
||||
|
||||
* ``distances`` : dictionary with the following keys
|
||||
if ``asymmetry = True``:
|
||||
|
||||
- ``data`` : distances as ``np.ndarray``
|
||||
- ``col_names`` : surface labels as list of str
|
||||
|
||||
References
|
||||
----------
|
||||
|
|
@ -539,130 +457,3 @@ class BrainPrint(BaseMarker):
|
|||
"col_names": list(distances.keys()),
|
||||
}
|
||||
return output
|
||||
|
||||
def _fix_nan(
|
||||
self,
|
||||
input_data: List[Union[float, str, npt.ArrayLike]],
|
||||
) -> np.ndarray:
|
||||
"""Convert BrainPrint output with string NaN to ``numpy.nan``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_data : list of str, float or numpy.ndarray-like
|
||||
The data to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
np.ndarray
|
||||
The converted data as ``numpy.ndarray``.
|
||||
|
||||
"""
|
||||
arr = np.asarray(input_data)
|
||||
arr[arr == "NaN"] = np.nan
|
||||
return arr.astype(np.float64)
|
||||
|
||||
# TODO: overridden to allow storing multiple outputs from single input;
|
||||
# should be removed later
|
||||
def store(
|
||||
self,
|
||||
type_: str,
|
||||
feature: str,
|
||||
out: Dict[str, Any],
|
||||
storage: "BaseFeatureStorage",
|
||||
) -> None:
|
||||
"""Store.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
type_ : str
|
||||
The data type to store.
|
||||
feature : {"eigenvalues", "distances", "areas", "volumes"}
|
||||
The feature name to store.
|
||||
out : dict
|
||||
The computed result as a dictionary to store.
|
||||
storage : storage-like
|
||||
The storage class, for example, SQLiteFeatureStorage.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If ``feature`` is invalid.
|
||||
|
||||
"""
|
||||
if feature == "eigenvalues":
|
||||
output_type = "scalar_table"
|
||||
elif feature in ["distances", "areas", "volumes"]:
|
||||
output_type = "vector"
|
||||
else:
|
||||
raise_error(f"Unknown feature: {feature}")
|
||||
|
||||
logger.debug(f"Storing {output_type} in {storage}")
|
||||
storage.store(kind=output_type, **out)
|
||||
|
||||
# TODO: overridden to allow storing multiple outputs from single input;
|
||||
# should be removed later
|
||||
def _fit_transform(
|
||||
self,
|
||||
input: Dict[str, Dict],
|
||||
storage: Optional["BaseFeatureStorage"] = None,
|
||||
) -> Dict:
|
||||
"""Fit and transform.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input : dict
|
||||
The Junifer Data object.
|
||||
storage : storage-like, optional
|
||||
The storage class, for example, SQLiteFeatureStorage.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
The processed output as a dictionary. If `storage` is provided,
|
||||
empty dictionary is returned.
|
||||
|
||||
"""
|
||||
out = {}
|
||||
for type_ in self._on:
|
||||
if type_ in input.keys():
|
||||
logger.info(f"Computing {type_}")
|
||||
t_input = input[type_]
|
||||
extra_input = input.copy()
|
||||
extra_input.pop(type_)
|
||||
t_meta = t_input["meta"].copy()
|
||||
t_meta["type"] = type_
|
||||
|
||||
# Returns multiple features
|
||||
t_out = self.compute(input=t_input, extra_input=extra_input)
|
||||
|
||||
if storage is None:
|
||||
out[type_] = {}
|
||||
|
||||
for feature_name, feature_data in t_out.items():
|
||||
# Make deep copy of the feature data for manipulation
|
||||
feature_data_copy = deepcopy(feature_data)
|
||||
# Make deep copy of metadata and add to feature data
|
||||
feature_data_copy["meta"] = deepcopy(t_meta)
|
||||
# Update metadata for the feature,
|
||||
# feature data is not manipulated, only meta
|
||||
self.update_meta(feature_data_copy, "marker")
|
||||
# Update marker feature's metadata name
|
||||
feature_data_copy["meta"]["marker"][
|
||||
"name"
|
||||
] += f"_{feature_name}"
|
||||
|
||||
if storage is not None:
|
||||
logger.info(f"Storing in {storage}")
|
||||
self.store(
|
||||
type_=type_,
|
||||
feature=feature_name,
|
||||
out=feature_data_copy,
|
||||
storage=storage,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"No storage specified, returning dictionary"
|
||||
)
|
||||
out[type_][feature_name] = feature_data_copy
|
||||
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -53,6 +53,12 @@ class ComplexityBase(BaseMarker):
|
|||
|
||||
_DEPENDENCIES: ClassVar[Set[str]] = {"nilearn", "neurokit2"}
|
||||
|
||||
_MARKER_INOUT_MAPPINGS: ClassVar[Dict[str, Dict[str, str]]] = {
|
||||
"BOLD": {
|
||||
"complexity": "vector",
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parcellation: Union[str, List[str]],
|
||||
|
|
@ -78,33 +84,6 @@ class ComplexityBase(BaseMarker):
|
|||
klass=NotImplementedError,
|
||||
)
|
||||
|
||||
def get_valid_inputs(self) -> List[str]:
|
||||
"""Get valid data types for input.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list of str
|
||||
The list of data types that can be used as input for this marker.
|
||||
|
||||
"""
|
||||
return ["BOLD"]
|
||||
|
||||
def get_output_type(self, input_type: str) -> str:
|
||||
"""Get output type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_type : str
|
||||
The data type input to the marker.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The storage type output by the marker.
|
||||
|
||||
"""
|
||||
return "vector"
|
||||
|
||||
def compute(
|
||||
self,
|
||||
input: Dict[str, Any],
|
||||
|
|
@ -124,29 +103,30 @@ class ComplexityBase(BaseMarker):
|
|||
Returns
|
||||
-------
|
||||
dict
|
||||
The computed result as dictionary. The following keys will be
|
||||
included in the dictionary:
|
||||
The computed result as dictionary. This will be either returned
|
||||
to the user or stored in the storage by calling the store method
|
||||
with this as a parameter. The dictionary has the following keys:
|
||||
|
||||
* ``data`` : ROI-wise complexity measures as ``numpy.ndarray``
|
||||
* ``col_names`` : ROI labels for the complexity measures as list
|
||||
* ``complexity`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : ROI-wise complexity measures as ``numpy.ndarray``
|
||||
- ``col_names`` : ROI labels as list of str
|
||||
|
||||
"""
|
||||
# Initialize a ParcelAggregation
|
||||
# Extract the 2D time series using ParcelAggregation
|
||||
parcel_aggregation = ParcelAggregation(
|
||||
parcellation=self.parcellation,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
on="BOLD",
|
||||
)
|
||||
# Extract the 2D time series using parcel aggregation
|
||||
parcel_aggregation_map = parcel_aggregation.compute(
|
||||
input=input, extra_input=extra_input
|
||||
)
|
||||
|
||||
).compute(input=input, extra_input=extra_input)
|
||||
# Compute complexity measure
|
||||
parcel_aggregation_map["data"] = self.compute_complexity(
|
||||
parcel_aggregation_map["data"]
|
||||
)
|
||||
|
||||
return parcel_aggregation_map
|
||||
return {
|
||||
"complexity": {
|
||||
"data": self.compute_complexity(
|
||||
parcel_aggregation["aggregation"]["data"]
|
||||
),
|
||||
"col_names": parcel_aggregation["aggregation"]["col_names"],
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,13 +40,14 @@ def test_compute() -> None:
|
|||
# Compute the marker
|
||||
feature_map = marker.fit_transform(element_data)
|
||||
# Assert the dimension of timeseries
|
||||
assert feature_map["BOLD"]["data"].ndim == 2
|
||||
assert feature_map["BOLD"]["complexity"]["data"].ndim == 2
|
||||
|
||||
|
||||
def test_get_output_type() -> None:
|
||||
"""Test HurstExponent get_output_type()."""
|
||||
marker = HurstExponent(parcellation=PARCELLATION)
|
||||
assert marker.get_output_type("BOLD") == "vector"
|
||||
assert "vector" == HurstExponent(
|
||||
parcellation=PARCELLATION
|
||||
).get_output_type(input_type="BOLD", output_feature="complexity")
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
|
|
|
|||
|
|
@ -39,13 +39,14 @@ def test_compute() -> None:
|
|||
# Compute the marker
|
||||
feature_map = marker.fit_transform(element_data)
|
||||
# Assert the dimension of timeseries
|
||||
assert feature_map["BOLD"]["data"].ndim == 2
|
||||
assert feature_map["BOLD"]["complexity"]["data"].ndim == 2
|
||||
|
||||
|
||||
def test_get_output_type() -> None:
|
||||
"""Test MultiscaleEntropyAUC get_output_type()."""
|
||||
marker = MultiscaleEntropyAUC(parcellation=PARCELLATION)
|
||||
assert marker.get_output_type("BOLD") == "vector"
|
||||
assert "vector" == MultiscaleEntropyAUC(
|
||||
parcellation=PARCELLATION
|
||||
).get_output_type(input_type="BOLD", output_feature="complexity")
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
|
|
|
|||
|
|
@ -39,13 +39,14 @@ def test_compute() -> None:
|
|||
# Compute the marker
|
||||
feature_map = marker.fit_transform(element_data)
|
||||
# Assert the dimension of timeseries
|
||||
assert feature_map["BOLD"]["data"].ndim == 2
|
||||
assert feature_map["BOLD"]["complexity"]["data"].ndim == 2
|
||||
|
||||
|
||||
def test_get_output_type() -> None:
|
||||
"""Test PermEntropy get_output_type()."""
|
||||
marker = PermEntropy(parcellation=PARCELLATION)
|
||||
assert marker.get_output_type("BOLD") == "vector"
|
||||
assert "vector" == PermEntropy(parcellation=PARCELLATION).get_output_type(
|
||||
input_type="BOLD", output_feature="complexity"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
|
|
|
|||
|
|
@ -40,13 +40,14 @@ def test_compute() -> None:
|
|||
# Compute the marker
|
||||
feature_map = marker.fit_transform(element_data)
|
||||
# Assert the dimension of timeseries
|
||||
assert feature_map["BOLD"]["data"].ndim == 2
|
||||
assert feature_map["BOLD"]["complexity"]["data"].ndim == 2
|
||||
|
||||
|
||||
def test_get_output_type() -> None:
|
||||
"""Test RangeEntropy get_output_type()."""
|
||||
marker = RangeEntropy(parcellation=PARCELLATION)
|
||||
assert marker.get_output_type("BOLD") == "vector"
|
||||
assert "vector" == RangeEntropy(parcellation=PARCELLATION).get_output_type(
|
||||
input_type="BOLD", output_feature="complexity"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
|
|
|
|||
|
|
@ -40,13 +40,14 @@ def test_compute() -> None:
|
|||
# Compute the marker
|
||||
feature_map = marker.fit_transform(element_data)
|
||||
# Assert the dimension of timeseries
|
||||
assert feature_map["BOLD"]["data"].ndim == 2
|
||||
assert feature_map["BOLD"]["complexity"]["data"].ndim == 2
|
||||
|
||||
|
||||
def test_get_output_type() -> None:
|
||||
"""Test RangeEntropyAUC get_output_type()."""
|
||||
marker = RangeEntropyAUC(parcellation=PARCELLATION)
|
||||
assert marker.get_output_type("BOLD") == "vector"
|
||||
assert "vector" == RangeEntropyAUC(
|
||||
parcellation=PARCELLATION
|
||||
).get_output_type(input_type="BOLD", output_feature="complexity")
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
|
|
|
|||
|
|
@ -39,13 +39,14 @@ def test_compute() -> None:
|
|||
# Compute the marker
|
||||
feature_map = marker.fit_transform(element_data)
|
||||
# Assert the dimension of timeseries
|
||||
assert feature_map["BOLD"]["data"].ndim == 2
|
||||
assert feature_map["BOLD"]["complexity"]["data"].ndim == 2
|
||||
|
||||
|
||||
def test_get_output_type() -> None:
|
||||
"""Test SampleEntropy get_output_type()."""
|
||||
marker = SampleEntropy(parcellation=PARCELLATION)
|
||||
assert marker.get_output_type("BOLD") == "vector"
|
||||
assert "vector" == SampleEntropy(
|
||||
parcellation=PARCELLATION
|
||||
).get_output_type(input_type="BOLD", output_feature="complexity")
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
|
|
|
|||
|
|
@ -39,13 +39,14 @@ def test_compute() -> None:
|
|||
# Compute the marker
|
||||
feature_map = marker.fit_transform(element_data)
|
||||
# Assert the dimension of timeseries
|
||||
assert feature_map["BOLD"]["data"].ndim == 2
|
||||
assert feature_map["BOLD"]["complexity"]["data"].ndim == 2
|
||||
|
||||
|
||||
def test_get_output_type() -> None:
|
||||
"""Test WeightedPermEntropy get_output_type()."""
|
||||
marker = WeightedPermEntropy(parcellation=PARCELLATION)
|
||||
assert marker.get_output_type("BOLD") == "vector"
|
||||
assert "vector" == WeightedPermEntropy(
|
||||
parcellation=PARCELLATION
|
||||
).get_output_type(input_type="BOLD", output_feature="complexity")
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
|
|
|
|||
|
|
@ -47,6 +47,12 @@ class RSSETSMarker(BaseMarker):
|
|||
|
||||
_DEPENDENCIES: ClassVar[Set[str]] = {"nilearn"}
|
||||
|
||||
_MARKER_INOUT_MAPPINGS: ClassVar[Dict[str, Dict[str, str]]] = {
|
||||
"BOLD": {
|
||||
"rss_ets": "timeseries",
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parcellation: Union[str, List[str]],
|
||||
|
|
@ -61,33 +67,6 @@ class RSSETSMarker(BaseMarker):
|
|||
self.masks = masks
|
||||
super().__init__(name=name)
|
||||
|
||||
def get_valid_inputs(self) -> List[str]:
|
||||
"""Get valid data types for input.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list of str
|
||||
The list of data types that can be used as input for this marker.
|
||||
|
||||
"""
|
||||
return ["BOLD"]
|
||||
|
||||
def get_output_type(self, input_type: str) -> str:
|
||||
"""Get output type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_type : str
|
||||
The data type input to the marker.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The storage type output by the marker.
|
||||
|
||||
"""
|
||||
return "timeseries"
|
||||
|
||||
def compute(
|
||||
self,
|
||||
input: Dict[str, Any],
|
||||
|
|
@ -109,8 +88,9 @@ class RSSETSMarker(BaseMarker):
|
|||
Returns
|
||||
-------
|
||||
dict
|
||||
The computed result as dictionary. The dictionary has the following
|
||||
keys:
|
||||
The computed result as dictionary. This will be either returned
|
||||
to the user or stored in the storage by calling the store method
|
||||
with this as a parameter. The dictionary has the following keys:
|
||||
|
||||
* ``data`` : the actual computed values as a numpy.ndarray
|
||||
* ``col_names`` : the column labels for the computed values as list
|
||||
|
|
@ -124,20 +104,22 @@ class RSSETSMarker(BaseMarker):
|
|||
|
||||
"""
|
||||
logger.debug("Calculating root sum of squares of edgewise timeseries.")
|
||||
# Initialize a ParcelAggregation
|
||||
parcel_aggregation = ParcelAggregation(
|
||||
# Perform aggregation
|
||||
aggregation = ParcelAggregation(
|
||||
parcellation=self.parcellation,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
)
|
||||
# Compute the parcel aggregation
|
||||
out = parcel_aggregation.compute(input=input, extra_input=extra_input)
|
||||
edge_ts, _ = _ets(out["data"])
|
||||
# Compute the RSS
|
||||
out["data"] = np.sum(edge_ts**2, 1) ** 0.5
|
||||
# Make it 2D
|
||||
out["data"] = out["data"][:, np.newaxis]
|
||||
# Set correct column label
|
||||
out["col_names"] = ["root_sum_of_squares_ets"]
|
||||
return out
|
||||
).compute(input=input, extra_input=extra_input)
|
||||
# Compute edgewise timeseries
|
||||
edge_ts, _ = _ets(aggregation["aggregation"]["data"])
|
||||
# Compute the RSS of edgewise timeseries
|
||||
rss = np.sum(edge_ts**2, 1) ** 0.5
|
||||
|
||||
return {
|
||||
"rss_ets": {
|
||||
# Make it 2D
|
||||
"data": rss[:, np.newaxis],
|
||||
"col_names": ["root_sum_of_squares_ets"],
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@ class ALFFBase(BaseMarker):
|
|||
|
||||
Parameters
|
||||
----------
|
||||
fractional : bool
|
||||
Whether to compute fractional ALFF.
|
||||
highpass : positive float
|
||||
Highpass cutoff frequency.
|
||||
lowpass : positive float
|
||||
|
|
@ -85,9 +83,15 @@ class ALFFBase(BaseMarker):
|
|||
},
|
||||
]
|
||||
|
||||
_MARKER_INOUT_MAPPINGS: ClassVar[Dict[str, Dict[str, str]]] = {
|
||||
"BOLD": {
|
||||
"alff": "vector",
|
||||
"falff": "vector",
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
fractional: bool,
|
||||
highpass: float,
|
||||
lowpass: float,
|
||||
using: str,
|
||||
|
|
@ -110,45 +114,12 @@ class ALFFBase(BaseMarker):
|
|||
)
|
||||
self.using = using
|
||||
self.tr = tr
|
||||
self.fractional = fractional
|
||||
|
||||
# Create a name based on the class name if none is provided
|
||||
if name is None:
|
||||
suffix = "_fractional" if fractional else ""
|
||||
name = f"{self.__class__.__name__}{suffix}"
|
||||
super().__init__(on="BOLD", name=name)
|
||||
|
||||
def get_valid_inputs(self) -> List[str]:
|
||||
"""Get valid data types for input.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list of str
|
||||
The list of data types that can be used as input for this marker.
|
||||
|
||||
"""
|
||||
return ["BOLD"]
|
||||
|
||||
def get_output_type(self, input_type: str) -> str:
|
||||
"""Get output type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
input_type : str
|
||||
The data type input to the marker.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The storage type output by the marker.
|
||||
|
||||
"""
|
||||
return "vector"
|
||||
|
||||
def _compute(
|
||||
self,
|
||||
input_data: Dict[str, Any],
|
||||
) -> Tuple["Nifti1Image", Path]:
|
||||
) -> Tuple["Nifti1Image", "Nifti1Image", Path, Path]:
|
||||
"""Compute ALFF and fALFF.
|
||||
|
||||
Parameters
|
||||
|
|
@ -161,9 +132,13 @@ class ALFFBase(BaseMarker):
|
|||
Returns
|
||||
-------
|
||||
Niimg-like object
|
||||
The ALFF / fALFF as NIfTI.
|
||||
The ALFF as NIfTI.
|
||||
Niimg-like object
|
||||
The fALFF as NIfTI.
|
||||
pathlib.Path
|
||||
The path to the ALFF / fALFF as NIfTI.
|
||||
The path to the ALFF as NIfTI.
|
||||
pathlib.Path
|
||||
The path to the fALFF as NIfTI.
|
||||
|
||||
"""
|
||||
logger.debug("Calculating ALFF and fALFF")
|
||||
|
|
@ -186,11 +161,7 @@ class ALFFBase(BaseMarker):
|
|||
# parcellation / coordinates to native space, else the
|
||||
# path should be passed for use later if required.
|
||||
# TODO(synchon): will be taken care in #292
|
||||
if input_data["space"] == "native" and self.fractional:
|
||||
return falff, input_data["path"]
|
||||
elif input_data["space"] == "native" and not self.fractional:
|
||||
return alff, input_data["path"]
|
||||
elif input_data["space"] != "native" and self.fractional:
|
||||
return falff, falff_path
|
||||
if input_data["space"] == "native":
|
||||
return alff, falff, input_data["path"], input_data["path"]
|
||||
else:
|
||||
return alff, alff_path
|
||||
return alff, falff, alff_path, falff_path
|
||||
|
|
|
|||
|
|
@ -26,8 +26,6 @@ class ALFFParcels(ALFFBase):
|
|||
parcellation : str or list of str
|
||||
The name(s) of the parcellation(s). Check valid options by calling
|
||||
:func:`.list_parcellations`.
|
||||
fractional : bool
|
||||
Whether to compute fractional ALFF.
|
||||
using : {"junifer", "afni"}
|
||||
Implementation to use for computing ALFF:
|
||||
|
||||
|
|
@ -73,7 +71,6 @@ class ALFFParcels(ALFFBase):
|
|||
def __init__(
|
||||
self,
|
||||
parcellation: Union[str, List[str]],
|
||||
fractional: bool,
|
||||
using: str,
|
||||
highpass: float = 0.01,
|
||||
lowpass: float = 0.1,
|
||||
|
|
@ -85,7 +82,6 @@ class ALFFParcels(ALFFBase):
|
|||
) -> None:
|
||||
# Superclass init first to validate `using` parameter
|
||||
super().__init__(
|
||||
fractional=fractional,
|
||||
highpass=highpass,
|
||||
lowpass=lowpass,
|
||||
using=using,
|
||||
|
|
@ -114,33 +110,63 @@ class ALFFParcels(ALFFBase):
|
|||
Returns
|
||||
-------
|
||||
dict
|
||||
The computed result as dictionary. The dictionary has the following
|
||||
keys:
|
||||
The computed result as dictionary. This will be either returned
|
||||
to the user or stored in the storage by calling the store method
|
||||
with this as a parameter. The dictionary has the following keys:
|
||||
|
||||
* ``data`` : the actual computed values as a numpy.ndarray
|
||||
* ``col_names`` : the column labels for the computed values as list
|
||||
* ``alff`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : ROI values as ``numpy.ndarray``
|
||||
- ``col_names`` : ROI labels as list of str
|
||||
|
||||
* ``falff`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : ROI values as ``numpy.ndarray``
|
||||
- ``col_names`` : ROI labels as list of str
|
||||
|
||||
"""
|
||||
logger.info("Calculating ALFF / fALFF for parcels")
|
||||
|
||||
# Compute ALFF / fALFF
|
||||
output_data, output_file_path = self._compute(input_data=input)
|
||||
|
||||
# Initialize parcel aggregation
|
||||
parcel_aggregation = ParcelAggregation(
|
||||
parcellation=self.parcellation,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
on="BOLD",
|
||||
)
|
||||
# Perform aggregation on ALFF / fALFF
|
||||
parcel_aggregation_input = dict(input.items())
|
||||
parcel_aggregation_input["data"] = output_data
|
||||
parcel_aggregation_input["path"] = output_file_path
|
||||
output = parcel_aggregation.compute(
|
||||
input=parcel_aggregation_input,
|
||||
extra_input=extra_input,
|
||||
# Compute ALFF + fALFF
|
||||
alff_output, falff_output, alff_output_path, falff_output_path = (
|
||||
self._compute(input_data=input)
|
||||
)
|
||||
|
||||
return output
|
||||
# Perform aggregation on ALFF + fALFF
|
||||
aggregation_alff_input = dict(input.items())
|
||||
aggregation_falff_input = dict(input.items())
|
||||
aggregation_alff_input["data"] = alff_output
|
||||
aggregation_falff_input["data"] = falff_output
|
||||
aggregation_alff_input["path"] = alff_output_path
|
||||
aggregation_falff_input["path"] = falff_output_path
|
||||
|
||||
return {
|
||||
"alff": {
|
||||
**ParcelAggregation(
|
||||
parcellation=self.parcellation,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
on="BOLD",
|
||||
).compute(
|
||||
input=aggregation_alff_input,
|
||||
extra_input=extra_input,
|
||||
)[
|
||||
"aggregation"
|
||||
],
|
||||
},
|
||||
"falff": {
|
||||
**ParcelAggregation(
|
||||
parcellation=self.parcellation,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
on="BOLD",
|
||||
).compute(
|
||||
input=aggregation_falff_input,
|
||||
extra_input=extra_input,
|
||||
)[
|
||||
"aggregation"
|
||||
],
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,8 +26,6 @@ class ALFFSpheres(ALFFBase):
|
|||
coords : str
|
||||
The name of the coordinates list to use. See
|
||||
:func:`.list_coordinates` for options.
|
||||
fractional : bool
|
||||
Whether to compute fractional ALFF.
|
||||
using : {"junifer", "afni"}
|
||||
Implementation to use for computing ALFF:
|
||||
|
||||
|
|
@ -80,7 +78,6 @@ class ALFFSpheres(ALFFBase):
|
|||
def __init__(
|
||||
self,
|
||||
coords: str,
|
||||
fractional: bool,
|
||||
using: str,
|
||||
radius: Optional[float] = None,
|
||||
allow_overlap: bool = False,
|
||||
|
|
@ -94,7 +91,6 @@ class ALFFSpheres(ALFFBase):
|
|||
) -> None:
|
||||
# Superclass init first to validate `using` parameter
|
||||
super().__init__(
|
||||
fractional=fractional,
|
||||
highpass=highpass,
|
||||
lowpass=lowpass,
|
||||
using=using,
|
||||
|
|
@ -125,35 +121,67 @@ class ALFFSpheres(ALFFBase):
|
|||
Returns
|
||||
-------
|
||||
dict
|
||||
The computed result as dictionary. The dictionary has the following
|
||||
keys:
|
||||
The computed result as dictionary. This will be either returned
|
||||
to the user or stored in the storage by calling the store method
|
||||
with this as a parameter. The dictionary has the following keys:
|
||||
|
||||
* ``data`` : the actual computed values as a numpy.ndarray
|
||||
* ``col_names`` : the column labels for the computed values as list
|
||||
* ``alff`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : ROI values as ``numpy.ndarray``
|
||||
- ``col_names`` : ROI labels as list of str
|
||||
|
||||
* ``falff`` : dictionary with the following keys:
|
||||
|
||||
- ``data`` : ROI values as ``numpy.ndarray``
|
||||
- ``col_names`` : ROI labels as list of str
|
||||
|
||||
"""
|
||||
logger.info("Calculating ALFF / fALFF for spheres")
|
||||
|
||||
# Compute ALFF / fALFF
|
||||
output_data, output_file_path = self._compute(input_data=input)
|
||||
|
||||
# Initialize sphere aggregation
|
||||
sphere_aggregation = SphereAggregation(
|
||||
coords=self.coords,
|
||||
radius=self.radius,
|
||||
allow_overlap=self.allow_overlap,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
on="BOLD",
|
||||
# Compute ALFF + fALFF
|
||||
alff_output, falff_output, alff_output_path, falff_output_path = (
|
||||
self._compute(input_data=input)
|
||||
)
|
||||
|
||||
# Perform aggregation on ALFF / fALFF
|
||||
sphere_aggregation_input = dict(input.items())
|
||||
sphere_aggregation_input["data"] = output_data
|
||||
sphere_aggregation_input["path"] = output_file_path
|
||||
output = sphere_aggregation.compute(
|
||||
input=sphere_aggregation_input,
|
||||
extra_input=extra_input,
|
||||
)
|
||||
aggregation_alff_input = dict(input.items())
|
||||
aggregation_falff_input = dict(input.items())
|
||||
aggregation_alff_input["data"] = alff_output
|
||||
aggregation_falff_input["data"] = falff_output
|
||||
aggregation_alff_input["path"] = alff_output_path
|
||||
aggregation_falff_input["path"] = falff_output_path
|
||||
|
||||
return output
|
||||
return {
|
||||
"alff": {
|
||||
**SphereAggregation(
|
||||
coords=self.coords,
|
||||
radius=self.radius,
|
||||
allow_overlap=self.allow_overlap,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
on="BOLD",
|
||||
).compute(
|
||||
input=aggregation_alff_input,
|
||||
extra_input=extra_input,
|
||||
)[
|
||||
"aggregation"
|
||||
],
|
||||
},
|
||||
"falff": {
|
||||
**SphereAggregation(
|
||||
coords=self.coords,
|
||||
radius=self.radius,
|
||||
allow_overlap=self.allow_overlap,
|
||||
method=self.agg_method,
|
||||
method_params=self.agg_method_params,
|
||||
masks=self.masks,
|
||||
on="BOLD",
|
||||
).compute(
|
||||
input=aggregation_falff_input,
|
||||
extra_input=extra_input,
|
||||
)[
|
||||
"aggregation"
|
||||
],
|
||||
},
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue