How to use NiMARE - 10 common examples

To help you get started, we’ve selected a few NiMARE examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github neurostuff / NiMARE / nimare / meta / cbma / model.py View on Github external
References
    ----------
    .. [1] Kang, Jian, et al. "Meta analysis of functional neuroimaging data
        via Bayesian spatial point processes." Journal of the American
        Statistical Association 106.493 (2011): 124-134.
        https://doi.org/10.1198/jasa.2011.ap09735
    """
    def __init__(self):
        pass

    def _fit(self, dataset):
        pass


@due.dcite(references.HPGRF, description='Introduces the HPGRF model.')
class HPGRF(CBMAEstimator):
    """
    Hierarchical Poisson/Gamma random field model [1]_.

    Warnings
    --------
    This method is not yet implemented.

    References
    ----------
    .. [1] Kang, Jian, et al. "A Bayesian hierarchical spatial point process
        model for multi-type neuroimaging meta-analysis." The annals of applied
        statistics 8.3 (2014): 1800.
    """
    def __init__(self):
        pass
github neurostuff / NiMARE / nimare / meta / cbma / mkda.py View on Github external
>>> meta = MKDAChi2()
        >>> result = meta.fit(dset)
        >>> corrector = FDRCorrector(method='bh', alpha=0.05)
        >>> cresult = corrector.transform(result)
        """
        pAgF_p_vals = result.get_map('consistency_p', return_type='array')
        pFgA_p_vals = result.get_map('specificity_p', return_type='array')
        pAgF_z_vals = result.get_map('consistency_z', return_type='array')
        pFgA_z_vals = result.get_map('specificity_z', return_type='array')
        pAgF_sign = np.sign(pAgF_z_vals)
        pFgA_sign = np.sign(pFgA_z_vals)
        _, pAgF_p_FDR, _, _ = multipletests(pAgF_p_vals, alpha=alpha,
                                            method='fdr_bh',
                                            is_sorted=False,
                                            returnsorted=False)
        pAgF_z_FDR = p_to_z(pAgF_p_FDR, tail='two') * pAgF_sign

        _, pFgA_p_FDR, _, _ = multipletests(pFgA_p_vals, alpha=alpha,
                                            method='fdr_bh',
                                            is_sorted=False,
                                            returnsorted=False)
        pFgA_z_FDR = p_to_z(pFgA_p_FDR, tail='two') * pFgA_sign

        images = {
            'consistency_z_FDR': pAgF_z_FDR,
            'specificity_z_FDR': pFgA_z_FDR,
        }
        return images
github neurostuff / NiMARE / examples / 03_annotation / run_gclda.py View on Github external
###############################################################################
# Start with the necessary imports
# --------------------------------
import os

import numpy as np
import nibabel as nib

import nimare
from nimare import annotate, decode
from nimare.tests.utils import get_test_data_path

###############################################################################
# Load dataset with abstracts
# ---------------------------
dset = nimare.dataset.Dataset.load(
    os.path.join(get_test_data_path(), 'neurosynth_laird_studies.pkl.gz'))

###############################################################################
# Generate term counts
# --------------------
counts_df = annotate.text.generate_counts(
    dset.texts, text_column='abstract', tfidf=False, max_df=0.99, min_df=0)

###############################################################################
# Run model
# ---------
# Five iterations will take ~10 minutes
model = annotate.topic.GCLDAModel(
    counts_df, dset.coordinates, mask=dset.masker.mask_img)
model.fit(n_iters=5, loglikely_freq=5)
model.save('gclda_model.pkl.gz')
github neurostuff / NiMARE / nimare / extract / extract.py View on Github external
Email address to use to call the PubMed API

    Returns
    -------
    dataset : :obj:`nimare.dataset.Dataset`
    """
    try:
        from Bio import Entrez, Medline
    except:
        raise Exception(
            'Module biopython is required for downloading abstracts from '
            'PubMed.')

    Entrez.email = email

    if isinstance(dataset, Dataset):
        pmids = dataset.coordinates['id'].astype(str).tolist()
        pmids = [pmid.split('-')[0] for pmid in pmids]
        pmids = sorted(list(set(pmids)))
    elif isinstance(dataset, list):
        pmids = [str(pmid) for pmid in dataset]
    else:
        raise Exception(
            'Dataset type not recognized: {0}'.format(type(dataset)))

    records = []
    # PubMed only allows you to search ~1000 at a time. I chose 900 to be safe.
    chunks = [pmids[x: x + 900] for x in range(0, len(pmids), 900)]
    for i, chunk in enumerate(chunks):
        LGR.info('Downloading chunk {0} of {1}'.format(i + 1, len(chunks)))
        h = Entrez.efetch(db='pubmed', id=chunk, rettype='medline',
                          retmode='text')
github neurostuff / NiMARE / examples / 02_meta-analyses / run_cbmas.py View on Github external
import numpy as np
import pandas as pd
import nibabel as nib
from scipy.stats import t
from nilearn.masking import apply_mask
from nilearn.plotting import plot_stat_map

import nimare
from nimare.tests.utils import get_test_data_path

###############################################################################
# Load Dataset
# --------------------------------------------------
dset_file = os.path.join(get_test_data_path(), 'nidm_pain_dset.json')
dset = nimare.dataset.Dataset(dset_file)

mask_img = dset.masker.mask_img

###############################################################################
# MKDA density analysis
# --------------------------------------------------
mkda = nimare.meta.cbma.MKDADensity(kernel__r=10)
mkda.fit(dset)
corr = nimare.correct.FWECorrector(method='permutation', n_iters=10, n_cores=1)
cres = corr.transform(mkda.results)
plot_stat_map(cres.get_map('logp_level-voxel_corr-FWE_method-permutation'),
              cut_coords=[0, 0, -8], draw_cross=False, cmap='RdBu_r')

###############################################################################
# MKDA Chi2 with FDR correction
# --------------------------------------------------
github neurostuff / NiMARE / examples / 03_annotation / run_lda.py View on Github external
using abstracts from Neurosynth.

"""
###############################################################################
# Start with the necessary imports
# --------------------------------
import os

import nimare
from nimare import annotate
from nimare.tests.utils import get_test_data_path

###############################################################################
# Load dataset with abstracts
# ---------------------------
dset = nimare.dataset.Dataset.load(
    os.path.join(get_test_data_path(), 'neurosynth_laird_studies.pkl.gz'))

###############################################################################
# Download MALLET
# ---------------
# LDAModel will do this automatically.
mallet_dir = nimare.extract.download_mallet()

###############################################################################
# Run model
# ---------
# Five iterations will take ~10 minutes
model = annotate.topic.LDAModel(dset.texts, text_column='abstract', n_iters=5)
model.fit()
model.save('lda_model.pkl.gz')
github neurostuff / NiMARE / nimare / meta / cbma / model.py View on Github external
References
    ----------
    .. [1] Kang, Jian, et al. "Meta analysis of functional neuroimaging data
        via Bayesian spatial point processes." Journal of the American
        Statistical Association 106.493 (2011): 124-134.
        https://doi.org/10.1198/jasa.2011.ap09735
    """
    def __init__(self):
        pass

    def _fit(self, dataset):
        pass


@due.dcite(references.HPGRF, description='Introduces the HPGRF model.')
class HPGRF(CBMAEstimator):
    """
    Hierarchical Poisson/Gamma random field model [1]_.

    Warnings
    --------
    This method is not yet implemented.

    References
    ----------
    .. [1] Kang, Jian, et al. "A Bayesian hierarchical spatial point process
        model for multi-type neuroimaging meta-analysis." The annals of applied
        statistics 8.3 (2014): 1800.
    """
    def __init__(self):
        pass
github neurostuff / NiMARE / nimare / meta / cbma / model.py View on Github external
References
    ----------
    .. [1] Kang, Jian, et al. "A Bayesian hierarchical spatial point process
        model for multi-type neuroimaging meta-analysis." The annals of applied
        statistics 8.3 (2014): 1800.
    """
    def __init__(self):
        pass

    def _fit(self, dataset):
        pass


@due.dcite(references.SBLFR, description='Introduces the SBLFR model.')
class SBLFR(CBMAEstimator):
    """
    Spatial Bayesian latent factor regression model [1]_.

    Warnings
    --------
    This method is not yet implemented.

    References
    ----------
    .. [1] Montagna, Silvia, et al. "Spatial Bayesian latent factor regression
        modeling of coordinate‐based meta‐analysis data." Biometrics 74.1
        (2018): 342-353. https://doi.org/10.1111/biom.12713
    """
    def __init__(self):
        pass
github neurostuff / NiMARE / nimare / meta / cbma / model.py View on Github external
References
    ----------
    .. [1] Montagna, Silvia, et al. "Spatial Bayesian latent factor regression
        modeling of coordinate‐based meta‐analysis data." Biometrics 74.1
        (2018): 342-353. https://doi.org/10.1111/biom.12713
    """
    def __init__(self):
        pass

    def _fit(self, dataset):
        pass


@due.dcite(references.SBR, description='Introduces the SBR model.')
class SBR(CBMAEstimator):
    """
    Spatial binary regression model [1]_.

    Warnings
    --------
    This method is not yet implemented.

    References
    ----------
    .. [1] Yue, Yu Ryan, Martin A. Lindquist, and Ji Meng Loh. "Meta-analysis
        of functional neuroimaging data using Bayesian nonparametric binary
        regression." The Annals of Applied Statistics 6.2 (2012): 697-718.
        https://doi.org/10.1214/11-AOAS523
    """
    def __init__(self):
        pass
github neurostuff / NiMARE / nimare / extract / extract.py View on Github external
package's default path for downloaded data.
    overwrite : :obj:`bool`, optional
        Whether to overwrite existing files or not. Default is False.
    verbose : :obj:`int`, optional
        Default is 1.

    Returns
    -------
    data_dir : :obj:`str`
        Updated data directory pointing to dataset files.
    """
    url = 'https://neurovault.org/collections/1425/download'

    dataset_name = 'nidm_21pain'

    data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir, verbose=verbose)
    desc_file = op.join(data_dir, 'description.txt')
    if op.isfile(desc_file) and overwrite is False:
        return data_dir

    # Download
    fname = op.join(data_dir, url.split('/')[-1])
    _download_zipped_file(url, filename=fname)

    # Unzip
    with zipfile.ZipFile(fname, 'r') as zip_ref:
        zip_ref.extractall(data_dir)

    collection_folders = [f for f in glob(op.join(data_dir, '*')) if '.nidm' not in f]
    collection_folders = [f for f in collection_folders if op.isdir(f)]
    if len(collection_folders) > 1:
        raise Exception('More than one folder found: '