Поиск по блогу

вторник, 4 марта 2014 г.

IPython's Rich Display System (6) "IPython in Depth, SciPy2013 Tutorial, Part 2 of 3"

На 60-ой минуте речь зашла о "from IPython.display import display" ... получился длиннющий пост. Разбираем images, video, HTML, Javascript, Pandas, SymPy, Iframe, Latex... Примеров много, скрипты javascript читают и записывают файлы..., строят SVG картинку ... впечатляет импорт аудиоплеера.
In Python, objects can declare their textual representation using the __repr__ method. IPython expands on this idea and allows objects to declare other, richer 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 [10]:
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 []:
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 [6]:
from IPython.display import Image
In [7]:
i = Image(filename='figs/logo.png')
Returning an Image object from an expression will automatically display it:
In [8]:
i
Out[8]:
Or you can pass it to display:
In [11]:
display(i)
An image can also be displayed from raw data or a url
In [14]:
Image(url='http://www.python.org/static/community_logos/python-logo-master-v3-TM.png')
Out[14]:
When you display an image from a URL, the image data will not be embedded in the Notebook file. This means you will have to re-run that cell to see the image again. You can override this behavior by setting embed=True:
In [15]:
Image(url='http://www.python.org/static/community_logos/python-logo-master-v3-TM.png', embed=True)
Out[15]:
SVG images are also supported out of the box (since modern browsers do a good job of rendering them):
In [16]:
from IPython.display import SVG
SVG(filename='figs/python-logo.svg')
Out[16]:
image/svg+xml

Exercise

Find an image online and use IPython's Image class to embed it in a Notebook using its URL. Then try downloading the image into your Notebook directory and embedding it by filename.

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 (and writing a similar wrapper for other hosted content is trivial):
In []:
from IPython.display import YouTubeVideo
YouTubeVideo('sjfsUzECqK0')

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 [18]:
from IPython.display import HTML
In [19]:
s = """<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>"""
In [20]:
h = HTML(s)
h
Out[20]:
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
If you want to write HTML or Javascript straight to the frontend, you can use %%html or %%javascript cell magics.
These are exactly the same as writing display(HTML("""cell contents""")), etc.
In [17]:
%%html
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

JavaScript

In [2]:
from IPython.display import Javascript
In [3]:
# fetch d3 from cloudflare
Javascript("""$.getScript('//cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')""")
Out[3]:
<IPython.core.display.Javascript at 0x7f0b748>
In [4]:
%%html
<style type="text/css">

circle {
  fill: rgb(31, 119, 180);
  fill-opacity: .25;
  stroke: rgb(31, 119, 180);
  stroke-width: 1px;
}

.leaf circle {
  fill: #ff7f0e;
  fill-opacity: 1;
}

text {
  font: 10px sans-serif;
}

</style>
In [5]:
%%javascript
// This unhides the output area
container.show();

// element is the jQuery element we will append to
var e = element.get(0);
    
var diameter = 600,
    format = d3.format(",d");

var pack = d3.layout.pack()
    .size([diameter - 4, diameter - 4])
    .value(function(d) { return d.size; });

var svg = d3.select(e).append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
  .append("g")
    .attr("transform", "translate(2,2)");

d3.json("files/flare.json", function(error, root) {
  var node = svg.datum(root).selectAll(".node")
      .data(pack.nodes)
    .enter().append("g")
      .attr("class", function(d) { return d.children ? "node" : "leaf node"; })
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
      .text(function(d) { return d.name + (d.children ? "" : ": " + format(d.size)); });

  node.append("circle")
      .attr("r", function(d) { return d.r; });

  node.filter(function(d) { return !d.children; }).append("text")
      .attr("dy", ".3em")
      .style("text-anchor", "middle")
      .text(function(d) { return d.name.substring(0, d.r / 3); });
});

d3.select(self.frameElement).style("height", diameter + "px");
<IPython.core.display.Javascript at 0x7f0b4a8>

Pandas

Pandas makes use of this capability to allow DataFrames to be represented as HTML tables.
In [21]:
import pandas
By default, DataFrames will be represented as text; to enable HTML representations we need to set a print option:
In [22]:
pandas.set_option('display.notebook_repr_html', True)
Here is a small amount of stock data for APPL:
In [23]:
%%writefile data.csv
Date,Open,High,Low,Close,Volume,Adj Close
2012-06-01,569.16,590.00,548.50,584.00,14077000,581.50
2012-05-01,584.90,596.76,522.18,577.73,18827900,575.26
2012-04-02,601.83,644.00,555.00,583.98,28759100,581.48
2012-03-01,548.17,621.45,516.22,599.55,26486000,596.99
2012-02-01,458.41,547.61,453.98,542.44,22001000,540.12
2012-01-03,409.40,458.24,409.00,456.48,12949100,454.53
Writing data.csv

Read this as into a DataFrame:
In [24]:
df = pandas.read_csv('data.csv')
And view the HTML representation:
In [25]:
df
Out[25]:
Date Open High Low Close Volume Adj Close
0 2012-06-01 569.16 590.00 548.50 584.00 14077000 581.50
1 2012-05-01 584.90 596.76 522.18 577.73 18827900 575.26
2 2012-04-02 601.83 644.00 555.00 583.98 28759100 581.48
3 2012-03-01 548.17 621.45 516.22 599.55 26486000 596.99
4 2012-02-01 458.41 547.61 453.98 542.44 22001000 540.12
5 2012-01-03 409.40 458.24 409.00 456.48 12949100 454.53
6 rows × 7 columns

SymPy

In [26]:
from sympy.interactive.printing import init_printing
init_printing()
In [27]:
from __future__ import division
import sympy as sym
from sympy import *
x, y, z = symbols("x y z")
k, m, n = symbols("k m n", integer=True)
f, g, h = map(Function, 'fgh')
In [29]:
Rational(3,2)*pi + exp(I*x) / (x**2 + y)
Out[29]:
$$\frac{3 \pi}{2} + \frac{e^{i x}}{x^{2} + y}$$
Out[29]:
$$\frac{3 \pi}{2} + \frac{e^{i x}}{x^{2} + y}$$
In [31]:
a = 1/x + (x*sin(x) - 1)/x
a
Out[31]:
$$\frac{1}{x} \left(x \sin{\left (x \right )} - 1\right) + \frac{1}{x}$$
Out[31]:
$$\frac{1}{x} \left(x \sin{\left (x \right )} - 1\right) + \frac{1}{x}$$
In [32]:
(1/cos(x)).series(x, 0, 6)
Out[32]:
$$1 + \frac{x^{2}}{2} + \frac{5 x^{4}}{24} + \mathcal{O}\left(x^{6}\right)$$

External sites

You can even embed an entire page from another site in an iframe; for example this is today's Wikipedia page for mobile users:
In [33]:
from IPython.display import IFrame
In [34]:
IFrame('http://euroscipy.org',700,350)
Out[34]:

Exercise

Go to SoundCloud and search for a sound clip you want to embed in your Notebook. To find the HTML code to embed the sound, click on the "Share" link and copy the "Widget" HTML. Then paste it into HTML(""" """) in a Notebook cell.
In [35]:
%load soln/soundcloud.py
In [36]:
from IPython.display import HTML
h = HTML("""<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F94543639"></iframe>""")
display(h)

LaTeX

And we also support the display of mathematical expressions typeset in LaTeX, which is rendered in the browser thanks to the MathJax library.
In [37]:
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
Out[37]:
$$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 [38]:
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}""")
Out[38]:
\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}
In []:



Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий