30_wrapping.ipynb 13.3 KB
Newer Older
paugier's avatar
paugier committed
1
2
3
4
5
6
7
8
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Wrapping codes in static languages"
   ]
9
  },
Franck Thollard's avatar
Franck Thollard committed
10
11
12
13
14
15
16
17
18
19
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We consider here wrapping two static languages: C and fortran.\n",
    "\n",
    "We classically wrapp already existing code to access them via python. \n",
    "\n"
   ]
  },
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
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fortran with [f2py](https://docs.scipy.org/doc/numpy/f2py/)\n",
    "\n",
    "`f2py` is a tool that allows to call Fortran code into Python. It is a part of `numpy` meaning that to use it, we only need to install and import numpy (which should already be done if you do scientific Python !) :\n",
    "\n",
    "```bash\n",
    "pip3 install numpy\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How does it work ?\n",
    "The documentation gives several ways to wrap Fortran codes but it all boils down to the same thing:\n",
    "\n",
    "**f2py allows to wrap the Fortran code in a Python module that can be then imported**\n",
    "\n",
    "Given this simple Fortran (F90) snippet, that computes the sum of squares of the element of an array:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*pyfiles/f2py/file_to_wrap.f90*\n",
    "\n",
    "```fortran\n",
    "subroutine sum_squares(A, res)\n",
    "    implicit none\n",
    "    real, dimension(:) :: A\n",
    "    real :: res\n",
    "    integer :: i, N\n",
    "\n",
    "    N = size(A)\n",
    "    res = 0.\n",
    "\n",
    "    do i=1, N\n",
    "        res = res + A(i)*A(i)\n",
    "    end do\n",
    "\n",
    "end subroutine\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Fortran code can then be wrapped in one command:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```bash\n",
    "# Syntax: python3 -m numpy.f2py -c <Fortran_files> -m <module_name>\n",
    "python3 -m numpy.f2py -c \"../pyfiles/f2py/file_to_wrap.f90\" -m wrap_f90\n",
    "```\n",
    "\n",
    "This command calls the module `f2py` of `numpy` to compile (`-c`) *file_to_wrap.f90* into a Python module (`-m`) named *wrap_f90*. The module can then be imported in Python:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import wrap_f90\n",
    "\n",
    "A = np.ones(10)\n",
    "result = 0.\n",
    "\n",
    "wrap_f90.sum_squares(A, result)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### With intents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In Fortran, it is considered best practice to put intents to subroutine arguments. This also helps `f2py` to wrap efficiently the code but also changes the subroutine a bit.\n",
    "\n",
    "Let's wrap the code updated with intents:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*pyfiles/f2py/file_to_wrap2.f90*\n",
    "\n",
    "```fortran\n",
    "subroutine sum_squares(A, res)\n",
    "    implicit none\n",
    "    real, dimension(:), intent(in) :: A\n",
    "    real, intent(out) :: res\n",
    "    integer :: i, N\n",
    "\n",
    "    N = size(A)\n",
    "    res = 0.\n",
    "\n",
    "    do i=1, N\n",
    "        res = res + A(i)*A(i)\n",
    "    end do\n",
    "\n",
    "end subroutine\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Again, we wrap..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```bash\n",
    "python3 -m numpy.f2py -c \"../pyfiles/f2py/file_to_wrap2.f90\" -m wrap_f90\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And we import..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import wrap_f90\n",
    "\n",
    "A = np.ones(10)\n",
    "\n",
    "result = wrap_f90.sum_squares(A)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This time, f2py recognized that `result` was a outgoing arg. As a consequence, the subroutine was wrapped smartly and made to return the arg.\n",
    "\n",
    "Note that using a `function` (in the Fortran sense of the term) leads to the same result (see the other example in *pyfiles/f2py/file_to_wrap2.f90*)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### With modules"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In Fortran, it is also considered best practice to organize the subroutines in modules. These are highly similar to Python modules and are in fact, intepreted as such by f2py !\n",
    "\n",
    "Consider the following code that implements the dtw and cort computations in Fortran:\n",
    "\n",
    "*pyfiles/dtw_cort_dist/V9_fortran/dtw_cort.f90*\n",
    "```fortran\n",
    "module dtw_cort\n",
    "    implicit none\n",
    "\n",
    "    contains\n",
    "        subroutine dtwdistance(s1, s2, dtw_result)\n",
    "            ! Computes the dtw between s1 and s2 with distance the absolute distance\n",
    "            doubleprecision, intent(in) :: s1(:), s2(:)\n",
    "            doubleprecision, intent(out) :: dtw_result\n",
    "\n",
    "            integer :: i, j\n",
    "            integer :: len_s1, len_s2\n",
    "            doubleprecision :: dist\n",
    "            doubleprecision, allocatable :: dtw_mat(:, :)\n",
    "\n",
    "            len_s1 = size(s1)\n",
    "            len_s2 = size(s1)\n",
    "\n",
    "            allocate(dtw_mat(len_s1, len_s2))\n",
    "\n",
    "            dtw_mat(1, 1) = dabs(s1(1) - s2(1))\n",
    "\n",
    "            do j = 2, len_s2\n",
    "                dist = dabs(s1(1) - s2(j))\n",
    "                dtw_mat(1, j) = dist + dtw_mat(1, j-1)\n",
    "            end do\n",
    "\n",
    "            do i = 2, len_s1\n",
    "                dist = dabs(s1(i) - s2(1))\n",
    "                dtw_mat(i, 1) = dist + dtw_mat(i-1, 1)\n",
    "            end do\n",
    "\n",
    "            ! Fill the dtw_matrix\n",
    "            do i = 2, len_s1\n",
    "                do j = 2, len_s2\n",
    "                    dist = dabs(s1(i) - s2(j))\n",
    "                    dtw_mat(i, j) = dist + dmin1(dtw_mat(i - 1, j), &\n",
    "                                                 dtw_mat(i, j - 1), &\n",
    "                                                 dtw_mat(i - 1, j - 1))\n",
    "                end do\n",
    "            end do\n",
    "\n",
    "            dtw_result = dtw_mat(len_s1, len_s2)\n",
    "\n",
    "        end subroutine dtwdistance\n",
    "\n",
    "        doubleprecision function cort(s1, s2)\n",
    "            ! Computes the cort between s1 and s2 (assuming they have the same length)\n",
    "            doubleprecision, intent(in) :: s1(:), s2(:)\n",
    "\n",
    "            integer :: len_s1, t\n",
    "            doubleprecision :: slope_1, slope_2\n",
    "            doubleprecision :: num, sum_square_x, sum_square_y\n",
    "\n",
    "            len_s1 = size(s1)\n",
    "            num = 0\n",
    "            sum_square_x = 0\n",
    "            sum_square_y = 0\n",
    "\n",
    "            do t=1, len_s1 - 1\n",
    "                slope_1 = s1(t + 1) - s1(t)\n",
    "                slope_2 = s2(t + 1) - s2(t)\n",
    "                num = num + slope_1 * slope_2\n",
    "                sum_square_x = sum_square_x + slope_1 * slope_1\n",
    "                sum_square_y = sum_square_y + slope_2 * slope_2\n",
    "            end do\n",
    "\n",
    "            cort = num / (dsqrt(sum_square_x*sum_square_y))\n",
    "\n",
    "        end function cort\n",
    "end module dtw_cort\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The subroutines `dtwdistance` and `cort` are part of the `dtw_cort` module. The file can be wrapped as before\n",
    "```bash\n",
    "    python3 -m numpy.f2py -c \"../pyfiles/dtw_cort_dist/V9_fortran/dtw_cort.f90\" -m distances_fort\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But the import slighlty changes as `dtw_cort` is now a module of `distances_fort`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from distances_fort import dtw_cort\n",
    "\n",
    "cort_result = dtw_cort.cort(s1, s2)\n",
    "print(cort_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the wrapping integrates the documentation of the function (if written...) !"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from distances_fort import dtw_cort\n",
    "\n",
    "print(dtw_cort.cort.__doc__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### To go further...\n",
    "\n",
    "Running the command `python3 -m numpy.f2py` (without arguments) gives a lot of information on the supported arguments for further uses of `f2py`. Know that you can this way:\n",
    "* Specify the compiler to use\n",
    "* Give the compiler flags (warnings, optimisations...)\n",
    "* Specify the functions to wrap\n",
    "* ...\n",
    "\n",
    "The documentation of f2py (https://docs.scipy.org/doc/numpy/f2py/) can also help, covering notably:\n",
    "* `Cf2py` directives to overcome F77 limitations (e.g. intents)\n",
    "* How to integrate Fortran sources to your Python packages and compile them on install\n",
    "* How to use `f2py` inside Python scripts\n",
    "* ..."
   ]
Franck Thollard's avatar
Franck Thollard committed
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
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Wrapping C code\n",
    "--------------------------"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "They are different ways of wrapping C code. We present CFFI. \n",
    "\n",
    "The workflow is the following:\n",
    "  1. Get your C code working (with a .c and a .h)\n",
    "  2. Set up your packaging to compile your code as a module\n",
    "  3. Compile your code\n",
    "  4. In the python code, declare the function you will be using\n",
    "  5. In the python code, open/load the compiled module\n",
    "  6. Use your functions\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**1. Get your C code working (with a .c and a .h)**\n",
    "\n",
    "Ok, supposed to be done"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**2. Set up your packaging to compile your code as a module**\n",
    "\n",
    "We give the compilation instructions in the file setup.py:\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "from setuptools import setup, Extension\n",
    "\n",
    "version = \"0.1\"\n",
    "\n",
    "module_distance = Extension(\n",
    "    name=\"cdtw\",\n",
    "    sources=[\"cdtw.c\"],\n",
    ")\n",
    "\n",
    "setup(\n",
    "    name=\"dtw_cort_dist_mat\",\n",
    "    version=version,\n",
    "    description=\"data scientist tool for time series\",\n",
    "    long_description=\"data scientist tool for time series\",\n",
    "    classifiers=[], \n",
    "    author=\"Robert Bidochon\",\n",
    "    author_email=\"robert@bidochon.fr\",\n",
    "    license=\"GPL\",\n",
    "    include_package_data=True,\n",
    "    install_requires=[\"cffi\", \"numpy\", \"setuptools\"],\n",
    "    entry_points=\"\",\n",
    "    ext_modules=[module_distance],\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**3. Compile your code**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "in a terminal, type:\n",
    "\n",
    "python3 setup.py build_ext"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**4. In the python code, declare the function you will be using**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from cffi import FFI\n",
    "\n",
    "ffi = FFI()\n",
    "ffi.cdef(\"double square(double x, double y);\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**5. In the python code, open/load the compiled module**"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "dllib = ffi.dlopen(\n",
    "    str(my_dir / (\"cdtw\" + sysconfig.get_config_var(\"EXT_SUFFIX\")))\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**6. Use your functions**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "sq = dllib.square(2.0, 3.0)"
   ]
paugier's avatar
paugier committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
  }
 ],
 "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",
Franck Thollard's avatar
Franck Thollard committed
500
   "version": "3.7.3"
paugier's avatar
paugier committed
501
502
503
504
505
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}