{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Deploying Bokeh Apps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import holoviews as hv\n",
    "hv.extension('bokeh')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Purpose\n",
    "\n",
    "HoloViews is an incredibly convenient way of working interactively and exploratively within a notebook or commandline context. However, once you have implemented a polished interactive dashboard or some other complex interactive visualization, you will often want to deploy it outside the notebook to share with others who may not be comfortable with the notebook interface. \n",
    "\n",
    "In the simplest case, to visualize some HoloViews container or element `obj`, you can export it to a standalone HTML file for sharing using the `save` function of the Bokeh renderer:\n",
    "\n",
    "```\n",
    "hv.save(obj, 'out.html')\n",
    "```\n",
    "\n",
    "This command will generate a file `out.html` that you can put on any web server, email directly to colleagues, etc.; it is fully self-contained and does not require any Python server to be installed or running.  \n",
    "\n",
    "Unfortunately, a static approach like this cannot support any HoloViews object that uses DynamicMap (either directly or via operations that return DynamicMaps like `decimate`, `datashade`, and `rasterize`).  Anything with DynamicMap requires a live, running Python server to dynamically select and provide the data for the various parameters that can be selected by the user. Luckily, when you need a live Python process during the visualization, the [Bokeh server](http://bokeh.pydata.org/en/latest/docs/user_guide/server.html) provides a very convenient way of deploying HoloViews plots and interactive dashboards in a scalable and flexible manner. The Bokeh server allows all the usual interactions that HoloViews lets you define and more including:\n",
    "\n",
    "* responding to plot events and tool interactions via [Linked Streams](./13-Custom_Interactivity.ipynb)\n",
    "* generating and interacting with plots via the usual widgets that HoloViews supports for HoloMap and DynamicMap objects.\n",
    "* using periodic and timeout events to drive plot updates\n",
    "* combining HoloViews plots with custom Bokeh plots to quickly write highly customized apps.\n",
    "\n",
    "## Overview\n",
    "\n",
    "In this guide we will cover how we can deploy a Bokeh app from a HoloViews plot in a number of different ways:\n",
    "\n",
    "1. Inline from within the Jupyter notebook\n",
    "\n",
    "2. Starting a server interactively and open it in a new browser window.\n",
    "\n",
    "3. From a standalone script file\n",
    "\n",
    "4. Combining HoloViews and Bokeh models to create a more customized app\n",
    "\n",
    "If you have read a bit about HoloViews you will know that HoloViews objects are not themselves plots, instead they contain sufficient data and metadata allowing them to be rendered automatically in a notebook context. In other words, when a HoloViews object is evaluated a backend specific ``Renderer`` converts the HoloViews object into Bokeh models, a Matplotlib figure or a Plotly graph. This intermediate representation is then rendered as an image or as HTML with associated Javascript, which is what ends up being displayed.\n",
    "\n",
    "## The workflow\n",
    "\n",
    "The most convenient way to work with HoloViews is to iteratively improve a visualization in the notebook. Once you have developed a visualization or dashboard that you would like to deploy you can use the ``BokehRenderer`` to export the visualization as illustrated above, or you can deploy it as a Bokeh server app. \n",
    "\n",
    "Here we will create a small interactive plot, using [Linked Streams](./13-Custom_Interactivity.ipynb), which mirrors the points selected using box- and lasso-select tools in a second plot and computes some statistics:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Declare some points\n",
    "points = hv.Points(np.random.randn(1000,2 ))\n",
    "\n",
    "# Declare points as source of selection stream\n",
    "selection = hv.streams.Selection1D(source=points)\n",
    "\n",
    "# Write function that uses the selection indices to slice points and compute stats\n",
    "def selected_info(index):\n",
    "    arr = points.array()[index]\n",
    "    if index:\n",
    "        label = 'Mean x, y: %.3f, %.3f' % tuple(arr.mean(axis=0))\n",
    "    else:\n",
    "        label = 'No selection'\n",
    "    return points.clone(arr, label=label).opts(color='red')\n",
    "\n",
    "# Combine points and DynamicMap\n",
    "selected_points = hv.DynamicMap(selected_info, streams=[selection])\n",
    "layout = points.opts(tools=['box_select', 'lasso_select']) + selected_points\n",
    "\n",
    "layout"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src='https://assets.holoviews.org/gifs/examples/streams/bokeh/point_selection1d.gif'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Working with the BokehRenderer\n",
    "\n",
    "When working with Bokeh server or wanting to manipulate a backend specific plot object you will have to use a HoloViews ``Renderer`` directly to convert the HoloViews object into the backend specific representation. Therefore we will start by getting a hold of a ``BokehRenderer``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "renderer = hv.renderer('bokeh')\n",
    "print(renderer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "BokehRenderer()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All ``Renderer`` classes in HoloViews are so called ParameterizedFunctions; they provide both classmethods and instance methods to render an object. You can easily create a new ``Renderer`` instance using the ``.instance`` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "renderer = renderer.instance(mode='server')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Renderers can also have different modes. In this case we will instantiate the renderer in ``'server'`` mode, which tells the Renderer to render the HoloViews object to a format that can easily be deployed as a server app. Before going into more detail about deploying server apps we will quickly remind ourselves how the renderer turns HoloViews objects into Bokeh models."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Figures\n",
    "\n",
    "The BokehRenderer converts the HoloViews object to a HoloViews ``Plot``, which holds the Bokeh models that will be rendered to screen. As a very simple example we can convert a HoloViews ``Image`` to a HoloViews plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot = renderer.get_plot(layout)\n",
    "print(plot)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "<LayoutPlot LayoutPlot01811>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using the ``state`` attribute on the HoloViews plot we can access the Bokeh ``Column`` model, which we can then work with directly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot.state"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Column**(id='1570', ...)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the background this is how HoloViews converts any HoloViews object into Bokeh models, which can then be converted to embeddable or standalone HTML and be rendered in the browser. This conversion is usually done in the background using the ``figure_data`` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "html = renderer._figure_data(plot, 'html')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bokeh Documents\n",
    "\n",
    "In Bokeh the [``Document``](http://bokeh.pydata.org/en/latest/docs/reference/document.html) is the basic unit at which Bokeh models (such as plots, layouts and widgets) are held and serialized. The serialized JSON representation is then sent to BokehJS on the client-side browser. When in ``'server'`` mode the BokehRenderer will automatically return a server Document:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "renderer(layout)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "(<bokeh.document.Document at 0x11afc7590>,\n",
    " {'file-ext': 'html', 'mime_type': u'text/html'})\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also easily use the ``server_doc`` method to get a Bokeh ``Document``, which does not require you to make an instance in 'server' mode."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "doc = renderer.server_doc(layout)\n",
    "doc.title = 'HoloViews App'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the background however, HoloViews uses the Panel library to render components to a Bokeh model which can be rendered in the notebook, to a file or on a server:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import panel as pn\n",
    "\n",
    "model = pn.panel(layout).get_root()\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For more information on the interaction between Panel and HoloViews see the the [Panel documentation](https://panel.holoviz.org/reference/panes/HoloViews.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Deploying with ``panel serve``"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Deployment from a script with `panel serve` is one of the most common ways to deploy a Bokeh app. Any ``.py`` or ``.ipynb`` file that attaches a plot to Bokeh's ``curdoc`` can be deployed using ``panel serve``. The easiest way to do this is using wrapping the HoloViews component in Panel using ``pn.panel(hvobj)`` and then calling the ``panel_obj.servable()`` method, which accepts any HoloViews object ensures that the plot is discoverable by Panel and the underlying Bokeh server. See below to see a full standalone script:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "import numpy as np\n",
    "import panel as pn\n",
    "import holoviews as hv\n",
    "import holoviews.plotting.bokeh\n",
    "\n",
    "points = hv.Points(np.random.randn(1000,2 )).opts(tools=['box_select', 'lasso_select'])\n",
    "selection = hv.streams.Selection1D(source=points)\n",
    "\n",
    "def selected_info(index):\n",
    "    arr = points.array()[index]\n",
    "    if index:\n",
    "        label = 'Mean x, y: %.3f, %.3f' % tuple(arr.mean(axis=0))\n",
    "    else:\n",
    "        label = 'No selection'\n",
    "    return points.clone(arr, label=label).opts(color='red')\n",
    "\n",
    "layout = points + hv.DynamicMap(selected_info, streams=[selection])\n",
    "\n",
    "pn.panel(layout).servable(title='HoloViews App')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In just a few steps we can iteratively refine in the notebook to a deployable Panel app. Note also that we can also deploy an app directly from a notebook. By using `.servable()` in a notebook any regular ``.ipynb`` file can be made into a valid Panel/Bokeh app, which can be served with ``panel serve example.ipynb``.\n",
    "\n",
    "It is also possible to create a Bokeh `Document` more directly working with the underlying Bokeh representation instead. This in itself is sufficient to make the plot servable using `bokeh serve`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.renderer('bokeh').server_doc(layout)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition to starting a server from a script we can also start up a server interactively, so let's do a quick deep dive into Bokeh ``Application`` and ``Server`` objects and how we can work with them from within HoloViews."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bokeh Server\n",
    "\n",
    "To start a Bokeh server directly from a notebook we can also use Panel, specifically we'll use the `panel.serve` function. We'll define a ``DynamicMap`` of a sine ``Curve`` varying by frequency, phase and an offset and then create a server instance using Panel:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sine(frequency, phase, amplitude):\n",
    "    xs = np.linspace(0, np.pi*4)\n",
    "    return hv.Curve((xs, np.sin(frequency*xs+phase)*amplitude)).opts(width=800)\n",
    "\n",
    "ranges = dict(frequency=(1, 5), phase=(-np.pi, np.pi), amplitude=(-2, 2), y=(-2, 2))\n",
    "dmap = hv.DynamicMap(sine, kdims=['frequency', 'phase', 'amplitude']).redim.range(**ranges)\n",
    "\n",
    "server = pn.serve(dmap, start=False, show=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "<bokeh.server.server.Server object at 0x10b3a0510>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we can define a callback on the IOLoop that will open the server app in a new browser window and actually start the app (and if outside the notebook the IOLoop):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "server.start()\n",
    "server.show('/')\n",
    "\n",
    "# Outside the notebook ioloop needs to be started\n",
    "# from tornado.ioloop import IOLoop\n",
    "# loop = IOLoop.current()\n",
    "# loop.start() "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After running the cell above you should have noticed a new browser window popping up displaying our plot. Once you are done playing with it you can stop it with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "server.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can achieve the equivalent using the `.show` method on a Panel object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "server = pn.panel(dmap).show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img width='80%' src=\"https://assets.holoviews.org/gifs/guides/user_guide/Deploying_Bokeh_Apps/bokeh_server_new_window.png\"></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will once again stop this Server before continuing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "server.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inlining apps in the notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Instead of displaying our app in a new browser window we can also display an app inline in the notebook simply by using the `.app` method on Panel object. The server app will be killed whenever you rerun or delete the cell that contains the output. Additionally, if your Jupyter Notebook server is not running on the default address or port (``localhost:8888``) supply the websocket origin, which should match the first part of the URL of your notebook:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dmap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img width='80%' src='https://assets.holoviews.org/gifs/guides/user_guide/Deploying_Bokeh_Apps/bokeh_server_inline_simple.gif'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Periodic callbacks\n",
    "\n",
    "One of the most important features of deploying apps is the ability to attach asynchronous, periodic callbacks, which update the plot. The simplest way of achieving this is to attach a ``Counter`` stream on the plot which is incremented on each callback. As a simple demo we'll simply compute a phase offset from the counter value, animating the sine wave:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sine(counter):\n",
    "    phase = counter*0.1%np.pi*2\n",
    "    xs = np.linspace(0, np.pi*4)\n",
    "    return hv.Curve((xs, np.sin(xs+phase))).opts(width=800)\n",
    "\n",
    "counter = hv.streams.Counter()\n",
    "hv.DynamicMap(sine, streams=[counter])\n",
    "\n",
    "dmap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img width='80%' src='https://assets.holoviews.org/gifs/guides/user_guide/Deploying_Bokeh_Apps/bokeh_server_periodic.gif'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once we have created a Panel object we can call the `add_periodic_callback` method to set up a periodic callback. The first argument to the method is the callback and the second argument period specified in milliseconds. As soon as we start this callback you should see the Curve above become animated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def update():\n",
    "    counter.event(counter=counter.counter+1)\n",
    "\n",
    "cb = pn.state.add_periodic_callback(update, period=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once started we can stop and start it at will using the `.stop` and `.start` methods:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cb.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Combining Bokeh Application and Flask Application\n",
    "\n",
    "While Panel and Bokeh are great ways to create an application often we want to leverage the simplicity of a Flask server. With Flask we can easily embed a HoloViews, Bokeh and Panel application in a regular website. The main idea for getting Bokeh and Flask to work together is to run both apps on ports and then use Flask to pull the Bokeh Serve session with `pull_session` from [bokeh.client.session](https://bokeh.pydata.org/en/latest/docs/reference/client/session.html). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sine(frequency, phase, amplitude):\n",
    "    xs = np.linspace(0, np.pi*4)\n",
    "    return hv.Curve((xs, np.sin(frequency*xs+phase)*amplitude)).options(width=800)\n",
    "\n",
    "ranges = dict(frequency=(1, 5), phase=(-np.pi, np.pi), amplitude=(-2, 2), y=(-2, 2))\n",
    "dmap = hv.DynamicMap(sine, kdims=['frequency', 'phase', 'amplitude']).redim.range(**ranges)\n",
    "\n",
    "pn.serve(dmap, websocket_origin='localhost:5000', port=5006, show=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We run load up our dynamic map into a Bokeh Application with the parameter `allow_websocket_origin=[\"localhost:5000\"]`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "from bokeh.client import pull_session\n",
    "from bokeh.embed import server_session\n",
    "from flask import Flask, render_template\n",
    "from flask import send_from_directory\n",
    "\n",
    "app = Flask(__name__)\n",
    "\n",
    "\n",
    "# locally creates a page\n",
    "@app.route('/')\n",
    "def index():\n",
    "    with pull_session(url=\"http://localhost:5006/\") as session:\n",
    "        # generate a script to load the customized session\n",
    "        script = server_session(session_id=session.id, url='http://localhost:5006')\n",
    "        # use the script in the rendered page\n",
    "    return render_template(\"embed.html\", script=script, template=\"Flask\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    # runs app in debug mode\n",
    "    app.run(port=5000, debug=True)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that in a notebook context we cannot use `pull_session` but this example demonstrates how we can embed the Bokeh server inside a simple flask app.\n",
    "\n",
    "This is an example of a basic flask app. To find out more about Flask a tutorial can be found on the [Flask Quickstart Guide](http://flask.pocoo.org/docs/1.0/quickstart/#). \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Below is an example of a basic Flask App that pulls from the Bokeh Application. The Bokeh Application is using `Server` from Bokeh and `IOLoop` from tornado to run the app. \n",
    "\n",
    "```python\n",
    "# holoviews.py\n",
    "\n",
    "import holoviews as hv\n",
    "import panel as pn\n",
    "import numpy as np\n",
    "\n",
    "hv.extension('bokeh')\n",
    "\n",
    "def sine(frequency, phase, amplitude):\n",
    "    xs = np.linspace(0, np.pi*4)\n",
    "    return hv.Curve((xs, np.sin(frequency*xs+phase)*amplitude)).options(width=800)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    ranges = dict(frequency=(1, 5), phase=(-np.pi, np.pi), amplitude=(-2, 2), y=(-2, 2))\n",
    "    dmap = hv.DynamicMap(sine, kdims=['frequency', 'phase', 'amplitude']).redim.range(**ranges)\n",
    "    pn.serve(dmap, port=5006, allow_websocket_origin=[\"localhost:5000\"], show=False)\n",
    "```\n",
    "\n",
    "```python\n",
    "#flaskApp.py\n",
    "\n",
    "from bokeh.client import pull_session\n",
    "from bokeh.embed import server_session\n",
    "from flask import Flask, render_template\n",
    "from flask import send_from_directory\n",
    "\n",
    "app = Flask(__name__)\n",
    "\n",
    "# locally creates a page\n",
    "@app.route('/')\n",
    "def index():\n",
    "    with pull_session(url=\"http://localhost:5006/\") as session:\n",
    "            # generate a script to load the customized session\n",
    "            script = server_session(session_id=session.id, url='http://localhost:5006')\n",
    "            # use the script in the rendered page\n",
    "    return render_template(\"embed.html\", script=script, template=\"Flask\")\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    # runs app in debug mode\n",
    "    app.run(port=5000, debug=True)\n",
    "```\n",
    "\n",
    "```html\n",
    "<!-- embed.html -->\n",
    "\n",
    "<!doctype html>\n",
    "\n",
    "<html lang=\"en\">\n",
    "<head>\n",
    "  <meta charset=\"utf-8\">\n",
    "  <title>Embedding a Bokeh Server With Flask</title>\n",
    "</head>\n",
    "\n",
    "<body>\n",
    "  <div>\n",
    "    This Bokeh app below served by a Bokeh server that has been embedded\n",
    "    in another web app framework. For more information see the section\n",
    "    <a  target=\"_blank\" href=\"https://bokeh.pydata.org/en/latest/docs/user_guide/server.html#embedding-bokeh-server-as-a-library\">Embedding Bokeh Server as a Library</a>\n",
    "    in the User's Guide.\n",
    "  </div>\n",
    "  {{ script|safe }}\n",
    "</body>\n",
    "</html>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you wish to replicate navigate to the `examples/gallery/apps/flask` directory and follow the these steps:\n",
    "\n",
    "* Step One: call `python holoviews_app.py` in the terminal (this will start the Panel/Bokeh server)\n",
    "* Step Two: open a new terminal and call `python flask_app.py` (this will start the Flask application)\n",
    "* Step Three: go to web browser and type `localhost:5000` and the app will appear"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Combining HoloViews and Panel or Bokeh Plots/Widgets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While HoloViews provides very convenient ways of creating an app it is not as fully featured as Bokeh itself is. Therefore we often want to extend a HoloViews based app with Panel or Bokeh plots and widgets. Here we will discover to achieve this with both Panel and then the equivalent using pure Bokeh."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import holoviews as hv\n",
    "import numpy as np\n",
    "import panel as pn\n",
    "\n",
    "# Create the holoviews app again\n",
    "def sine(phase):\n",
    "    xs = np.linspace(0, np.pi*4)\n",
    "    return hv.Curve((xs, np.sin(xs+phase))).opts(width=800)\n",
    "\n",
    "stream = hv.streams.Stream.define('Phase', phase=0.)()\n",
    "dmap = hv.DynamicMap(sine, streams=[stream])\n",
    "\n",
    "start, end = 0, np.pi*2\n",
    "slider = pn.widgets.FloatSlider(start=start, end=end, value=start, step=0.2, name=\"Phase\")\n",
    "\n",
    "# Create a slider and play buttons\n",
    "def animate_update():\n",
    "    year = slider.value + 0.2\n",
    "    if year > end:\n",
    "        year = start\n",
    "    slider.value = year\n",
    "\n",
    "def slider_update(event):\n",
    "    # Notify the HoloViews stream of the slider update \n",
    "    stream.event(phase=event.new)\n",
    "\n",
    "slider.param.watch(slider_update, 'value')\n",
    "\n",
    "def animate(event):\n",
    "    if button.name == '► Play':\n",
    "        button.name = '❚❚ Pause'\n",
    "        callback.start()\n",
    "    else:\n",
    "        button.name = '► Play'\n",
    "        callback.stop()\n",
    "\n",
    "button = pn.widgets.Button(name='► Play', width=60, align='end')\n",
    "button.on_click(animate)\n",
    "callback = pn.state.add_periodic_callback(animate_update, 50, start=False)\n",
    "\n",
    "app = pn.Column(\n",
    "    dmap,\n",
    "    pn.Row(slider, button)\n",
    ")\n",
    "\n",
    "app"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If instead we want to deploy this we could add `.servable` as discussed before or use `pn.serve`. Note however that when using `pn.serve` all sessions will share the same state therefore it is best to \n",
    "wrap the creation of the app in a function which we can then provide to `pn.serve`. For more detail on deploying Panel applications also see the [Panel server deployment guide](https://panel.holoviz.org/user_guide/Server_Deployment.html).\n",
    "\n",
    "Now we can reimplement the same example using Bokeh allowing us to compare and contrast the approaches:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import holoviews as hv\n",
    "\n",
    "from bokeh.io import show, curdoc\n",
    "from bokeh.layouts import layout\n",
    "from bokeh.models import Slider, Button\n",
    "\n",
    "renderer = hv.renderer('bokeh').instance(mode='server')\n",
    "\n",
    "# Create the holoviews app again\n",
    "def sine(phase):\n",
    "    xs = np.linspace(0, np.pi*4)\n",
    "    return hv.Curve((xs, np.sin(xs+phase))).opts(width=800)\n",
    "\n",
    "stream = hv.streams.Stream.define('Phase', phase=0.)()\n",
    "dmap = hv.DynamicMap(sine, streams=[stream])\n",
    "\n",
    "# Define valid function for FunctionHandler\n",
    "# when deploying as script, simply attach to curdoc\n",
    "def modify_doc(doc):\n",
    "    # Create HoloViews plot and attach the document\n",
    "    hvplot = renderer.get_plot(dmap, doc)\n",
    "\n",
    "    # Create a slider and play buttons\n",
    "    def animate_update():\n",
    "        year = slider.value + 0.2\n",
    "        if year > end:\n",
    "            year = start\n",
    "        slider.value = year\n",
    "\n",
    "    def slider_update(attrname, old, new):\n",
    "        # Notify the HoloViews stream of the slider update \n",
    "        stream.event(phase=new)\n",
    "        \n",
    "    start, end = 0, np.pi*2\n",
    "    slider = Slider(start=start, end=end, value=start, step=0.2, title=\"Phase\")\n",
    "    slider.on_change('value', slider_update)\n",
    "    \n",
    "    callback_id = None\n",
    "\n",
    "    def animate():\n",
    "        global callback_id\n",
    "        if button.label == '► Play':\n",
    "            button.label = '❚❚ Pause'\n",
    "            callback_id = doc.add_periodic_callback(animate_update, 50)\n",
    "        else:\n",
    "            button.label = '► Play'\n",
    "            doc.remove_periodic_callback(callback_id)\n",
    "    button = Button(label='► Play', width=60)\n",
    "    button.on_click(animate)\n",
    "    \n",
    "    # Combine the holoviews plot and widgets in a layout\n",
    "    plot = layout([\n",
    "    [hvplot.state],\n",
    "    [slider, button]], sizing_mode='fixed')\n",
    "    \n",
    "    doc.add_root(plot)\n",
    "    return doc\n",
    "\n",
    "# To display in the notebook\n",
    "show(modify_doc, notebook_url='localhost:8888')\n",
    "\n",
    "# To display in a script\n",
    "#    doc = modify_doc(curdoc()) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img width='80%' src='https://assets.holoviews.org/gifs/guides/user_guide/Deploying_Bokeh_Apps/bokeh_server_play.gif'></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see depending on your needs you have complete freedom whether to use just HoloViews and deploy your application, combine it Panel or even with pure Bokeh."
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
