{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from imp import reload"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## UAT for NbAgg backend.\n",
    "\n",
    "The first line simply reloads matplotlib, uses the nbagg backend and then reloads the backend, just to ensure we have the latest modification to the backend code. Note: The underlying JavaScript will not be updated by this process, so a refresh of the browser after clearing the output and saving is necessary to clear everything fully."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib\n",
    "reload(matplotlib)\n",
    "\n",
    "matplotlib.use('nbagg')\n",
    "\n",
    "import matplotlib.backends.backend_nbagg\n",
    "reload(matplotlib.backends.backend_nbagg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 1 - Simple figure creation using pyplot\n",
    "\n",
    "Should produce a figure window which is interactive with the pan and zoom buttons. (Do not press the close button, but any others may be used)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.backends.backend_webagg_core\n",
    "reload(matplotlib.backends.backend_webagg_core)\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "plt.interactive(False)\n",
    "\n",
    "fig1 = plt.figure()\n",
    "plt.plot(range(10))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 2 - Creation of another figure, without the need to do plt.figure.\n",
    "\n",
    "As above, a new figure should be created."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot([3, 2, 1])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 3 - Connection info\n",
    "\n",
    "The printout should show that there are two figures which have active CommSockets, and no figures pending show."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(matplotlib.backends.backend_nbagg.connection_info())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 4 - Closing figures\n",
    "\n",
    "Closing a specific figure instance should turn the figure into a plain image - the UI should have been removed. In this case, scroll back to the first figure and assert this is the case."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.close(fig1)\n",
    "plt.close('all')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 5 - No show without plt.show in non-interactive mode\n",
    "\n",
    "Simply doing a plt.plot should not show a new figure, nor indeed update an existing one (easily verified in UAT 6).\n",
    "The output should simply be a list of Line2D instances."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(range(10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 6 - Connection information\n",
    "\n",
    "We just created a new figure, but didn't show it. Connection info should no longer have \"Figure 1\" (as we closed it in UAT 4) and should have figure 2 and 3, with Figure 3 without any connections. There should be 1 figure pending."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(matplotlib.backends.backend_nbagg.connection_info())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 7 - Show of previously created figure\n",
    "\n",
    "We should be able to show a figure we've previously created. The following should produce two figure windows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.show()\n",
    "plt.figure()\n",
    "plt.plot(range(5))\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 8 - Interactive mode\n",
    "\n",
    "In interactive mode, creating a line should result in a figure being shown."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.interactive(True)\n",
    "plt.figure()\n",
    "plt.plot([3, 2, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Subsequent lines should be added to the existing figure, rather than creating a new one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(range(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Calling connection_info in interactive mode should not show any pending figures."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(matplotlib.backends.backend_nbagg.connection_info())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Disable interactive mode again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.interactive(False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 9 - Multiple shows\n",
    "\n",
    "Unlike most of the other matplotlib backends, we may want to see a figure multiple times (with or without synchronisation between the views, though the former is not yet implemented). Assert that plt.gcf().canvas.manager.reshow() results in another figure window which is synchronised upon pan & zoom."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.gcf().canvas.manager.reshow()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 10 - Saving notebook\n",
    "\n",
    "Saving the notebook (with CTRL+S or File->Save) should result in the saved notebook having static versions of the figues embedded within. The image should be the last update from user interaction and interactive plotting. (check by converting with ``ipython nbconvert <notebook>``)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 11 - Creation of a new figure on second show\n",
    "\n",
    "Create a figure, show it, then create a new axes and show it. The result should be a new figure.\n",
    "\n",
    "**BUG: Sometimes this doesn't work - not sure why (@pelson).**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure()\n",
    "plt.axes()\n",
    "plt.show()\n",
    "\n",
    "plt.plot([1, 2, 3])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 12 - OO interface\n",
    "\n",
    "Should produce a new figure and plot it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib.backends.backend_nbagg import new_figure_manager,show\n",
    "\n",
    "manager = new_figure_manager(1000)\n",
    "fig = manager.canvas.figure\n",
    "ax = fig.add_subplot(1,1,1)\n",
    "ax.plot([1,2,3])\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## UAT 13 - Animation\n",
    "\n",
    "The following should generate an animated line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.animation as animation\n",
    "import numpy as np\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "\n",
    "x = np.arange(0, 2*np.pi, 0.01)        # x-array\n",
    "line, = ax.plot(x, np.sin(x))\n",
    "\n",
    "def animate(i):\n",
    "    line.set_ydata(np.sin(x+i/10.0))  # update the data\n",
    "    return line,\n",
    "\n",
    "#Init only required for blitting to give a clean slate.\n",
    "def init():\n",
    "    line.set_ydata(np.ma.array(x, mask=True))\n",
    "    return line,\n",
    "\n",
    "ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,\n",
    "                              interval=100., blit=True)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 14 - Keyboard shortcuts in IPython after close of figure\n",
    "\n",
    "After closing the previous figure (with the close button above the figure) the IPython keyboard shortcuts should still function.\n",
    "\n",
    "### UAT 15 - Figure face colours\n",
    "\n",
    "The nbagg honours all colours apart from that of the figure.patch. The two plots below should produce a figure with a red background. There should be no yellow figure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib\n",
    "matplotlib.rcParams.update({'figure.facecolor': 'red',\n",
    "                            'savefig.facecolor': 'yellow'})\n",
    "plt.figure()\n",
    "plt.plot([3, 2, 1])\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 16 - Events\n",
    "\n",
    "Pressing any keyboard key or mouse button (or scrolling) should cycle the line line while the figure has focus.  The figure should have focus by default when it is created and re-gain it by clicking on the canvas.  Clicking anywhere outside of the figure should release focus, but moving the mouse out of the figure should not release focus."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import itertools\n",
    "fig, ax = plt.subplots()\n",
    "x = np.linspace(0,10,10000)\n",
    "y = np.sin(x)\n",
    "ln, = ax.plot(x,y)\n",
    "evt = []\n",
    "colors = iter(itertools.cycle(['r', 'g', 'b', 'k', 'c']))\n",
    "def on_event(event):\n",
    "    if event.name.startswith('key'):\n",
    "        fig.suptitle('%s: %s' % (event.name, event.key))\n",
    "    elif event.name == 'scroll_event':\n",
    "        fig.suptitle('%s: %s' % (event.name, event.step))\n",
    "    else:\n",
    "        fig.suptitle('%s: %s' % (event.name, event.button))\n",
    "    evt.append(event)\n",
    "    ln.set_color(next(colors))\n",
    "    fig.canvas.draw()\n",
    "    fig.canvas.draw_idle()\n",
    "\n",
    "fig.canvas.mpl_connect('button_press_event', on_event)\n",
    "fig.canvas.mpl_connect('button_release_event', on_event)\n",
    "fig.canvas.mpl_connect('scroll_event', on_event)\n",
    "fig.canvas.mpl_connect('key_press_event', on_event)\n",
    "fig.canvas.mpl_connect('key_release_event', on_event)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 17 - Timers\n",
    "\n",
    "Single-shot timers follow a completely different code path in the nbagg backend than regular timers (such as those used in the animation example above.)  The next set of tests ensures that both \"regular\" and \"single-shot\" timers work properly.\n",
    "\n",
    "The following should show a simple clock that updates twice a second:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "text = ax.text(0.5, 0.5, '', ha='center')\n",
    "\n",
    "def update(text):\n",
    "    text.set(text=time.ctime())\n",
    "    text.axes.figure.canvas.draw()\n",
    "    \n",
    "timer = fig.canvas.new_timer(500, [(update, [text], {})])\n",
    "timer.start()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, the following should only update once and then stop:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "text = ax.text(0.5, 0.5, '', ha='center') \n",
    "timer = fig.canvas.new_timer(500, [(update, [text], {})])\n",
    "\n",
    "timer.single_shot = True\n",
    "timer.start()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the next two examples should never show any visible text at all:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "text = ax.text(0.5, 0.5, '', ha='center')\n",
    "timer = fig.canvas.new_timer(500, [(update, [text], {})])\n",
    "\n",
    "timer.start()\n",
    "timer.stop()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "text = ax.text(0.5, 0.5, '', ha='center')\n",
    "timer = fig.canvas.new_timer(500, [(update, [text], {})])\n",
    "\n",
    "timer.single_shot = True\n",
    "timer.start()\n",
    "timer.stop()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### UAT 18 - stopping figure when removed from DOM\n",
    "\n",
    "When the div that contains from the figure is removed from the DOM the figure should shut down it's comm, and if the python-side figure has no more active comms, it should destroy the figure. Repeatedly running the cell below should always have the same figure number"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(range(5))\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Running the cell below will re-show the figure. After this, re-running the cell above should result in a new figure number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig.canvas.manager.reshow()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### UAT 19 - Blitting\n",
    "\n",
    "Clicking on the figure should plot a green horizontal line moving up the axes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import itertools\n",
    "\n",
    "cnt = itertools.count()\n",
    "bg = None\n",
    "\n",
    "def onclick_handle(event):\n",
    "    \"\"\"Should draw elevating green line on each mouse click\"\"\"\n",
    "    global bg\n",
    "    if bg is None:\n",
    "        bg = ax.figure.canvas.copy_from_bbox(ax.bbox) \n",
    "    ax.figure.canvas.restore_region(bg)\n",
    "\n",
    "    cur_y = (next(cnt) % 10) * 0.1\n",
    "    ln.set_ydata([cur_y, cur_y])\n",
    "    ax.draw_artist(ln)\n",
    "    ax.figure.canvas.blit(ax.bbox)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot([0, 1], [0, 1], 'r')\n",
    "ln, = ax.plot([0, 1], [0, 0], 'g', animated=True)\n",
    "plt.show()\n",
    "ax.figure.canvas.draw()\n",
    "\n",
    "ax.figure.canvas.mpl_connect('button_press_event', onclick_handle)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
