##// END OF EJS Templates
regen rst
Matthias BUSSONNIER -
Show More
@@ -1,698 +1,661
1 1 A brief tour of the IPython notebook
2 2 ====================================
3 3
4 4 This document will give you a brief tour of the capabilities of the
5 5 IPython notebook.
6 6 You can view its contents by scrolling around, or execute each cell by
7 7 typing ``Shift-Enter``. After you conclude this brief high-level tour,
8 8 you should read the accompanying notebook titled
9 9 ``01_notebook_introduction``, which takes a more step-by-step approach
10 10 to the features of the system.
11 11
12 12 The rest of the notebooks in this directory illustrate various other
13 13 aspects and capabilities of the IPython notebook; some of them may
14 14 require additional libraries to be executed.
15 15
16 16 **NOTE:** This notebook *must* be run from its own directory, so you
17 17 must ``cd`` to this directory and then start the notebook, but do *not*
18 18 use the ``--notebook-dir`` option to run it from another location.
19 19
20 20 The first thing you need to know is that you are still controlling the
21 21 same old IPython you're used to, so things like shell aliases and magic
22 22 commands still work:
23 23
24 24 In[1]:
25 25
26 26 .. code:: python
27 27
28 28 pwd
29 29
30 30 Out[1]:
31
32 31 .. parsed-literal::
33 32
34 33 u'/Users/minrk/dev/ip/mine/docs/examples/notebooks'
35 34
35
36 36 In[2]:
37 37
38 38 .. code:: python
39 39
40 40 ls
41 41
42
42 43 .. parsed-literal::
43 44
44 45 00_notebook_tour.ipynb callbacks.ipynb python-logo.svg
45 46 01_notebook_introduction.ipynb cython_extension.ipynb rmagic_extension.ipynb
46 47 Animations_and_Progress.ipynb display_protocol.ipynb sympy.ipynb
47 48 Capturing Output.ipynb formatting.ipynb sympy_quantum_computing.ipynb
48 49 Script Magics.ipynb octavemagic_extension.ipynb trapezoid_rule.ipynb
49 50 animation.m4v progbar.ipynb
50 51
51
52 52 In[3]:
53 53
54 54 .. code:: python
55 55
56 56 message = 'The IPython notebook is great!'
57 57 # note: the echo command does not run on Windows, it's a unix command.
58 58 !echo $message
59 59
60
60 61 .. parsed-literal::
61 62
62 63 The IPython notebook is great!
63 64
64
65 65 Plots with matplotlib
66 66 ---------------------
67 67
68 68 IPython adds an 'inline' matplotlib backend, which embeds any matplotlib
69 69 figures into the notebook.
70 70
71 71 In[4]:
72 72
73 73 .. code:: python
74 74
75 75 %pylab inline
76 76
77
77 78 .. parsed-literal::
78 79
79 80
80 81 Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
81 82 For more information, type 'help(pylab)'.
82 83
83
84 84 In[5]:
85 85
86 86 .. code:: python
87 87
88 88 x = linspace(0, 3*pi, 500)
89 89 plot(x, sin(x**2))
90 90 title('A simple chirp');
91 91
92 .. image:: tests/ipynbref/00_notebook_tour_orig_files/00_notebook_tour_orig_fig_00.png
92 .. image:: _fig_07.png
93 93
94 94 You can paste blocks of input with prompt markers, such as those from
95 95 `the official Python
96 96 tutorial <http://docs.python.org/tutorial/interpreter.html#interactive-mode>`_
97 97
98 98 In[6]:
99 99
100 100 .. code:: python
101 101
102 102 >>> the_world_is_flat = 1
103 103 >>> if the_world_is_flat:
104 104 ... print "Be careful not to fall off!"
105 105
106
106 107 .. parsed-literal::
107 108
108 109 Be careful not to fall off!
109 110
110
111 111 Errors are shown in informative ways:
112 112
113 113 In[7]:
114 114
115 115 .. code:: python
116 116
117 117 %run non_existent_file
118 118
119
119 120 .. parsed-literal::
120 121
121 122 ERROR: File `u'non_existent_file.py'` not found.
122
123 123 In[8]:
124 124
125 125 .. code:: python
126 126
127 127 x = 1
128 128 y = 4
129 129 z = y/(1-x)
130 130
131 131 ::
132 132
133 133 ---------------------------------------------------------------------------
134 134 ZeroDivisionError Traceback (most recent call last)
135 135 <ipython-input-8-dc39888fd1d2> in <module>()
136 136 1 x = 1
137 137 2 y = 4
138 138 ----> 3 z = y/(1-x)
139 139
140 140 ZeroDivisionError: integer division or modulo by zero
141
142 141 When IPython needs to display additional information (such as providing
143 142 details on an object via ``x?`` it will automatically invoke a pager at
144 143 the bottom of the screen:
145 144
146 145 In[18]:
147 146
148 147 .. code:: python
149 148
150 149 magic
151 150
152 151 Non-blocking output of kernel
153 152 -----------------------------
154 153
155 154 If you execute the next cell, you will see the output arriving as it is
156 155 generated, not all at the end.
157 156
158 157 In[19]:
159 158
160 159 .. code:: python
161 160
162 161 import time, sys
163 162 for i in range(8):
164 163 print i,
165 164 time.sleep(0.5)
166 165
167 .. parsed-literal::
168
169 0
170 166
171 167 .. parsed-literal::
172 168
173 1
174
175 .. parsed-literal::
176
177 2
178
179 .. parsed-literal::
180
181 3
182
183 .. parsed-literal::
184
185 4
186
187 .. parsed-literal::
188
189 5
190
191 .. parsed-literal::
192
193 6
194
195 .. parsed-literal::
196
197 7
198
169 0 1 2 3 4 5 6 7
199 170
200 171 Clean crash and restart
201 172 -----------------------
202 173
203 174 We call the low-level system libc.time routine with the wrong argument
204 175 via ctypes to segfault the Python interpreter:
205 176
206 177 In[*]:
207 178
208 179 .. code:: python
209 180
210 181 import sys
211 182 from ctypes import CDLL
212 183 # This will crash a Linux or Mac system; equivalent calls can be made on Windows
213 184 dll = 'dylib' if sys.platform == 'darwin' else '.so.6'
214 185 libc = CDLL("libc.%s" % dll)
215 186 libc.time(-1) # BOOM!!
216 187
217 188 Markdown cells can contain formatted text and code
218 189 --------------------------------------------------
219 190
220 191 You can *italicize*, **boldface**
221 192
222 193 - build
223 194 - lists
224 195
225 196 and embed code meant for illustration instead of execution in Python:
226 197
227 198 ::
228 199
229 200 def f(x):
230 201 """a docstring"""
231 202 return x**2
232 203
233 204 or other languages:
234 205
235 206 ::
236 207
237 208 if (i=0; i<n; i++) {
238 209 printf("hello %d\n", i);
239 210 x += 4;
240 211 }
241 212
242 213
243 214 Courtesy of MathJax, you can include mathematical expressions both
244 215 inline: :math:`e^{i\pi} + 1 = 0` and displayed:
245 216
246 217 .. math:: e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i
247 218
248 219
249 220
250 221 Rich displays: include anyting a browser can show
251 222 -------------------------------------------------
252 223
253 224 Note that we have an actual protocol for this, see the
254 225 ``display_protocol`` notebook for further details.
255 226
256 227 Images
257 228 ~~~~~~
258 229
259 230
260 231 In[1]:
261 232
262 233 .. code:: python
263 234
264 235 from IPython.display import Image
265 236 Image(filename='../../source/_static/logo.png')
266 237
267 238 Out[1]:
239 .. image:: _fig_22.png
268 240
269 .. parsed-literal::
270
271 <IPython.core.display.Image at 0x10faeafd0>
272 241
273 242 An image can also be displayed from raw data or a url
274 243
275 244 In[2]:
276 245
277 246 .. code:: python
278 247
279 248 Image(url='http://python.org/images/python-logo.gif')
280 249
281 250 Out[2]:
282
283 251 .. parsed-literal::
284 252
285 253 <IPython.core.display.Image at 0x1060e7410>
286 254
255
287 256 SVG images are also supported out of the box (since modern browsers do a
288 257 good job of rendering them):
289 258
290 259 In[3]:
291 260
292 261 .. code:: python
293 262
294 263 from IPython.display import SVG
295 264 SVG(filename='python-logo.svg')
296 265
297 266 Out[3]:
267 .. image:: _fig_26.svg
298 268
299 .. parsed-literal::
300
301 <IPython.core.display.SVG at 0x10fb998d0>
302 269
303 270 Embedded vs Non-embedded Images
304 271 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
305 272
306 273
307 274 As of IPython 0.13, images are embedded by default for compatibility
308 275 with QtConsole, and the ability to still be displayed offline.
309 276
310 277 Let's look at the differences:
311 278
312 279 In[4]:
313 280
314 281 .. code:: python
315 282
316 283 # by default Image data are embedded
317 284 Embed = Image( 'http://scienceview.berkeley.edu/view/images/newview.jpg')
318 285
319 286 # if kwarg `url` is given, the embedding is assumed to be false
320 287 SoftLinked = Image(url='http://scienceview.berkeley.edu/view/images/newview.jpg')
321 288
322 289 # In each case, embed can be specified explicitly with the `embed` kwarg
323 290 # ForceEmbed = Image(url='http://scienceview.berkeley.edu/view/images/newview.jpg', embed=True)
324 291
325 292 Today's image from a webcam at Berkeley, (at the time I created this
326 293 notebook). This should also work in the Qtconsole. Drawback is that the
327 294 saved notebook will be larger, but the image will still be present
328 295 offline.
329 296
330 297 In[5]:
331 298
332 299 .. code:: python
333 300
334 301 Embed
335 302
336 303 Out[5]:
304 ..jpg image::
337 305
338 .. parsed-literal::
339
340 <IPython.core.display.Image at 0x10fb99b50>
341 306
342 307 Today's image from same webcam at Berkeley, (refreshed every minutes, if
343 308 you reload the notebook), visible only with an active internet
344 309 connexion, that should be different from the previous one. This will not
345 310 work on Qtconsole. Notebook saved with this kind of image will be
346 311 lighter and always reflect the current version of the source, but the
347 312 image won't display offline.
348 313
349 314 In[6]:
350 315
351 316 .. code:: python
352 317
353 318 SoftLinked
354 319
355 320 Out[6]:
356
357 321 .. parsed-literal::
358 322
359 323 <IPython.core.display.Image at 0x10fb99b10>
360 324
325
361 326 Of course, if you re-run the all notebook, the two images will be the
362 327 same again.
363 328
364 329 Video
365 330 ~~~~~
366 331
367 332
368 333 And more exotic objects can also be displayed, as long as their
369 334 representation supports the IPython display protocol.
370 335
371 336 For example, videos hosted externally on YouTube are easy to load (and
372 337 writing a similar wrapper for other hosted content is trivial):
373 338
374 339 In[7]:
375 340
376 341 .. code:: python
377 342
378 343 from IPython.display import YouTubeVideo
379 344 # a talk about IPython at Sage Days at U. Washington, Seattle.
380 345 # Video credit: William Stein.
381 346 YouTubeVideo('1j_HxD4iLn8')
382 347
383 348 Out[7]:
384
385 349 .. parsed-literal::
386 350
387 351 <IPython.lib.display.YouTubeVideo at 0x10fba2190>
388 352
353
389 354 Using the nascent video capabilities of modern browsers, you may also be
390 355 able to display local videos. At the moment this doesn't work very well
391 356 in all browsers, so it may or may not work for you; we will continue
392 357 testing this and looking for ways to make it more robust.
393 358
394 359 The following cell loads a local file called ``animation.m4v``, encodes
395 360 the raw video as base64 for http transport, and uses the HTML5 video tag
396 361 to load it. On Chrome 15 it works correctly, displaying a control bar at
397 362 the bottom with a play/pause button and a location slider.
398 363
399 364 In[8]:
400 365
401 366 .. code:: python
402 367
403 368 from IPython.display import HTML
404 369 video = open("animation.m4v", "rb").read()
405 370 video_encoded = video.encode("base64")
406 371 video_tag = '<video controls alt="test" src="data:video/x-m4v;base64,{0}">'.format(video_encoded)
407 372 HTML(data=video_tag)
408 373
409 374 Out[8]:
410
411 375 .. parsed-literal::
412 376
413 377 <IPython.core.display.HTML at 0x10fba28d0>
414 378
379
415 380 Local Files
416 381 -----------
417 382
418 383 The above examples embed images and video from the notebook filesystem
419 384 in the output areas of code cells. It is also possible to request these
420 385 files directly in markdown cells if they reside in the notebook
421 386 directory via relative urls prefixed with ``files/``:
422 387
423 388 ::
424 389
425 390 files/[subdirectory/]<filename>
426 391
427 392 For example, in the example notebook folder, we have the Python logo,
428 393 addressed as:
429 394
430 395 ::
431 396
432 397 <img src="files/python-logo.svg" />
433 398
434 399 and a video with the HTML5 video tag:
435 400
436 401 ::
437 402
438 403 <video controls src="files/animation.m4v" />
439 404
440 405 These do not embed the data into the notebook file, and require that the
441 406 files exist when you are viewing the notebook.
442 407
443 408 Security of local files
444 409 ~~~~~~~~~~~~~~~~~~~~~~~
445 410
446 411 Note that this means that the IPython notebook server also acts as a
447 412 generic file server for files inside the same tree as your notebooks.
448 413 Access is not granted outside the notebook folder so you have strict
449 414 control over what files are visible, but for this reason it is highly
450 415 recommended that you do not run the notebook server with a notebook
451 416 directory at a high level in your filesystem (e.g. your home directory).
452 417
453 418 When you run the notebook in a password-protected manner, local file
454 419 access is restricted to authenticated users unless read-only views are
455 420 active.
456 421
457 422 Linking to files and directories for viewing in the browser
458 423 -----------------------------------------------------------
459 424
460 425 It is also possible to link directly to files or directories so they can
461 426 be opened in the browser. This is especially convenient if you're
462 427 interacting with a tool within IPython that generates HTML pages, and
463 428 you'd like to easily be able to open those in a new browser window.
464 429 Alternatively, if your IPython notebook server is on a remote system,
465 430 creating links provides an easy way to download any files that get
466 431 generated.
467 432
468 433 As we saw above, there are a bunch of ``.ipynb`` files in our current
469 434 directory.
470 435
471 436 In[1]:
472 437
473 438 .. code:: python
474 439
475 440 ls
476 441
442
477 443 .. parsed-literal::
478 444
479 445 00_notebook_tour.ipynb formatting.ipynb
480 446 01_notebook_introduction.ipynb octavemagic_extension.ipynb
481 447 Animations_and_Progress.ipynb publish_data.ipynb
482 448 Capturing Output.ipynb python-logo.svg
483 449 Script Magics.ipynb rmagic_extension.ipynb
484 450 animation.m4v sympy.ipynb
485 451 cython_extension.ipynb sympy_quantum_computing.ipynb
486 452 display_protocol.ipynb trapezoid_rule.ipynb
487 453
488
489 454 If we want to create a link to one of them, we can call use the
490 455 ``FileLink`` object.
491 456
492 457 In[2]:
493 458
494 459 .. code:: python
495 460
496 461 from IPython.display import FileLink
497 462 FileLink('00_notebook_tour.ipynb')
498 463
499 464 Out[2]:
500
501 465 .. parsed-literal::
502 466
503 467 <IPython.lib.display.FileLink at 0x10f7ea3d0>
504 468
469
505 470 Alternatively, if we want to link to all of them, we can use the
506 471 ``FileLinks`` object, passing ``'.'`` to indicate that we want links
507 472 generated for the current working directory. Note that if there were
508 473 other directories under the current directory, ``FileLinks`` would work
509 474 in a recursive manner creating links to files in all sub-directories as
510 475 well.
511 476
512 477 In[7]:
513 478
514 479 .. code:: python
515 480
516 481 from IPython.display import FileLinks
517 482 FileLinks('.')
518 483
519 484 Out[7]:
520
521 485 .. parsed-literal::
522 486
523 487 <IPython.lib.display.FileLinks at 0x10f7eaad0>
524 488
489
525 490 External sites
526 491 ~~~~~~~~~~~~~~
527 492
528 493 You can even embed an entire page from another site in an iframe; for
529 494 example this is today's Wikipedia page for mobile users:
530 495
531 496 In[9]:
532 497
533 498 .. code:: python
534 499
535 500 HTML('<iframe src=http://en.mobile.wikipedia.org/?useformat=mobile width=700 height=350></iframe>')
536 501
537 502 Out[9]:
538
539 503 .. parsed-literal::
540 504
541 505 <IPython.core.display.HTML at 0x1094900d0>
542 506
507
543 508 Mathematics
544 509 ~~~~~~~~~~~
545 510
546 511 And we also support the display of mathematical expressions typeset in
547 512 LaTeX, which is rendered in the browser thanks to the `MathJax
548 513 library <http://mathjax.org>`_.
549 514
550 515 Note that this is *different* from the above examples. Above we were
551 516 typing mathematical expressions in Markdown cells (along with normal
552 517 text) and letting the browser render them; now we are displaying the
553 518 output of a Python computation as a LaTeX expression wrapped by the
554 519 ``Math()`` object so the browser renders it. The ``Math`` object will
555 520 add the needed LaTeX delimiters (``$$``) if they are not provided:
556 521
557 522 In[10]:
558 523
559 524 .. code:: python
560 525
561 526 from IPython.display import Math
562 527 Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
563 528
564 529 Out[10]:
565
566 530 .. math::
567 531
568 532 $$F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$$
569 533
570 .. parsed-literal::
571
572 <IPython.core.display.Math at 0x10fba26d0>
573 534
574 535 With the ``Latex`` class, you have to include the delimiters yourself.
575 536 This allows you to use other LaTeX modes such as ``eqnarray``:
576 537
577 538 In[11]:
578 539
579 540 .. code:: python
580 541
581 542 from IPython.display import Latex
582 543 Latex(r"""\begin{eqnarray}
583 544 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
584 545 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
585 546 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
586 547 \nabla \cdot \vec{\mathbf{B}} & = 0
587 548 \end{eqnarray}""")
588 549
589 550 Out[11]:
590
591 551 .. math::
592 552
593 553 \begin{eqnarray}
594 554 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
595 555 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
596 556 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
597 557 \nabla \cdot \vec{\mathbf{B}} & = 0
598 558 \end{eqnarray}
599 559
600 .. parsed-literal::
601
602 <IPython.core.display.Latex at 0x10fba2c10>
603 560
604 561 Or you can enter latex directly with the ``%%latex`` cell magic:
605 562
606 563 In[12]:
607 564
608 565 .. code:: python
609 566
610 567 %%latex
611 568 \begin{aligned}
612 569 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
613 570 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
614 571 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
615 572 \nabla \cdot \vec{\mathbf{B}} & = 0
616 573 \end{aligned}
617 574
618 .. parsed-literal::
575 .. math::
619 576
620 <IPython.core.display.Latex at 0x10a617c90>
577 \begin{aligned}
578 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
579 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
580 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
581 \nabla \cdot \vec{\mathbf{B}} & = 0
582 \end{aligned}
621 583
622 584 There is also a ``%%javascript`` cell magic for running javascript
623 585 directly, and ``%%svg`` for manually entering SVG content.
624 586
625 587 Loading external codes
626 588 ======================
627 589
628 590 - Drag and drop a ``.py`` in the dashboard
629 591 - Use ``%load`` with any local or remote url: `the Matplotlib
630 592 Gallery! <http://matplotlib.sourceforge.net/gallery.html>`_
631 593
632 594 In this notebook we've kept the output saved so you can see the result,
633 595 but you should run the next cell yourself (with an active internet
634 596 connection).
635 597
636 598 Let's make sure we have pylab again, in case we have restarted the
637 599 kernel due to the crash demo above
638 600
639 601 In[12]:
640 602
641 603 .. code:: python
642 604
643 605 %pylab inline
644 606
607
645 608 .. parsed-literal::
646 609
647 610
648 611 Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
649 612 For more information, type 'help(pylab)'.
650 613
651
652 614 In[15]:
653 615
654 616 .. code:: python
655 617
656 618 %load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py
657 619
658 620 In[16]:
659 621
660 622 .. code:: python
661 623
662 624 #!/usr/bin/env python
663 625
664 626 # implement the example graphs/integral from pyx
665 627 from pylab import *
666 628 from matplotlib.patches import Polygon
667 629
668 630 def func(x):
669 631 return (x-3)*(x-5)*(x-7)+85
670 632
671 633 ax = subplot(111)
672 634
673 635 a, b = 2, 9 # integral area
674 636 x = arange(0, 10, 0.01)
675 637 y = func(x)
676 638 plot(x, y, linewidth=1)
677 639
678 640 # make the shaded region
679 641 ix = arange(a, b, 0.01)
680 642 iy = func(ix)
681 643 verts = [(a,0)] + zip(ix,iy) + [(b,0)]
682 644 poly = Polygon(verts, facecolor='0.8', edgecolor='k')
683 645 ax.add_patch(poly)
684 646
685 647 text(0.5 * (a + b), 30,
686 648 r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center',
687 649 fontsize=20)
688 650
689 651 axis([0,10, 0, 180])
690 652 figtext(0.9, 0.05, 'x')
691 653 figtext(0.1, 0.9, 'y')
692 654 ax.set_xticks((a,b))
693 655 ax.set_xticklabels(('a','b'))
694 656 ax.set_yticks([])
695 657 show()
696 658
697 659
698 .. image:: tests/ipynbref/00_notebook_tour_orig_files/00_notebook_tour_orig_fig_01.png
660 .. image:: _fig_60.png
661
@@ -1,660 +1,661
1 1 A brief tour of the IPython notebook
2 2 ====================================
3 3
4 4 This document will give you a brief tour of the capabilities of the
5 5 IPython notebook.
6 6 You can view its contents by scrolling around, or execute each cell by
7 7 typing ``Shift-Enter``. After you conclude this brief high-level tour,
8 8 you should read the accompanying notebook titled
9 9 ``01_notebook_introduction``, which takes a more step-by-step approach
10 10 to the features of the system.
11 11
12 12 The rest of the notebooks in this directory illustrate various other
13 13 aspects and capabilities of the IPython notebook; some of them may
14 14 require additional libraries to be executed.
15 15
16 16 **NOTE:** This notebook *must* be run from its own directory, so you
17 17 must ``cd`` to this directory and then start the notebook, but do *not*
18 18 use the ``--notebook-dir`` option to run it from another location.
19 19
20 20 The first thing you need to know is that you are still controlling the
21 21 same old IPython you're used to, so things like shell aliases and magic
22 22 commands still work:
23 23
24 24 In[1]:
25 25
26 26 .. code:: python
27 27
28 28 pwd
29 29
30 30 Out[1]:
31 31 .. parsed-literal::
32 32
33 33 u'/Users/minrk/dev/ip/mine/docs/examples/notebooks'
34 34
35 35
36 36 In[2]:
37 37
38 38 .. code:: python
39 39
40 40 ls
41 41
42 42
43 43 .. parsed-literal::
44 44
45 45 00_notebook_tour.ipynb callbacks.ipynb python-logo.svg
46 46 01_notebook_introduction.ipynb cython_extension.ipynb rmagic_extension.ipynb
47 47 Animations_and_Progress.ipynb display_protocol.ipynb sympy.ipynb
48 48 Capturing Output.ipynb formatting.ipynb sympy_quantum_computing.ipynb
49 49 Script Magics.ipynb octavemagic_extension.ipynb trapezoid_rule.ipynb
50 50 animation.m4v progbar.ipynb
51 51
52 52 In[3]:
53 53
54 54 .. code:: python
55 55
56 56 message = 'The IPython notebook is great!'
57 57 # note: the echo command does not run on Windows, it's a unix command.
58 58 !echo $message
59 59
60 60
61 61 .. parsed-literal::
62 62
63 63 The IPython notebook is great!
64 64
65 65 Plots with matplotlib
66 66 ---------------------
67 67
68 68 IPython adds an 'inline' matplotlib backend, which embeds any matplotlib
69 69 figures into the notebook.
70 70
71 71 In[4]:
72 72
73 73 .. code:: python
74 74
75 75 %pylab inline
76 76
77 77
78 78 .. parsed-literal::
79 79
80 80
81 81 Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
82 82 For more information, type 'help(pylab)'.
83 83
84 84 In[5]:
85 85
86 86 .. code:: python
87 87
88 88 x = linspace(0, 3*pi, 500)
89 89 plot(x, sin(x**2))
90 90 title('A simple chirp');
91 91
92 92 .. image:: _fig_07.png
93 93
94 94 You can paste blocks of input with prompt markers, such as those from
95 95 `the official Python
96 96 tutorial <http://docs.python.org/tutorial/interpreter.html#interactive-mode>`_
97 97
98 98 In[6]:
99 99
100 100 .. code:: python
101 101
102 102 >>> the_world_is_flat = 1
103 103 >>> if the_world_is_flat:
104 104 ... print "Be careful not to fall off!"
105 105
106 106
107 107 .. parsed-literal::
108 108
109 109 Be careful not to fall off!
110 110
111 111 Errors are shown in informative ways:
112 112
113 113 In[7]:
114 114
115 115 .. code:: python
116 116
117 117 %run non_existent_file
118 118
119 119
120 120 .. parsed-literal::
121 121
122 122 ERROR: File `u'non_existent_file.py'` not found.
123 123 In[8]:
124 124
125 125 .. code:: python
126 126
127 127 x = 1
128 128 y = 4
129 129 z = y/(1-x)
130 130
131 131 ::
132 132
133 133 ---------------------------------------------------------------------------
134 134 ZeroDivisionError Traceback (most recent call last)
135 135 <ipython-input-8-dc39888fd1d2> in <module>()
136 136 1 x = 1
137 137 2 y = 4
138 138 ----> 3 z = y/(1-x)
139 139
140 140 ZeroDivisionError: integer division or modulo by zero
141 141 When IPython needs to display additional information (such as providing
142 142 details on an object via ``x?`` it will automatically invoke a pager at
143 143 the bottom of the screen:
144 144
145 145 In[18]:
146 146
147 147 .. code:: python
148 148
149 149 magic
150 150
151 151 Non-blocking output of kernel
152 152 -----------------------------
153 153
154 154 If you execute the next cell, you will see the output arriving as it is
155 155 generated, not all at the end.
156 156
157 157 In[19]:
158 158
159 159 .. code:: python
160 160
161 161 import time, sys
162 162 for i in range(8):
163 163 print i,
164 164 time.sleep(0.5)
165 165
166 166
167 167 .. parsed-literal::
168 168
169 169 0 1 2 3 4 5 6 7
170 170
171 171 Clean crash and restart
172 172 -----------------------
173 173
174 174 We call the low-level system libc.time routine with the wrong argument
175 175 via ctypes to segfault the Python interpreter:
176 176
177 177 In[*]:
178 178
179 179 .. code:: python
180 180
181 181 import sys
182 182 from ctypes import CDLL
183 183 # This will crash a Linux or Mac system; equivalent calls can be made on Windows
184 184 dll = 'dylib' if sys.platform == 'darwin' else '.so.6'
185 185 libc = CDLL("libc.%s" % dll)
186 186 libc.time(-1) # BOOM!!
187 187
188 188 Markdown cells can contain formatted text and code
189 189 --------------------------------------------------
190 190
191 191 You can *italicize*, **boldface**
192 192
193 193 - build
194 194 - lists
195 195
196 196 and embed code meant for illustration instead of execution in Python:
197 197
198 198 ::
199 199
200 200 def f(x):
201 201 """a docstring"""
202 202 return x**2
203 203
204 204 or other languages:
205 205
206 206 ::
207 207
208 208 if (i=0; i<n; i++) {
209 209 printf("hello %d\n", i);
210 210 x += 4;
211 211 }
212 212
213 213
214 214 Courtesy of MathJax, you can include mathematical expressions both
215 215 inline: :math:`e^{i\pi} + 1 = 0` and displayed:
216 216
217 217 .. math:: e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i
218 218
219 219
220 220
221 221 Rich displays: include anyting a browser can show
222 222 -------------------------------------------------
223 223
224 224 Note that we have an actual protocol for this, see the
225 225 ``display_protocol`` notebook for further details.
226 226
227 227 Images
228 228 ~~~~~~
229 229
230 230
231 231 In[1]:
232 232
233 233 .. code:: python
234 234
235 235 from IPython.display import Image
236 236 Image(filename='../../source/_static/logo.png')
237 237
238 238 Out[1]:
239 239 .. image:: _fig_22.png
240 240
241 241
242 242 An image can also be displayed from raw data or a url
243 243
244 244 In[2]:
245 245
246 246 .. code:: python
247 247
248 248 Image(url='http://python.org/images/python-logo.gif')
249 249
250 250 Out[2]:
251 251 .. parsed-literal::
252 252
253 253 <IPython.core.display.Image at 0x1060e7410>
254 254
255 255
256 256 SVG images are also supported out of the box (since modern browsers do a
257 257 good job of rendering them):
258 258
259 259 In[3]:
260 260
261 261 .. code:: python
262 262
263 263 from IPython.display import SVG
264 264 SVG(filename='python-logo.svg')
265 265
266 266 Out[3]:
267 267 .. image:: _fig_26.svg
268 268
269 269
270 270 Embedded vs Non-embedded Images
271 271 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
272 272
273 273
274 274 As of IPython 0.13, images are embedded by default for compatibility
275 275 with QtConsole, and the ability to still be displayed offline.
276 276
277 277 Let's look at the differences:
278 278
279 279 In[4]:
280 280
281 281 .. code:: python
282 282
283 283 # by default Image data are embedded
284 284 Embed = Image( 'http://scienceview.berkeley.edu/view/images/newview.jpg')
285 285
286 286 # if kwarg `url` is given, the embedding is assumed to be false
287 287 SoftLinked = Image(url='http://scienceview.berkeley.edu/view/images/newview.jpg')
288 288
289 289 # In each case, embed can be specified explicitly with the `embed` kwarg
290 290 # ForceEmbed = Image(url='http://scienceview.berkeley.edu/view/images/newview.jpg', embed=True)
291 291
292 292 Today's image from a webcam at Berkeley, (at the time I created this
293 293 notebook). This should also work in the Qtconsole. Drawback is that the
294 294 saved notebook will be larger, but the image will still be present
295 295 offline.
296 296
297 297 In[5]:
298 298
299 299 .. code:: python
300 300
301 301 Embed
302 302
303 303 Out[5]:
304 304 ..jpg image::
305 305
306 306
307 307 Today's image from same webcam at Berkeley, (refreshed every minutes, if
308 308 you reload the notebook), visible only with an active internet
309 309 connexion, that should be different from the previous one. This will not
310 310 work on Qtconsole. Notebook saved with this kind of image will be
311 311 lighter and always reflect the current version of the source, but the
312 312 image won't display offline.
313 313
314 314 In[6]:
315 315
316 316 .. code:: python
317 317
318 318 SoftLinked
319 319
320 320 Out[6]:
321 321 .. parsed-literal::
322 322
323 323 <IPython.core.display.Image at 0x10fb99b10>
324 324
325 325
326 326 Of course, if you re-run the all notebook, the two images will be the
327 327 same again.
328 328
329 329 Video
330 330 ~~~~~
331 331
332 332
333 333 And more exotic objects can also be displayed, as long as their
334 334 representation supports the IPython display protocol.
335 335
336 336 For example, videos hosted externally on YouTube are easy to load (and
337 337 writing a similar wrapper for other hosted content is trivial):
338 338
339 339 In[7]:
340 340
341 341 .. code:: python
342 342
343 343 from IPython.display import YouTubeVideo
344 344 # a talk about IPython at Sage Days at U. Washington, Seattle.
345 345 # Video credit: William Stein.
346 346 YouTubeVideo('1j_HxD4iLn8')
347 347
348 348 Out[7]:
349 349 .. parsed-literal::
350 350
351 351 <IPython.lib.display.YouTubeVideo at 0x10fba2190>
352 352
353 353
354 354 Using the nascent video capabilities of modern browsers, you may also be
355 355 able to display local videos. At the moment this doesn't work very well
356 356 in all browsers, so it may or may not work for you; we will continue
357 357 testing this and looking for ways to make it more robust.
358 358
359 359 The following cell loads a local file called ``animation.m4v``, encodes
360 360 the raw video as base64 for http transport, and uses the HTML5 video tag
361 361 to load it. On Chrome 15 it works correctly, displaying a control bar at
362 362 the bottom with a play/pause button and a location slider.
363 363
364 364 In[8]:
365 365
366 366 .. code:: python
367 367
368 368 from IPython.display import HTML
369 369 video = open("animation.m4v", "rb").read()
370 370 video_encoded = video.encode("base64")
371 371 video_tag = '<video controls alt="test" src="data:video/x-m4v;base64,{0}">'.format(video_encoded)
372 372 HTML(data=video_tag)
373 373
374 374 Out[8]:
375 375 .. parsed-literal::
376 376
377 377 <IPython.core.display.HTML at 0x10fba28d0>
378 378
379 379
380 380 Local Files
381 381 -----------
382 382
383 383 The above examples embed images and video from the notebook filesystem
384 384 in the output areas of code cells. It is also possible to request these
385 385 files directly in markdown cells if they reside in the notebook
386 386 directory via relative urls prefixed with ``files/``:
387 387
388 388 ::
389 389
390 390 files/[subdirectory/]<filename>
391 391
392 392 For example, in the example notebook folder, we have the Python logo,
393 393 addressed as:
394 394
395 395 ::
396 396
397 397 <img src="files/python-logo.svg" />
398 398
399 399 and a video with the HTML5 video tag:
400 400
401 401 ::
402 402
403 403 <video controls src="files/animation.m4v" />
404 404
405 405 These do not embed the data into the notebook file, and require that the
406 406 files exist when you are viewing the notebook.
407 407
408 408 Security of local files
409 409 ~~~~~~~~~~~~~~~~~~~~~~~
410 410
411 411 Note that this means that the IPython notebook server also acts as a
412 412 generic file server for files inside the same tree as your notebooks.
413 413 Access is not granted outside the notebook folder so you have strict
414 414 control over what files are visible, but for this reason it is highly
415 415 recommended that you do not run the notebook server with a notebook
416 416 directory at a high level in your filesystem (e.g. your home directory).
417 417
418 418 When you run the notebook in a password-protected manner, local file
419 419 access is restricted to authenticated users unless read-only views are
420 420 active.
421 421
422 422 Linking to files and directories for viewing in the browser
423 423 -----------------------------------------------------------
424 424
425 425 It is also possible to link directly to files or directories so they can
426 426 be opened in the browser. This is especially convenient if you're
427 427 interacting with a tool within IPython that generates HTML pages, and
428 428 you'd like to easily be able to open those in a new browser window.
429 429 Alternatively, if your IPython notebook server is on a remote system,
430 430 creating links provides an easy way to download any files that get
431 431 generated.
432 432
433 433 As we saw above, there are a bunch of ``.ipynb`` files in our current
434 434 directory.
435 435
436 436 In[1]:
437 437
438 438 .. code:: python
439 439
440 440 ls
441 441
442 442
443 443 .. parsed-literal::
444 444
445 445 00_notebook_tour.ipynb formatting.ipynb
446 446 01_notebook_introduction.ipynb octavemagic_extension.ipynb
447 447 Animations_and_Progress.ipynb publish_data.ipynb
448 448 Capturing Output.ipynb python-logo.svg
449 449 Script Magics.ipynb rmagic_extension.ipynb
450 450 animation.m4v sympy.ipynb
451 451 cython_extension.ipynb sympy_quantum_computing.ipynb
452 452 display_protocol.ipynb trapezoid_rule.ipynb
453 453
454 454 If we want to create a link to one of them, we can call use the
455 455 ``FileLink`` object.
456 456
457 457 In[2]:
458 458
459 459 .. code:: python
460 460
461 461 from IPython.display import FileLink
462 462 FileLink('00_notebook_tour.ipynb')
463 463
464 464 Out[2]:
465 465 .. parsed-literal::
466 466
467 467 <IPython.lib.display.FileLink at 0x10f7ea3d0>
468 468
469 469
470 470 Alternatively, if we want to link to all of them, we can use the
471 471 ``FileLinks`` object, passing ``'.'`` to indicate that we want links
472 472 generated for the current working directory. Note that if there were
473 473 other directories under the current directory, ``FileLinks`` would work
474 474 in a recursive manner creating links to files in all sub-directories as
475 475 well.
476 476
477 477 In[7]:
478 478
479 479 .. code:: python
480 480
481 481 from IPython.display import FileLinks
482 482 FileLinks('.')
483 483
484 484 Out[7]:
485 485 .. parsed-literal::
486 486
487 487 <IPython.lib.display.FileLinks at 0x10f7eaad0>
488 488
489 489
490 490 External sites
491 491 ~~~~~~~~~~~~~~
492 492
493 493 You can even embed an entire page from another site in an iframe; for
494 494 example this is today's Wikipedia page for mobile users:
495 495
496 496 In[9]:
497 497
498 498 .. code:: python
499 499
500 500 HTML('<iframe src=http://en.mobile.wikipedia.org/?useformat=mobile width=700 height=350></iframe>')
501 501
502 502 Out[9]:
503 503 .. parsed-literal::
504 504
505 505 <IPython.core.display.HTML at 0x1094900d0>
506 506
507 507
508 508 Mathematics
509 509 ~~~~~~~~~~~
510 510
511 511 And we also support the display of mathematical expressions typeset in
512 512 LaTeX, which is rendered in the browser thanks to the `MathJax
513 513 library <http://mathjax.org>`_.
514 514
515 515 Note that this is *different* from the above examples. Above we were
516 516 typing mathematical expressions in Markdown cells (along with normal
517 517 text) and letting the browser render them; now we are displaying the
518 518 output of a Python computation as a LaTeX expression wrapped by the
519 519 ``Math()`` object so the browser renders it. The ``Math`` object will
520 520 add the needed LaTeX delimiters (``$$``) if they are not provided:
521 521
522 522 In[10]:
523 523
524 524 .. code:: python
525 525
526 526 from IPython.display import Math
527 527 Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
528 528
529 529 Out[10]:
530 530 .. math::
531 531
532 532 $$F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$$
533 533
534 534
535 535 With the ``Latex`` class, you have to include the delimiters yourself.
536 536 This allows you to use other LaTeX modes such as ``eqnarray``:
537 537
538 538 In[11]:
539 539
540 540 .. code:: python
541 541
542 542 from IPython.display import Latex
543 543 Latex(r"""\begin{eqnarray}
544 544 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
545 545 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
546 546 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
547 547 \nabla \cdot \vec{\mathbf{B}} & = 0
548 548 \end{eqnarray}""")
549 549
550 550 Out[11]:
551 551 .. math::
552 552
553 553 \begin{eqnarray}
554 554 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
555 555 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
556 556 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
557 557 \nabla \cdot \vec{\mathbf{B}} & = 0
558 558 \end{eqnarray}
559 559
560 560
561 561 Or you can enter latex directly with the ``%%latex`` cell magic:
562 562
563 563 In[12]:
564 564
565 565 .. code:: python
566 566
567 567 %%latex
568 568 \begin{aligned}
569 569 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
570 570 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
571 571 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
572 572 \nabla \cdot \vec{\mathbf{B}} & = 0
573 573 \end{aligned}
574 574
575 575 .. math::
576 576
577 577 \begin{aligned}
578 578 \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
579 579 \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
580 580 \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
581 581 \nabla \cdot \vec{\mathbf{B}} & = 0
582 582 \end{aligned}
583 583
584 584 There is also a ``%%javascript`` cell magic for running javascript
585 585 directly, and ``%%svg`` for manually entering SVG content.
586 586
587 587 Loading external codes
588 588 ======================
589 589
590 590 - Drag and drop a ``.py`` in the dashboard
591 591 - Use ``%load`` with any local or remote url: `the Matplotlib
592 592 Gallery! <http://matplotlib.sourceforge.net/gallery.html>`_
593 593
594 594 In this notebook we've kept the output saved so you can see the result,
595 595 but you should run the next cell yourself (with an active internet
596 596 connection).
597 597
598 598 Let's make sure we have pylab again, in case we have restarted the
599 599 kernel due to the crash demo above
600 600
601 601 In[12]:
602 602
603 603 .. code:: python
604 604
605 605 %pylab inline
606 606
607 607
608 608 .. parsed-literal::
609 609
610 610
611 611 Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
612 612 For more information, type 'help(pylab)'.
613 613
614 614 In[15]:
615 615
616 616 .. code:: python
617 617
618 618 %load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py
619 619
620 620 In[16]:
621 621
622 622 .. code:: python
623 623
624 624 #!/usr/bin/env python
625 625
626 626 # implement the example graphs/integral from pyx
627 627 from pylab import *
628 628 from matplotlib.patches import Polygon
629 629
630 630 def func(x):
631 631 return (x-3)*(x-5)*(x-7)+85
632 632
633 633 ax = subplot(111)
634 634
635 635 a, b = 2, 9 # integral area
636 636 x = arange(0, 10, 0.01)
637 637 y = func(x)
638 638 plot(x, y, linewidth=1)
639 639
640 640 # make the shaded region
641 641 ix = arange(a, b, 0.01)
642 642 iy = func(ix)
643 643 verts = [(a,0)] + zip(ix,iy) + [(b,0)]
644 644 poly = Polygon(verts, facecolor='0.8', edgecolor='k')
645 645 ax.add_patch(poly)
646 646
647 647 text(0.5 * (a + b), 30,
648 648 r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center',
649 649 fontsize=20)
650 650
651 651 axis([0,10, 0, 180])
652 652 figtext(0.9, 0.05, 'x')
653 653 figtext(0.1, 0.9, 'y')
654 654 ax.set_xticks((a,b))
655 655 ax.set_xticklabels(('a','b'))
656 656 ax.set_yticks([])
657 657 show()
658 658
659 659
660 660 .. image:: _fig_60.png
661
General Comments 0
You need to be logged in to leave comments. Login now