Show More
@@ -1,379 +1,378 | |||||
1 | { |
|
1 | { | |
2 |
|
|
2 | "metadata": { | |
3 |
|
|
3 | "name": "display_protocol" | |
4 |
|
|
4 | }, | |
5 |
|
|
5 | "nbformat": 2, | |
6 |
|
|
6 | "worksheets": [ | |
7 | { |
|
7 | { | |
8 |
|
|
8 | "cells": [ | |
9 | { |
|
9 | { | |
10 |
|
|
10 | "cell_type": "markdown", | |
11 |
|
|
11 | "source": [ | |
12 |
|
|
12 | "# Using the IPython display protocol for your own objects", | |
13 | "", |
|
13 | "", | |
14 |
|
|
14 | "IPython extends the idea of the ``__repr__`` method in Python to support multiple representations for a given", | |
15 |
|
|
15 | "object, which clients can use to display the object according to their capabilities. An object can return multiple", | |
16 |
|
|
16 | "representations of itself by implementing special methods, and you can also define at runtime custom display ", | |
17 |
|
|
17 | "functions for existing objects whose methods you can't or won't modify. In this notebook, we show how both approaches work.", | |
18 | "", |
|
18 | "", | |
19 |
|
|
19 | "<br/>", | |
20 |
|
|
20 | "**Note:** this notebook has had all output cells stripped out so we can include it in the IPython documentation with ", | |
21 |
|
|
21 | "a minimal file size. You'll need to manually execute the cells to see the output (you can run all of them with the ", | |
22 |
|
|
22 | "\"Run All\" button, or execute each individually). You must start this notebook with", | |
23 |
|
|
23 | "<pre>", | |
24 |
|
|
24 | "ipython notebook --pylab inline", | |
25 |
|
|
25 | "</pre>", | |
26 | "", |
|
26 | "", | |
27 |
|
|
27 | "to ensure pylab support is available for plots.", | |
28 | "", |
|
28 | "", | |
29 |
|
|
29 | "## Custom-built classes with dedicated ``_repr_*_`` methods", | |
30 | "", |
|
30 | "", | |
31 |
|
|
31 | "In our first example, we illustrate how objects can expose directly to IPython special representations of", | |
32 |
|
|
32 | "themselves, by providing methods such as ``_repr_svg_``, ``_repr_png_``, ``_repr_latex_``, etc. For a full", | |
33 |
|
|
33 | "list of the special ``_repr_*_`` methods supported, see the code in ``IPython.core.displaypub``.", | |
34 | "", |
|
34 | "", | |
35 |
|
|
35 | "As an illustration, we build a class that holds data generated by sampling a Gaussian distribution with given mean ", | |
36 |
|
|
36 | "and variance. The class can display itself in a variety of ways: as a LaTeX expression or as an image in PNG or SVG ", | |
37 |
|
|
37 | "format. Each frontend can then decide which representation it can handle.", | |
38 |
|
|
38 | "Further, we illustrate how to expose directly to the user the ability to directly access the various alternate ", | |
39 |
|
|
39 | "representations (since by default displaying the object itself will only show one, and which is shown will depend on the ", | |
40 |
|
|
40 | "required representations that even cache necessary data in cases where it may be expensive to compute.", | |
41 | "", |
|
41 | "", | |
42 |
|
|
42 | "The next cell defines the Gaussian class:" | |
43 | ] |
|
43 | ] | |
44 | }, |
|
44 | }, | |
45 | { |
|
45 | { | |
46 |
|
|
46 | "cell_type": "code", | |
47 |
|
|
47 | "collapsed": true, | |
48 |
|
|
48 | "input": [ | |
49 |
|
|
49 | "from IPython.lib.pylabtools import print_figure", | |
50 |
|
|
50 | "from IPython.core.display import Image, SVG, Math", | |
51 | "", |
|
51 | "", | |
52 |
|
|
52 | "class Gaussian(object):", | |
53 |
|
|
53 | " \"\"\"A simple object holding data sampled from a Gaussian distribution.", | |
54 |
|
|
54 | " \"\"\"", | |
55 |
|
|
55 | " def __init__(self, mean=0, std=1, size=1000):", | |
56 |
|
|
56 | " self.data = np.random.normal(mean, std, size)", | |
57 |
|
|
57 | " self.mean = mean", | |
58 |
|
|
58 | " self.std = std", | |
59 |
|
|
59 | " self.size = size", | |
60 |
|
|
60 | " # For caching plots that may be expensive to compute", | |
61 |
|
|
61 | " self._png_data = None", | |
62 |
|
|
62 | " self._svg_data = None", | |
63 |
|
|
63 | " ", | |
64 |
|
|
64 | " def _figure_data(self, format):", | |
65 |
|
|
65 | " fig, ax = plt.subplots()", | |
66 |
|
|
66 | " ax.plot(self.data, 'o')", | |
67 |
|
|
67 | " ax.set_title(self._repr_latex_())", | |
68 |
|
|
68 | " data = print_figure(fig, format)", | |
69 |
|
|
69 | " # We MUST close the figure, otherwise IPython's display machinery", | |
70 |
|
|
70 | " # will pick it up and send it as output, resulting in a double display", | |
71 |
|
|
71 | " plt.close(fig)", | |
72 |
|
|
72 | " return data", | |
73 |
|
|
73 | " ", | |
74 |
|
|
74 | " # Here we define the special repr methods that provide the IPython display protocol", | |
75 |
|
|
75 | " # Note that for the two figures, we cache the figure data once computed.", | |
76 |
|
|
76 | " ", | |
77 |
|
|
77 | " def _repr_png_(self):", | |
78 |
|
|
78 | " if self._png_data is None:", | |
79 |
|
|
79 | " self._png_data = self._figure_data('png')", | |
80 |
|
|
80 | " return self._png_data", | |
81 | "", |
|
81 | "", | |
82 | "", |
|
82 | "", | |
83 |
|
|
83 | " def _repr_svg_(self):", | |
84 |
|
|
84 | " if self._svg_data is None:", | |
85 |
|
|
85 | " self._svg_data = self._figure_data('svg')", | |
86 |
|
|
86 | " return self._svg_data", | |
87 |
|
|
87 | " ", | |
88 |
|
|
88 | " def _repr_latex_(self):", | |
89 |
|
|
89 | " return r'$\\mathcal{N}(\\mu=%.2g, \\sigma=%.2g),\\ N=%d$' % (self.mean,", | |
90 |
|
|
90 | " self.std, self.size)", | |
91 |
|
|
91 | " ", | |
92 |
|
|
92 | " # We expose as properties some of the above reprs, so that the user can see them", | |
93 |
|
|
93 | " # directly (since otherwise the client dictates which one it shows by default)", | |
94 |
|
|
94 | " @property", | |
95 |
|
|
95 | " def png(self):", | |
96 |
|
|
96 | " return Image(self._repr_png_(), embed=True)", | |
97 |
|
|
97 | " ", | |
98 |
|
|
98 | " @property", | |
99 |
|
|
99 | " def svg(self):", | |
100 |
|
|
100 | " return SVG(self._repr_svg_())", | |
101 |
|
|
101 | " ", | |
102 |
|
|
102 | " @property", | |
103 |
|
|
103 | " def latex(self):", | |
104 |
|
|
104 | " return Math(self._repr_svg_())", | |
105 |
|
|
105 | " ", | |
106 |
|
|
106 | " # An example of using a property to display rich information, in this case", | |
107 |
|
|
107 | " # the histogram of the distribution. We've hardcoded the format to be png", | |
108 |
|
|
108 | " # in this case, but in production code it would be trivial to make it an option", | |
109 |
|
|
109 | " @property", | |
110 |
|
|
110 | " def hist(self):", | |
111 |
|
|
111 | " fig, ax = plt.subplots()", | |
112 |
|
|
112 | " ax.hist(self.data, bins=100)", | |
113 |
|
|
113 | " ax.set_title(self._repr_latex_())", | |
114 |
|
|
114 | " data = print_figure(fig, 'png')", | |
115 |
|
|
115 | " plt.close(fig)", | |
116 |
|
|
116 | " return Image(data, embed=True)" | |
117 | ], |
|
117 | ], | |
118 |
|
|
118 | "language": "python", | |
119 |
|
|
119 | "outputs": [], | |
120 |
|
|
120 | "prompt_number": 1 | |
121 | }, |
|
121 | }, | |
122 | { |
|
122 | { | |
123 |
|
|
123 | "cell_type": "markdown", | |
124 |
|
|
124 | "source": [ | |
125 |
|
|
125 | "Now, we create an instance of the Gaussian distribution, whose default representation will be its LaTeX form:" | |
126 | ] |
|
126 | ] | |
127 | }, |
|
127 | }, | |
128 | { |
|
128 | { | |
129 |
|
|
129 | "cell_type": "code", | |
130 |
|
|
130 | "collapsed": false, | |
131 |
|
|
131 | "input": [ | |
132 |
|
|
132 | "x = Gaussian()", | |
133 | "x" |
|
133 | "x" | |
134 | ], |
|
134 | ], | |
135 |
|
|
135 | "language": "python", | |
136 |
|
|
136 | "outputs": [], | |
137 |
|
|
137 | "prompt_number": 2 | |
138 | }, |
|
138 | }, | |
139 | { |
|
139 | { | |
140 |
|
|
140 | "cell_type": "markdown", | |
141 |
|
|
141 | "source": [ | |
142 |
|
|
142 | "We can view the data in png or svg formats:" | |
143 | ] |
|
143 | ] | |
144 | }, |
|
144 | }, | |
145 | { |
|
145 | { | |
146 |
|
|
146 | "cell_type": "code", | |
147 |
|
|
147 | "collapsed": false, | |
148 |
|
|
148 | "input": [ | |
149 | "x.png" |
|
149 | "x.png" | |
150 | ], |
|
150 | ], | |
151 |
|
|
151 | "language": "python", | |
152 |
|
|
152 | "outputs": [], | |
153 |
|
|
153 | "prompt_number": 3 | |
154 | }, |
|
154 | }, | |
155 | { |
|
155 | { | |
156 |
|
|
156 | "cell_type": "code", | |
157 |
|
|
157 | "collapsed": false, | |
158 |
|
|
158 | "input": [ | |
159 | "x.svg" |
|
159 | "x.svg" | |
160 | ], |
|
160 | ], | |
161 |
|
|
161 | "language": "python", | |
162 |
|
|
162 | "outputs": [], | |
163 |
|
|
163 | "prompt_number": 4 | |
164 | }, |
|
164 | }, | |
165 | { |
|
165 | { | |
166 |
|
|
166 | "cell_type": "markdown", | |
167 |
|
|
167 | "source": [ | |
168 |
|
|
168 | "Since IPython only displays by default as an ``Out[]`` cell the result of the last computation, we can use the", | |
169 |
|
|
169 | "``display()`` function to show more than one representation in a single cell:" | |
170 | ] |
|
170 | ] | |
171 | }, |
|
171 | }, | |
172 | { |
|
172 | { | |
173 |
|
|
173 | "cell_type": "code", | |
174 |
|
|
174 | "collapsed": false, | |
175 |
|
|
175 | "input": [ | |
176 |
|
|
176 | "display(x.png)", | |
177 |
|
|
177 | "display(x.svg)" | |
178 | ], |
|
178 | ], | |
179 |
|
|
179 | "language": "python", | |
180 |
|
|
180 | "outputs": [], | |
181 |
|
|
181 | "prompt_number": 5 | |
182 | }, |
|
182 | }, | |
183 | { |
|
183 | { | |
184 |
|
|
184 | "cell_type": "markdown", | |
185 |
|
|
185 | "source": [ | |
186 |
|
|
186 | "Now let's create a new Gaussian with different parameters" | |
187 | ] |
|
187 | ] | |
188 | }, |
|
188 | }, | |
189 | { |
|
189 | { | |
190 |
|
|
190 | "cell_type": "code", | |
191 |
|
|
191 | "collapsed": false, | |
192 |
|
|
192 | "input": [ | |
193 |
|
|
193 | "x2 = Gaussian(0.5, 0.2, 2000)", | |
194 | "x2" |
|
194 | "x2" | |
195 | ], |
|
195 | ], | |
196 |
|
|
196 | "language": "python", | |
197 |
|
|
197 | "outputs": [], | |
198 |
|
|
198 | "prompt_number": 6 | |
199 | }, |
|
199 | }, | |
200 | { |
|
200 | { | |
201 |
|
|
201 | "cell_type": "markdown", | |
202 |
|
|
202 | "source": [ | |
203 |
|
|
203 | "We can easily compare them by displaying their histograms" | |
204 | ] |
|
204 | ] | |
205 | }, |
|
205 | }, | |
206 | { |
|
206 | { | |
207 |
|
|
207 | "cell_type": "code", | |
208 |
|
|
208 | "collapsed": false, | |
209 |
|
|
209 | "input": [ | |
210 |
|
|
210 | "display(x.hist)", | |
211 |
|
|
211 | "display(x2.hist)" | |
212 | ], |
|
212 | ], | |
213 |
|
|
213 | "language": "python", | |
214 |
|
|
214 | "outputs": [], | |
215 |
|
|
215 | "prompt_number": 7 | |
216 | }, |
|
216 | }, | |
217 | { |
|
217 | { | |
218 |
|
|
218 | "cell_type": "markdown", | |
219 |
|
|
219 | "source": [ | |
220 |
|
|
220 | "## Adding IPython display support to existing objects", | |
221 | "", |
|
221 | "", | |
222 |
|
|
222 | "When you are directly writing your own classes, you can adapt them for display in IPython by ", | |
223 |
|
|
223 | "following the above example. But in practice, we often need to work with existing code we", | |
224 |
|
|
224 | "can't modify. ", | |
225 | "", |
|
225 | "", | |
226 |
|
|
226 | "We now illustrate how to add these kinds of extended display capabilities to existing objects.", | |
227 |
|
|
227 | "We will use the numpy polynomials and change their default representation to be a formatted", | |
228 |
|
|
228 | "LaTeX expression.", | |
229 | "", |
|
229 | "", | |
230 |
|
|
230 | "First, consider how a numpy polynomial object renders by default:" | |
231 | ] |
|
231 | ] | |
232 | }, |
|
232 | }, | |
233 | { |
|
233 | { | |
234 |
|
|
234 | "cell_type": "code", | |
235 |
|
|
235 | "collapsed": false, | |
236 |
|
|
236 | "input": [ | |
237 |
|
|
237 | "p = np.polynomial.Polynomial([1,2,3], [-10, 10])", | |
238 | "p" |
|
238 | "p" | |
239 | ], |
|
239 | ], | |
240 |
|
|
240 | "language": "python", | |
241 |
|
|
241 | "outputs": [], | |
242 |
|
|
242 | "prompt_number": 8 | |
243 | }, |
|
243 | }, | |
244 | { |
|
244 | { | |
245 |
|
|
245 | "cell_type": "markdown", | |
246 |
|
|
246 | "source": [ | |
247 |
|
|
247 | "Next, we define a function that pretty-prints a polynomial as a LaTeX string:" | |
248 | ] |
|
248 | ] | |
249 | }, |
|
249 | }, | |
250 | { |
|
250 | { | |
251 |
|
|
251 | "cell_type": "code", | |
252 |
|
|
252 | "collapsed": true, | |
253 |
|
|
253 | "input": [ | |
254 |
|
|
254 | "def poly2latex(p):", | |
255 |
|
|
255 | " terms = ['%.2g' % p.coef[0]]", | |
256 |
|
|
256 | " if len(p) > 1:", | |
257 |
|
|
257 | " term = 'x'", | |
258 |
|
|
258 | " c = p.coef[1]", | |
259 |
|
|
259 | " if c!=1:", | |
260 |
|
|
260 | " term = ('%.2g ' % c) + term", | |
261 |
|
|
261 | " terms.append(term)", | |
262 |
|
|
262 | " if len(p) > 2:", | |
263 |
|
|
263 | " for i in range(2, len(p)):", | |
264 |
|
|
264 | " term = 'x^%d' % i", | |
265 |
|
|
265 | " c = p.coef[i]", | |
266 |
|
|
266 | " if c!=1:", | |
267 |
|
|
267 | " term = ('%.2g ' % c) + term", | |
268 |
|
|
268 | " terms.append(term)", | |
269 |
|
|
269 | " px = '$P(x)=%s$' % '+'.join(terms)", | |
270 |
|
|
270 | " dom = r', domain: $[%.2g,\\ %.2g]$' % tuple(p.domain)", | |
271 | " win = r', window: $[%.2g,\\ %.2g]$' % tuple(p.window)", |
|
271 | " return px+dom" | |
272 | " return px+dom+win" |
|
|||
273 | ], |
|
272 | ], | |
274 |
|
|
273 | "language": "python", | |
275 |
|
|
274 | "outputs": [], | |
276 |
|
|
275 | "prompt_number": 11 | |
277 | }, |
|
276 | }, | |
278 | { |
|
277 | { | |
279 |
|
|
278 | "cell_type": "markdown", | |
280 |
|
|
279 | "source": [ | |
281 |
|
|
280 | "This produces, on our polynomial ``p``, the following:" | |
282 | ] |
|
281 | ] | |
283 | }, |
|
282 | }, | |
284 | { |
|
283 | { | |
285 |
|
|
284 | "cell_type": "code", | |
286 |
|
|
285 | "collapsed": false, | |
287 |
|
|
286 | "input": [ | |
288 |
|
|
287 | "poly2latex(p)" | |
289 | ], |
|
288 | ], | |
290 |
|
|
289 | "language": "python", | |
291 |
|
|
290 | "outputs": [], | |
292 |
|
|
291 | "prompt_number": 12 | |
293 | }, |
|
292 | }, | |
294 | { |
|
293 | { | |
295 |
|
|
294 | "cell_type": "markdown", | |
296 |
|
|
295 | "source": [ | |
297 |
|
|
296 | "Note that this did *not* produce a formated LaTeX object, because it is simply a string ", | |
298 |
|
|
297 | "with LaTeX code. In order for this to be interpreted as a mathematical expression, it", | |
299 |
|
|
298 | "must be properly wrapped into a Math object:" | |
300 | ] |
|
299 | ] | |
301 | }, |
|
300 | }, | |
302 | { |
|
301 | { | |
303 |
|
|
302 | "cell_type": "code", | |
304 |
|
|
303 | "collapsed": false, | |
305 |
|
|
304 | "input": [ | |
306 |
|
|
305 | "from IPython.core.display import Math", | |
307 |
|
|
306 | "Math(poly2latex(p))" | |
308 | ], |
|
307 | ], | |
309 |
|
|
308 | "language": "python", | |
310 |
|
|
309 | "outputs": [], | |
311 |
|
|
310 | "prompt_number": 13 | |
312 | }, |
|
311 | }, | |
313 | { |
|
312 | { | |
314 |
|
|
313 | "cell_type": "markdown", | |
315 |
|
|
314 | "source": [ | |
316 |
|
|
315 | "But we can configure IPython to do this automatically for us as follows. We hook into the", | |
317 |
|
|
316 | "IPython display system and instruct it to use ``poly2latex`` for the latex mimetype, when", | |
318 |
|
|
317 | "encountering objects of the ``Polynomial`` type defined in the", | |
319 |
|
|
318 | "``numpy.polynomial.polynomial`` module:" | |
320 | ] |
|
319 | ] | |
321 | }, |
|
320 | }, | |
322 | { |
|
321 | { | |
323 |
|
|
322 | "cell_type": "code", | |
324 |
|
|
323 | "collapsed": true, | |
325 |
|
|
324 | "input": [ | |
326 |
|
|
325 | "ip = get_ipython()", | |
327 |
|
|
326 | "latex_formatter = ip.display_formatter.formatters['text/latex']", | |
328 |
|
|
327 | "latex_formatter.for_type_by_name('numpy.polynomial.polynomial',", | |
329 |
|
|
328 | " 'Polynomial', poly2latex)" | |
330 | ], |
|
329 | ], | |
331 |
|
|
330 | "language": "python", | |
332 |
|
|
331 | "outputs": [], | |
333 |
|
|
332 | "prompt_number": 14 | |
334 | }, |
|
333 | }, | |
335 | { |
|
334 | { | |
336 |
|
|
335 | "cell_type": "markdown", | |
337 |
|
|
336 | "source": [ | |
338 |
|
|
337 | "For more examples on how to use the above system, and how to bundle similar print functions", | |
339 |
|
|
338 | "into a convenient IPython extension, see the ``IPython/extensions/sympyprinting.py`` file. ", | |
340 |
|
|
339 | "The machinery that defines the display system is in the ``display.py`` and ``displaypub.py`` ", | |
341 |
|
|
340 | "files in ``IPython/core``.", | |
342 | "", |
|
341 | "", | |
343 |
|
|
342 | "Once our special printer has been loaded, all polynomials will be represented by their ", | |
344 |
|
|
343 | "mathematical form instead:" | |
345 | ] |
|
344 | ] | |
346 | }, |
|
345 | }, | |
347 | { |
|
346 | { | |
348 |
|
|
347 | "cell_type": "code", | |
349 |
|
|
348 | "collapsed": false, | |
350 |
|
|
349 | "input": [ | |
351 | "p" |
|
350 | "p" | |
352 | ], |
|
351 | ], | |
353 |
|
|
352 | "language": "python", | |
354 |
|
|
353 | "outputs": [], | |
355 |
|
|
354 | "prompt_number": 15 | |
356 | }, |
|
355 | }, | |
357 | { |
|
356 | { | |
358 |
|
|
357 | "cell_type": "code", | |
359 |
|
|
358 | "collapsed": false, | |
360 |
|
|
359 | "input": [ | |
361 |
|
|
360 | "p2 = np.polynomial.Polynomial([-20, 71, -15, 1])", | |
362 | "p2" |
|
361 | "p2" | |
363 | ], |
|
362 | ], | |
364 |
|
|
363 | "language": "python", | |
365 |
|
|
364 | "outputs": [], | |
366 |
|
|
365 | "prompt_number": 16 | |
367 | }, |
|
366 | }, | |
368 | { |
|
367 | { | |
369 |
|
|
368 | "cell_type": "code", | |
370 |
|
|
369 | "collapsed": true, | |
371 |
|
|
370 | "input": [], | |
372 |
|
|
371 | "language": "python", | |
373 |
|
|
372 | "outputs": [], | |
374 |
|
|
373 | "prompt_number": 14 | |
375 | } |
|
374 | } | |
376 | ] |
|
375 | ] | |
377 | } |
|
376 | } | |
378 | ] |
|
377 | ] | |
379 | } No newline at end of file |
|
378 | } |
General Comments 0
You need to be logged in to leave comments.
Login now