{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "from matplotlib import pyplot, cm\n",
    "from pystencils.session import *\n",
    "from pystencils.boundaries import add_neumann_boundary, Neumann, Dirichlet, BoundaryHandling\n",
    "from pystencils.slicing import slice_from_direction\n",
    "import math\n",
    "import time\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Test to see if pycuda is installed which is needed to run calculations on the GPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    import pycuda\n",
    "except ImportError:\n",
    "    pycuda = None\n",
    "    print('No pycuda installed')\n",
    "    \n",
    "if pycuda:\n",
    "    import pycuda.gpuarray as gpuarray"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial 06: Datahandling"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is a tutorial about the `DataHandling` class of pystencils. This class is an abstraction layer to\n",
    "- link numpy arrays to pystencils fields\n",
    "- handle CPU-GPU array transfer, such that one can write code that works on CPU and GPU\n",
    "- makes it possible to write MPI parallel simulations to run on distributed-memory clusters using the waLBerla library\n",
    "\n",
    "We will look at a small and easy example to demonstrate the usage of `DataHandling` objects. We will define an averaging kernel to every cell of an array, that writes the average of the neighbor cell values to the center."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Manual \n",
    "\n",
    "### 1.1. CPU kernels\n",
    "\n",
    "In this first part, we set up a scenario manually without a `DataHandling`. In the next sections we then repeat the same setup with the help of the data handling. \n",
    "\n",
    "One concept of *pystencils* that may be confusing at first, is the differences between pystencils fields and numpy arrays. Fields are used to describe the computation *symbolically* with sympy, while numpy arrays hold the actual values where the computation is executed on. \n",
    "\n",
    "One option to create and execute a *pystencils* kernel is listed below. For reason that become clear later we call this the **variable-field-size workflow**:\n",
    "\n",
    "1. define pystencils fields\n",
    "2. use sympy and the pystencils fields to define an update rule, that describes what should be done on *every cell* \n",
    "3. compile the update rule to a real function, that can be called from Python. For each field that was referenced in the symbolic description the function expects a numpy array, passed as named parameter\n",
    "4. create some numpy arrays with actual data \n",
    "5. call the kernel - usually many times\n",
    "\n",
    "Now, lets see how this actually looks in Python code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. field definitions\n",
    "src_field, dst_field = ps.fields(\"src, dst:[2D]\")\n",
    "\n",
    "# 2. define update rule\n",
    "update_rule = [ps.Assignment(lhs=dst_field[0, 0],\n",
    "                             rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)]\n",
    "\n",
    "# 3. compile update rule to function\n",
    "kernel_function = ps.create_kernel(update_rule).compile()\n",
    "\n",
    "# 4. create numpy arrays and call kernel\n",
    "src_arr, dst_arr = np.random.rand(30, 30), np.zeros([30, 30])\n",
    "\n",
    "# 5. call kernel\n",
    "kernel_function(src=src_arr, dst=dst_arr)  # names of arguments have to match names passed to ps.fields()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This workflow separates the symbolic and the numeric stages very cleanly. The separation also makes it possible to stop after step 3, write the C-code to a file and call the kernel from a C program. Speaking of the C-Code - lets have a look at the generated sources:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>.highlight .hll { background-color: #ffffcc }\n",
       ".highlight  { background: #f8f8f8; }\n",
       ".highlight .c { color: #408080; font-style: italic } /* Comment */\n",
       ".highlight .err { border: 1px solid #FF0000 } /* Error */\n",
       ".highlight .k { color: #008000; font-weight: bold } /* Keyword */\n",
       ".highlight .o { color: #666666 } /* Operator */\n",
       ".highlight .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
       ".highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
       ".highlight .cp { color: #BC7A00 } /* Comment.Preproc */\n",
       ".highlight .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
       ".highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
       ".highlight .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
       ".highlight .gd { color: #A00000 } /* Generic.Deleted */\n",
       ".highlight .ge { font-style: italic } /* Generic.Emph */\n",
       ".highlight .gr { color: #FF0000 } /* Generic.Error */\n",
       ".highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
       ".highlight .gi { color: #00A000 } /* Generic.Inserted */\n",
       ".highlight .go { color: #888888 } /* Generic.Output */\n",
       ".highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
       ".highlight .gs { font-weight: bold } /* Generic.Strong */\n",
       ".highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
       ".highlight .gt { color: #0044DD } /* Generic.Traceback */\n",
       ".highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
       ".highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
       ".highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
       ".highlight .kp { color: #008000 } /* Keyword.Pseudo */\n",
       ".highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
       ".highlight .kt { color: #B00040 } /* Keyword.Type */\n",
       ".highlight .m { color: #666666 } /* Literal.Number */\n",
       ".highlight .s { color: #BA2121 } /* Literal.String */\n",
       ".highlight .na { color: #7D9029 } /* Name.Attribute */\n",
       ".highlight .nb { color: #008000 } /* Name.Builtin */\n",
       ".highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
       ".highlight .no { color: #880000 } /* Name.Constant */\n",
       ".highlight .nd { color: #AA22FF } /* Name.Decorator */\n",
       ".highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
       ".highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
       ".highlight .nf { color: #0000FF } /* Name.Function */\n",
       ".highlight .nl { color: #A0A000 } /* Name.Label */\n",
       ".highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
       ".highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
       ".highlight .nv { color: #19177C } /* Name.Variable */\n",
       ".highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
       ".highlight .w { color: #bbbbbb } /* Text.Whitespace */\n",
       ".highlight .mb { color: #666666 } /* Literal.Number.Bin */\n",
       ".highlight .mf { color: #666666 } /* Literal.Number.Float */\n",
       ".highlight .mh { color: #666666 } /* Literal.Number.Hex */\n",
       ".highlight .mi { color: #666666 } /* Literal.Number.Integer */\n",
       ".highlight .mo { color: #666666 } /* Literal.Number.Oct */\n",
       ".highlight .sa { color: #BA2121 } /* Literal.String.Affix */\n",
       ".highlight .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
       ".highlight .sc { color: #BA2121 } /* Literal.String.Char */\n",
       ".highlight .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
       ".highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
       ".highlight .s2 { color: #BA2121 } /* Literal.String.Double */\n",
       ".highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
       ".highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
       ".highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
       ".highlight .sx { color: #008000 } /* Literal.String.Other */\n",
       ".highlight .sr { color: #BB6688 } /* Literal.String.Regex */\n",
       ".highlight .s1 { color: #BA2121 } /* Literal.String.Single */\n",
       ".highlight .ss { color: #19177C } /* Literal.String.Symbol */\n",
       ".highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
       ".highlight .fm { color: #0000FF } /* Name.Function.Magic */\n",
       ".highlight .vc { color: #19177C } /* Name.Variable.Class */\n",
       ".highlight .vg { color: #19177C } /* Name.Variable.Global */\n",
       ".highlight .vi { color: #19177C } /* Name.Variable.Instance */\n",
       ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
       ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */</style>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div class=\"highlight\"><pre><span></span><span class=\"n\">FUNC_PREFIX</span> <span class=\"kt\">void</span> <span class=\"nf\">kernel</span><span class=\"p\">(</span><span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">_data_dst</span><span class=\"p\">,</span> <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src</span><span class=\"p\">,</span> <span class=\"kt\">int64_t</span> <span class=\"k\">const</span> <span class=\"n\">_size_dst_0</span><span class=\"p\">,</span> <span class=\"kt\">int64_t</span> <span class=\"k\">const</span> <span class=\"n\">_size_dst_1</span><span class=\"p\">,</span> <span class=\"kt\">int64_t</span> <span class=\"k\">const</span> <span class=\"n\">_stride_dst_0</span><span class=\"p\">,</span> <span class=\"kt\">int64_t</span> <span class=\"k\">const</span> <span class=\"n\">_stride_dst_1</span><span class=\"p\">,</span> <span class=\"kt\">int64_t</span> <span class=\"k\">const</span> <span class=\"n\">_stride_src_0</span><span class=\"p\">,</span> <span class=\"kt\">int64_t</span> <span class=\"k\">const</span> <span class=\"n\">_stride_src_1</span><span class=\"p\">)</span>\n",
       "<span class=\"p\">{</span>\n",
       "   <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int</span> <span class=\"n\">ctr_0</span> <span class=\"o\">=</span> <span class=\"mi\">1</span><span class=\"p\">;</span> <span class=\"n\">ctr_0</span> <span class=\"o\">&lt;</span> <span class=\"n\">_size_dst_0</span> <span class=\"o\">-</span> <span class=\"mi\">1</span><span class=\"p\">;</span> <span class=\"n\">ctr_0</span> <span class=\"o\">+=</span> <span class=\"mi\">1</span><span class=\"p\">)</span>\n",
       "   <span class=\"p\">{</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">_data_dst_00</span> <span class=\"o\">=</span> <span class=\"n\">_data_dst</span> <span class=\"o\">+</span> <span class=\"n\">_stride_dst_0</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span><span class=\"p\">;</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src_01</span> <span class=\"o\">=</span> <span class=\"n\">_data_src</span> <span class=\"o\">+</span> <span class=\"n\">_stride_src_0</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span> <span class=\"o\">+</span> <span class=\"n\">_stride_src_0</span><span class=\"p\">;</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src_00</span> <span class=\"o\">=</span> <span class=\"n\">_data_src</span> <span class=\"o\">+</span> <span class=\"n\">_stride_src_0</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span><span class=\"p\">;</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src_0m1</span> <span class=\"o\">=</span> <span class=\"n\">_data_src</span> <span class=\"o\">+</span> <span class=\"n\">_stride_src_0</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span> <span class=\"o\">-</span> <span class=\"n\">_stride_src_0</span><span class=\"p\">;</span>\n",
       "      <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int</span> <span class=\"n\">ctr_1</span> <span class=\"o\">=</span> <span class=\"mi\">1</span><span class=\"p\">;</span> <span class=\"n\">ctr_1</span> <span class=\"o\">&lt;</span> <span class=\"n\">_size_dst_1</span> <span class=\"o\">-</span> <span class=\"mi\">1</span><span class=\"p\">;</span> <span class=\"n\">ctr_1</span> <span class=\"o\">+=</span> <span class=\"mi\">1</span><span class=\"p\">)</span>\n",
       "      <span class=\"p\">{</span>\n",
       "         <span class=\"n\">_data_dst_00</span><span class=\"p\">[</span><span class=\"n\">_stride_dst_1</span><span class=\"o\">*</span><span class=\"n\">ctr_1</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_00</span><span class=\"p\">[</span><span class=\"n\">_stride_src_1</span><span class=\"o\">*</span><span class=\"n\">ctr_1</span> <span class=\"o\">+</span> <span class=\"n\">_stride_src_1</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_00</span><span class=\"p\">[</span><span class=\"n\">_stride_src_1</span><span class=\"o\">*</span><span class=\"n\">ctr_1</span> <span class=\"o\">-</span> <span class=\"n\">_stride_src_1</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_01</span><span class=\"p\">[</span><span class=\"n\">_stride_src_1</span><span class=\"o\">*</span><span class=\"n\">ctr_1</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_0m1</span><span class=\"p\">[</span><span class=\"n\">_stride_src_1</span><span class=\"o\">*</span><span class=\"n\">ctr_1</span><span class=\"p\">];</span>\n",
       "      <span class=\"p\">}</span>\n",
       "   <span class=\"p\">}</span>\n",
       "<span class=\"p\">}</span>\n",
       "</pre></div>\n"
      ],
      "text/plain": [
       "FUNC_PREFIX void kernel(double * _data_dst, double * const _data_src, int64_t const _size_dst_0, int64_t const _size_dst_1, int64_t const _stride_dst_0, int64_t const _stride_dst_1, int64_t const _stride_src_0, int64_t const _stride_src_1)\n",
       "{\n",
       "   for (int ctr_0 = 1; ctr_0 < _size_dst_0 - 1; ctr_0 += 1)\n",
       "   {\n",
       "      double * _data_dst_00 = _data_dst + _stride_dst_0*ctr_0;\n",
       "      double * const _data_src_01 = _data_src + _stride_src_0*ctr_0 + _stride_src_0;\n",
       "      double * const _data_src_00 = _data_src + _stride_src_0*ctr_0;\n",
       "      double * const _data_src_0m1 = _data_src + _stride_src_0*ctr_0 - _stride_src_0;\n",
       "      for (int ctr_1 = 1; ctr_1 < _size_dst_1 - 1; ctr_1 += 1)\n",
       "      {\n",
       "         _data_dst_00[_stride_dst_1*ctr_1] = 0.25*_data_src_00[_stride_src_1*ctr_1 + _stride_src_1] + 0.25*_data_src_00[_stride_src_1*ctr_1 - _stride_src_1] + 0.25*_data_src_01[_stride_src_1*ctr_1] + 0.25*_data_src_0m1[_stride_src_1*ctr_1];\n",
       "      }\n",
       "   }\n",
       "}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ps.show_code(kernel_function.ast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Even if it looks very ugly and low-level :) lets look at this code in a bit more detail. The code is generated in a way that is works for different array sizes. The size of the array is passed in the `_size_dst_` variables that specifiy the shape of the array for each dimension. Also, the memory layout (linearization) of the array can be different. That means the array could be stored in row-major or column-major order - if we pass in the array strides correctly the kernel does the right thing. If you're not familiar with the concept of strides check out [this stackoverflow post](https://stackoverflow.com/questions/53097952/how-to-understand-numpy-strides-for-layman) or search in the numpy documentation for strides - C vs Fortran order.\n",
    "\n",
    "The goal of *pystencils* is to produce the fastest possible code. On technique to do this is to use all available information already on compile time and generate code that is highly adapted to the specific problem. In our case we already know the shape and strides of the arrays we want to apply the kernel on, so we can make use of this information. This idea leads to the **fixed-field-size workflow**. The main difference there is that we define the arrays first and therefore let *pystencils* know about the array shapes and strides, so that is can generate more specific code:\n",
    "\n",
    "1. create numpy arrays that hold your data\n",
    "2. define pystencils fields, this time telling pystencils already which arrays they correspond to, so that it knows about the size and strides\n",
    "\n",
    "in the other steps nothing has changed\n",
    "\n",
    "3. define the update rule \n",
    "4. compile update rule to kernel\n",
    "5. run the kernel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. create arrays first\n",
    "src_arr, dst_arr = np.random.rand(30, 30), np.zeros([30, 30])\n",
    "\n",
    "# 2. define symbolic fields - note the additional parameter that link an array to each field\n",
    "src_field, dst_field = ps.fields(\"src, dst:[2D]\", src=src_arr, dst=dst_arr)\n",
    "\n",
    "# 3. define update rule\n",
    "update_rule = [ps.Assignment(lhs=dst_field[0, 0],\n",
    "                             rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)]\n",
    "\n",
    "# 4. compile it\n",
    "kernel_function = ps.create_kernel(update_rule).compile()\n",
    "\n",
    "# 5. call kernel\n",
    "kernel_function(src=src_arr, dst=dst_arr)  # names of arguments have to match names passed to ps.fields()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Functionally, both variants are equivalent. We see the difference only when we look at the generated code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>.highlight .hll { background-color: #ffffcc }\n",
       ".highlight  { background: #f8f8f8; }\n",
       ".highlight .c { color: #408080; font-style: italic } /* Comment */\n",
       ".highlight .err { border: 1px solid #FF0000 } /* Error */\n",
       ".highlight .k { color: #008000; font-weight: bold } /* Keyword */\n",
       ".highlight .o { color: #666666 } /* Operator */\n",
       ".highlight .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
       ".highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
       ".highlight .cp { color: #BC7A00 } /* Comment.Preproc */\n",
       ".highlight .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
       ".highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
       ".highlight .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
       ".highlight .gd { color: #A00000 } /* Generic.Deleted */\n",
       ".highlight .ge { font-style: italic } /* Generic.Emph */\n",
       ".highlight .gr { color: #FF0000 } /* Generic.Error */\n",
       ".highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
       ".highlight .gi { color: #00A000 } /* Generic.Inserted */\n",
       ".highlight .go { color: #888888 } /* Generic.Output */\n",
       ".highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
       ".highlight .gs { font-weight: bold } /* Generic.Strong */\n",
       ".highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
       ".highlight .gt { color: #0044DD } /* Generic.Traceback */\n",
       ".highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
       ".highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
       ".highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
       ".highlight .kp { color: #008000 } /* Keyword.Pseudo */\n",
       ".highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
       ".highlight .kt { color: #B00040 } /* Keyword.Type */\n",
       ".highlight .m { color: #666666 } /* Literal.Number */\n",
       ".highlight .s { color: #BA2121 } /* Literal.String */\n",
       ".highlight .na { color: #7D9029 } /* Name.Attribute */\n",
       ".highlight .nb { color: #008000 } /* Name.Builtin */\n",
       ".highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
       ".highlight .no { color: #880000 } /* Name.Constant */\n",
       ".highlight .nd { color: #AA22FF } /* Name.Decorator */\n",
       ".highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
       ".highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
       ".highlight .nf { color: #0000FF } /* Name.Function */\n",
       ".highlight .nl { color: #A0A000 } /* Name.Label */\n",
       ".highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
       ".highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
       ".highlight .nv { color: #19177C } /* Name.Variable */\n",
       ".highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
       ".highlight .w { color: #bbbbbb } /* Text.Whitespace */\n",
       ".highlight .mb { color: #666666 } /* Literal.Number.Bin */\n",
       ".highlight .mf { color: #666666 } /* Literal.Number.Float */\n",
       ".highlight .mh { color: #666666 } /* Literal.Number.Hex */\n",
       ".highlight .mi { color: #666666 } /* Literal.Number.Integer */\n",
       ".highlight .mo { color: #666666 } /* Literal.Number.Oct */\n",
       ".highlight .sa { color: #BA2121 } /* Literal.String.Affix */\n",
       ".highlight .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
       ".highlight .sc { color: #BA2121 } /* Literal.String.Char */\n",
       ".highlight .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
       ".highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
       ".highlight .s2 { color: #BA2121 } /* Literal.String.Double */\n",
       ".highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
       ".highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
       ".highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
       ".highlight .sx { color: #008000 } /* Literal.String.Other */\n",
       ".highlight .sr { color: #BB6688 } /* Literal.String.Regex */\n",
       ".highlight .s1 { color: #BA2121 } /* Literal.String.Single */\n",
       ".highlight .ss { color: #19177C } /* Literal.String.Symbol */\n",
       ".highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
       ".highlight .fm { color: #0000FF } /* Name.Function.Magic */\n",
       ".highlight .vc { color: #19177C } /* Name.Variable.Class */\n",
       ".highlight .vg { color: #19177C } /* Name.Variable.Global */\n",
       ".highlight .vi { color: #19177C } /* Name.Variable.Instance */\n",
       ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
       ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */</style>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div class=\"highlight\"><pre><span></span><span class=\"n\">FUNC_PREFIX</span> <span class=\"kt\">void</span> <span class=\"nf\">kernel</span><span class=\"p\">(</span><span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">_data_dst</span><span class=\"p\">,</span> <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src</span><span class=\"p\">)</span>\n",
       "<span class=\"p\">{</span>\n",
       "   <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int</span> <span class=\"n\">ctr_0</span> <span class=\"o\">=</span> <span class=\"mi\">1</span><span class=\"p\">;</span> <span class=\"n\">ctr_0</span> <span class=\"o\">&lt;</span> <span class=\"mi\">29</span><span class=\"p\">;</span> <span class=\"n\">ctr_0</span> <span class=\"o\">+=</span> <span class=\"mi\">1</span><span class=\"p\">)</span>\n",
       "   <span class=\"p\">{</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">_data_dst_00</span> <span class=\"o\">=</span> <span class=\"n\">_data_dst</span> <span class=\"o\">+</span> <span class=\"mi\">30</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span><span class=\"p\">;</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src_01</span> <span class=\"o\">=</span> <span class=\"n\">_data_src</span> <span class=\"o\">+</span> <span class=\"mi\">30</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span> <span class=\"o\">+</span> <span class=\"mi\">30</span><span class=\"p\">;</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src_00</span> <span class=\"o\">=</span> <span class=\"n\">_data_src</span> <span class=\"o\">+</span> <span class=\"mi\">30</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span><span class=\"p\">;</span>\n",
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"k\">const</span> <span class=\"n\">_data_src_0m1</span> <span class=\"o\">=</span> <span class=\"n\">_data_src</span> <span class=\"o\">+</span> <span class=\"mi\">30</span><span class=\"o\">*</span><span class=\"n\">ctr_0</span> <span class=\"o\">-</span> <span class=\"mi\">30</span><span class=\"p\">;</span>\n",
       "      <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int</span> <span class=\"n\">ctr_1</span> <span class=\"o\">=</span> <span class=\"mi\">1</span><span class=\"p\">;</span> <span class=\"n\">ctr_1</span> <span class=\"o\">&lt;</span> <span class=\"mi\">29</span><span class=\"p\">;</span> <span class=\"n\">ctr_1</span> <span class=\"o\">+=</span> <span class=\"mi\">1</span><span class=\"p\">)</span>\n",
       "      <span class=\"p\">{</span>\n",
       "         <span class=\"n\">_data_dst_00</span><span class=\"p\">[</span><span class=\"n\">ctr_1</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_00</span><span class=\"p\">[</span><span class=\"n\">ctr_1</span> <span class=\"o\">+</span> <span class=\"mi\">1</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_00</span><span class=\"p\">[</span><span class=\"n\">ctr_1</span> <span class=\"o\">-</span> <span class=\"mi\">1</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_01</span><span class=\"p\">[</span><span class=\"n\">ctr_1</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"mf\">0.25</span><span class=\"o\">*</span><span class=\"n\">_data_src_0m1</span><span class=\"p\">[</span><span class=\"n\">ctr_1</span><span class=\"p\">];</span>\n",
       "      <span class=\"p\">}</span>\n",
       "   <span class=\"p\">}</span>\n",
       "<span class=\"p\">}</span>\n",
       "</pre></div>\n"
      ],
      "text/plain": [
       "FUNC_PREFIX void kernel(double * _data_dst, double * const _data_src)\n",
       "{\n",
       "   for (int ctr_0 = 1; ctr_0 < 29; ctr_0 += 1)\n",
       "   {\n",
       "      double * _data_dst_00 = _data_dst + 30*ctr_0;\n",
       "      double * const _data_src_01 = _data_src + 30*ctr_0 + 30;\n",
       "      double * const _data_src_00 = _data_src + 30*ctr_0;\n",
       "      double * const _data_src_0m1 = _data_src + 30*ctr_0 - 30;\n",
       "      for (int ctr_1 = 1; ctr_1 < 29; ctr_1 += 1)\n",
       "      {\n",
       "         _data_dst_00[ctr_1] = 0.25*_data_src_00[ctr_1 + 1] + 0.25*_data_src_00[ctr_1 - 1] + 0.25*_data_src_01[ctr_1] + 0.25*_data_src_0m1[ctr_1];\n",
       "      }\n",
       "   }\n",
       "}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ps.show_code(kernel_function.ast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare this to the code above! It looks much simpler. The reason is that all index computations are already simplified since the exact field sizes and strides are known. This kernel now only works on arrays of the previously specified size. \n",
    "\n",
    "Lets try what happens if we try to use a different array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wrong shape of array dst. Expected (30, 30)\n"
     ]
    }
   ],
   "source": [
    "src_arr2, dst_arr2 = np.random.rand(40, 40), np.zeros([40, 40])\n",
    "try:\n",
    "    kernel_function(src=src_arr2, dst=dst_arr2)\n",
    "except ValueError as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2. GPU simulations\n",
    "\n",
    "Let's now jump to a seemingly unrelated topic: running kernels on the GPU. \n",
    "To run on GPU not many changes are required: When creating the kernel an additional parameter `target='gpu'` has to be passed. Also, the compiled kernel cannot be called with numpy arrays, but has to be called with `pycuda.gpuarray`s instead. That means, we have to transfer our numpy array to GPU first. From this step we obtain a gpuarray, then we can run the kernel, hopefully multiple times so that the data transfer was worth the time. Finally we transfer the finished result back to CPU. In code this looks like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "if pycuda:\n",
    "    kernel_function_gpu = ps.create_kernel(update_rule, target='gpu').compile()\n",
    "    # transfer to GPU\n",
    "    src_arr_gpu = pycuda.gpuarray.to_gpu(src_arr)\n",
    "    dst_arr_gpu = pycuda.gpuarray.to_gpu(dst_arr)\n",
    "    \n",
    "    # run kernel on GPU, this is done many times in real setups\n",
    "    kernel_function_gpu(src=src_arr_gpu, dst=dst_arr_gpu)\n",
    "    \n",
    "    # transfer result back to CPU\n",
    "    dst_arr_gpu.get(dst_arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  1.3. Summary: manual way\n",
    "\n",
    "- Don't confuse *pystencils* fields and *numpy* arrays\n",
    "    - fields are symbolic\n",
    "    - arrays are numeric\n",
    "- Use the fixed-field-size workflow whenever possible, since code might be faster. Create arrays first, then create fields from arrays\n",
    "- if we run GPU kernels, arrays have to transferred to the GPU first\n",
    "\n",
    "As demonstrated in the examples above we have to define 2 or 3 corresponding objects for each grid:\n",
    "\n",
    "- symbolic pystencils field\n",
    "- numpy array on CPU \n",
    "- for GPU run also a pycuda.gpuarray to mirror the data on the GPU\n",
    "\n",
    "Managing these three objects manually is tedious and error-prone. We'll see in the next section how the data handling object takes care of this problem."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Introducing the data handling - serial version\n",
    "\n",
    "### 2.1. Example for CPU simulations\n",
    "\n",
    "The data handling internally keeps a mapping between symbolic fields and numpy arrays. When we create a field, automatically a corresponding array is allocated as well. Optionally we can also allocate memory on the GPU for the array as well. Lets dive right in and see how our example looks like, when implemented with a data handling."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "dh = ps.create_data_handling(domain_size=(30, 30))\n",
    "\n",
    "# fields are now created using the data handling\n",
    "src_field = dh.add_array('src', values_per_cell=1)\n",
    "dst_field = dh.add_array('dst', values_per_cell=1)\n",
    "\n",
    "# kernel is created just like before\n",
    "update_rule = [ps.Assignment(lhs=dst_field[0, 0],\n",
    "                             rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)]\n",
    "kernel_function = ps.create_kernel(update_rule).compile()\n",
    "\n",
    "# have a look at the generated code - it uses \n",
    "# the fast version where array sizes are compiled-in\n",
    "#  ps.show_code(kernel_function.ast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data handling has methods to create fields - but where are the corresponding arrays? \n",
    "In the serial case you can access them as a member of the data handling, for example to initialize our 'src' array we can write"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "src_arr = dh.cpu_arrays['src']\n",
    "src_arr.fill(0.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This method is nice and easy, but you should not use it if you want your simulation to run on distributed-memory clusters. We'll see why in the next section about distributed memory parallelization. So it is good habit to not access the arrays directly but use the data handling to do so. We can, for example, initialize the array also with the following code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "dh.fill('src', 0.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To run the kernels with the same code as before, we would also need the arrays. We could do that accessing the `cpu_arrays`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "kernel_function(src=dh.cpu_arrays['src'],\n",
    "                dst=dh.cpu_arrays['dst'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "but to be prepared for MPI parallel simulations, again a method of the data handling should be used for this. \n",
    "Besides, this method is also simpler to use - since it automatically detects which arrays a kernel uses and passes them in."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "dh.run_kernel(kernel_function)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2. Example for GPU simulations\n",
    "\n",
    "In this section we have a look at GPU simulations using the data handling. Only minimal changes are required.\n",
    "When creating the data handling we can pass a 'default_target'. This means for every added field an array on the CPU and the GPU is allocated. This is a useful default, for more fine-grained control the `add_array` method also takes additional parameters controlling where the array should be allocated.\n",
    "\n",
    "Additionally we also need to compile a GPU version of the kernel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "dh = ps.create_data_handling(domain_size=(30, 30), default_target='gpu')\n",
    "\n",
    "# fields are now created using the data handling\n",
    "src_field = dh.add_array('src', values_per_cell=1)\n",
    "dst_field = dh.add_array('dst', values_per_cell=1)\n",
    "\n",
    "# kernel is created just like before\n",
    "update_rule = [ps.Assignment(lhs=dst_field[0, 0],\n",
    "                             rhs=(src_field[1, 0] + src_field[-1, 0] + src_field[0, 1] + src_field[0, -1]) / 4)]\n",
    "kernel_function = ps.create_kernel(update_rule, target=dh.default_target).compile()\n",
    "\n",
    "dh.fill('src', 0.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data handling provides function to transfer data between CPU and GPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "dh.to_gpu('src')\n",
    "dh.run_kernel(kernel_function)\n",
    "dh.to_cpu('dst')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "usually one wants to transfer all fields that have been allocated on CPU and GPU at the same time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "dh.all_to_gpu()\n",
    "dh.run_kernel(kernel_function)\n",
    "dh.all_to_cpu()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can always include the `all_to_*` functions in our code, since they do nothing if there are no arrays allocated on the GPU. Thus there is only a single point in the code where we can switch between CPU and GPU version: the `default_target` of the data handling. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 Ghost Layers and periodicity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Going (MPI) parallel - the parallel data handling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(-1, -1)\n"
     ]
    }
   ],
   "source": [
    "dh = ps.create_data_handling(domain_size=(30, 30), parallel=True)\n",
    "field = dh.add_array('field')\n",
    "for block in dh.iterate():\n",
    "    print(block.offset) # offset is in global coordinates, where first inner cell has coordiante (0,0) and ghost layers have negative coordinates\n",
    "    \n",
    "    # use offset to create a local array 'my_data' for the part of the domain\n",
    "    #np.copyto(block[field.name], my_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "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.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}