{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using Fortran and C code with Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "J.R. Johansson (jrjohansson at gmail.com)\n",
    "\n",
    "The latest version of this [IPython notebook](http://ipython.org/notebook.html) lecture is available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/scientific-python-lectures).\n",
    "\n",
    "The other notebooks in this lecture series are indexed at [http://jrjohansson.github.io](http://jrjohansson.github.io)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Populating the interactive namespace from numpy and matplotlib\n"
     ]
    }
   ],
   "source": [
    "%pylab inline\n",
    "from IPython.display import Image"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The advantage of Python is that it is flexible and easy to program. The time it takes to setup a new calculation is therefore short. But for certain types of calculations Python (and any other interpreted language) can be very slow. It is particularly iterations over large arrays that is difficult to do efficiently.\n",
    "\n",
    "Such calculations may be implemented in a compiled language such as C or Fortran. In Python it is relatively easy to call out to libraries with compiled C or Fortran code. In this lecture we will look at how to do that.\n",
    "\n",
    "But before we go ahead and work on optimizing anything, it is always worthwhile to ask.... "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 45208 characters]",
      "text/plain": [
       "<IPython.core.display.Image at 0x7f70a37df110>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Image(filename='images/optimizing-what.png')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fortran"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### F2PY"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "F2PY is a program that (almost) automatically wraps fortran code for use in Python: By using the `f2py` program we can compile fortran code into a module that we can import in a Python program.\n",
    "\n",
    "F2PY is a part of NumPy, but you will also need to have a fortran compiler to run the examples below."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 0: scalar input, no output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting hellofortran.f\n"
     ]
    }
   ],
   "source": [
    "%%file hellofortran.f\n",
    "C File  hellofortran.f\n",
    "        subroutine hellofortran (n)\n",
    "        integer n\n",
    "       \n",
    "        do 100 i=0, n\n",
    "            print *, \"Fortran says hello\"\n",
    "100     continue\n",
    "        end"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Generate a python module using `f2py`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[39mrunning build\u001b[0m\n",
      "\u001b[39mrunning config_cc\u001b[0m\n",
      "\u001b[39munifing config_cc, config, build_clib, build_ext, build commands --compiler options\u001b[0m\n",
      "\u001b[39mrunning config_fc\u001b[0m\n",
      "\u001b[39munifing config_fc, config, build_clib, build_ext, build commands --fcompiler options\u001b[0m\n",
      "\u001b[39mrunning build_src\u001b[0m\n",
      "\u001b[39mbuild_src\u001b[0m\n",
      "\u001b[39mbuilding extension \"hellofortran\" sources\u001b[0m\n",
      "\u001b[39mf2py options: []\u001b[0m\n",
      "\u001b[39mf2py:> /tmp/tmpz2IPjB/src.linux-x86_64-2.7/hellofortranmodule.c\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpz2IPjB/src.linux-x86_64-2.7\u001b[0m\n",
      "Reading fortran codes...\n",
      "\tReading file 'hellofortran.f' (format:fix,strict)\n",
      "Post-processing...\n",
      "\tBlock: hellofortran\n",
      "\t\t\tBlock: hellofortran\n",
      "Post-processing (stage 2)...\n",
      "Building modules...\n",
      "\tBuilding module \"hellofortran\"...\n",
      "\t\tConstructing wrapper function \"hellofortran\"...\n",
      "\t\t  hellofortran(n)\n",
      "\tWrote C/API module \"hellofortran\" to file \"/tmp/tmpz2IPjB/src.linux-x86_64-2.7/hellofortranmodule.c\"\n",
      "\u001b[39m  adding '/tmp/tmpz2IPjB/src.linux-x86_64-2.7/fortranobject.c' to sources.\u001b[0m\n",
      "\u001b[39m  adding '/tmp/tmpz2IPjB/src.linux-x86_64-2.7' to include_dirs.\u001b[0m\n",
      "\u001b[39mcopying /usr/lib/python2.7/dist-packages/numpy/f2py/src/fortranobject.c -> /tmp/tmpz2IPjB/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mcopying /usr/lib/python2.7/dist-packages/numpy/f2py/src/fortranobject.h -> /tmp/tmpz2IPjB/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mbuild_src: building npy-pkg config files\u001b[0m\n",
      "\u001b[39mrunning build_ext\u001b[0m\n",
      "\u001b[39mcustomize UnixCCompiler\u001b[0m\n",
      "\u001b[39mcustomize UnixCCompiler using build_ext\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler\u001b[0m\n",
      "\u001b[39mFound executable /usr/bin/gfortran\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler using build_ext\u001b[0m\n",
      "\u001b[39mbuilding 'hellofortran' extension\u001b[0m\n",
      "\u001b[39mcompiling C sources\u001b[0m\n",
      "\u001b[39mC compiler: x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC\n",
      "\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpz2IPjB/tmp\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpz2IPjB/tmp/tmpz2IPjB\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpz2IPjB/tmp/tmpz2IPjB/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mcompile options: '-I/tmp/tmpz2IPjB/src.linux-x86_64-2.7 -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c'\u001b[0m\n",
      "\u001b[39mx86_64-linux-gnu-gcc: /tmp/tmpz2IPjB/src.linux-x86_64-2.7/hellofortranmodule.c\u001b[0m\n",
      "In file included from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1761:0,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4,\n",
      "                 from /tmp/tmpz2IPjB/src.linux-x86_64-2.7/fortranobject.h:13,\n",
      "                 from /tmp/tmpz2IPjB/src.linux-x86_64-2.7/hellofortranmodule.c:17:\n",
      "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning \"Using deprecated NumPy API, disable it by \" \"#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n",
      " #warning \"Using deprecated NumPy API, disable it by \" \\\n",
      "  ^\n",
      "\u001b[39mx86_64-linux-gnu-gcc: /tmp/tmpz2IPjB/src.linux-x86_64-2.7/fortranobject.c\u001b[0m\n",
      "In file included from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1761:0,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4,\n",
      "                 from /tmp/tmpz2IPjB/src.linux-x86_64-2.7/fortranobject.h:13,\n",
      "                 from /tmp/tmpz2IPjB/src.linux-x86_64-2.7/fortranobject.c:2:\n",
      "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning \"Using deprecated NumPy API, disable it by \" \"#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n",
      " #warning \"Using deprecated NumPy API, disable it by \" \\\n",
      "  ^\n",
      "\u001b[39mcompiling Fortran sources\u001b[0m\n",
      "\u001b[39mFortran f77 compiler: /usr/bin/gfortran -Wall -ffixed-form -fno-second-underscore -fPIC -O3 -funroll-loops\n",
      "Fortran f90 compiler: /usr/bin/gfortran -Wall -fno-second-underscore -fPIC -O3 -funroll-loops\n",
      "Fortran fix compiler: /usr/bin/gfortran -Wall -ffixed-form -fno-second-underscore -Wall -fno-second-underscore -fPIC -O3 -funroll-loops\u001b[0m\n",
      "\u001b[39mcompile options: '-I/tmp/tmpz2IPjB/src.linux-x86_64-2.7 -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c'\u001b[0m\n",
      "\u001b[39mgfortran:f77: hellofortran.f\u001b[0m\n",
      "\u001b[39m/usr/bin/gfortran -Wall -Wall -shared /tmp/tmpz2IPjB/tmp/tmpz2IPjB/src.linux-x86_64-2.7/hellofortranmodule.o /tmp/tmpz2IPjB/tmp/tmpz2IPjB/src.linux-x86_64-2.7/fortranobject.o /tmp/tmpz2IPjB/hellofortran.o -lgfortran -o ./hellofortran.so\u001b[0m\n",
      "Removing build directory /tmp/tmpz2IPjB\n"
     ]
    }
   ],
   "source": [
    "!f2py -c -m hellofortran hellofortran.f"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Example of a python script that use the module:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting hello.py\n"
     ]
    }
   ],
   "source": [
    "%%file hello.py\n",
    "import hellofortran\n",
    "\n",
    "hellofortran.hellofortran(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Fortran says hello\r\n",
      " Fortran says hello\r\n",
      " Fortran says hello\r\n",
      " Fortran says hello\r\n",
      " Fortran says hello\r\n",
      " Fortran says hello\r\n"
     ]
    }
   ],
   "source": [
    "# run the script\n",
    "!python hello.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 1: vector input and scalar output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting dprod.f\n"
     ]
    }
   ],
   "source": [
    "%%file dprod.f\n",
    "\n",
    "       subroutine dprod(x, y, n)\n",
    "    \n",
    "       double precision x(n), y\n",
    "       y = 1.0\n",
    "    \n",
    "       do 100 i=1, n\n",
    "           y = y * x(i)\n",
    "100    continue\n",
    "       end"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Reading fortran codes...\r\n",
      "\tReading file 'dprod.f' (format:fix,strict)\r\n",
      "Post-processing...\r\n",
      "\tBlock: dprod\r\n",
      "{}\r\n",
      "In: :dprod:dprod.f:dprod\r\n",
      "vars2fortran: No typespec for argument \"n\".\r\n",
      "\t\t\tBlock: dprod\r\n",
      "Post-processing (stage 2)...\r\n",
      "Saving signatures to file \"./dprod.pyf\"\r\n"
     ]
    }
   ],
   "source": [
    "!rm -f dprod.pyf\n",
    "!f2py -m dprod -h dprod.pyf dprod.f"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `f2py` program generated a module declaration file called `dsum.pyf`. Let's look what's in it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "!    -*- f90 -*-\r\n",
      "! Note: the context of this file is case sensitive.\r\n",
      "\r\n",
      "python module dprod ! in \r\n",
      "    interface  ! in :dprod\r\n",
      "        subroutine dprod(x,y,n) ! in :dprod:dprod.f\r\n",
      "            double precision dimension(n) :: x\r\n",
      "            double precision :: y\r\n",
      "            integer, optional,check(len(x)>=n),depend(x) :: n=len(x)\r\n",
      "        end subroutine dprod\r\n",
      "    end interface \r\n",
      "end python module dprod\r\n",
      "\r\n",
      "! This file was auto-generated with f2py (version:2).\r\n",
      "! See http://cens.ioc.ee/projects/f2py2e/\r\n"
     ]
    }
   ],
   "source": [
    "!cat dprod.pyf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The module does not know what Fortran subroutine arguments is input and output, so we need to manually edit the module declaration files and mark output variables with `intent(out)` and input variable with `intent(in)`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting dprod.pyf\n"
     ]
    }
   ],
   "source": [
    "%%file dprod.pyf\n",
    "python module dprod ! in \n",
    "    interface  ! in :dprod\n",
    "        subroutine dprod(x,y,n) ! in :dprod:dprod.f\n",
    "            double precision dimension(n), intent(in) :: x\n",
    "            double precision, intent(out) :: y\n",
    "            integer, optional,check(len(x)>=n),depend(x),intent(in) :: n=len(x)\n",
    "        end subroutine dprod\n",
    "    end interface \n",
    "end python module dprod"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compile the fortran code into a module that can be included in python:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[39mrunning build\u001b[0m\n",
      "\u001b[39mrunning config_cc\u001b[0m\n",
      "\u001b[39munifing config_cc, config, build_clib, build_ext, build commands --compiler options\u001b[0m\n",
      "\u001b[39mrunning config_fc\u001b[0m\n",
      "\u001b[39munifing config_fc, config, build_clib, build_ext, build commands --fcompiler options\u001b[0m\n",
      "\u001b[39mrunning build_src\u001b[0m\n",
      "\u001b[39mbuild_src\u001b[0m\n",
      "\u001b[39mbuilding extension \"dprod\" sources\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpWyCvx1/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mf2py options: []\u001b[0m\n",
      "\u001b[39mf2py: dprod.pyf\u001b[0m\n",
      "Reading fortran codes...\n",
      "\tReading file 'dprod.pyf' (format:free)\n",
      "Post-processing...\n",
      "\tBlock: dprod\n",
      "\t\t\tBlock: dprod\n",
      "Post-processing (stage 2)...\n",
      "Building modules...\n",
      "\tBuilding module \"dprod\"...\n",
      "\t\tConstructing wrapper function \"dprod\"...\n",
      "\t\t  y = dprod(x,[n])\n",
      "\tWrote C/API module \"dprod\" to file \"/tmp/tmpWyCvx1/src.linux-x86_64-2.7/dprodmodule.c\"\n",
      "\u001b[39m  adding '/tmp/tmpWyCvx1/src.linux-x86_64-2.7/fortranobject.c' to sources.\u001b[0m\n",
      "\u001b[39m  adding '/tmp/tmpWyCvx1/src.linux-x86_64-2.7' to include_dirs.\u001b[0m\n",
      "\u001b[39mcopying /usr/lib/python2.7/dist-packages/numpy/f2py/src/fortranobject.c -> /tmp/tmpWyCvx1/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mcopying /usr/lib/python2.7/dist-packages/numpy/f2py/src/fortranobject.h -> /tmp/tmpWyCvx1/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mbuild_src: building npy-pkg config files\u001b[0m\n",
      "\u001b[39mrunning build_ext\u001b[0m\n",
      "\u001b[39mcustomize UnixCCompiler\u001b[0m\n",
      "\u001b[39mcustomize UnixCCompiler using build_ext\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler\u001b[0m\n",
      "\u001b[39mFound executable /usr/bin/gfortran\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler using build_ext\u001b[0m\n",
      "\u001b[39mbuilding 'dprod' extension\u001b[0m\n",
      "\u001b[39mcompiling C sources\u001b[0m\n",
      "\u001b[39mC compiler: x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC\n",
      "\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpWyCvx1/tmp\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpWyCvx1/tmp/tmpWyCvx1\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpWyCvx1/tmp/tmpWyCvx1/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mcompile options: '-I/tmp/tmpWyCvx1/src.linux-x86_64-2.7 -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c'\u001b[0m\n",
      "\u001b[39mx86_64-linux-gnu-gcc: /tmp/tmpWyCvx1/src.linux-x86_64-2.7/dprodmodule.c\u001b[0m\n",
      "In file included from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1761:0,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4,\n",
      "                 from /tmp/tmpWyCvx1/src.linux-x86_64-2.7/fortranobject.h:13,\n",
      "                 from /tmp/tmpWyCvx1/src.linux-x86_64-2.7/dprodmodule.c:18:\n",
      "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning \"Using deprecated NumPy API, disable it by \" \"#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n",
      " #warning \"Using deprecated NumPy API, disable it by \" \\\n",
      "  ^\n",
      "/tmp/tmpWyCvx1/src.linux-x86_64-2.7/dprodmodule.c:111:12: warning: ‘f2py_size’ defined but not used [-Wunused-function]\n",
      " static int f2py_size(PyArrayObject* var, ...)\n",
      "            ^\n",
      "\u001b[39mx86_64-linux-gnu-gcc: /tmp/tmpWyCvx1/src.linux-x86_64-2.7/fortranobject.c\u001b[0m\n",
      "In file included from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1761:0,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4,\n",
      "                 from /tmp/tmpWyCvx1/src.linux-x86_64-2.7/fortranobject.h:13,\n",
      "                 from /tmp/tmpWyCvx1/src.linux-x86_64-2.7/fortranobject.c:2:\n",
      "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning \"Using deprecated NumPy API, disable it by \" \"#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n",
      " #warning \"Using deprecated NumPy API, disable it by \" \\\n",
      "  ^\n",
      "\u001b[39mcompiling Fortran sources\u001b[0m\n",
      "\u001b[39mFortran f77 compiler: /usr/bin/gfortran -Wall -ffixed-form -fno-second-underscore -fPIC -O3 -funroll-loops\n",
      "Fortran f90 compiler: /usr/bin/gfortran -Wall -fno-second-underscore -fPIC -O3 -funroll-loops\n",
      "Fortran fix compiler: /usr/bin/gfortran -Wall -ffixed-form -fno-second-underscore -Wall -fno-second-underscore -fPIC -O3 -funroll-loops\u001b[0m\n",
      "\u001b[39mcompile options: '-I/tmp/tmpWyCvx1/src.linux-x86_64-2.7 -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c'\u001b[0m\n",
      "\u001b[39mgfortran:f77: dprod.f\u001b[0m\n",
      "\u001b[39m/usr/bin/gfortran -Wall -Wall -shared /tmp/tmpWyCvx1/tmp/tmpWyCvx1/src.linux-x86_64-2.7/dprodmodule.o /tmp/tmpWyCvx1/tmp/tmpWyCvx1/src.linux-x86_64-2.7/fortranobject.o /tmp/tmpWyCvx1/dprod.o -lgfortran -o ./dprod.so\u001b[0m\n",
      "Removing build directory /tmp/tmpWyCvx1\n"
     ]
    }
   ],
   "source": [
    "!f2py -c dprod.pyf dprod.f"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Using the module from Python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import dprod"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on module dprod:\n",
      "\n",
      "NAME\n",
      "    dprod\n",
      "\n",
      "FILE\n",
      "    /home/rob/Desktop/scientific-python-lectures/dprod.so\n",
      "\n",
      "DESCRIPTION\n",
      "    This module 'dprod' is auto-generated with f2py (version:2).\n",
      "    Functions:\n",
      "      y = dprod(x,n=len(x))\n",
      "    .\n",
      "\n",
      "DATA\n",
      "    __version__ = '$Revision: $'\n",
      "    dprod = <fortran object>\n",
      "\n",
      "VERSION\n",
      "\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(dprod)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6.082818640342675e+62"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dprod.dprod(arange(1,50))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6.0828186403426752e+62"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# compare to numpy\n",
    "prod(arange(1.0,50.0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "120.0"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dprod.dprod(arange(1,10), 5) # only the 5 first elements"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare performance:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "xvec = rand(500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000000 loops, best of 3: 882 ns per loop\n"
     ]
    }
   ],
   "source": [
    "timeit dprod.dprod(xvec)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100000 loops, best of 3: 4.45 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit xvec.prod()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 2: cummulative sum, vector input and vector output"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The cumulative sum function for an array of data is a good example of a loop intense algorithm: Loop through a vector and store the cumulative sum in another vector."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# simple python algorithm: example of a SLOW implementation\n",
    "# Why? Because the loop is implemented in python.\n",
    "def py_dcumsum(a):\n",
    "    b = empty_like(a)\n",
    "    b[0] = a[0]\n",
    "    for n in range(1,len(a)):\n",
    "        b[n] = b[n-1]+a[n]\n",
    "    return b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fortran subroutine for the same thing: here we have added the `intent(in)` and `intent(out)` as comment lines in the original fortran code, so we do not need to manually edit the fortran module declaration file generated by `f2py`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting dcumsum.f\n"
     ]
    }
   ],
   "source": [
    "%%file dcumsum.f\n",
    "c File dcumsum.f\n",
    "       subroutine dcumsum(a, b, n)\n",
    "       double precision a(n)\n",
    "       double precision b(n)\n",
    "       integer n\n",
    "cf2py  intent(in) :: a\n",
    "cf2py  intent(out) :: b\n",
    "cf2py  intent(hide) :: n\n",
    "\n",
    "       b(1) = a(1)\n",
    "       do 100 i=2, n\n",
    "           b(i) = b(i-1) + a(i)\n",
    "100    continue\n",
    "       end"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can directly compile the fortran code to a python module:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[39mrunning build\u001b[0m\n",
      "\u001b[39mrunning config_cc\u001b[0m\n",
      "\u001b[39munifing config_cc, config, build_clib, build_ext, build commands --compiler options\u001b[0m\n",
      "\u001b[39mrunning config_fc\u001b[0m\n",
      "\u001b[39munifing config_fc, config, build_clib, build_ext, build commands --fcompiler options\u001b[0m\n",
      "\u001b[39mrunning build_src\u001b[0m\n",
      "\u001b[39mbuild_src\u001b[0m\n",
      "\u001b[39mbuilding extension \"dcumsum\" sources\u001b[0m\n",
      "\u001b[39mf2py options: []\u001b[0m\n",
      "\u001b[39mf2py:> /tmp/tmpfvrMl6/src.linux-x86_64-2.7/dcumsummodule.c\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpfvrMl6/src.linux-x86_64-2.7\u001b[0m\n",
      "Reading fortran codes...\n",
      "\tReading file 'dcumsum.f' (format:fix,strict)\n",
      "Post-processing...\n",
      "\tBlock: dcumsum\n",
      "\t\t\tBlock: dcumsum\n",
      "Post-processing (stage 2)...\n",
      "Building modules...\n",
      "\tBuilding module \"dcumsum\"...\n",
      "\t\tConstructing wrapper function \"dcumsum\"...\n",
      "\t\t  b = dcumsum(a)\n",
      "\tWrote C/API module \"dcumsum\" to file \"/tmp/tmpfvrMl6/src.linux-x86_64-2.7/dcumsummodule.c\"\n",
      "\u001b[39m  adding '/tmp/tmpfvrMl6/src.linux-x86_64-2.7/fortranobject.c' to sources.\u001b[0m\n",
      "\u001b[39m  adding '/tmp/tmpfvrMl6/src.linux-x86_64-2.7' to include_dirs.\u001b[0m\n",
      "\u001b[39mcopying /usr/lib/python2.7/dist-packages/numpy/f2py/src/fortranobject.c -> /tmp/tmpfvrMl6/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mcopying /usr/lib/python2.7/dist-packages/numpy/f2py/src/fortranobject.h -> /tmp/tmpfvrMl6/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mbuild_src: building npy-pkg config files\u001b[0m\n",
      "\u001b[39mrunning build_ext\u001b[0m\n",
      "\u001b[39mcustomize UnixCCompiler\u001b[0m\n",
      "\u001b[39mcustomize UnixCCompiler using build_ext\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler\u001b[0m\n",
      "\u001b[39mFound executable /usr/bin/gfortran\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler\u001b[0m\n",
      "\u001b[39mcustomize Gnu95FCompiler using build_ext\u001b[0m\n",
      "\u001b[39mbuilding 'dcumsum' extension\u001b[0m\n",
      "\u001b[39mcompiling C sources\u001b[0m\n",
      "\u001b[39mC compiler: x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC\n",
      "\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpfvrMl6/tmp\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpfvrMl6/tmp/tmpfvrMl6\u001b[0m\n",
      "\u001b[39mcreating /tmp/tmpfvrMl6/tmp/tmpfvrMl6/src.linux-x86_64-2.7\u001b[0m\n",
      "\u001b[39mcompile options: '-I/tmp/tmpfvrMl6/src.linux-x86_64-2.7 -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c'\u001b[0m\n",
      "\u001b[39mx86_64-linux-gnu-gcc: /tmp/tmpfvrMl6/src.linux-x86_64-2.7/dcumsummodule.c\u001b[0m\n",
      "In file included from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1761:0,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4,\n",
      "                 from /tmp/tmpfvrMl6/src.linux-x86_64-2.7/fortranobject.h:13,\n",
      "                 from /tmp/tmpfvrMl6/src.linux-x86_64-2.7/dcumsummodule.c:18:\n",
      "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning \"Using deprecated NumPy API, disable it by \" \"#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n",
      " #warning \"Using deprecated NumPy API, disable it by \" \\\n",
      "  ^\n",
      "/tmp/tmpfvrMl6/src.linux-x86_64-2.7/dcumsummodule.c:111:12: warning: ‘f2py_size’ defined but not used [-Wunused-function]\n",
      " static int f2py_size(PyArrayObject* var, ...)\n",
      "            ^\n",
      "\u001b[39mx86_64-linux-gnu-gcc: /tmp/tmpfvrMl6/src.linux-x86_64-2.7/fortranobject.c\u001b[0m\n",
      "In file included from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1761:0,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:17,\n",
      "                 from /usr/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4,\n",
      "                 from /tmp/tmpfvrMl6/src.linux-x86_64-2.7/fortranobject.h:13,\n",
      "                 from /tmp/tmpfvrMl6/src.linux-x86_64-2.7/fortranobject.c:2:\n",
      "/usr/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning \"Using deprecated NumPy API, disable it by \" \"#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n",
      " #warning \"Using deprecated NumPy API, disable it by \" \\\n",
      "  ^\n",
      "\u001b[39mcompiling Fortran sources\u001b[0m\n",
      "\u001b[39mFortran f77 compiler: /usr/bin/gfortran -Wall -ffixed-form -fno-second-underscore -fPIC -O3 -funroll-loops\n",
      "Fortran f90 compiler: /usr/bin/gfortran -Wall -fno-second-underscore -fPIC -O3 -funroll-loops\n",
      "Fortran fix compiler: /usr/bin/gfortran -Wall -ffixed-form -fno-second-underscore -Wall -fno-second-underscore -fPIC -O3 -funroll-loops\u001b[0m\n",
      "\u001b[39mcompile options: '-I/tmp/tmpfvrMl6/src.linux-x86_64-2.7 -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c'\u001b[0m\n",
      "\u001b[39mgfortran:f77: dcumsum.f\u001b[0m\n",
      "\u001b[39m/usr/bin/gfortran -Wall -Wall -shared /tmp/tmpfvrMl6/tmp/tmpfvrMl6/src.linux-x86_64-2.7/dcumsummodule.o /tmp/tmpfvrMl6/tmp/tmpfvrMl6/src.linux-x86_64-2.7/fortranobject.o /tmp/tmpfvrMl6/dcumsum.o -lgfortran -o ./dcumsum.so\u001b[0m\n",
      "Removing build directory /tmp/tmpfvrMl6\n"
     ]
    }
   ],
   "source": [
    "!f2py -c dcumsum.f -m dcumsum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import dcumsum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = array([1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1.,   3.,   6.,  10.,  15.,  21.,  28.,  36.])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "py_dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1.,   3.,   6.,  10.,  15.,  21.,  28.,  36.])"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dcumsum.dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1.,   3.,   6.,  10.,  15.,  21.,  28.,  36.])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cumsum(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Benchmark the different implementations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = rand(10000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100 loops, best of 3: 4.83 ms per loop\n"
     ]
    }
   ],
   "source": [
    "timeit py_dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100000 loops, best of 3: 12.2 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit dcumsum.dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10000 loops, best of 3: 27.4 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit a.cumsum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Further reading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. http://www.scipy.org/F2py\n",
    "1. http://dsnra.jpl.nasa.gov/software/Python/F2PY_tutorial.pdf\n",
    "1. http://www.shocksolution.com/2009/09/f2py-binding-fortran-python/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## C"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ctypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ctypes is a Python library for calling out to C code. It is not as automatic as `f2py`, and we manually need to load the library and set properties such as the functions return and argument types. On the other hand we do not need to touch the C code at all. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting functions.c\n"
     ]
    }
   ],
   "source": [
    "%%file functions.c\n",
    "\n",
    "#include <stdio.h>\n",
    "\n",
    "void hello(int n);\n",
    "\n",
    "double dprod(double *x, int n);\n",
    "\n",
    "void dcumsum(double *a, double *b, int n);\n",
    "\n",
    "void\n",
    "hello(int n)\n",
    "{\n",
    "    int i;\n",
    "    \n",
    "    for (i = 0; i < n; i++)\n",
    "    {\n",
    "        printf(\"C says hello\\n\");\n",
    "    }\n",
    "}\n",
    "\n",
    "\n",
    "double \n",
    "dprod(double *x, int n)\n",
    "{\n",
    "    int i;\n",
    "    double y = 1.0;\n",
    "    \n",
    "    for (i = 0; i < n; i++)\n",
    "    {\n",
    "        y *= x[i];\n",
    "    }\n",
    "\n",
    "    return y;\n",
    "}\n",
    "\n",
    "void\n",
    "dcumsum(double *a, double *b, int n)\n",
    "{\n",
    "    int i;\n",
    "    \n",
    "    b[0] = a[0];\n",
    "    for (i = 1; i < n; i++)\n",
    "    {\n",
    "        b[i] = a[i] + b[i-1];\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compile the C file into a shared library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "!gcc -c -Wall -O2 -Wall -ansi -pedantic -fPIC -o functions.o functions.c\n",
    "!gcc -o libfunctions.so -shared functions.o"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is a compiled shared library `libfunctions.so`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "libfunctions.so: ELF 64-bit LSB  shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=d68173ae6a804f703472af96f413b81a189db4b8, not stripped\r\n"
     ]
    }
   ],
   "source": [
    "!file libfunctions.so"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we need to write wrapper functions to access the C library: To load the library we use the ctypes package, which included in the Python standard library (with extensions from numpy for passing arrays to C). Then we manually set the types of the argument and return values (no automatic code inspection here!). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting functions.py\n"
     ]
    }
   ],
   "source": [
    "%%file functions.py\n",
    "\n",
    "import numpy\n",
    "import ctypes\n",
    "\n",
    "_libfunctions = numpy.ctypeslib.load_library('libfunctions', '.')\n",
    "\n",
    "_libfunctions.hello.argtypes = [ctypes.c_int]\n",
    "_libfunctions.hello.restype  =  ctypes.c_void_p\n",
    "\n",
    "_libfunctions.dprod.argtypes = [numpy.ctypeslib.ndpointer(dtype=numpy.float), ctypes.c_int]\n",
    "_libfunctions.dprod.restype  = ctypes.c_double\n",
    "\n",
    "_libfunctions.dcumsum.argtypes = [numpy.ctypeslib.ndpointer(dtype=numpy.float), numpy.ctypeslib.ndpointer(dtype=numpy.float), ctypes.c_int]\n",
    "_libfunctions.dcumsum.restype  = ctypes.c_void_p\n",
    "\n",
    "def hello(n):\n",
    "    return _libfunctions.hello(int(n))\n",
    "\n",
    "def dprod(x, n=None):\n",
    "    if n is None:\n",
    "        n = len(x)\n",
    "    x = numpy.asarray(x, dtype=numpy.float)\n",
    "    return _libfunctions.dprod(x, int(n))\n",
    "\n",
    "def dcumsum(a, n):\n",
    "    a = numpy.asarray(a, dtype=numpy.float)\n",
    "    b = numpy.empty(len(a), dtype=numpy.float)\n",
    "    _libfunctions.dcumsum(a, b, int(n))\n",
    "    return b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting run_hello_c.py\n"
     ]
    }
   ],
   "source": [
    "%%file run_hello_c.py\n",
    "\n",
    "import functions\n",
    "\n",
    "functions.hello(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C says hello\r\n",
      "C says hello\r\n",
      "C says hello\r\n"
     ]
    }
   ],
   "source": [
    "!python run_hello_c.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import functions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Product function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "120.0"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "functions.dprod([1,2,3,4,5]) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Cumulative sum:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = rand(100000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "res_c = functions.dcumsum(a, len(a)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "res_fortran = dcumsum.dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.,  0.,  0., ...,  0.,  0.,  0.])"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res_c - res_fortran"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Simple benchmark"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000 loops, best of 3: 286 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit functions.dcumsum(a, len(a))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10000 loops, best of 3: 119 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit dcumsum.dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000 loops, best of 3: 261 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit a.cumsum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Further reading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* http://docs.python.org/2/library/ctypes.html\n",
    "* http://www.scipy.org/Cookbook/Ctypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cython"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A hybrid between python and C that can be compiled: Basically Python code with type declarations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting cy_dcumsum.pyx\n"
     ]
    }
   ],
   "source": [
    "%%file cy_dcumsum.pyx\n",
    "\n",
    "cimport numpy\n",
    "\n",
    "def dcumsum(numpy.ndarray[numpy.float64_t, ndim=1] a, numpy.ndarray[numpy.float64_t, ndim=1] b):\n",
    "    cdef int i, n = len(a)\n",
    "    b[0] = a[0]\n",
    "    for i from 1 <= i < n:\n",
    "        b[i] = b[i-1] + a[i]\n",
    "    return b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A build file for generating C code and compiling it into a Python module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting setup.py\n"
     ]
    }
   ],
   "source": [
    "%%file setup.py\n",
    "\n",
    "from distutils.core import setup\n",
    "from distutils.extension import Extension\n",
    "from Cython.Distutils import build_ext\n",
    "\n",
    "setup(\n",
    "    cmdclass = {'build_ext': build_ext},\n",
    "    ext_modules = [Extension(\"cy_dcumsum\", [\"cy_dcumsum.pyx\"])]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "running build_ext\n",
      "cythoning cy_dcumsum.pyx to cy_dcumsum.c\n",
      "warning: /usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy.pxd:869:17: Non-trivial type declarators in shared declaration (e.g. mix of pointers and values). Each pointer declaration should be on its own line.\n",
      "warning: /usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy.pxd:869:24: Non-trivial type declarators in shared declaration (e.g. mix of pointers and values). Each pointer declaration should be on its own line.\n",
      "building 'cy_dcumsum' extension\n",
      "x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c cy_dcumsum.c -o build/temp.linux-x86_64-2.7/cy_dcumsum.o\n",
      "In file included from /usr/include/python2.7/numpy/ndarraytypes.h:1761:0,\n",
      "                 from /usr/include/python2.7/numpy/ndarrayobject.h:17,\n",
      "                 from /usr/include/python2.7/numpy/arrayobject.h:4,\n",
      "                 from cy_dcumsum.c:352:\n",
      "/usr/include/python2.7/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning \"Using deprecated NumPy API, disable it by \" \"#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n",
      " #warning \"Using deprecated NumPy API, disable it by \" \\\n",
      "  ^\n",
      "In file included from /usr/include/python2.7/numpy/ndarrayobject.h:26:0,\n",
      "                 from /usr/include/python2.7/numpy/arrayobject.h:4,\n",
      "                 from cy_dcumsum.c:352:\n",
      "/usr/include/python2.7/numpy/__multiarray_api.h:1629:1: warning: ‘_import_array’ defined but not used [-Wunused-function]\n",
      " _import_array(void)\n",
      " ^\n",
      "In file included from /usr/include/python2.7/numpy/ufuncobject.h:327:0,\n",
      "                 from cy_dcumsum.c:353:\n",
      "/usr/include/python2.7/numpy/__ufunc_api.h:241:1: warning: ‘_import_umath’ defined but not used [-Wunused-function]\n",
      " _import_umath(void)\n",
      " ^\n",
      "x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/cy_dcumsum.o -o /home/rob/Desktop/scientific-python-lectures/cy_dcumsum.so\n"
     ]
    }
   ],
   "source": [
    "!python setup.py build_ext --inplace"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import cy_dcumsum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1.,   3.,   6.,  10.])"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = array([1,2,3,4], dtype=float)\n",
    "b = empty_like(a)\n",
    "cy_dcumsum.dcumsum(a,b)\n",
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1.,   3.,   6.,  10.,  15.,  21.,  28.,  36.])"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = empty_like(a)\n",
    "cy_dcumsum.dcumsum(a, b)\n",
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1.,   3.,   6.,  10.,  15.,  21.,  28.,  36.])"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "py_dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a = rand(100000)\n",
    "b = empty_like(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 loops, best of 3: 50.1 ms per loop\n"
     ]
    }
   ],
   "source": [
    "timeit py_dcumsum(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000 loops, best of 3: 263 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit cy_dcumsum.dcumsum(a,b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Cython in the IPython notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When working with the IPython (especially in the notebook), there is a more convenient way of compiling and loading Cython code. Using the `%%cython` IPython magic (command to IPython), we can simply type the Cython code in a code cell and let IPython take care of the conversion to C code, compilation and loading of the function. To be able to use the `%%cython` magic, we first need to load the extension `cythonmagic`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%load_ext cythonmagic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%%cython\n",
    "\n",
    "cimport numpy\n",
    "\n",
    "def cy_dcumsum2(numpy.ndarray[numpy.float64_t, ndim=1] a, numpy.ndarray[numpy.float64_t, ndim=1] b):\n",
    "    cdef int i, n = len(a)\n",
    "    b[0] = a[0]\n",
    "    for i from 1 <= i < n:\n",
    "        b[i] = b[i-1] + a[i]\n",
    "    return b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000 loops, best of 3: 265 µs per loop\n"
     ]
    }
   ],
   "source": [
    "timeit cy_dcumsum2(a,b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Further reading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* http://cython.org\n",
    "* http://docs.cython.org/src/userguide/tutorial.html\n",
    "* http://wiki.cython.org/tutorials/numpy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Versions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "application/json": {
       "Software versions": [
        {
         "module": "Python",
         "version": "2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2]"
        },
        {
         "module": "IPython",
         "version": "1.1.0"
        },
        {
         "module": "OS",
         "version": "posix [linux2]"
        },
        {
         "module": "ctypes",
         "version": "1.1.0"
        },
        {
         "module": "Cython",
         "version": "0.20.2"
        }
       ]
      },
      "text/html": [
       "<table><tr><th>Software</th><th>Version</th></tr><tr><td>Python</td><td>2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2]</td></tr><tr><td>IPython</td><td>1.1.0</td></tr><tr><td>OS</td><td>posix [linux2]</td></tr><tr><td>ctypes</td><td>1.1.0</td></tr><tr><td>Cython</td><td>0.20.2</td></tr><tr><td colspan='2'>Tue Aug 26 23:37:29 2014 JST</td></tr></table>"
      ],
      "text/latex": [
       "\\begin{table}\n",
       "\\begin{tabular}{|l|l|}\\hline\n",
       "{\\bf Software} & {\\bf Version} \\\\ \\hline\\hline\n",
       "Python & 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] \\\\ \\hline\n",
       "IPython & 1.1.0 \\\\ \\hline\n",
       "OS & posix [linux2] \\\\ \\hline\n",
       "ctypes & 1.1.0 \\\\ \\hline\n",
       "Cython & 0.20.2 \\\\ \\hline\n",
       "\\hline \\multicolumn{2}{|l|}{Tue Aug 26 23:37:29 2014 JST} \\\\ \\hline\n",
       "\\end{tabular}\n",
       "\\end{table}\n"
      ],
      "text/plain": [
       "Software versions\n",
       "Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2]\n",
       "IPython 1.1.0\n",
       "OS posix [linux2]\n",
       "ctypes 1.1.0\n",
       "Cython 0.20.2\n",
       "\n",
       "Tue Aug 26 23:37:29 2014 JST"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%reload_ext version_information\n",
    "\n",
    "%version_information ctypes, Cython"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
