summaryrefslogtreecommitdiff
path: root/docs/examples/Cython Magics.ipynb
blob: 9bbf934c8d0a2f1958863d89ea8cd9f4e0ecadfd (plain)
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
{
 "metadata": {
  "name": "Cython Magics",
  "signature": "sha256:c357b93e9480d6347c6677862bf43750745cef4b30129c5bc53cb879a19d4074"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "heading",
     "level": 1,
     "metadata": {},
     "source": [
      "Cython Magic Functions"
     ]
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Loading the extension"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Cython has an IPython extension that contains a number of magic functions for working with Cython code. This extension can be loaded using the `%load_ext` magic as follows:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%load_ext cython"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 1
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "The %cython_inline magic"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "The `%%cython_inline` magic uses `Cython.inline` to compile a Cython expression. This allows you to enter and run a function body with Cython code. Use a bare `return` statement to return values. "
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "a = 10\n",
      "b = 20"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 2
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%cython_inline\n",
      "return a+b"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 3,
       "text": [
        "30"
       ]
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "The %cython_pyximport magic"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "The `%%cython_pyximport` magic allows you to enter arbitrary Cython code into a cell. That Cython code is written as a `.pyx` file in the current working directory and then imported using `pyximport`.  You have the specify the name of the module that the Code will appear in. All symbols from the module are imported automatically by the magic function."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%cython_pyximport foo\n",
      "def f(x):\n",
      "    return 4.0*x"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 4
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "f(10)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 5,
       "text": [
        "40.0"
       ]
      }
     ],
     "prompt_number": 5
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "The %cython magic"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Probably the most important magic is the `%cython` magic.  This is similar to the `%%cython_pyximport` magic, but doesn't require you to specify a module name. Instead, the `%%cython` magic uses manages everything using temporary files in the `~/.cython/magic` directory.  All of the symbols in the Cython module are imported automatically by the magic.\n",
      "\n",
      "Here is a simple example of a Black-Scholes options pricing algorithm written in Cython. Please note that this example might not compile on non-POSIX systems (e.g., Windows) because of a missing `erf` symbol."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%cython\n",
      "cimport cython\n",
      "from libc.math cimport exp, sqrt, pow, log, erf\n",
      "\n",
      "@cython.cdivision(True)\n",
      "cdef double std_norm_cdf_cy(double x) nogil:\n",
      "    return 0.5*(1+erf(x/sqrt(2.0)))\n",
      "\n",
      "@cython.cdivision(True)\n",
      "def black_scholes_cy(double s, double k, double t, double v,\n",
      "                     double rf, double div, double cp):\n",
      "    \"\"\"Price an option using the Black-Scholes model.\n",
      "    \n",
      "    s : initial stock price\n",
      "    k : strike price\n",
      "    t : expiration time\n",
      "    v : volatility\n",
      "    rf : risk-free rate\n",
      "    div : dividend\n",
      "    cp : +1/-1 for call/put\n",
      "    \"\"\"\n",
      "    cdef double d1, d2, optprice\n",
      "    with nogil:\n",
      "        d1 = (log(s/k)+(rf-div+0.5*pow(v,2))*t)/(v*sqrt(t))\n",
      "        d2 = d1 - v*sqrt(t)\n",
      "        optprice = cp*s*exp(-div*t)*std_norm_cdf_cy(cp*d1) - \\\n",
      "            cp*k*exp(-rf*t)*std_norm_cdf_cy(cp*d2)\n",
      "    return optprice"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 6
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "black_scholes_cy(100.0, 100.0, 1.0, 0.3, 0.03, 0.0, -1)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 7,
       "text": [
        "10.327861752731728"
       ]
      }
     ],
     "prompt_number": 7
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "For comparison, the same code is implemented here in pure python."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "from math import exp, sqrt, pow, log, erf\n",
      "\n",
      "def std_norm_cdf_py(x):\n",
      "    return 0.5*(1+erf(x/sqrt(2.0)))\n",
      "\n",
      "def black_scholes_py(s, k, t, v, rf, div, cp):\n",
      "    \"\"\"Price an option using the Black-Scholes model.\n",
      "    \n",
      "    s : initial stock price\n",
      "    k : strike price\n",
      "    t : expiration time\n",
      "    v : volatility\n",
      "    rf : risk-free rate\n",
      "    div : dividend\n",
      "    cp : +1/-1 for call/put\n",
      "    \"\"\"\n",
      "    d1 = (log(s/k)+(rf-div+0.5*pow(v,2))*t)/(v*sqrt(t))\n",
      "    d2 = d1 - v*sqrt(t)\n",
      "    optprice = cp*s*exp(-div*t)*std_norm_cdf_py(cp*d1) - \\\n",
      "        cp*k*exp(-rf*t)*std_norm_cdf_py(cp*d2)\n",
      "    return optprice"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 8
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "black_scholes_py(100.0, 100.0, 1.0, 0.3, 0.03, 0.0, -1)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 9,
       "text": [
        "10.327861752731728"
       ]
      }
     ],
     "prompt_number": 9
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Below we see the runtime of the two functions: the Cython version is nearly a factor of 10 faster."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%timeit black_scholes_cy(100.0, 100.0, 1.0, 0.3, 0.03, 0.0, -1)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "1000000 loops, best of 3: 319 ns per loop\n"
       ]
      }
     ],
     "prompt_number": 10
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%timeit black_scholes_py(100.0, 100.0, 1.0, 0.3, 0.03, 0.0, -1)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "100000 loops, best of 3: 2.28 \u00b5s per loop\n"
       ]
      }
     ],
     "prompt_number": 11
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "External libraries"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Cython allows you to specify additional libraries to be linked with your extension, you can do so with the `-l` flag (also spelled `--lib`).  Note that this flag can be passed more than once to specify multiple libraries, such as `-lm -llib2 --lib lib3`.  Here's a simple example of how to access the system math library:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%cython -lm\n",
      "from libc.math cimport sin\n",
      "print 'sin(1)=', sin(1)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "sin(1)= 0.841470984808\n"
       ]
      }
     ],
     "prompt_number": 12
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "You can similarly use the `-I/--include` flag to add include directories to the search path, and `-c/--compile-args` to add extra flags that are passed to Cython via the `extra_compile_args` of the distutils `Extension` class.  Please see [the Cython docs on C library usage](https://docs.cython.org/src/tutorial/clibraries.html) for more details on the use of these flags."
     ]
    }
   ],
   "metadata": {}
  }
 ]
}