.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/02_meta-analyses/03_plot_kernel_transformers.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_02_meta-analyses_03_plot_kernel_transformers.py: .. _metas_kernels: =========================== KernelTransformers and CBMA =========================== ``KernelTransformer`` classes are tools for converting individual studies' coordinates into images. For coordinate-based meta-analyses, individual studies' statistical maps are mimicked by generating "modeled activation" (MA) maps from the coordinates. These MA maps are used in the CBMA algorithms, although the specific method used to generate the MA maps differs by algorithm. This example provides an introduction to the ``KernelTransformer`` class and a tour of available types. .. GENERATED FROM PYTHON SOURCE LINES 20-26 .. code-block:: Python import os import matplotlib.pyplot as plt from nilearn.plotting import plot_stat_map .. GENERATED FROM PYTHON SOURCE LINES 28-30 Load Studyset ----------------------------------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 30-41 .. code-block:: Python from nimare.nimads import Studyset from nimare.utils import get_resource_path studyset_file = os.path.join(get_resource_path(), "nidm_pain_studyset.json") studyset = Studyset(studyset_file, target="mni152_2mm") # First, let us reduce this Studyset to only two studies. source = studyset.to_dict() source["studies"] = source["studies"][2:4] studyset = Studyset(source, target="mni152_2mm") .. GENERATED FROM PYTHON SOURCE LINES 42-44 Kernels ingest Studysets and can produce a few types of outputs ----------------------------------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 44-52 .. code-block:: Python from nimare.meta.kernel import MKDAKernel # First, the kernel should be initialized with any parameters. kernel = MKDAKernel() # Then, the ``transform`` method takes in the Studyset and produces the MA maps. output = kernel.transform(studyset) .. GENERATED FROM PYTHON SOURCE LINES 53-56 ``return_type="image"`` returns a list of 3D niimg objects. This is the default option. .. GENERATED FROM PYTHON SOURCE LINES 56-61 .. code-block:: Python image_output = kernel.transform(studyset, return_type="image") print(type(image_output)) print(type(image_output[0])) print(image_output[0].shape) .. rst-class:: sphx-glr-script-out .. code-block:: none (91, 109, 91) .. GENERATED FROM PYTHON SOURCE LINES 62-63 ``return_type="array"`` returns a 2D numpy array .. GENERATED FROM PYTHON SOURCE LINES 63-67 .. code-block:: Python array_output = kernel.transform(studyset, return_type="array") print(type(array_output)) print(array_output.shape) .. rst-class:: sphx-glr-script-out .. code-block:: none (2, 228483) .. GENERATED FROM PYTHON SOURCE LINES 68-69 ``return_type="summary_array"`` returns a 1D summary map across studies. .. GENERATED FROM PYTHON SOURCE LINES 69-73 .. code-block:: Python summary_output = kernel.transform(studyset, return_type="summary_array") print(type(summary_output)) print(summary_output.shape) .. rst-class:: sphx-glr-script-out .. code-block:: none (228483,) .. GENERATED FROM PYTHON SOURCE LINES 74-78 Each kernel can accept certain parameters that control behavior ----------------------------------------------------------------------------- You can see what options are available via the API documentation or through the help string. .. GENERATED FROM PYTHON SOURCE LINES 78-80 .. code-block:: Python help(MKDAKernel) .. rst-class:: sphx-glr-script-out .. code-block:: none Help on class MKDAKernel in module nimare.meta.kernel: class MKDAKernel(KDAKernel) | MKDAKernel(r=10, value=1, memory=Memory(location=None), memory_level=0) | | Generate MKDA modeled activation images from coordinates. | | .. versionchanged:: 0.2.1 | | - New parameters: ``memory`` and ``memory_level`` for memory caching. | - Add new parameter ``return_type`` to transform method. | | .. versionchanged:: 0.0.13 | | - Remove "dataset" `return_type` option. | | .. versionchanged:: 0.0.12 | | * Remove low-memory option in favor of sparse arrays for kernel transformers. | | Parameters | ---------- | r : :obj:`int`, default=10 | Sphere radius, in mm. | value : :obj:`int`, default=1 | Value for sphere. | memory : instance of :class:`joblib.Memory`, :obj:`str`, or :class:`pathlib.Path` | Used to cache the output of a function. By default, no caching is done. | If a :obj:`str` is given, it is the path to the caching directory. | memory_level : :obj:`int`, default=0 | Rough estimator of the amount of memory used by caching. | Higher value means more memory for caching. Zero means no caching. | | Method resolution order: | MKDAKernel | KDAKernel | KernelTransformer | nimare.base.NiMAREBase | nilearn._utils.cache_mixin.CacheMixin | builtins.object | | Data and other attributes defined here: | | __abstractmethods__ = frozenset() | | __annotations__ = {} | | __slotnames__ = [] | | ---------------------------------------------------------------------- | Methods inherited from KDAKernel: | | __init__(self, r=10, value=1, memory=Memory(location=None), memory_level=0) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from KernelTransformer: | | transform(self, dataset, masker=None, return_type='image') | Generate modeled activation images for each Contrast in dataset. | | Parameters | ---------- | dataset : :obj:`~nimare.dataset.Dataset`, :obj:`~nimare.nimads.Studyset`, or :obj:`pandas.DataFrame` | Collection for which to make images. Can be a DataFrame if necessary. | DataFrame inputs may provide precomputed matrix indices in ``i``, ``j``, and ``k``. | When those columns are present, they are used directly and ``x``, ``y``, and ``z`` | are ignored. | masker : img_like or None, optional | Mask to apply to MA maps. Required if ``dataset`` is a DataFrame. | If None, the input collection's masker attribute will be used. | Required only for DataFrame inputs. Default is None. | return_type : {'sparse', 'array', 'image', 'summary_array'}, optional | Whether to return a sparse matrix ('sparse'), a numpy array ('array'), | or a list of niimgs ('image'). | Default is 'image'. | | Returns | ------- | imgs : (C x V) :class:`numpy.ndarray` or :obj:`list` of :class:`nibabel.Nifti1Image` or sparse matrix | If return_type is 'sparse', the kernel-specific sparse representation is returned. | For ALE, KDA, and MKDA this is a study-by-masked-voxel CSR matrix. | If return_type is 'array', a 2D numpy array (C x V), where C is | contrast and V is voxel. | If return_type is 'summary_array', a 1D numpy array (V,) containing | a summary measure for each voxel that has been combined across experiments. | If return_type is 'image', a list of modeled activation images | (one for each of the Contrasts in the input dataset). | | Attributes | ---------- | filename_pattern : str | Filename pattern for MA maps. If :meth:`_infer_names` is executed. | image_type : str | Name of the corresponding column in the Dataset.images DataFrame. | If :meth:`_infer_names` is executed. | | .. warning:: | Support for :class:`~nimare.dataset.Dataset` inputs is deprecated and will be removed | in a future release. Prefer :class:`~nimare.nimads.Studyset`. | | ---------------------------------------------------------------------- | Methods inherited from nimare.base.NiMAREBase: | | __repr__(self) | Show basic NiMARE class representation. | | Specifically, this shows the name of the class, along with any parameters | that are **not** set to the default. | | get_params(self, deep=True) | Get parameters for this estimator. | | Parameters | ---------- | deep : :obj:`bool`, default=True | If True, will return the parameters for this estimator and | contained subobjects that are estimators. | | Returns | ------- | params : :obj:`dict` | Parameter names mapped to their values. | | save(self, filename, compress=True) | Pickle the class instance to the provided file. | | Parameters | ---------- | filename : :obj:`str` | File to which object will be saved. | compress : :obj:`bool`, optional | If True, the file will be compressed with gzip. Otherwise, the | uncompressed version will be saved. Default = True. | | set_params(self, **params) | Set the parameters of this estimator. | | The method works on simple estimators as well as on nested objects | (such as pipelines). The latter have parameters of the form | ``__`` so that it's possible to update each | component of a nested object. | | Returns | ------- | self | | ---------------------------------------------------------------------- | Class methods inherited from nimare.base.NiMAREBase: | | load(filename, compressed=True) | Load a pickled class instance from file. | | Parameters | ---------- | filename : :obj:`str` | Name of file containing object. | compressed : :obj:`bool`, default=True | If True, the file is assumed to be compressed and gzip will be used | to load it. Otherwise, it will assume that the file is not | compressed. Default = True. | | Returns | ------- | obj : class object | Loaded class object. | | ---------------------------------------------------------------------- | Data descriptors inherited from nilearn._utils.cache_mixin.CacheMixin: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object .. GENERATED FROM PYTHON SOURCE LINES 81-83 For example, :class:`~nimare.meta.kernel.MKDAKernel` kernel accepts an ``r`` argument to control the radius of the kernel. .. GENERATED FROM PYTHON SOURCE LINES 83-103 .. code-block:: Python RADIUS_VALUES = [4, 8, 12] fig, axes = plt.subplots(ncols=3, figsize=(20, 10)) for i, radius in enumerate(RADIUS_VALUES): kernel = MKDAKernel(r=radius) ma_maps = kernel.transform(studyset, return_type="image") plot_stat_map( ma_maps[0], display_mode="z", cut_coords=[-2], title=f"r={radius}mm", axes=axes[i], draw_cross=False, annotate=False, colorbar=False, cmap="RdBu_r", symmetric_cbar=True, ) .. image-sg:: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_001.png :alt: 03 plot kernel transformers :srcset: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 104-108 There are several kernels available ----------------------------------------------------------------------------- :class:`~nimare.meta.kernel.MKDAKernel` convolves coordinates with a sphere and takes the union across voxels. .. GENERATED FROM PYTHON SOURCE LINES 108-120 .. code-block:: Python kernel = MKDAKernel(r=10) ma_maps = kernel.transform(studyset, return_type="image") plot_stat_map( ma_maps[0], cut_coords=[-2, -10, -4], title="MKDA", draw_cross=False, cmap="RdBu_r", symmetric_cbar=True, ) .. image-sg:: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_002.png :alt: 03 plot kernel transformers :srcset: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 121-123 :class:`~nimare.meta.kernel.KDAKernel` convolves coordinates with a sphere as well, but takes the *sum* across voxels. .. GENERATED FROM PYTHON SOURCE LINES 123-137 .. code-block:: Python from nimare.meta.kernel import KDAKernel kernel = KDAKernel(r=10) ma_maps = kernel.transform(studyset, return_type="image") plot_stat_map( ma_maps[0], cut_coords=[-2, -10, -4], title="KDA", draw_cross=False, cmap="RdBu_r", symmetric_cbar=True, ) .. image-sg:: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_003.png :alt: 03 plot kernel transformers :srcset: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 138-143 :class:`~nimare.meta.kernel.ALEKernel` convolves coordinates with a 3D Gaussian, for which the FWHM is determined by the sample size of each study. This sample size will be inferred automatically, if that information is available in the Studyset, or it can be set as a constant value across all studies in the Studyset with the ``sample_size`` argument. .. GENERATED FROM PYTHON SOURCE LINES 143-156 .. code-block:: Python from nimare.meta.kernel import ALEKernel kernel = ALEKernel(sample_size=20) ma_maps = kernel.transform(studyset, return_type="image") plot_stat_map( ma_maps[0], cut_coords=[-2, -10, -4], title="ALE", draw_cross=False, cmap="RdBu_r", symmetric_cbar=True, ) .. image-sg:: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_004.png :alt: 03 plot kernel transformers :srcset: /auto_examples/02_meta-analyses/images/sphx_glr_03_plot_kernel_transformers_004.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 1.438 seconds) .. _sphx_glr_download_auto_examples_02_meta-analyses_03_plot_kernel_transformers.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: 03_plot_kernel_transformers.ipynb <03_plot_kernel_transformers.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: 03_plot_kernel_transformers.py <03_plot_kernel_transformers.py>` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: 03_plot_kernel_transformers.zip <03_plot_kernel_transformers.zip>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_