#!/usr/bin/env python # coding: utf-8 # # Rich Output # In Python, objects can declare their textual representation using the `__repr__` method. IPython expands on this idea and allows objects to declare other, rich representations including: # # * HTML # * JSON # * PNG # * JPEG # * SVG # * LaTeX # # A single object can declare some or all of these representations; all are handled by IPython's *display system*. This Notebook shows how you can use this display system to incorporate a broad range of content into your Notebooks. # ## Basic display imports # The `display` function is a general purpose tool for displaying different representations of objects. Think of it as `print` for these rich representations. # In[1]: from IPython.display import display # A few points: # # * Calling `display` on an object will send **all** possible representations to the Notebook. # * These representations are stored in the Notebook document. # * In general the Notebook will use the richest available representation. # # If you want to display a particular representation, there are specific functions for that: # In[2]: from IPython.display import ( display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg ) # ## Images # To work with images (JPEG, PNG) use the `Image` class. # In[3]: from IPython.display import Image # In[4]: i = Image(filename='../images/ipython_logo.png') # Returning an `Image` object from an expression will automatically display it: # In[5]: i # Or you can pass an object with a rich representation to `display`: # In[6]: display(i) # An image can also be displayed from raw data or a URL. # In[7]: Image(url='http://python.org/images/python-logo.gif') # SVG images are also supported out of the box. # In[8]: from IPython.display import SVG SVG(filename='../images/python_logo.svg') # ### Embedded vs non-embedded Images # By default, image data is embedded in the notebook document so that the images can be viewed offline. However it is also possible to tell the `Image` class to only store a *link* to the image. Let's see how this works using a webcam at Berkeley. # In[9]: from IPython.display import Image img_url = 'http://www.lawrencehallofscience.org/static/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg' # by default Image data are embedded Embed = Image(img_url) # if kwarg `url` is given, the embedding is assumed to be false SoftLinked = Image(url=img_url) # In each case, embed can be specified explicitly with the `embed` kwarg # ForceEmbed = Image(url=img_url, embed=True) # Here is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image. # In[10]: Embed # Here is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one. Notebooks saved with this kind of image will be smaller and always reflect the current version of the source, but the image won't display offline. # In[11]: SoftLinked # Of course, if you re-run this Notebook, the two images will be the same again. # ## HTML # Python objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the `HTML` class. # In[12]: from IPython.display import HTML # In[13]: s = """
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
""" # In[14]: h = HTML(s) # In[15]: display(h) # You can also use the `%%html` cell magic to accomplish the same thing. # In[16]: get_ipython().run_cell_magic('html', '', '\n\n\n\n\n\n\n\n\n\n\n\n\n
Header 1Header 2
row 1, cell 1row 1, cell 2
row 2, cell 1row 2, cell 2
\n') # ## JavaScript # The Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as [d3.js](http://d3js.org) for output. # In[17]: from IPython.display import Javascript # Pass a string of JavaScript source code to the `JavaScript` object and then display it. # In[18]: js = Javascript('alert("hi")'); # In[19]: display(js) # The same thing can be accomplished using the `%%javascript` cell magic: # In[20]: get_ipython().run_cell_magic('javascript', '', '\nalert("hi");\n') # Here is a more complicated example that loads `d3.js` from a CDN, uses the `%%html` magic to load CSS styles onto the page and then runs ones of the `d3.js` examples. # In[21]: Javascript( """$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')""" ) # In[22]: get_ipython().run_cell_magic('html', '', '\n') # In[23]: get_ipython().run_cell_magic('javascript', '', '\n// element is the jQuery element we will append to\nvar e = element.get(0);\n \nvar diameter = 600,\n format = d3.format(",d");\n\nvar pack = d3.layout.pack()\n .size([diameter - 4, diameter - 4])\n .value(function(d) { return d.size; });\n\nvar svg = d3.select(e).append("svg")\n .attr("width", diameter)\n .attr("height", diameter)\n .append("g")\n .attr("transform", "translate(2,2)");\n\nd3.json("data/flare.json", function(error, root) {\n var node = svg.datum(root).selectAll(".node")\n .data(pack.nodes)\n .enter().append("g")\n .attr("class", function(d) { return d.children ? "node" : "leaf node"; })\n .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });\n\n node.append("title")\n .text(function(d) { return d.name + (d.children ? "" : ": " + format(d.size)); });\n\n node.append("circle")\n .attr("r", function(d) { return d.r; });\n\n node.filter(function(d) { return !d.children; }).append("text")\n .attr("dy", ".3em")\n .style("text-anchor", "middle")\n .text(function(d) { return d.name.substring(0, d.r / 3); });\n});\n\nd3.select(self.frameElement).style("height", diameter + "px");\n') # ## LaTeX # The IPython display system also has builtin support for the display of mathematical expressions typeset in LaTeX, which is rendered in the browser using [MathJax](http://mathjax.org). # You can pass raw LaTeX test as a string to the `Math` object: # In[24]: from IPython.display import Math Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx') # With the `Latex` class, you have to include the delimiters yourself. This allows you to use other LaTeX modes such as `eqnarray`: # In[25]: from IPython.display import Latex Latex(r"""\begin{eqnarray} \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\ \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\ \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\ \nabla \cdot \vec{\mathbf{B}} & = 0 \end{eqnarray}""") # Or you can enter LaTeX directly with the `%%latex` cell magic: # In[26]: get_ipython().run_cell_magic('latex', '', '\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n') # ## Audio # IPython makes it easy to work with sounds interactively. The `Audio` display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the `Image` display class. All audio formats supported by the browser can be used. Note that no single format is presently supported in all browsers. # In[27]: from IPython.display import Audio Audio(url="http://www.nch.com.au/acm/8k16bitpcm.wav") # A NumPy array can be auralized automatically. The `Audio` class normalizes and encodes the data and embeds the resulting audio in the Notebook. # # For instance, when two sine waves with almost the same frequency are superimposed a phenomena known as [beats](https://en.wikipedia.org/wiki/Beat_%28acoustics%29) occur. This can be auralised as follows: # In[28]: import numpy as np max_time = 3 f1 = 220.0 f2 = 224.0 rate = 8000.0 L = 3 times = np.linspace(0,L,rate*L) signal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times) Audio(data=signal, rate=rate) # ## Video # More exotic objects can also be displayed, as long as their representation supports the IPython display protocol. For example, videos hosted externally on YouTube are easy to load: # In[29]: from IPython.display import YouTubeVideo YouTubeVideo('sjfsUzECqK0') # Using the nascent video capabilities of modern browsers, you may also be able to display local # videos. At the moment this doesn't work very well in all browsers, so it may or may not work for you; # we will continue testing this and looking for ways to make it more robust. # # The following cell loads a local file called `animation.m4v`, encodes the raw video as base64 for http # transport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control bar at the bottom with a play/pause button and a location slider. # In[30]: from IPython.display import HTML from base64 import b64encode video = open("../images/animation.m4v", "rb").read() video_encoded = b64encode(video).decode('ascii') video_tag = '