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