Skip to content
Snippets Groups Projects
07_jupyter.ipynb 12.9 KiB
Newer Older
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Jupyter notebook and IPython\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
    "Our main interaction with python so far has been through the [Jupyter\n",
    "notebook](http://jupyter.org/).  These notebooks are extremely popular these\n",
    "days within the python scientific community, however they support many more\n",
    "languages, such as R and octave (and even matlab with the right\n",
    "[plugin](https://github.com/Calysto/matlab_kernel)).  They allow for\n",
    "interactive analysis of your data interspersed by explanatory notes (including\n",
    "LaTeX) with inline plotting.  However, they can not be called as scripts on\n",
    "the command line or be imported from other python code, which makes them\n",
    "rather stand-alone.  This makes them more useful for analysis that needs to be\n",
    "reproducible, but does not need to be replicated on different datasets (e.g.,\n",
    "making a plot for a paper).\n",
    "\n",
    "For more ad-hoc analysis it can be useful to just use the command line (i.e.,\n",
    "a REPL<sup>*</sup>).  We strongly recommend to use the IPython (available as\n",
    "`fslipython` or `ipython`) rather than default python REPL (available through\n",
    "`fslpython` or `python`), as IPython is much more user-friendly.\n",
    "\n",
    "> <sup>*</sup>REPL = **R**ead-**E**val-**P**rint-**L**oop - the geeky term for\n",
    "> an interactive prompt. You may hear younger generations using the term\n",
    "> [ESRR](https://www.youtube.com/watch?v=wBoRkg5-Ieg) instead.\n",
    "\n",
    "Both Ipython and the jupyter notebook offer a whole range of magic commands, which all start with a `%` sign.\n",
    "* A magic command starting with a single `%` sign will only affect the single line.\n",
    "* A magic command starting with two '%' signs will affect the whole block of code.\n",
    "\n",
    "Note that the normal python interpreter will not understand these magic commands, so you will have to take them out when writing a python script or library.\n",
    "\n",
    "Here we will discuss some of the many features available to you in Ipython and the Jupyter notebook\n",
    "\n",
    "---\n",
    "\n",
    "## Getting help\n",
    "To get the documentation for any object or method simply append a question mark"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import string\n",
    "string.capwords?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This also works for any of the magic commands discussed below"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternatively you can put two questions marks to get the complete code for the method or object class"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import string\n",
    "string.capwords??"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both Ipython and Jupyter also come with autocomplete, which is available at any time by pressing the tab key\n",
    "\n",
    "---\n",
    "\n",
    "## Running shell commands\n",
    "Commands starting with a `!` will be sent to the shell rather than the python interpreter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!fslstats ${FSLDIR}/data/standard/FMRIB58_FA_1mm.nii.gz -r"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can even capture the output from the shell command in a variable:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r = !fslstats ${FSLDIR}/data/standard/FMRIB58_FA_1mm.nii.gz -r\n",
    "r_lower, r_upper = [float(element) for element in r[0].split()]\n",
    "print('Bounds are ({:.0f}, {:.0f})'.format(r_lower, r_upper))"
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Running python scripts\n",
    "We could run a python script as a shell command above. However, it will often be more convenient to use `%run` instead.\n",
    "> ```\n",
    "> %run <python script> <arguments...>\n",
    "> ```\n",
    "Arguments are provided in exactly the same way as if you called `python` in the shell. The main advantages are:\n",
    "- Any top-level variables will be made available to you after the script finishes\n",
    "- All the debugging/timing/profiling tools discussed below will be available to you\n",
    "A common workflow, when writing a python script is to have an Ipython terminal open next to your text editor and regularly use %run to test the script\n",
    "\n",
    "---\n",
    "\n",
    "## Running other programming languages\n",
    "In the notebook you can include a whole code block using another language by using `%%<language>` (for many languages you will have to install a toolkit first, just google your favorite language besides python)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "for filename in `ls *.md` ; do\n",
    "    head -n 1 ${filename}\n",
    "done"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Timing/profiling code\n",
    "We can time a line of code with `%time` or a whole code block using `%%time`.\n",
    "To get the time needed to calculate the sine of a million random numbers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "numbers = np.random.rand(int(1e6))\n",
    "%time np.sin(numbers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For very fast evaluation, you might need to run it multiple times to get an accurate estimate. The `%timeit` (or `%%timeit` for a code block) takes care of this for you."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "numbers = np.random.rand(10)\n",
    "%timeit np.sin(numbers)  # this will take a few seconds to run"
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, if you want to figure out what part of the code is actually slowing you down you can use `%prun`, which gives you an overview of how long the interpreter spent in each method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nibabel as nib\n",
    "import os.path as op\n",
    "%prun nib.load(op.expandvars('${FSLDIR}/data/standard/FMRIB58_FA_1mm.nii.gz'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Debugging\n",
    "Despite your best efforts in many cases some error will crop up"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "def total(a_list):\n",
    "    \"\"\"Calculate the total of a list.\n",
    "\n",
    "    This is a very naive (not recommended) and bugged implementation\n",
    "    \"\"\"\n",
    "    # create local copy befor changing the input\n",
    "    local_list = list(a_list)\n",
    "    total = 0.\n",
    "    while len(local_list) > 0:\n",
    "        total += local_list.pop(1)  # returns element at index=1 and removes it\n",
    "    return total\n",
    "\n",
    "print(total([2, 3, 4]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can always open a debugger at the location of the last error by using the `%debug` magic command. You can find a list of commands available in the debugger [here](http://www.georgejhunt.com/olpc/pydebug/pydebug/ipdb.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%debug"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Try to check the value of `a_list` and `local_list` from within the debugger.\n",
    "\n",
    "> WARNING: you need to quit the debugger before any further commands will run (type `q` into the prompt)!\n",
    "\n",
    "If you always want to enter the debugger when an error is raised you can call `%pdb on` at any time (call `%pdf off` to reverse this)\n",
    "\n",
    "---\n",
    "\n",
    "## Enabling plotting\n",
    "By far the most popular scientific plotting library is [matplotlib](https://matplotlib.org/).\n",
    "You can enable plotting in Ipython or the jupyter notebook using `%matplotlib <backend>`, where [backend](https://matplotlib.org/faq/usage_faq.html#what-is-a-backend) is the system that will be used to display the plots.\n",
    "When failing to provide a backend it will simply use the default (which is usually fine).\n",
    "* In the jupyter notebook use the `nbagg` backend for interactive plots or the `inline` backend for non-interactive plots\n",
    "* Otherwise on Mac OSx use the `macosx` backend"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib nbagg"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Keep in mind that as soon as you have started plotting you can no longer change your backend without exiting the python interpreter and restarting `python` (note that in the jupyter notebook you can just press `Restart` in the `Kernel` menu).\n",
    "To do the equivalent in a python script would look like\n",
    "> ```\n",
    "> import matplotlib as mpl\n",
    "> mpl.use(<backend>)\n",
    "> ```\n",
    "\n",
    "For interactive use it can be handy to have all the `numpy` numeric functions and `matplotlib` plotting functions directly available without importing them explicitly.\n",
    "This can be achieved using the `%pylab <backend>` magic command."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pylab nbagg"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is equivalent in python code to:\n",
    "> ```\n",
    "> import matplotlib as mpl\n",
    "> mpl.use(<backend>)\n",
    "> from matplotlib.pylab import *\n",
    "> ```\n",
    "> The last line imports everything from the matplotlib.pylab module into the namespace.\n",
    "I start most of my notebooks or terminals with the `%pylab` command, because afterwards I can just do stuff like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = linspace(0, pi, 301)\n",
    "y = sin(x)\n",
    "plot(x, y, 'r-')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The main disadvantage is that it will not be obvious to the naive reader of this code, whether functions like `linspace`, `sin`, or `plot` are originate from numpy, matplotlib, or are built-in.\n",
    "This is why we dont recommend `from <module> import *` statements in any longer code or code you intend to share.\n",
    "\n",
    "---\n",
    "\n",
    "## Exporting code from the Jupyter notebook\n",
    "If you have a code cell in the jupyter notebook, that you want to convert into a script, you can use the %%writefile"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile script_from_notebook.py\n",
    "# a bunch of imports\n",
    "import numpy as np\n",
    "from datetime import datetime\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Any additional code cells need to contain the `-a` flag to stop jupyter from overwriting the original code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile -a script_from_notebook.py\n",
    "\n",
    "print('today is ', datetime.now())\n",
    "print('sin(3) is ', np.sin(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now run this script"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run script_from_notebook.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Exporting code from the Ipython terminal\n",
    "You can access the full history of your session using `%history`.\n",
    "To save the history to a file use `%history -f <filename>`.\n",
    "You will probably have to clean a lot of erroneous commands you typed from that file before you are able to run it as a script."
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}