{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/oesteban/workspace/niworkflows/niworkflows/__init__.py:24: UserWarning: \n", "This call to matplotlib.use() has no effect because the backend has already\n", "been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,\n", "or matplotlib.backends is imported for the first time.\n", "\n", "The backend was *originally* set to 'pgf' by the following code:\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/runpy.py\", line 193, in _run_module_as_main\n", " \"__main__\", mod_spec)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/runpy.py\", line 85, in _run_code\n", " exec(code, run_globals)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py\", line 16, in \n", " app.launch_new_instance()\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/traitlets/config/application.py\", line 658, in launch_instance\n", " app.start()\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/ipykernel/kernelapp.py\", line 477, in start\n", " ioloop.IOLoop.instance().start()\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/zmq/eventloop/ioloop.py\", line 177, in start\n", " super(ZMQIOLoop, self).start()\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/tornado/ioloop.py\", line 888, in start\n", " handler_func(fd_obj, events)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/tornado/stack_context.py\", line 277, in null_wrapper\n", " return fn(*args, **kwargs)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py\", line 440, in _handle_events\n", " self._handle_recv()\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py\", line 472, in _handle_recv\n", " self._run_callback(callback, msg)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py\", line 414, in _run_callback\n", " callback(*args, **kwargs)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/tornado/stack_context.py\", line 277, in null_wrapper\n", " return fn(*args, **kwargs)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/ipykernel/kernelbase.py\", line 283, in dispatcher\n", " return self.dispatch_shell(stream, msg)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/ipykernel/kernelbase.py\", line 235, in dispatch_shell\n", " handler(stream, idents, msg)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/ipykernel/kernelbase.py\", line 399, in execute_request\n", " user_expressions, allow_stdin)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/ipykernel/ipkernel.py\", line 196, in do_execute\n", " res = shell.run_cell(code, store_history=store_history, silent=silent)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/ipykernel/zmqshell.py\", line 533, in run_cell\n", " return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py\", line 2717, in run_cell\n", " interactivity=interactivity, compiler=compiler, result=result)\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py\", line 2821, in run_ast_nodes\n", " if self.run_code(code, result):\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py\", line 2881, in run_code\n", " exec(code_obj, self.user_global_ns, self.user_ns)\n", " File \"\", line 14, in \n", " from matplotlib import pyplot as plt\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py\", line 71, in \n", " from matplotlib.backends import pylab_setup\n", " File \"/home/oesteban/.anaconda3/lib/python3.6/site-packages/matplotlib/backends/__init__.py\", line 16, in \n", " line for line in traceback.format_stack()\n", "\n", "\n", " matplotlib.use('Agg')\n", "/home/oesteban/.anaconda3/lib/python3.6/importlib/_bootstrap.py:219: ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__\n", " return f(*args, **kwds)\n" ] } ], "source": [ "%load_ext autoreload\n", "%autoreload 2\n", "# %matplotlib inline\n", "import os\n", "from pathlib import Path\n", "import warnings\n", "\n", "import numpy as np\n", "import nibabel as nb\n", "import pandas as pd\n", "\n", "import matplotlib as mpl\n", "mpl.use('pgf')\n", "from matplotlib import pyplot as plt\n", "from matplotlib import gridspec, colors\n", "import seaborn as sn\n", "import palettable\n", "\n", "from niworkflows.data import get_template\n", "\n", "from nilearn.image import concat_imgs, mean_img\n", "from nilearn import plotting\n", "\n", "warnings.simplefilter('ignore')\n", "\n", "DATA_HOME = Path(os.getenv('FMRIPREP_DATA_HOME', os.getcwd())).resolve()\n", "DS030_HOME = DATA_HOME / 'ds000030' / '1.0.3'\n", "DERIVS_HOME = DS030_HOME / 'derivatives'\n", "ATLAS_HOME = get_template('MNI152NLin2009cAsym')\n", "ANALYSIS_HOME = DERIVS_HOME / 'fmriprep_vs_feat_2.0-oe'\n", "\n", "fprep_home = DERIVS_HOME / 'fmriprep_1.0.8' / 'fmriprep'\n", "feat_home = DERIVS_HOME / 'fslfeat_5.0.10' / 'featbids'\n", "\n", "out_folder = Path(os.getenv('FMRIPREP_OUTPUTS') or '').resolve()\n", "\n", "# Load MNI152 nonlinear, asymmetric 2009c atlas\n", "atlas = nb.load(str(ATLAS_HOME / 'tpl-MNI152NLin2009cAsym_space-MNI_res-01_T1w.nii.gz'))\n", "mask1mm = nb.load(str(ATLAS_HOME / 'tpl-MNI152NLin2009cAsym_space-MNI_res-01_brainmask.nii.gz')).get_data() > 0\n", "mask2mm = nb.load(str(ATLAS_HOME / 'tpl-MNI152NLin2009cAsym_space-MNI_res-02_brainmask.nii.gz')).get_data() > 0\n", "data = atlas.get_data()\n", "data[~mask1mm] = data[~mask1mm].max()\n", "atlas = nb.Nifti1Image(data, atlas.affine, atlas.header)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# sn.set_style(\"whitegrid\", {\n", "# 'ytick.major.size': 5,\n", "# 'xtick.major.size': 5,\n", "# })\n", "# sn.set_context(\"notebook\", font_scale=1.5)\n", "\n", "# pgf_with_custom_preamble = {\n", "# 'ytick.major.size': 0,\n", "# 'xtick.major.size': 0,\n", "# 'font.size': 30,\n", "# 'font.sans-serif': ['HelveticaLTStd-Light'],\n", "# 'font.family': 'sans-serif', # use serif/main font for text elements\n", "# 'text.usetex': False, # use inline math for ticks\n", "# }\n", "# mpl.rcParams.update(pgf_with_custom_preamble)\n", "\n", "\n", "pgf_with_custom_preamble = {\n", " 'text.usetex': True, # use inline math for ticks\n", " 'pgf.rcfonts': False, # don't setup fonts from rc parameters\n", " 'pgf.texsystem': 'xelatex',\n", " 'verbose.level': 'debug-annoying',\n", " \"pgf.preamble\": [\n", " r\"\"\"\\usepackage{fontspec}\n", "\\setsansfont{HelveticaLTStd-Light}[\n", "Extension=.otf,\n", "BoldFont=HelveticaLTStd-Bold,\n", "ItalicFont=HelveticaLTStd-LightObl,\n", "BoldItalicFont=HelveticaLTStd-BoldObl,\n", "]\n", "\\setmainfont{HelveticaLTStd-Light}[\n", "Extension=.otf,\n", "BoldFont=HelveticaLTStd-Bold,\n", "ItalicFont=HelveticaLTStd-LightObl,\n", "BoldItalicFont=HelveticaLTStd-BoldObl,\n", "]\n", "\\setmonofont{Inconsolata-dz}\n", "\"\"\",\n", " r'\\renewcommand\\familydefault{\\sfdefault}',\n", "# r'\\setsansfont[Extension=.otf]{Helvetica-LightOblique}',\n", "# r'\\setmainfont[Extension=.ttf]{DejaVuSansCondensed}',\n", "# r'\\setmainfont[Extension=.otf]{FiraSans-Light}',\n", "# r'\\setsansfont[Extension=.otf]{FiraSans-Light}',\n", " ]\n", "}\n", "mpl.rcParams.update(pgf_with_custom_preamble)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "res_shape = np.array(mask1mm.shape[:3])\n", "bbox = np.argwhere(mask1mm)\n", "new_origin = np.clip(bbox.min(0) - 5, a_min=0, a_max=None)\n", "new_end = np.clip(bbox.max(0) + 5, a_min=0,\n", " a_max=res_shape - 1)\n", "\n", "# Find new origin, and set into new affine\n", "new_affine_4 = atlas.affine.copy()\n", "new_affine_4[:3, 3] = new_affine_4[:3, :3].dot(\n", " new_origin) + new_affine_4[:3, 3]\n", "\n", "cropped_atlas = atlas.__class__(\n", " atlas.get_data()[new_origin[0]:new_end[0], new_origin[1]:new_end[1], new_origin[2]:new_end[2]],\n", " new_affine_4,\n", " atlas.header\n", ")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "draw_scale_bar() got multiple values for keyword argument 'bg_color'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 19\u001b[0m disp.annotate(size=24, left_right=False, positions=False, scalebar=True,\n\u001b[1;32m 20\u001b[0m \u001b[0mloc\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msize_vertical\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabel_top\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mframeon\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mborderpad\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0.1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 21\u001b[0;31m bg_color='None')\n\u001b[0m\u001b[1;32m 22\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m/home/oesteban/workspace/nilearn/nilearn/plotting/displays.py\u001b[0m in \u001b[0;36mannotate\u001b[0;34m(self, left_right, positions, scalebar, size, **kwargs)\u001b[0m\n\u001b[1;32m 995\u001b[0m display_axis.draw_scale_bar(bg_color=bg_color,\n\u001b[1;32m 996\u001b[0m \u001b[0mfontsize\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0msize\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 997\u001b[0;31m **kwargs)\n\u001b[0m\u001b[1;32m 998\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 999\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mclose\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: draw_scale_bar() got multiple values for keyword argument 'bg_color'" ] } ], "source": [ "plt.clf()\n", "fig = plt.gcf()\n", "_ = fig.set_size_inches(12, 10)\n", "gs = gridspec.GridSpec(4, 3, height_ratios=[15, 15, 4, 0.5], hspace=0.0, wspace=0.)\n", "ax1 = plt.subplot(gs[0, :])\n", "ax2 = plt.subplot(gs[1, :])\n", "\n", "cut_coords = [0, 15, 30]\n", "disp = plotting.plot_stat_map(str(ANALYSIS_HOME / 'acm_fpre.nii.gz'),\n", " bg_img=cropped_atlas, threshold=0.25, display_mode='z',\n", " cut_coords=cut_coords, vmax=0.8, alpha=0.8,\n", " axes=ax1, colorbar=False, annotate=False)\n", "disp.annotate(size=20, left_right=True, positions=True)\n", "\n", "disp = plotting.plot_stat_map(str(ANALYSIS_HOME / 'acm_feat.nii.gz'),\n", " bg_img=cropped_atlas, threshold=0.25, display_mode='z',\n", " cut_coords=cut_coords, vmax=0.8, alpha=0.8,\n", " axes=ax2, colorbar=False, annotate=False)\n", "disp.annotate(size=24, left_right=False, positions=False, scalebar=True,\n", " loc=3, size_vertical=2, label_top=False, frameon=True, borderpad=0.1,\n", " bg_color='None')\n", "\n", "\n", "ax1.annotate(\n", " 'fMRIPrep',\n", " xy=(0., .5), xycoords='axes fraction', xytext=(-40, .0),\n", " textcoords='offset points', va='center', color='k', size=24,\n", " rotation=90);\n", "\n", "ax2.annotate(\n", " r'\\texttt{feat}',\n", " xy=(0., .5), xycoords='axes fraction', xytext=(-40, .0),\n", " textcoords='offset points', va='center', color='k', size=24,\n", " rotation=90);\n", "\n", "ax3 = fig.add_subplot(gs[3, 2])\n", "\n", "cmap = plotting.cm.cold_hot\n", "gradient = np.linspace(-0.8, 0.8, cmap.N)\n", "\n", "# istart = int(norm(-offset, clip=True) * (our_cmap.N - 1))\n", "# istop = int(norm(offset, clip=True) * (our_cmap.N - 1))\n", "GRAY = (0.85, 0.85, 0.85, 1.)\n", "cmaplist = []\n", "for i in range(cmap.N):\n", " cmaplist += [cmap(i)] if not -0.25 < gradient[i] < 0.25 else [GRAY] # just an average gray color\n", "\n", "cmap = colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplist, cmap.N)\n", "\n", "th_index = cmaplist.index(GRAY)\n", "\n", "gradient = np.vstack((gradient, gradient))\n", "ax3.imshow(gradient, aspect='auto', cmap=cmap)\n", "ax3.set_title(r'\\noindent\\parbox{7.5cm}{\\centering\\textbf{Fraction of participants} \\\\ with significant response}',\n", " size=18, position=(0.5, 3.0))\n", "ax3.xaxis.set_ticklabels(['80\\%', '25\\%', '25\\%', '80\\%'], size=20)\n", "ax3.xaxis.set_ticks([0, th_index, cmap.N - th_index - 1, cmap.N])\n", "ax3.yaxis.set_ticklabels([])\n", "ax3.yaxis.set_ticks([])\n", "for pos in ['top', 'bottom', 'left', 'right']:\n", "# ax3.spines[pos].set_visible(False)\n", " ax3.spines[pos].set_color(GRAY)\n", "\n", "# ax3.annotate(\n", "# r'\\noindent\\parbox{15cm}{'\n", "# r'Cold hues represent negative activation (response inhibition). '\n", "# r'Warm hues represent positive activation. '\n", "# r'Activation count maps are derived from N=257 biologically independent participants.}',\n", "# xy=(-2.05, 0.07), xycoords='axes fraction', xytext=(.0, 10.0),\n", "# textcoords='offset points', va='center', color='k', size=14,\n", "# )\n", "\n", "\n", "plt.savefig(str(out_folder / 'figure04.pdf'),\n", " format='pdf', bbox_inches='tight', pad_inches=0.2, dpi=300)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }