#!/usr/bin/env python # coding: utf-8 # # An introduction to the Jupyther Notebook (formerly known as IPython notebook) # In[1]: import addutils.toc ; addutils.toc.js(ipy_notebook=True) # In[2]: from addutils import css_notebook css_notebook() # ## 1 Before starting... # The Jupyter Notebook is an interactive computing environment that enables users to author notebook documents that include: # # * Live code # * Interactive widgets # * Plots # * Narrative text # * Equations # * Images # * Video # # These documents provide a complete and self-contained record of a computation that can be converted to various formats and shared with others using email, [Dropbox](http://dropbox.com), version control systems (like git/[GitHub](http://github.com)) or [nbviewer.jupyter.org](http://nbviewer.jupyter.org). # # To find more documentation and examples check the follwing links: # # * [Jupyter Project page](http://jupyter.org/) # * [Jupyther Documentation](http://jupyter.readthedocs.org/en/latest/) # * [Notebook Gallery](http://nb.bianp.net/sort/views/) # # The document you are reading now is precisely an example of one such notebook, and we will show you here how to best use this new interface. The first thing to understand is that a notebook consists of a sequence of 'cells' that can contain either text or code meant for execution: # # * Text cells can be written using [Markdown syntax](http://daringfireball.net/projects/markdown/syntax) (in a future release there will be support for reStructuredText and Sphinx integration). # * Code cells take IPython input (i.e. Python code, `%magics, !system calls`, etc). When you type `Shift-Enter`, the cell content is executed, output displayed and a new cell is created below. **Try it now** by putting your cursor on the next cell and typing `Shift-Enter`: # In[3]: print ('This is the new IPython notebook') # *You can re-execute the same cell over and over as many times as you want.* Simply put your # cursor in the cell again, edit at will, and type `Shift-Enter` to execute. # # **Tip:** A cell can also be executed # *in-place*, where IPython executes its content but leaves the cursor in the same cell. This is done by # typing `Ctrl-Enter` instead, and is useful if you want to quickly run a command to check something # before typing the real content you want to leave in the cell. For example, in the next cell, try issuing # several system commands in-place with `Ctrl-Enter`, such as `pwd` and then `ls`: # In[4]: pwd # In a cell, you can type anything from a single python expression to an arbitrarily long amount of code # (although for reasons of readability, you should probably limit this to a few dozen lines): # In[5]: def f(x): '''My function description''' return x+6 value = 3 print ('f({0:.2f})= {0:.2f}'.format(value, f(value))) # ### 1.1 Kernels # The Notebook allows code to be run in a range of different programming languages. For each notebook document that a user opens, the web application starts a kernel that runs the code for that notebook. Each kernel is capable of running code in a single programming language and there are kernels available in the following languages: # # * Python(https://github.com/ipython/ipython) # * Julia (https://github.com/JuliaLang/IJulia.jl) # * R (https://github.com/takluyver/IRkernel) # * Ruby (https://github.com/minrk/iruby) # * Haskell (https://github.com/gibiansky/IHaskell) # * Scala (https://github.com/Bridgewater/scala-notebook) # * node.js (https://gist.github.com/Carreau/4279371) # * Go (https://github.com/takluyver/igo) # # The default kernel runs Python code. The notebook provides a simple way for users to pick which of these kernels is used for a given notebook. # # Each of these kernels communicate with the notebook web application and web browser using a JSON over ZeroMQ/WebSockets message protocol. # ## 2 User interface # When you start a new notebook server with `ipython notebook`, your # browser should open into the *Dashboard*, a page listing all notebooks # available in the current directory, which allow to create new # notebooks. In this page, you can also drag and drop existing `.py` files # over the file list to import them as notebooks (see the manual for # [further details on how these files are # interpreted](http://ipython.org/ipython-doc/stable/interactive/htmlnotebook.html)). # # Once you open an existing notebook (like this one) or create a new one, # you are in the main notebook interface, which consists of a main editing # area (where these cells are contained) as well as a menu and # permanent header area at the top, and a pager that rises from the # bottom when needed and can be collapsed again. # ### 2.1 Main editing area # Here, you can move with the arrow keys or use the # scroll bars. The cursor enters code cells immediately, but only selects # text (markdown) cells without entering them; to enter a text cell, # use `Enter` (or double-click), and `Shift-Enter` to exit it again (just like executing a # code cell). # ### 2.2 Menu # The menu bar contains all the commands you can use to manipulate the notebook. # # * The ***File*** menu has the usual open/save file operations, as well as Export, for downloading the notebook to your computer. # * ***Edit*** has controls for cut/copy/paste. # * ***View*** lets you toggle visibility of the header elements. # * The ***Cell*** menu lets you manipulate individual cells. # * The ***Kernel*** menu lets you signal the kernel executing your code. # `Interrupt` stops the running computation while # `Restart` fully kills the kernel and starts a fresh one. Obviously this means that all your previous variables are destroyed, but it also makes it easy to get a fresh kernel in which to re-execute a notebook, perhaps after changing an extension module for which Python's `reload` mechanism does not work. # * The ***Help*** menu contains links to the documentation of some projects closely related to IPython as well as the minimal keybindings you need to know. You should use `Ctrl-m h` (or click the `QuickHelp` button at # the top) to show keybindings. # * You will also see a ***few buttons*** there for common actions, and hovering over each button will tell you which command they correspond to, if the icons are not clear enough. # ### 2.3 Help and Keyboard Shortcuts # Go to **Help -> Keyboard Shortcuts** to see the complete shortcuts list # To access the help system symply type `help()` in a code cell. Use `quit` to finish: # In[6]: help() # ### 2.4 Header bar # The header area at the top allows you to rename an existing notebook. This area also indicates whenever the kernel is busy executing code. # ### 2.5 The pager at the bottom # Whenever IPython needs to display additional information, such as when you type `somefunction?` in a cell, the notebook # opens a pane at the bottom. You can keep this pager pane open for reference (it doesn't block input in the main area) or dismiss it by clicking on its divider bar. Try this: # In[7]: get_ipython().run_line_magic('pinfo2', 'print') # ## 3 Tab completion and tooltips # Whey you complete with the `Tab` key, IPython shows a drop list with all available completions. If you type more characters while this list is open, IPython automatically refines the search; once there is only one option left you can hit `Tab` once more (or `Enter`) to complete. You can also select the completion you want with the arrow keys or the mouse, and then hit `Enter`. # # In addition, if you hit `Tab` inside of open parentheses, IPython will search for the docstring of the last object left of the parens and will display it on a tooltip. For example, type `list(` and you will see the docstring for the builtin `list` constructor. Moreover, pressing tab several time in a row allows you change the behaviour of the tooltip: # In[8]: # Remove comment, then position your cursor after the ( and hit the Tab key: #list( # ## 4 Plotting support # You can enable inline plotting with `%pylab inline`: # In[9]: import numpy as np import bokeh.plotting as bk bk.output_notebook() # In[10]: # NOTICE: In Jupyter and Python3 you can use UNICODE identifiers as variable names. # Example: just type \alpha and press β = np.linspace(0, 3*np.pi, 700) fig = bk.figure(title="A simple Chirp", plot_width = 700, plot_height = 300) fig.title.text_font_size="18pt" fig.line(β, np.sin(β**2), line_width=2, line_color='magenta') bk.show(fig) # ## 5 Interactive Widgets # IPython comes with basic widgets that represent common interactive controls. # ### 5.1 Plot controlled by Widgets # In[11]: import ipywidgets from ipywidgets import interact # Here "interact" is used as a decorator: @interact(n=(2.0,30.0), lw=(0.5, 10.0, 0.5), c=(['blue', 'green', 'red'])) def edit_myplot(n=2.0, lw=1.0, c='blue'): fig = bk.figure(title="An interactive Chirp", plot_width = 700, plot_height = 300) fig.title.text_font_size="18pt" fig.line(β, np.sin(β**n), line_width=lw, line_color=c) bk.show(fig) return # ### 5.2 Factorization Example using Interactive Widgets and SimPy # In[12]: from IPython.display import display from sympy import Symbol, Eq, factor, init_printing init_printing(use_latex='mathjax') # In[13]: def factorit(n): x = Symbol('x') display(Eq(x**n-1, factor(x**n-1))) # In[14]: interact(factorit, n=(2,60)); # ## 6 Markdown cells can contain formatted text and code # You can *italicize*, **boldface** or `typewrite` text # # * build # * lists # # and embed code meant for illustration instead of execution in Python: # # def f(x): # """a docstring""" # return x**2 # # or other languages: # # if (i=0; i') # ## 8 Loading external codes # * Drag and drop a ``.py`` in the dashboard # * Use ``%load`` with any local or remote url: [the Matplotlib Gallery!](http://matplotlib.sourceforge.net/gallery.html) # # In this notebook we've kept the output saved so you can see the result, remove the comment `#` and run the next cell (with an active internet connection). # In[17]: get_ipython().run_line_magic('matplotlib', 'inline') # In[18]: # %load http://matplotlib.org/mpl_examples/pie_and_polar_charts/polar_scatter_demo.py # In[19]: """ Demo of scatter plot on a polar axis. Size increases radially in this example and color increases with angle (just to verify the symbols are being scattered correctly). """ import numpy as np import matplotlib.pyplot as plt N = 150 r = 2 * np.random.rand(N) theta = 2 * np.pi * np.random.rand(N) area = 200 * r**2 * np.random.rand(N) colors = theta ax = plt.subplot(111, polar=True) c = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.hsv) c.set_alpha(0.75) plt.show() # --- # # Visit [www.add-for.com]() for more tutorials and updates. # # This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.