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