##// END OF EJS Templates
add deprecation warning for renamed engine/controller_launcher config...
add deprecation warning for renamed engine/controller_launcher config These have been renamed to add _class, which makes it clearer that they are class names/paths. This allows 0.11-style specification of the names to work, but with a warning that the old name is deprecated.

File last commit:

r4776:e1d65dd0
r5182:79c1f62f
Show More
display_protocol.ipynb
179 lines | 13.1 KiB | text/plain | TextLexer
/ docs / examples / notebooks / display_protocol.ipynb
Fernando Perez
Add example notebooks about display protocol and simple math/plots.
r4776 {
"worksheets": [
{
"cells": [
{
"source": "# Using the IPython display protocol for your own objects\n\nIPython extends the idea of the ``__repr__`` method in Python to support multiple representations for a given\nobject, which clients can use to display the object according to their capabilities. An object can return multiple\nrepresentations of itself by implementing special methods, and you can also define at runtime custom display \nfunctions for existing objects whose methods you can't or won't modify. In this notebook, we show how both approaches work.\n\n<br/>\n**Note:** this notebook has had all output cells stripped out so we can include it in the IPython documentation with \na minimal file size. You'll need to manually execute the cells to see the output (you can run all of them with the \n\"Run All\" button, or execute each individually). You must start this notebook with\n<pre>\nipython notebook --pylab inline\n</pre>\n\nto ensure pylab support is available for plots.\n\n## Custom-built classes with dedicated ``_repr_*_`` methods\n\nIn our first example, we illustrate how objects can expose directly to IPython special representations of\nthemselves, by providing methods such as ``_repr_svg_``, ``_repr_png_``, ``_repr_latex_``, etc. For a full\nlist of the special ``_repr_*_`` methods supported, see the code in ``IPython.core.displaypub``.\n\nAs an illustration, we build a class that holds data generated by sampling a Gaussian distribution with given mean \nand variance. The class can display itself in a variety of ways: as a LaTeX expression or as an image in PNG or SVG \nformat. Each frontend can then decide which representation it can handle.\nFurther, we illustrate how to expose directly to the user the ability to directly access the various alternate \nrepresentations (since by default displaying the object itself will only show one, and which is shown will depend on the \nrequired representations that even cache necessary data in cases where it may be expensive to compute.\n\nThe next cell defines the Gaussian class:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": true,
"prompt_number": 1,
"input": "from IPython.lib.pylabtools import print_figure\nfrom IPython.core.display import Image, SVG, Math\n\nclass Gaussian(object):\n \"\"\"A simple object holding data sampled from a Gaussian distribution.\n \"\"\"\n def __init__(self, mean=0, std=1, size=1000):\n self.data = np.random.normal(mean, std, size)\n self.mean = mean\n self.std = std\n self.size = size\n # For caching plots that may be expensive to compute\n self._png_data = None\n self._svg_data = None\n \n def _figure_data(self, format):\n fig, ax = plt.subplots()\n ax.plot(self.data, 'o')\n ax.set_title(self._repr_latex_())\n data = print_figure(fig, format)\n # We MUST close the figure, otherwise IPython's display machinery\n # will pick it up and send it as output, resulting in a double display\n plt.close(fig)\n return data\n \n # Here we define the special repr methods that provide the IPython display protocol\n # Note that for the two figures, we cache the figure data once computed.\n \n def _repr_png_(self):\n if self._png_data is None:\n self._png_data = self._figure_data('png')\n return self._png_data\n\n\n def _repr_svg_(self):\n if self._svg_data is None:\n self._svg_data = self._figure_data('svg')\n return self._svg_data\n \n def _repr_latex_(self):\n return r'$\\mathcal{N}(\\mu=%.2g, \\sigma=%.2g),\\ N=%d$' % (self.mean,\n self.std, self.size)\n \n # We expose as properties some of the above reprs, so that the user can see them\n # directly (since otherwise the client dictates which one it shows by default)\n @property\n def png(self):\n return Image(self._repr_png_(), embed=True)\n \n @property\n def svg(self):\n return SVG(self._repr_svg_())\n \n @property\n def latex(self):\n return Math(self._repr_svg_())\n \n # An example of using a property to display rich information, in this case\n # the histogram of the distribution. We've hardcoded the format to be png\n # in this case, but in production code it would be trivial to make it an option\n @property\n def hist(self):\n fig, ax = plt.subplots()\n ax.hist(self.data, bins=100)\n ax.set_title(self._repr_latex_())\n data = print_figure(fig, 'png')\n plt.close(fig)\n return Image(data, embed=True)"
},
{
"source": "Now, we create an instance of the Gaussian distribution, whose default representation will be its LaTeX form:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 2,
"input": "x = Gaussian()\nx"
},
{
"source": "We can view the data in png or svg formats:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 3,
"input": "x.png"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 4,
"input": "x.svg"
},
{
"source": "Since IPython only displays by default as an ``Out[]`` cell the result of the last computation, we can use the\n``display()`` function to show more than one representation in a single cell:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 5,
"input": "display(x.png)\ndisplay(x.svg)"
},
{
"source": "Now let's create a new Gaussian with different parameters",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 6,
"input": "x2 = Gaussian(0.5, 0.2, 2000)\nx2"
},
{
"source": "We can easily compare them by displaying their histograms",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 7,
"input": "display(x.hist)\ndisplay(x2.hist)"
},
{
"source": "## Adding IPython display support to existing objects\n\nWhen you are directly writing your own classes, you can adapt them for display in IPython by \nfollowing the above example. But in practice, we often need to work with existing code we\ncan't modify. \n\nWe now illustrate how to add these kinds of extended display capabilities to existing objects.\nWe will use the numpy polynomials and change their default representation to be a formatted\nLaTeX expression.\n\nFirst, consider how a numpy polynomial object renders by default:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 8,
"input": "p = np.polynomial.Polynomial([1,2,3], [-10, 10])\np"
},
{
"source": "Next, we define a function that pretty-prints a polynomial as a LaTeX string:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": true,
"prompt_number": 9,
"input": "def poly2latex(p):\n terms = ['%.2g' % p.coef[0]]\n if len(p) > 1:\n term = 'x'\n c = p.coef[1]\n if c!=1:\n term = ('%.2g ' % c) + term\n terms.append(term)\n if len(p) > 2:\n for i in range(2, len(p)):\n term = 'x^%d' % i\n c = p.coef[i]\n if c!=1:\n term = ('%.2g ' % c) + term\n terms.append(term)\n px = '$P(x)=%s$' % '+'.join(terms)\n dom = r', domain: $[%.2g,\\ %.2g]$' % tuple(p.domain)\n win = r', window: $[%.2g,\\ %.2g]$' % tuple(p.window)\n return px+dom+win"
},
{
"source": "This produces, on our polynomial ``p``, the following:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 10,
"input": "poly2latex(p)"
},
{
"source": "Note that this did *not* produce a formated LaTeX object, because it is simply a string \nwith LaTeX code. In order for this to be interpreted as a mathematical expression, it\nmust be properly wrapped into a Math object:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 11,
"input": "from IPython.core.display import Math\nMath(poly2latex(p))"
},
{
"source": "But we can configure IPython to do this automatically for us as follows. We hook into the\nIPython display system and instruct it to use ``poly2latex`` for the latex mimetype, when\nencountering objects of the ``Polynomial`` type defined in the\n``numpy.polynomial.polynomial`` module:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": true,
"prompt_number": 12,
"input": "ip = get_ipython()\nlatex_formatter = ip.display_formatter.formatters['text/latex']\nlatex_formatter.for_type_by_name('numpy.polynomial.polynomial',\n 'Polynomial', poly2latex)"
},
{
"source": "For more examples on how to use the above system, and how to bundle similar print functions\ninto a convenient IPython extension, see the ``IPython/extensions/sympyprinting.py`` file. \nThe machinery that defines the display system is in the ``display.py`` and ``displaypub.py`` \nfiles in ``IPython/core``.\n\nOnce our special printer has been loaded, all polynomials will be represented by their \nmathematical form instead:",
"cell_type": "markdown"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 13,
"input": "p"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": false,
"prompt_number": 14,
"input": "p2 = np.polynomial.Polynomial([-20, 71, -15, 1])\np2"
},
{
"cell_type": "code",
"language": "python",
"outputs": [],
"collapsed": true,
"prompt_number": 14,
"input": ""
}
]
}
],
"metadata": {
"name": "display_protocol"
},
"nbformat": 2
}