03_tutorial_datahandling.ipynb 59.7 KB
Newer Older
1
2
3
4
5
6
7
8
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
Jan Hönig's avatar
Jan Hönig committed
9
    "import psutil\n",
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    "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": [
47
    "# Tutorial 03: Datahandling"
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
   ]
  },
  {
   "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",
Martin Bauer's avatar
Martin Bauer committed
74
    "One option to create and execute a *pystencils* kernel is listed below. For reasons that become clear later we call this the **variable-field-size workflow**:\n",
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    "\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",
Martin Bauer's avatar
Martin Bauer committed
96
97
    "                             rhs=(src_field[1, 0] + src_field[-1, 0] + \n",
    "                                  src_field[0, 1] + src_field[0, -1]) / 4)]\n",
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    "\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": [
Jan Hönig's avatar
Jan Hönig committed
124
125
126
127
128
129
130
       "<style>pre { line-height: 125%; }\n",
       "td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\n",
       "span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\n",
       "td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n",
       "span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n",
       ".highlight .hll { background-color: #ffffcc }\n",
       ".highlight { background: #f8f8f8; }\n",
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
       ".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": [
Jan Hönig's avatar
Jan Hönig committed
209
       "<div class=\"highlight\"><pre><span></span><span class=\"n\">FUNC_PREFIX</span> <span class=\"kt\">void</span> <span class=\"n\">kernel</span><span class=\"p\">(</span><span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">RESTRICT</span> <span class=\"n\">_data_dst</span><span class=\"p\">,</span> <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">RESTRICT</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",
210
       "<span class=\"p\">{</span>\n",
Jan Hönig's avatar
Jan Hönig committed
211
       "   <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int64_t</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",
212
       "   <span class=\"p\">{</span>\n",
Markus Holzer's avatar
Markus Holzer committed
213
214
215
216
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">RESTRICT</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=\"n\">RESTRICT</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=\"n\">RESTRICT</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=\"n\">RESTRICT</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",
Jan Hönig's avatar
Jan Hönig committed
217
       "      <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int64_t</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",
218
219
220
221
222
223
224
225
       "      <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": [
Markus Holzer's avatar
Markus Holzer committed
226
       "FUNC_PREFIX void kernel(double * RESTRICT _data_dst, double * RESTRICT 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",
227
       "{\n",
Jan Hönig's avatar
Jan Hönig committed
228
       "   for (int64_t ctr_0 = 1; ctr_0 < _size_dst_0 - 1; ctr_0 += 1)\n",
229
       "   {\n",
Markus Holzer's avatar
Markus Holzer committed
230
231
232
233
       "      double * RESTRICT _data_dst_00 = _data_dst + _stride_dst_0*ctr_0;\n",
       "      double * RESTRICT _data_src_01 = _data_src + _stride_src_0*ctr_0 + _stride_src_0;\n",
       "      double * RESTRICT _data_src_00 = _data_src + _stride_src_0*ctr_0;\n",
       "      double * RESTRICT _data_src_0m1 = _data_src + _stride_src_0*ctr_0 - _stride_src_0;\n",
Jan Hönig's avatar
Jan Hönig committed
234
       "      for (int64_t ctr_1 = 1; ctr_1 < _size_dst_1 - 1; ctr_1 += 1)\n",
235
236
237
238
239
240
241
242
       "      {\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",
       "}"
      ]
     },
     "metadata": {},
Markus Holzer's avatar
Markus Holzer committed
243
     "output_type": "display_data"
244
245
246
247
248
249
250
251
252
253
    }
   ],
   "source": [
    "ps.show_code(kernel_function.ast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Martin Bauer's avatar
Martin Bauer committed
254
    "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 it 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",
255
    "\n",
Martin Bauer's avatar
Martin Bauer committed
256
    "The goal of *pystencils* is to produce the fastest possible code. One 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 to, 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 it can generate more specific code:\n",
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    "\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",
Martin Bauer's avatar
Martin Bauer committed
282
283
    "                             rhs=(src_field[1, 0] + src_field[-1, 0] + \n",
    "                                  src_field[0, 1] + src_field[0, -1]) / 4)]\n",
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
    "\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": [
Jan Hönig's avatar
Jan Hönig committed
307
308
309
310
311
312
313
       "<style>pre { line-height: 125%; }\n",
       "td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\n",
       "span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\n",
       "td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n",
       "span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n",
       ".highlight .hll { background-color: #ffffcc }\n",
       ".highlight { background: #f8f8f8; }\n",
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
       ".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": [
Jan Hönig's avatar
Jan Hönig committed
392
       "<div class=\"highlight\"><pre><span></span><span class=\"n\">FUNC_PREFIX</span> <span class=\"kt\">void</span> <span class=\"n\">kernel</span><span class=\"p\">(</span><span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">RESTRICT</span> <span class=\"n\">_data_dst</span><span class=\"p\">,</span> <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">RESTRICT</span> <span class=\"k\">const</span> <span class=\"n\">_data_src</span><span class=\"p\">)</span>\n",
393
       "<span class=\"p\">{</span>\n",
Jan Hönig's avatar
Jan Hönig committed
394
       "   <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int64_t</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",
395
       "   <span class=\"p\">{</span>\n",
Markus Holzer's avatar
Markus Holzer committed
396
397
398
399
       "      <span class=\"kt\">double</span> <span class=\"o\">*</span> <span class=\"n\">RESTRICT</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=\"n\">RESTRICT</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=\"n\">RESTRICT</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=\"n\">RESTRICT</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",
Jan Hönig's avatar
Jan Hönig committed
400
       "      <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"kt\">int64_t</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",
401
402
403
404
405
406
407
408
       "      <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": [
Markus Holzer's avatar
Markus Holzer committed
409
       "FUNC_PREFIX void kernel(double * RESTRICT _data_dst, double * RESTRICT const _data_src)\n",
410
       "{\n",
Jan Hönig's avatar
Jan Hönig committed
411
       "   for (int64_t ctr_0 = 1; ctr_0 < 29; ctr_0 += 1)\n",
412
       "   {\n",
Markus Holzer's avatar
Markus Holzer committed
413
414
415
416
       "      double * RESTRICT _data_dst_00 = _data_dst + 30*ctr_0;\n",
       "      double * RESTRICT _data_src_01 = _data_src + 30*ctr_0 + 30;\n",
       "      double * RESTRICT _data_src_00 = _data_src + 30*ctr_0;\n",
       "      double * RESTRICT _data_src_0m1 = _data_src + 30*ctr_0 - 30;\n",
Jan Hönig's avatar
Jan Hönig committed
417
       "      for (int64_t ctr_1 = 1; ctr_1 < 29; ctr_1 += 1)\n",
418
419
420
421
422
423
424
425
       "      {\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",
       "}"
      ]
     },
     "metadata": {},
Markus Holzer's avatar
Markus Holzer committed
426
     "output_type": "display_data"
427
428
429
430
431
432
433
434
435
436
437
438
    }
   ],
   "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",
Martin Bauer's avatar
Martin Bauer committed
439
    "Lets try what happens if we use a different array:"
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
   ]
  },
  {
   "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",
Jan Hönig's avatar
Jan Hönig committed
470
    "When creating the kernel, an additional parameter `target=ps.Target.GPU` has to be passed. Also, the compiled kernel cannot be called with numpy arrays directly, 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:"
471
472
473
474
475
476
477
478
479
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "if pycuda:\n",
Jan Hönig's avatar
Jan Hönig committed
480
481
    "    config = ps.CreateKernelConfig(target=ps.Target.GPU)\n",
    "    kernel_function_gpu = ps.create_kernel(update_rule, config=config).compile()\n",
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
    "    # 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": [
Martin Bauer's avatar
Martin Bauer committed
569
    "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 last section. 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:"
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
   ]
  },
  {
   "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)"
   ]
  },
Martin Bauer's avatar
Martin Bauer committed
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To access the data read-only instead of using `cpu_arrays` the gather function should be used.\n",
    "This function gives you a read-only copy of the domain or part of the domain. \n",
    "We will discuss this function later in more detail when we look at MPI parallel simulations.\n",
    "For serial simulations keep in mind that modifying the resulting array does not change your original data!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "read_only_copy = dh.gather_array('src', ps.make_slice[:, :], ghost_layers=False)"
   ]
  },
634
635
636
637
638
639
640
641
642
643
644
645
646
647
  {
   "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",
Martin Bauer's avatar
Martin Bauer committed
648
   "execution_count": 15,
649
650
651
   "metadata": {},
   "outputs": [],
   "source": [
Jan Hönig's avatar
Jan Hönig committed
652
    "dh = ps.create_data_handling(domain_size=(30, 30), default_target=ps.Target.GPU)\n",
653
654
655
656
657
658
659
660
    "\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",
Jan Hönig's avatar
Jan Hönig committed
661
662
    "config = ps.CreateKernelConfig(target=dh.default_target)\n",
    "kernel_function = ps.create_kernel(update_rule, config=config).compile()\n",
663
664
665
666
667
668
669
670
671
672
673
674
675
    "\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",
Martin Bauer's avatar
Martin Bauer committed
676
   "execution_count": 16,
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
   "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",
Martin Bauer's avatar
Martin Bauer committed
694
   "execution_count": 17,
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
   "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": [
Martin Bauer's avatar
Martin Bauer committed
714
715
716
    "### 2.2 Ghost Layers and periodicity\n",
    "\n",
    "The data handling can also provide periodic boundary conditions. Therefor the domain is extended by one layer of cells, the so-called ghost layer or halo layer."
717
718
719
720
   ]
  },
  {
   "cell_type": "code",
Martin Bauer's avatar
Martin Bauer committed
721
   "execution_count": 18,
722
   "metadata": {},
Martin Bauer's avatar
Martin Bauer committed
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Shape of domain          (30, 30)\n",
      "Direct access to arrays  (32, 32)\n",
      "Gather                   (32, 32)\n"
     ]
    }
   ],
   "source": [
    "print(\"Shape of domain         \", dh.shape)\n",
    "print(\"Direct access to arrays \", dh.cpu_arrays['src'].shape)\n",
    "print(\"Gather                  \", dh.gather_array('src', ghost_layers=True).shape)"
   ]
739
740
  },
  {
Martin Bauer's avatar
Martin Bauer committed
741
   "cell_type": "markdown",
742
   "metadata": {},
Martin Bauer's avatar
Martin Bauer committed
743
744
745
   "source": [
    " So the actual arrays are 2 cells larger than what you asked for. This additional layer is used to copy over the data from the other end of the array, such that for the stencil algorithm effectively the domain is periodic. This copying operation has to be started manually though:"
   ]
746
747
748
  },
  {
   "cell_type": "code",
Martin Bauer's avatar
Martin Bauer committed
749
   "execution_count": 19,
750
   "metadata": {},
Martin Bauer's avatar
Martin Bauer committed
751
752
753
   "outputs": [
    {
     "data": {
Jan Hönig's avatar
Jan Hönig committed
754
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAA5gAAAF1CAYAAACNjUXIAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQ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AAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwAiBCQAAwIhTBmZV3a2qPlhVH62qa6rqV87FYADA8dnNAGyqA0sc87Ukl3b3V6vq/CTvrar/1t3vX/FsAMDx2c0AbKRTBmZ3d5KvLj48f/HWqxwKADgxuxmATbXUazCr6ryqujrJzUmu6u4PrHQqAOCk7GYANtFSgdndt3X3JUkuTPKoqvq+Ox5TVZdX1eGqOnz06NHhMQGAY9nNAGyi07qLbHffkuRdSS47zs9d0d2HuvvQ3t7e0HgAwMnYzQBskmXuIrtXVfdevH/3JI9P8skVzwUAnIDdDMCmWuYusvdP8vKqOi/7Qfqa7n7TascCAE7CbgZgIy1zF9mPJXnkOZgFAFiC3QzApjqt12ACAADAiQhMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARghMAAAARpwyMKvqgVX1rqr6RFVdU1XPPReDAQDHZzcDsKkOLHHMrUme190frqp7JTlSVVd19ydWPBsAcHx2MwAb6ZTPYHb3n3b3hxfvfyXJtUkuWPVgAMDx2c0AbKrTeg1mVR1M8sgkH1jJNADAabGbAdgkSwdmVd0zyeuS/EJ3f/k4P395VR2uqsNHjx6dnBEAOA67GYBNs1RgVtX52V9gr+ju1x/vmO6+orsPdfehvb29yRkBgDuwmwHYRMvcRbaS/E6Sa7v7hasfCQA4GbsZgE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5Xsv+H64L1TnX2et9XFx+ev3jbiRdeV9WFSZ6U5CXrnoVTq6q/nuSHkvxOknT317v7lrUOxSnZzdvBbt4udjObYlW7eWMCc8dckOSGYz6+MTvwP8Q7i6o6mOSRST6w5lFGLC5VuTrJzUmu6u6dOK8kL0ry/CTfWPMcq9BJ3l5VR6rq8nUPM+QhSY4medni0qmXVNU91j0Udyp28xazm7fGi2I3b5OV7OZzGphV9Y6q+vhx3nbiXxDZflV1zySvS/IL3f3ldc8zobtv6+5LklyY5FFV9X1rHumsVdWTk9zc3UfWPcuKPK67vz/7l/L9bFX90LoHGnAgyfcn+a3ufmSSv0iyM6+B22Z2M5vObt4OdvNWWsluPnC2D3A6uvsfnMtfb41uSvLAYz6+cPE5NlhVnZ/9BfaK7n79uueZ1t23VNW7sv86nW2/EcRjkzylqn40yd2S/LWq+r3u/sk1zzWiu29a/HhzVb0h+5f2bftr4G5McuMx/0r/2gjMjWA3s8ns5q1iN2+flexml8iuxoeSPKyqHlJVd0nyzCRvXPNMnERVVfavP7+2u1+47nmmVNVeVd178f7dkzw+ySfXOtSA7v7l7r6wuw9m/8/XO3dlgVXVParqXre/n+QJ2f6/dKS7P5/khqp6xOJTfz/JJ9Y4Enc+dvOWsZu3i928fVa1mzcmMKvqH1bVjUkek+TNVfW2dc90prr71iQ/l+Rt2X9B+mu6+5r1TjWjql6V5H1JHlFVN1bVT697piGPTfLsJJcubj999eJf4Lbd/ZO8q6o+lv2/XF3V3Tt12/AddL8k762qjyb5YJI3d/db1zzTlJ9P8orFf4+XJPnV9Y7DqdjN28Fu3jp28/axm09Dde/ETasAAABYs415BhMAAIDtJjABAAAYITABAAAYITABAAAYITABAAAYITABAAAYITABAAAYITABAAAY8f8B7OpC0T9iaCoAAAAASUVORK5CYII=\n",
Martin Bauer's avatar
Martin Bauer committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
      "text/plain": [
       "<Figure size 1152x432 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "dh = ps.create_data_handling((4, 4), periodicity=(True, False))\n",
    "dh.add_array(\"src\")\n",
    "\n",
    "# get copy function\n",
    "copy_fct = dh.synchronization_function(['src'])\n",
    "\n",
    "dh.fill('src', 0.0, ghost_layers=True)\n",
    "dh.fill('src', 3.0, ghost_layers=False)\n",
    "before_sync = dh.gather_array('src', ghost_layers=True).copy()\n",
    "\n",
    "copy_fct() # copy over to get periodicity in x direction\n",
    "\n",
    "after_sync = dh.gather_array('src', ghost_layers=True).copy()\n",
    "plt.subplot(1,2,1)\n",
    "plt.scalar_field(before_sync);\n",
    "plt.title(\"Before\")\n",
    "plt.subplot(1,2,2)\n",
    "plt.scalar_field(after_sync);\n",
    "plt.title(\"After\");"
   ]
786
787
788
789
790
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Martin Bauer's avatar
Martin Bauer committed
791
792
793
794
795
796
797
798
799
800
    "## 3. Going (MPI) parallel - the parallel data handling\n",
    "\n",
    "### 3.1. Conceptual overview\n",
    "To run MPI parallel simulations the waLBerla framework is used. waLBerla has to be compiled against your local MPI library and thus is a bit hard to install. We suggest to use the version shipped with conda for testing. For production, when you want to run on a cluster the best option is to build waLBerla yourself against the MPI library that is installed on your cluster.\n",
    "\n",
    "Now lets have a look on how to write code that runs MPI parallel.\n",
    "Since the data is distributed, we don't have access to the full array any more but only to the part that is stored locally. The domain is split into so called blocks, where one process might get one (or sometimes multiple) blocks. To do anything with the local part of the data we iterate over the **local** blocks to get the contents as numpy arrays. The blocks returned in the loop differ from process to process.\n",
    "\n",
    "Copy the following snippet to a python file and run with multiple processes e.g.:\n",
    "``mpirun -np 4 myscript.py`` you will see that there are as many blocks as processes."
801
802
803
804
   ]
  },
  {
   "cell_type": "code",
Martin Bauer's avatar
Martin Bauer committed
805
   "execution_count": 20,
806
807
808
   "metadata": {},
   "outputs": [
    {
Jan Hönig's avatar
Jan Hönig committed
809
810
811
812
813
814
815
816
817
     "ename": "ValueError",
     "evalue": "Cannot create parallel data handling because walberla module is not available",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-20-779cf1a58f81>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdh\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mps\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcreate_data_handling\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdomain_size\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m30\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m30\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mparallel\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      2\u001b[0m \u001b[0mfield\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdh\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_array\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'field'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mblock\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdh\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0miterate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m     \u001b[0;31m# offset is in global coordinates, where first inner cell has coordiante (0,0)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m     \u001b[0;31m# and ghost layers have negative coordinates\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/git/pystencils/pystencils/datahandling/__init__.py\u001b[0m in \u001b[0;36mcreate_data_handling\u001b[0;34m(domain_size, periodicity, default_layout, default_target, parallel, default_ghost_layers, opencl_queue)\u001b[0m\n\u001b[1;32m     38\u001b[0m         \u001b[0;32massert\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mopencl_queue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"OpenCL is only supported for SerialDataHandling\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     39\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0mwlb\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 40\u001b[0;31m             \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Cannot create parallel data handling because walberla module is not available\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     41\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     42\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0mperiodicity\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mFalse\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mperiodicity\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mValueError\u001b[0m: Cannot create parallel data handling because walberla module is not available"
818
819
820
821
822
823
824
     ]
    }
   ],
   "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",
Martin Bauer's avatar
Martin Bauer committed
825
826
827
    "    # offset is in global coordinates, where first inner cell has coordiante (0,0) \n",
    "    # and ghost layers have negative coordinates\n",
    "    print(block.offset, block['field'].shape) \n",
828
829
830
831
832
    "    \n",
    "    # use offset to create a local array 'my_data' for the part of the domain\n",
    "    #np.copyto(block[field.name], my_data)"
   ]
  },
Martin Bauer's avatar
Martin Bauer committed
833
834
835
836
837
838
839
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get some more interesting results here in the notebook we put multiple blocks onto our single notebook process. This makes not much sense for real simulations, but for testing and demonstration purposes this is useful."
   ]
  },
840
841
  {
   "cell_type": "code",
Jan Hönig's avatar
Jan Hönig committed
842
   "execution_count": null,
843
   "metadata": {},
Jan Hönig's avatar
Jan Hönig committed
844
   "outputs": [],
Martin Bauer's avatar
Martin Bauer committed
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
   "source": [
    "from waLBerla import createUniformBlockGrid\n",
    "from pystencils.datahandling import ParallelDataHandling\n",
    "\n",
    "blocks = createUniformBlockGrid(blocks=(2,1,2), cellsPerBlock=(20, 10, 20), \n",
    "                                oneBlockPerProcess=False, periodic=(1, 0, 0))\n",
    "dh = ParallelDataHandling(blocks)\n",
    "field = dh.add_array('field')\n",
    "for block in dh.iterate():\n",
    "    print(block.offset, block['field'].shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we see that we have four blocks with (20, 10, 20) block each, and the global domain is (40, 10, 40) big.\n",
    "All subblock also have a ghost layer around them, which is used to synchronize with their neighboring blocks (over the network). For ghost layer synchronization the same `synchronization_function` is used that we used above for periodic boundaries, because copying between blocks and copying the ghost layer for periodicity uses the same mechanism."
   ]
864
865
866
  },
  {
   "cell_type": "code",
Jan Hönig's avatar
Jan Hönig committed
867
   "execution_count": null,
868
   "metadata": {},
Jan Hönig's avatar
Jan Hönig committed
869
   "outputs": [],
Martin Bauer's avatar
Martin Bauer committed
870
871
872
873
874
875
876
877
878
879
880
881
   "source": [
    "dh.gather_array('field').shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2. Parallel example \n",
    "\n",
    "To illustrate this in more detail, lets run a simple kernel on a parallel domain. waLBerla can handle 3D domains only, so we choose a z-size of 1."
   ]
882
883
884
  },
  {
   "cell_type": "code",
Jan Hönig's avatar
Jan Hönig committed
885
   "execution_count": null,
886
887
   "metadata": {},
   "outputs": [],
Martin Bauer's avatar
Martin Bauer committed
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
   "source": [
    "blocks = createUniformBlockGrid(blocks=(2,4,1), cellsPerBlock=(20, 10, 1), \n",
    "                                oneBlockPerProcess=False, periodic=(1, 1, 0))\n",
    "dh = ParallelDataHandling(blocks, dim=2)\n",
    "src_field = dh.add_array('src')\n",
    "dst_field = dh.add_array('dst')\n",
    "\n",
    "update_rule = [ps.Assignment(lhs=dst_field[0, 0 ],\n",
    "                             rhs=(src_field[1, 0] + src_field[-1, 0] + \n",
    "                                  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()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now lets initialize the arrays. To do this we can get arrays (meshgrids) from the block with the coordinates of the local cells. We use this to initialize a circular shape."
   ]
909
910
911
  },
  {
   "cell_type": "code",
Jan Hönig's avatar
Jan Hönig committed
912
   "execution_count": null,
Martin Bauer's avatar
Martin Bauer committed
913
   "metadata": {},
Jan Hönig's avatar
Jan Hönig committed
914
   "outputs": [],
Martin Bauer's avatar
Martin Bauer committed
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
   "source": [
    "dh.fill('src', 0.0)\n",
    "for block in dh.iterate(ghost_layers=False, inner_ghost_layers=False):\n",
    "    x, y = block.midpoint_arrays\n",
    "    inside_sphere = (x -20)**2 + (y-25)**2  < 8 ** 2\n",
    "    block['src'][inside_sphere] = 1.0\n",
    "plt.scalar_field( dh.gather_array('src') );"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can run our compute kernel on this data as usual. We just have to make sure that the field is synchronized after every step, i.e. that the ghost layers are correctly updated."
   ]
  },
  {
   "cell_type": "code",
Jan Hönig's avatar
Jan Hönig committed
933
   "execution_count": null,
934
935
   "metadata": {},
   "outputs": [],
Martin Bauer's avatar
Martin Bauer committed
936
937
938
939
940
941
942
943
944
945
   "source": [
    "sync = dh.synchronization_function(['src'])\n",
    "for i in range(40):\n",
    "    sync()\n",
    "    dh.run_kernel(kernel_function)\n",
    "    dh.swap('src', 'dst')"
   ]
  },
  {
   "cell_type": "code",
Jan Hönig's avatar
Jan Hönig committed
946
   "execution_count": null,
Martin Bauer's avatar
Martin Bauer committed
947
   "metadata": {},
Jan Hönig's avatar
Jan Hönig committed
948
   "outputs": [],
Martin Bauer's avatar
Martin Bauer committed
949
950
951
   "source": [
    "plt.scalar_field( dh.gather_array('src') );"
   ]
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
  }
 ],
 "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",
Jan Hönig's avatar
Jan Hönig committed
970
   "version": "3.9.2"
971
972
973
  }
 },
 "nbformat": 4,
Jan Hönig's avatar
Jan Hönig committed
974
 "nbformat_minor": 4
975
}