{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Using spatial null models\n\nThis example demonstrates how to use spatial null models in\n:mod:`neuromaps.nulls` to test the correlation between two brain\nannotations.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The brain\u2014and most features derived from it\u2014is spatially autocorrelated, and\ntherefore when making comparisons between brain features we need to account\nfor this spatial autocorrelation.\n\nEnter: spatial null models.\n\nSpatial null models need to be used whenever you're comparing brain maps. In\norder to demonstrate how use them in ``neuromaps`` we need two\nannotations to compare. We'll use the first principal component of cognitive\nterms from NeuroSynth (Yarkoni et al., 2011, Nat Methods) and the first\nprincipal component of gene expression across the brain (from the Allen Human\nBrain Atlas).\n\nNote that we pass `return_single=True` to\n:func:`neuromaps.datasets.fetch_annotation` so that the returned data are\na list of filepaths rather than the default dictionary format. (This only\nworks since we know that there is only one annotation matching our query; a\ndictionary will always be returned if multiple annotations match our query.)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from neuromaps import datasets\nnsynth = datasets.fetch_annotation(source='neurosynth', return_single=True)\ngenepc = datasets.fetch_annotation(desc='genepc1', return_single=True)\nprint('Neurosynth: ', nsynth)\nprint('Gene PC1: ', genepc)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "These annotations are in different spaces so we first need to resample them\nto the same space. Here, we'll choose to resample them to the 'fsaverage'\nsurface with a '10k' resolution (approx 10k vertices per hemisphere). Note\nthat the `genepc1` is already in this space so no resampling will be\nperformed for those data. (We could alternatively specify 'transform_to_trg'\nfor the `resampling` parameter and achieve the same outcome.)\n\nThe data returned will always be pre-loaded nibabel image instances:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from neuromaps import resampling\nnsynth, genepc = resampling.resample_images(src=nsynth, trg=genepc,\n                                            src_space='MNI152',\n                                            trg_space='fsaverage',\n                                            resampling='transform_to_alt',\n                                            alt_spec=('fsaverage', '10k'))\nprint(nsynth, genepc)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Once the images are resampled we can easily correlate them:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from neuromaps import stats\ncorr = stats.compare_images(nsynth, genepc)\nprint(f'Correlation: r = {corr:.02f}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "What if we want to assess the statistical significance of this correlation?\nIn this case, we can use a null model from the :mod:`neuromaps.nulls` module.\n\nHere, we'll employ the null model proposed in Alexander-Bloch et al., 2018,\n*NeuroImage*. We provide one of the maps we're comparing, the space + density\nof the map, and the number of permutations we want to generate. The returned\narray will have two dimensions, where each row corresponds to a vertex and\neach column to a unique permutation.\n\n(Note that we need to pass the loaded data from the provided map to the null\nfunction so we use the :func:`neuromaps.images.load_data` utility.)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from neuromaps import images, nulls\nnsynth_data = images.load_data(nsynth)\nrotated = nulls.alexander_bloch(nsynth_data, atlas='fsaverage', density='10k',\n                                n_perm=100, seed=1234)\nprint(rotated.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can supply the generated null array to the\n:func:`neuromaps.stats.compare_images` function and it will be used to\ngenerate a non-parameteric p-value. The function assumes that the array\nprovided to the `nulls` parameter corresponds to the *first* dataset passed\nto the function (i.e., `nsynth`).\n\nNote that the correlation remains identical to that above but the p-value is\nnow returned as well:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "corr, pval = stats.compare_images(nsynth, genepc, nulls=rotated)\nprint(f'Correlation: r = {corr:.02f}, p = {pval:.04f}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "There are a number of different null functions that can be used to generate\nnull maps; they have (nearly) identical function signatures, so refer to the\n`API reference <ref_nulls>` for more information.\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}