06_tutorial_datahandling.ipynb 40.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
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
47
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
124
125
126
127
128
129
130
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
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
470
471
472
473
474
475
476
477
478
479
480
481
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
569
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
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
786
{
 "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
}