{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Integration with Python\n", "\n", "This cookbook explains you how to perform azimuthal integration using the python interpreter.\n", "It is divided in two parts, the first part uses purely python while the second will use some advanced feature of the Jupyter notebook.\n", "\n", "We will re-use the same files as is the other tutorials.\n", "\n", "## Performing azimuthal integration with pyFAI of a bunch of images\n", "\n", "To be able to perform the azimuthal integration of some images, one needs:\n", "\n", "* The diffraction images themselves, in this example they are stored as TIFF files\n", "* The geometry of the experimental setup as obtained from the calibration and stored as a PONI-file\n", "* other files like flat-field, dark current images or detector distortion file (spline-fle).\n", "\n", "Image file: http://www.silx.org/pub/pyFAI/cookbook/calibration/LaB6_29.4keV.tif\n", "\n", "Detector distortion file: http://www.silx.org/pub/pyFAI/cookbook/calibration/F_K4320T_Cam43_30012013_distorsion.spline\n", "\n", "The calibration has been performed in the previous cookbook. The geometry is saved in \"LaB6_29.4keV.poni\".\n", "\n", "### Basic usage of pyFAI\n", "To perform azimuthal averaging, one can use the pyFAI and FabIO libraries, the former to load the geometry and later to read the image:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/mntdirect/_scisoft/users/jupyter/jupy35/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n", " from ._conv import register_converters as _register_converters\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "image: \n", "\n", "Integrator: \n", " Detector Detector\t Spline= /users/kieffer/workspace-400/pyFAI/doc/source/usage/cookbook/F_K4320T_Cam43_30012013_distorsion.spline\t PixelSize= 5.168e-05, 5.126e-05 m\n", "Wavelength= 4.217150e-11m\n", "SampleDetDist= 1.182208e-01m\tPONI= 5.394843e-02, 5.551600e-02m\trot1=0.006974 rot2= -0.003313 rot3= -0.000000 rad\n", "DirectBeamDist= 118.224mm\tCenter: x=1066.839, y=1036.336 pix\tTilt=0.442 deg tiltPlanRotation= -154.594 deg\n" ] } ], "source": [ "import pyFAI, fabio\n", "\n", "img = fabio.open(\"LaB6_29.4keV.tif\")\n", "print(\"image:\", img)\n", "\n", "ai = pyFAI.load(\"LaB6_29.4keV.poni\")\n", "print(\"\\nIntegrator: \\n\", ai)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Azimuthal averaging using pyFAI\n", "\n", "\n", "One needs first to retrieve the image as a numpy array. This allows to use other libraries than FabIO for image reading, for example HDF5.\n", "\n", "This shows how to perform the azimuthal integration of one image over 1000 bins:\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "img_array: (2048, 2048) float32\n" ] } ], "source": [ "img_array = img.data\n", "print(\"img_array:\", type(img_array), img_array.shape, img_array.dtype)\n", "\n", "res = ai.integrate1d(img_array, \n", " 1000, \n", " unit=\"2th_deg\", \n", " filename=\"integrated.dat\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Note:* There are 2 mandatory parameters for this method, the 2D-numpy array with the image and the number of bins. We specified in addition the name of the file, where to save the data and the unit for performing the integration.\n", "\n", "There are many other options to integrate1d:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on method integrate1d in module pyFAI.azimuthalIntegrator:\n", "\n", "integrate1d(data, npt, filename=None, correctSolidAngle=True, variance=None, error_model=None, radial_range=None, azimuth_range=None, mask=None, dummy=None, delta_dummy=None, polarization_factor=None, dark=None, flat=None, method='csr', unit=q_nm^-1, safe=True, normalization_factor=1.0, block_size=32, profile=False, all=False, metadata=None) method of pyFAI.azimuthalIntegrator.AzimuthalIntegrator instance\n", " Calculate the azimuthal integrated Saxs curve in q(nm^-1) by default\n", " \n", " Multi algorithm implementation (tries to be bullet proof), suitable for SAXS, WAXS, ... and much more\n", " \n", " \n", " \n", " :param data: 2D array from the Detector/CCD camera\n", " :type data: ndarray\n", " :param npt: number of points in the output pattern\n", " :type npt: int\n", " :param filename: output filename in 2/3 column ascii format\n", " :type filename: str\n", " :param correctSolidAngle: correct for solid angle of each pixel if True\n", " :type correctSolidAngle: bool\n", " :param variance: array containing the variance of the data. If not available, no error propagation is done\n", " :type variance: ndarray\n", " :param error_model: When the variance is unknown, an error model can be given: \"poisson\" (variance = I), \"azimuthal\" (variance = (I-)^2)\n", " :type error_model: str\n", " :param radial_range: The lower and upper range of the radial unit. If not provided, range is simply (data.min(), data.max()). Values outside the range are ignored.\n", " :type radial_range: (float, float), optional\n", " :param azimuth_range: The lower and upper range of the azimuthal angle in degree. If not provided, range is simply (data.min(), data.max()). Values outside the range are ignored.\n", " :type azimuth_range: (float, float), optional\n", " :param mask: array (same size as image) with 1 for masked pixels, and 0 for valid pixels\n", " :type mask: ndarray\n", " :param dummy: value for dead/masked pixels\n", " :type dummy: float\n", " :param delta_dummy: precision for dummy value\n", " :type delta_dummy: float\n", " :param polarization_factor: polarization factor between -1 (vertical) and +1 (horizontal).\n", " 0 for circular polarization or random,\n", " None for no correction,\n", " True for using the former correction\n", " :type polarization_factor: float\n", " :param dark: dark noise image\n", " :type dark: ndarray\n", " :param flat: flat field image\n", " :type flat: ndarray\n", " :param method: can be \"numpy\", \"cython\", \"BBox\" or \"splitpixel\", \"lut\", \"csr\", \"nosplit_csr\", \"full_csr\", \"lut_ocl\" and \"csr_ocl\" if you want to go on GPU. To Specify the device: \"csr_ocl_1,2\"\n", " :type method: str\n", " :param unit: Output units, can be \"q_nm^-1\", \"q_A^-1\", \"2th_deg\", \"2th_rad\", \"r_mm\" for now\n", " :type unit: pyFAI.units.Unit\n", " :param safe: Do some extra checks to ensure LUT/CSR is still valid. False is faster.\n", " :type safe: bool\n", " :param normalization_factor: Value of a normalization monitor\n", " :type normalization_factor: float\n", " :param block_size: size of the block for OpenCL integration (unused?)\n", " :param profile: set to True to enable profiling in OpenCL\n", " :param all: if true return a dictionary with many more parameters (deprecated, please refer to the documentation of Integrate1dResult).\n", " :type all: bool\n", " :param metadata: JSON serializable object containing the metadata, usually a dictionary.\n", " :return: q/2th/r bins center positions and regrouped intensity (and error array if variance or variance model provided), uneless all==True.\n", " :rtype: Integrate1dResult, dict\n", "\n" ] } ], "source": [ "help(ai.integrate1d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result file contains the integrated data with some headers as shown:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# == pyFAI calibration ==\n", "# Distance Sample to Detector: 0.118220810284 m\n", "# PONI: 5.395e-02, 5.552e-02 m\n", "# Rotations: 0.006974 -0.003313 -0.000000 rad\n", "#\n", "# == Fit2d calibration ==\n", "# Distance Sample-beamCenter: 118.224 mm\n", "# Center: x=1066.839, y=1036.336 pix\n", "# Tilt: 0.442 deg TiltPlanRot: -154.594 deg\n", "#\n", "# Detector Detector\t Spline= /users/kieffer/workspace-400/pyFAI/doc/source/usage/cookbook/F_K4320T_Cam43_30012013_distorsion.spline\t PixelSize= 5.168e-05, 5.126e-05 m\n", "# Detector has a mask: False\n", "# Detector has a dark current: False\n", "# detector has a flat field: False\n", "#\n", "# Wavelength: 4.21714957131e-11 m\n", "# Mask applied: False\n", "# Dark current applied: False\n", "# Flat field applied: False\n", "# Polarization factor: None\n", "# Normalization factor: 1.0\n", "# --> integrated.dat\n", "# 2th_deg I\n", "1.668855e-02 2.503605e+00\n", "5.006564e-02 2.749244e+00\n", "8.344273e-02 2.114206e+00\n", "1.168198e-01 2.755390e+00\n", "1.501969e-01 2.890013e+00\n", "1.835740e-01 2.658021e+00\n", "2.169511e-01 2.523173e+00\n", "2.503282e-01 2.822044e+00\n", "2.837053e-01 2.732563e+00\n", "3.170824e-01 2.823707e+00\n", "3.504595e-01 2.872520e+00\n", "3.838366e-01 2.791172e+00\n", "4.172137e-01 3.029095e+00\n", "4.505907e-01 3.121556e+00\n", "4.839678e-01 3.091311e+00\n", "5.173449e-01 3.026508e+00\n", "5.507220e-01 3.019458e+00\n", "5.840991e-01 3.050202e+00\n", "6.174762e-01 2.866862e+00\n", "6.508533e-01 3.191242e+00\n", "6.842304e-01 3.102998e+00\n", "7.176075e-01 2.914966e+00\n", "7.509846e-01 3.085007e+00\n", "7.843617e-01 3.014659e+00\n", "8.177388e-01 2.898686e+00\n", "8.511159e-01 3.031742e+00\n", "8.844929e-01 3.119843e+00\n" ] } ], "source": [ "with open(\"integrated.dat\") as f:\n", " for i in range(50):\n", " print(f.readline().strip())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Azimuthal regrouping using pyFAI\n", "\n", "This option is similar to the integration but perfroms N-integration on various azimuthal angle (chi) sections of the space. It is also named \"caking\" in Fit2D.\n", "\n", "The azimuthal regrouping of an image over 500 radial bins in 360 angular steps (of 1 degree) can be performed like this:\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "res2 = ai.integrate2d(img_array, \n", " 500, 360, \n", " unit=\"r_mm\", \n", " filename=\"integrated.edf\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"{\\nEDF_DataBlockID\": \"0.Image.Psd\",\n", " \"EDF_BinarySize\": \"720000\",\n", " \"EDF_HeaderSize\": \"1536\",\n", " \"ByteOrder\": \"LowByteFirst\",\n", " \"DataType\": \"FloatValue\",\n", " \"Dim_1\": \"500\",\n", " \"Dim_2\": \"360\",\n", " \"Image\": \"0\",\n", " \"HeaderID\": \"EH:000000:000000:000000\",\n", " \"Size\": \"720000\",\n", " \"Engine\": \"Detector Detector Spline= /users/kieffer/workspace-400/pyFAI/doc/source/usage/cookbook/F_K4320T_Cam43_30012013_distorsion.spline PixelSize= 5.168e-05, 5.126e-05 m Wavelength= 4.217150e-11m SampleDetDist= 1.182208e-01m PONI= 5.394843e-02, 5.551600e-02m rot1=0.006974 rot2= -0.003313 rot3= -0.000000 rad DirectBeamDist= 118.224mm Center: x=1066.839, y=1036.336 pix Tilt=0.442 deg tiltPlanRotation= -154.594 deg\",\n", " \"detector\": \"Detector\",\n", " \"pixel1\": \"5.1679e-05\",\n", " \"pixel2\": \"5.1265e-05\",\n", " \"splineFile\": \"/users/kieffer/workspace-400/pyFAI/doc/source/usage/cookbook/F_K4320T_Cam43_30012013_distorsion.spline\",\n", " \"dist\": \"0.118220810284\",\n", " \"poni1\": \"0.05394843456\",\n", " \"poni2\": \"0.0555160034482\",\n", " \"rot1\": \"0.00697431586749\",\n", " \"rot2\": \"-0.00331252162112\",\n", " \"rot3\": \"-4.98632051492e-10\",\n", " \"wavelength\": \"4.21714957131e-11\",\n", " \"r_mm_min\": \"0.07826394721632823\",\n", " \"r_mm_max\": \"78.18567447975511\",\n", " \"chi_min\": \"-179.50000495946867\",\n", " \"chi_max\": \"179.50000495946867\",\n", " \"has_mask_applied\": \"False\",\n", " \"has_dark_correction\": \"False\",\n", " \"has_flat_correction\": \"False\",\n", " \"polarization_factor\": \"None\",\n", " \"normalization_factor\": \"1.0\"\n", "}\n", "cake: (360, 500) float32\n" ] } ], "source": [ "cake = fabio.open(\"integrated.edf\")\n", "print(cake.header)\n", "print(\"cake:\", type(cake.data), cake.data.shape, cake.data.dtype)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "From this it is trivial to perform a loop and integrate many images. \n", "\n", "*Attention:* The AzimuthalIntegrator object (called ai here) is rather large and costly to initialize. The best practice is to crate it once and to use it many times, like this:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "import glob, os\n", "\n", "all_images = glob.glob(\"LaB6*.tif\")\n", "ai = pyFAI.load(\"LaB6_29.4keV.poni\")\n", "\n", "for one_image in all_images:\n", " fimg = fabio.open(one_image)\n", " dest = os.path.splitext(one_image)[0] + \".dat\"\n", " ai.integrate1d(fimg.data, \n", " 1000, \n", " unit=\"2th_deg\", \n", " filename=dest)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using some advanced feature of Jupyter Notebooks\n", "\n", "Jupyter notebooks offer some advanced visualization features, especially when used with *matplotlib* and *pyFAI*.\n", "Unfortunately, the example shown hereafter will not work properly in normal Python scipts.\n", "\n", "### Initialization of the notebook for matplotlib integration:\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Populating the interactive namespace from numpy and matplotlib\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/mntdirect/_scisoft/users/jupyter/jupy35/lib/python3.5/site-packages/IPython/core/magics/pylab.py:160: UserWarning: pylab import has clobbered these variables: ['f']\n", "`%matplotlib` prevents importing * from pylab and numpy\n", " \"\\n`%matplotlib` prevents importing * from pylab and numpy\"\n" ] } ], "source": [ "%pylab nbagg" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "from pyFAI.gui import jupyter" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "### Visualzation of different types of results reviously calculated" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", "window.mpl = {};\n", "\n", "\n", "mpl.get_websocket_type = function() {\n", " if (typeof(WebSocket) !== 'undefined') {\n", " return WebSocket;\n", " } else if (typeof(MozWebSocket) !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", " alert('Your browser does not have WebSocket support.' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.');\n", " };\n", "}\n", "\n", "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", " this.supports_binary = (this.ws.binaryType != undefined);\n", "\n", " if (!this.supports_binary) {\n", " var warnings = document.getElementById(\"mpl-warnings\");\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", " warnings.textContent = (\n", " \"This browser does not support binary websocket messages. \" +\n", " \"Performance may be slow.\");\n", " }\n", " }\n", "\n", " this.imageObj = new Image();\n", "\n", " this.context = undefined;\n", " this.message = undefined;\n", " this.canvas = undefined;\n", " this.rubberband_canvas = undefined;\n", " this.rubberband_context = undefined;\n", " this.format_dropdown = undefined;\n", "\n", " this.image_mode = 'full';\n", "\n", " this.root = $('
');\n", " this._root_extra_style(this.root)\n", " this.root.attr('style', 'display: inline-block');\n", "\n", " $(parent_element).append(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", " this._init_toolbar(this);\n", "\n", " var fig = this;\n", "\n", " this.waiting = false;\n", "\n", " this.ws.onopen = function () {\n", " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", " fig.send_message(\"send_image_mode\", {});\n", " if (mpl.ratio != 1) {\n", " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", " }\n", " fig.send_message(\"refresh\", {});\n", " }\n", "\n", " this.imageObj.onload = function() {\n", " if (fig.image_mode == 'full') {\n", " // Full images could contain transparency (where diff images\n", " // almost always do), so we need to clear the canvas so that\n", " // there is no ghosting.\n", " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", " }\n", " fig.context.drawImage(fig.imageObj, 0, 0);\n", " };\n", "\n", " this.imageObj.onunload = function() {\n", " fig.ws.close();\n", " }\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", "}\n", "\n", "mpl.figure.prototype._init_header = function() {\n", " var titlebar = $(\n", " '
');\n", " var titletext = $(\n", " '
');\n", " titlebar.append(titletext)\n", " this.root.append(titlebar);\n", " this.header = titletext[0];\n", "}\n", "\n", "\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "\n", "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "mpl.figure.prototype._init_canvas = function() {\n", " var fig = this;\n", "\n", " var canvas_div = $('
');\n", "\n", " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", "\n", " function canvas_keyboard_event(event) {\n", " return fig.key_event(event, event['data']);\n", " }\n", "\n", " canvas_div.keydown('key_press', canvas_keyboard_event);\n", " canvas_div.keyup('key_release', canvas_keyboard_event);\n", " this.canvas_div = canvas_div\n", " this._canvas_extra_style(canvas_div)\n", " this.root.append(canvas_div);\n", "\n", " var canvas = $('');\n", " canvas.addClass('mpl-canvas');\n", " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", "\n", " this.canvas = canvas[0];\n", " this.context = canvas[0].getContext(\"2d\");\n", "\n", " var backingStore = this.context.backingStorePixelRatio ||\n", "\tthis.context.webkitBackingStorePixelRatio ||\n", "\tthis.context.mozBackingStorePixelRatio ||\n", "\tthis.context.msBackingStorePixelRatio ||\n", "\tthis.context.oBackingStorePixelRatio ||\n", "\tthis.context.backingStorePixelRatio || 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", " var rubberband = $('');\n", " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", "\n", " var pass_mouse_events = true;\n", "\n", " canvas_div.resizable({\n", " start: function(event, ui) {\n", " pass_mouse_events = false;\n", " },\n", " resize: function(event, ui) {\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " stop: function(event, ui) {\n", " pass_mouse_events = true;\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " });\n", "\n", " function mouse_event_fn(event) {\n", " if (pass_mouse_events)\n", " return fig.mouse_event(event, event['data']);\n", " }\n", "\n", " rubberband.mousedown('button_press', mouse_event_fn);\n", " rubberband.mouseup('button_release', mouse_event_fn);\n", " // Throttle sequential mouse events to 1 every 20ms.\n", " rubberband.mousemove('motion_notify', mouse_event_fn);\n", "\n", " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", "\n", " canvas_div.on(\"wheel\", function (event) {\n", " event = event.originalEvent;\n", " event['data'] = 'scroll'\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", " mouse_event_fn(event);\n", " });\n", "\n", " canvas_div.append(canvas);\n", " canvas_div.append(rubberband);\n", "\n", " this.rubberband = rubberband;\n", " this.rubberband_canvas = rubberband[0];\n", " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", " this.rubberband_context.strokeStyle = \"#000000\";\n", "\n", " this._resize_canvas = function(width, height) {\n", " // Keep the size of the canvas, canvas container, and rubber band\n", " // canvas in synch.\n", " canvas_div.css('width', width)\n", " canvas_div.css('height', height)\n", "\n", " canvas.attr('width', width * mpl.ratio);\n", " canvas.attr('height', height * mpl.ratio);\n", " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", "\n", " rubberband.attr('width', width);\n", " rubberband.attr('height', height);\n", " }\n", "\n", " // Set the figure to an initial 600x600px, this will subsequently be updated\n", " // upon first draw.\n", " this._resize_canvas(600, 600);\n", "\n", " // Disable right mouse context menu.\n", " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", " return false;\n", " });\n", "\n", " function set_focus () {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", "}\n", "\n", "mpl.figure.prototype._init_toolbar = function() {\n", " var fig = this;\n", "\n", " var nav_element = $('
')\n", " nav_element.attr('style', 'width: 100%');\n", " this.root.append(nav_element);\n", "\n", " // Define a callback function for later on.\n", " function toolbar_event(event) {\n", " return fig.toolbar_button_onclick(event['data']);\n", " }\n", " function toolbar_mouse_event(event) {\n", " return fig.toolbar_button_onmouseover(event['data']);\n", " }\n", "\n", " for(var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", " // put a spacer in here.\n", " continue;\n", " }\n", " var button = $('');\n", " button.click(method_name, toolbar_event);\n", " button.mouseover(tooltip, toolbar_mouse_event);\n", " nav_element.append(button);\n", " }\n", "\n", " // Add the status bar.\n", " var status_bar = $('');\n", " nav_element.append(status_bar);\n", " this.message = status_bar[0];\n", "\n", " // Add the close button to the window.\n", " var buttongrp = $('
');\n", " var button = $('');\n", " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", " buttongrp.append(button);\n", " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", " titlebar.prepend(buttongrp);\n", "}\n", "\n", "mpl.figure.prototype._root_extra_style = function(el){\n", " var fig = this\n", " el.on(\"remove\", function(){\n", "\tfig.close_ws(fig, {});\n", " });\n", "}\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(el){\n", " // this is important to make the div 'focusable\n", " el.attr('tabindex', 0)\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", " }\n", " else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", "\n", "}\n", "\n", "mpl.figure.prototype._key_event_extra = function(event, name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", " if (!manager)\n", " manager = IPython.keyboard_manager;\n", "\n", " // Check for shift+enter\n", " if (event.shiftKey && event.which == 13) {\n", " this.canvas_div.blur();\n", " event.shiftKey = false;\n", " // Send a \"J\" for go to next cell\n", " event.which = 74;\n", " event.keyCode = 74;\n", " manager.command_mode();\n", " manager.handle_keydown(event);\n", " }\n", "}\n", "\n", "mpl.figure.prototype.handle_save = function(fig, msg) {\n", " fig.ondownload(fig, null);\n", "}\n", "\n", "\n", "mpl.find_output_cell = function(html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", " if (data['text/html'] == html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", "}\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", "if (IPython.notebook.kernel != null) {\n", " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", "}\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jupyter.plot1d(res)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", "window.mpl = {};\n", "\n", "\n", "mpl.get_websocket_type = function() {\n", " if (typeof(WebSocket) !== 'undefined') {\n", " return WebSocket;\n", " } else if (typeof(MozWebSocket) !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", " alert('Your browser does not have WebSocket support.' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.');\n", " };\n", "}\n", "\n", "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", " this.supports_binary = (this.ws.binaryType != undefined);\n", "\n", " if (!this.supports_binary) {\n", " var warnings = document.getElementById(\"mpl-warnings\");\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", " warnings.textContent = (\n", " \"This browser does not support binary websocket messages. \" +\n", " \"Performance may be slow.\");\n", " }\n", " }\n", "\n", " this.imageObj = new Image();\n", "\n", " this.context = undefined;\n", " this.message = undefined;\n", " this.canvas = undefined;\n", " this.rubberband_canvas = undefined;\n", " this.rubberband_context = undefined;\n", " this.format_dropdown = undefined;\n", "\n", " this.image_mode = 'full';\n", "\n", " this.root = $('
');\n", " this._root_extra_style(this.root)\n", " this.root.attr('style', 'display: inline-block');\n", "\n", " $(parent_element).append(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", " this._init_toolbar(this);\n", "\n", " var fig = this;\n", "\n", " this.waiting = false;\n", "\n", " this.ws.onopen = function () {\n", " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", " fig.send_message(\"send_image_mode\", {});\n", " if (mpl.ratio != 1) {\n", " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", " }\n", " fig.send_message(\"refresh\", {});\n", " }\n", "\n", " this.imageObj.onload = function() {\n", " if (fig.image_mode == 'full') {\n", " // Full images could contain transparency (where diff images\n", " // almost always do), so we need to clear the canvas so that\n", " // there is no ghosting.\n", " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", " }\n", " fig.context.drawImage(fig.imageObj, 0, 0);\n", " };\n", "\n", " this.imageObj.onunload = function() {\n", " fig.ws.close();\n", " }\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", "}\n", "\n", "mpl.figure.prototype._init_header = function() {\n", " var titlebar = $(\n", " '
');\n", " var titletext = $(\n", " '
');\n", " titlebar.append(titletext)\n", " this.root.append(titlebar);\n", " this.header = titletext[0];\n", "}\n", "\n", "\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "\n", "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "mpl.figure.prototype._init_canvas = function() {\n", " var fig = this;\n", "\n", " var canvas_div = $('
');\n", "\n", " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", "\n", " function canvas_keyboard_event(event) {\n", " return fig.key_event(event, event['data']);\n", " }\n", "\n", " canvas_div.keydown('key_press', canvas_keyboard_event);\n", " canvas_div.keyup('key_release', canvas_keyboard_event);\n", " this.canvas_div = canvas_div\n", " this._canvas_extra_style(canvas_div)\n", " this.root.append(canvas_div);\n", "\n", " var canvas = $('');\n", " canvas.addClass('mpl-canvas');\n", " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", "\n", " this.canvas = canvas[0];\n", " this.context = canvas[0].getContext(\"2d\");\n", "\n", " var backingStore = this.context.backingStorePixelRatio ||\n", "\tthis.context.webkitBackingStorePixelRatio ||\n", "\tthis.context.mozBackingStorePixelRatio ||\n", "\tthis.context.msBackingStorePixelRatio ||\n", "\tthis.context.oBackingStorePixelRatio ||\n", "\tthis.context.backingStorePixelRatio || 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", " var rubberband = $('');\n", " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", "\n", " var pass_mouse_events = true;\n", "\n", " canvas_div.resizable({\n", " start: function(event, ui) {\n", " pass_mouse_events = false;\n", " },\n", " resize: function(event, ui) {\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " stop: function(event, ui) {\n", " pass_mouse_events = true;\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " });\n", "\n", " function mouse_event_fn(event) {\n", " if (pass_mouse_events)\n", " return fig.mouse_event(event, event['data']);\n", " }\n", "\n", " rubberband.mousedown('button_press', mouse_event_fn);\n", " rubberband.mouseup('button_release', mouse_event_fn);\n", " // Throttle sequential mouse events to 1 every 20ms.\n", " rubberband.mousemove('motion_notify', mouse_event_fn);\n", "\n", " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", "\n", " canvas_div.on(\"wheel\", function (event) {\n", " event = event.originalEvent;\n", " event['data'] = 'scroll'\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", " mouse_event_fn(event);\n", " });\n", "\n", " canvas_div.append(canvas);\n", " canvas_div.append(rubberband);\n", "\n", " this.rubberband = rubberband;\n", " this.rubberband_canvas = rubberband[0];\n", " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", " this.rubberband_context.strokeStyle = \"#000000\";\n", "\n", " this._resize_canvas = function(width, height) {\n", " // Keep the size of the canvas, canvas container, and rubber band\n", " // canvas in synch.\n", " canvas_div.css('width', width)\n", " canvas_div.css('height', height)\n", "\n", " canvas.attr('width', width * mpl.ratio);\n", " canvas.attr('height', height * mpl.ratio);\n", " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", "\n", " rubberband.attr('width', width);\n", " rubberband.attr('height', height);\n", " }\n", "\n", " // Set the figure to an initial 600x600px, this will subsequently be updated\n", " // upon first draw.\n", " this._resize_canvas(600, 600);\n", "\n", " // Disable right mouse context menu.\n", " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", " return false;\n", " });\n", "\n", " function set_focus () {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", "}\n", "\n", "mpl.figure.prototype._init_toolbar = function() {\n", " var fig = this;\n", "\n", " var nav_element = $('
')\n", " nav_element.attr('style', 'width: 100%');\n", " this.root.append(nav_element);\n", "\n", " // Define a callback function for later on.\n", " function toolbar_event(event) {\n", " return fig.toolbar_button_onclick(event['data']);\n", " }\n", " function toolbar_mouse_event(event) {\n", " return fig.toolbar_button_onmouseover(event['data']);\n", " }\n", "\n", " for(var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", " // put a spacer in here.\n", " continue;\n", " }\n", " var button = $('