{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0b1323d6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/javascript": [
       "(function(root) {\n",
       "  function now() {\n",
       "    return new Date();\n",
       "  }\n",
       "\n",
       "  const force = true;\n",
       "\n",
       "  if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n",
       "    root._bokeh_onload_callbacks = [];\n",
       "    root._bokeh_is_loading = undefined;\n",
       "  }\n",
       "\n",
       "const JS_MIME_TYPE = 'application/javascript';\n",
       "  const HTML_MIME_TYPE = 'text/html';\n",
       "  const EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n",
       "  const CLASS_NAME = 'output_bokeh rendered_html';\n",
       "\n",
       "  /**\n",
       "   * Render data to the DOM node\n",
       "   */\n",
       "  function render(props, node) {\n",
       "    const script = document.createElement(\"script\");\n",
       "    node.appendChild(script);\n",
       "  }\n",
       "\n",
       "  /**\n",
       "   * Handle when an output is cleared or removed\n",
       "   */\n",
       "  function handleClearOutput(event, handle) {\n",
       "    const cell = handle.cell;\n",
       "\n",
       "    const id = cell.output_area._bokeh_element_id;\n",
       "    const server_id = cell.output_area._bokeh_server_id;\n",
       "    // Clean up Bokeh references\n",
       "    if (id != null && id in Bokeh.index) {\n",
       "      Bokeh.index[id].model.document.clear();\n",
       "      delete Bokeh.index[id];\n",
       "    }\n",
       "\n",
       "    if (server_id !== undefined) {\n",
       "      // Clean up Bokeh references\n",
       "      const cmd_clean = \"from bokeh.io.state import curstate; print(curstate().uuid_to_server['\" + server_id + \"'].get_sessions()[0].document.roots[0]._id)\";\n",
       "      cell.notebook.kernel.execute(cmd_clean, {\n",
       "        iopub: {\n",
       "          output: function(msg) {\n",
       "            const id = msg.content.text.trim();\n",
       "            if (id in Bokeh.index) {\n",
       "              Bokeh.index[id].model.document.clear();\n",
       "              delete Bokeh.index[id];\n",
       "            }\n",
       "          }\n",
       "        }\n",
       "      });\n",
       "      // Destroy server and session\n",
       "      const cmd_destroy = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n",
       "      cell.notebook.kernel.execute(cmd_destroy);\n",
       "    }\n",
       "  }\n",
       "\n",
       "  /**\n",
       "   * Handle when a new output is added\n",
       "   */\n",
       "  function handleAddOutput(event, handle) {\n",
       "    const output_area = handle.output_area;\n",
       "    const output = handle.output;\n",
       "\n",
       "    // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n",
       "    if ((output.output_type != \"display_data\") || (!Object.prototype.hasOwnProperty.call(output.data, EXEC_MIME_TYPE))) {\n",
       "      return\n",
       "    }\n",
       "\n",
       "    const toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n",
       "\n",
       "    if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n",
       "      toinsert[toinsert.length - 1].firstChild.textContent = output.data[JS_MIME_TYPE];\n",
       "      // store reference to embed id on output_area\n",
       "      output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n",
       "    }\n",
       "    if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n",
       "      const bk_div = document.createElement(\"div\");\n",
       "      bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n",
       "      const script_attrs = bk_div.children[0].attributes;\n",
       "      for (let i = 0; i < script_attrs.length; i++) {\n",
       "        toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n",
       "        toinsert[toinsert.length - 1].firstChild.textContent = bk_div.children[0].textContent\n",
       "      }\n",
       "      // store reference to server id on output_area\n",
       "      output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n",
       "    }\n",
       "  }\n",
       "\n",
       "  function register_renderer(events, OutputArea) {\n",
       "\n",
       "    function append_mime(data, metadata, element) {\n",
       "      // create a DOM node to render to\n",
       "      const toinsert = this.create_output_subarea(\n",
       "        metadata,\n",
       "        CLASS_NAME,\n",
       "        EXEC_MIME_TYPE\n",
       "      );\n",
       "      this.keyboard_manager.register_events(toinsert);\n",
       "      // Render to node\n",
       "      const props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n",
       "      render(props, toinsert[toinsert.length - 1]);\n",
       "      element.append(toinsert);\n",
       "      return toinsert\n",
       "    }\n",
       "\n",
       "    /* Handle when an output is cleared or removed */\n",
       "    events.on('clear_output.CodeCell', handleClearOutput);\n",
       "    events.on('delete.Cell', handleClearOutput);\n",
       "\n",
       "    /* Handle when a new output is added */\n",
       "    events.on('output_added.OutputArea', handleAddOutput);\n",
       "\n",
       "    /**\n",
       "     * Register the mime type and append_mime function with output_area\n",
       "     */\n",
       "    OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n",
       "      /* Is output safe? */\n",
       "      safe: true,\n",
       "      /* Index of renderer in `output_area.display_order` */\n",
       "      index: 0\n",
       "    });\n",
       "  }\n",
       "\n",
       "  // register the mime type if in Jupyter Notebook environment and previously unregistered\n",
       "  if (root.Jupyter !== undefined) {\n",
       "    const events = require('base/js/events');\n",
       "    const OutputArea = require('notebook/js/outputarea').OutputArea;\n",
       "\n",
       "    if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n",
       "      register_renderer(events, OutputArea);\n",
       "    }\n",
       "  }\n",
       "  if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n",
       "    root._bokeh_timeout = Date.now() + 5000;\n",
       "    root._bokeh_failed_load = false;\n",
       "  }\n",
       "\n",
       "  const NB_LOAD_WARNING = {'data': {'text/html':\n",
       "     \"<div style='background-color: #fdd'>\\n\"+\n",
       "     \"<p>\\n\"+\n",
       "     \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n",
       "     \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n",
       "     \"</p>\\n\"+\n",
       "     \"<ul>\\n\"+\n",
       "     \"<li>re-rerun `output_notebook()` to attempt to load from CDN again, or</li>\\n\"+\n",
       "     \"<li>use INLINE resources instead, as so:</li>\\n\"+\n",
       "     \"</ul>\\n\"+\n",
       "     \"<code>\\n\"+\n",
       "     \"from bokeh.resources import INLINE\\n\"+\n",
       "     \"output_notebook(resources=INLINE)\\n\"+\n",
       "     \"</code>\\n\"+\n",
       "     \"</div>\"}};\n",
       "\n",
       "  function display_loaded() {\n",
       "    const el = document.getElementById(null);\n",
       "    if (el != null) {\n",
       "      el.textContent = \"BokehJS is loading...\";\n",
       "    }\n",
       "    if (root.Bokeh !== undefined) {\n",
       "      if (el != null) {\n",
       "        el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n",
       "      }\n",
       "    } else if (Date.now() < root._bokeh_timeout) {\n",
       "      setTimeout(display_loaded, 100)\n",
       "    }\n",
       "  }\n",
       "\n",
       "  function run_callbacks() {\n",
       "    try {\n",
       "      root._bokeh_onload_callbacks.forEach(function(callback) {\n",
       "        if (callback != null)\n",
       "          callback();\n",
       "      });\n",
       "    } finally {\n",
       "      delete root._bokeh_onload_callbacks\n",
       "    }\n",
       "    console.debug(\"Bokeh: all callbacks have finished\");\n",
       "  }\n",
       "\n",
       "  function load_libs(css_urls, js_urls, callback) {\n",
       "    if (css_urls == null) css_urls = [];\n",
       "    if (js_urls == null) js_urls = [];\n",
       "\n",
       "    root._bokeh_onload_callbacks.push(callback);\n",
       "    if (root._bokeh_is_loading > 0) {\n",
       "      console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n",
       "      return null;\n",
       "    }\n",
       "    if (js_urls == null || js_urls.length === 0) {\n",
       "      run_callbacks();\n",
       "      return null;\n",
       "    }\n",
       "    console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n",
       "    root._bokeh_is_loading = css_urls.length + js_urls.length;\n",
       "\n",
       "    function on_load() {\n",
       "      root._bokeh_is_loading--;\n",
       "      if (root._bokeh_is_loading === 0) {\n",
       "        console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n",
       "        run_callbacks()\n",
       "      }\n",
       "    }\n",
       "\n",
       "    function on_error(url) {\n",
       "      console.error(\"failed to load \" + url);\n",
       "    }\n",
       "\n",
       "    for (let i = 0; i < css_urls.length; i++) {\n",
       "      const url = css_urls[i];\n",
       "      const element = document.createElement(\"link\");\n",
       "      element.onload = on_load;\n",
       "      element.onerror = on_error.bind(null, url);\n",
       "      element.rel = \"stylesheet\";\n",
       "      element.type = \"text/css\";\n",
       "      element.href = url;\n",
       "      console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n",
       "      document.body.appendChild(element);\n",
       "    }\n",
       "\n",
       "    for (let i = 0; i < js_urls.length; i++) {\n",
       "      const url = js_urls[i];\n",
       "      const element = document.createElement('script');\n",
       "      element.onload = on_load;\n",
       "      element.onerror = on_error.bind(null, url);\n",
       "      element.async = false;\n",
       "      element.src = url;\n",
       "      console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n",
       "      document.head.appendChild(element);\n",
       "    }\n",
       "  };\n",
       "\n",
       "  function inject_raw_css(css) {\n",
       "    const element = document.createElement(\"style\");\n",
       "    element.appendChild(document.createTextNode(css));\n",
       "    document.body.appendChild(element);\n",
       "  }\n",
       "\n",
       "  const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.min.js\"];\n",
       "  const css_urls = [];\n",
       "\n",
       "  const inline_js = [    function(Bokeh) {\n",
       "      Bokeh.set_log_level(\"info\");\n",
       "    },\n",
       "function(Bokeh) {\n",
       "    }\n",
       "  ];\n",
       "\n",
       "  function run_inline_js() {\n",
       "    if (root.Bokeh !== undefined || force === true) {\n",
       "          for (let i = 0; i < inline_js.length; i++) {\n",
       "      inline_js[i].call(root, root.Bokeh);\n",
       "    }\n",
       "} else if (Date.now() < root._bokeh_timeout) {\n",
       "      setTimeout(run_inline_js, 100);\n",
       "    } else if (!root._bokeh_failed_load) {\n",
       "      console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n",
       "      root._bokeh_failed_load = true;\n",
       "    } else if (force !== true) {\n",
       "      const cell = $(document.getElementById(null)).parents('.cell').data().cell;\n",
       "      cell.output_area.append_execute_result(NB_LOAD_WARNING)\n",
       "    }\n",
       "  }\n",
       "\n",
       "  if (root._bokeh_is_loading === 0) {\n",
       "    console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n",
       "    run_inline_js();\n",
       "  } else {\n",
       "    load_libs(css_urls, js_urls, function() {\n",
       "      console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n",
       "      run_inline_js();\n",
       "    });\n",
       "  }\n",
       "}(window));"
      ],
      "application/vnd.bokehjs_load.v0+json": "(function(root) {\n  function now() {\n    return new Date();\n  }\n\n  const force = true;\n\n  if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n    root._bokeh_onload_callbacks = [];\n    root._bokeh_is_loading = undefined;\n  }\n\n\n  if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n    root._bokeh_timeout = Date.now() + 5000;\n    root._bokeh_failed_load = false;\n  }\n\n  const NB_LOAD_WARNING = {'data': {'text/html':\n     \"<div style='background-color: #fdd'>\\n\"+\n     \"<p>\\n\"+\n     \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n     \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n     \"</p>\\n\"+\n     \"<ul>\\n\"+\n     \"<li>re-rerun `output_notebook()` to attempt to load from CDN again, or</li>\\n\"+\n     \"<li>use INLINE resources instead, as so:</li>\\n\"+\n     \"</ul>\\n\"+\n     \"<code>\\n\"+\n     \"from bokeh.resources import INLINE\\n\"+\n     \"output_notebook(resources=INLINE)\\n\"+\n     \"</code>\\n\"+\n     \"</div>\"}};\n\n  function display_loaded() {\n    const el = document.getElementById(null);\n    if (el != null) {\n      el.textContent = \"BokehJS is loading...\";\n    }\n    if (root.Bokeh !== undefined) {\n      if (el != null) {\n        el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n      }\n    } else if (Date.now() < root._bokeh_timeout) {\n      setTimeout(display_loaded, 100)\n    }\n  }\n\n  function run_callbacks() {\n    try {\n      root._bokeh_onload_callbacks.forEach(function(callback) {\n        if (callback != null)\n          callback();\n      });\n    } finally {\n      delete root._bokeh_onload_callbacks\n    }\n    console.debug(\"Bokeh: all callbacks have finished\");\n  }\n\n  function load_libs(css_urls, js_urls, callback) {\n    if (css_urls == null) css_urls = [];\n    if (js_urls == null) js_urls = [];\n\n    root._bokeh_onload_callbacks.push(callback);\n    if (root._bokeh_is_loading > 0) {\n      console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n      return null;\n    }\n    if (js_urls == null || js_urls.length === 0) {\n      run_callbacks();\n      return null;\n    }\n    console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n    root._bokeh_is_loading = css_urls.length + js_urls.length;\n\n    function on_load() {\n      root._bokeh_is_loading--;\n      if (root._bokeh_is_loading === 0) {\n        console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n        run_callbacks()\n      }\n    }\n\n    function on_error(url) {\n      console.error(\"failed to load \" + url);\n    }\n\n    for (let i = 0; i < css_urls.length; i++) {\n      const url = css_urls[i];\n      const element = document.createElement(\"link\");\n      element.onload = on_load;\n      element.onerror = on_error.bind(null, url);\n      element.rel = \"stylesheet\";\n      element.type = \"text/css\";\n      element.href = url;\n      console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n      document.body.appendChild(element);\n    }\n\n    for (let i = 0; i < js_urls.length; i++) {\n      const url = js_urls[i];\n      const element = document.createElement('script');\n      element.onload = on_load;\n      element.onerror = on_error.bind(null, url);\n      element.async = false;\n      element.src = url;\n      console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n      document.head.appendChild(element);\n    }\n  };\n\n  function inject_raw_css(css) {\n    const element = document.createElement(\"style\");\n    element.appendChild(document.createTextNode(css));\n    document.body.appendChild(element);\n  }\n\n  const js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.min.js\"];\n  const css_urls = [];\n\n  const inline_js = [    function(Bokeh) {\n      Bokeh.set_log_level(\"info\");\n    },\nfunction(Bokeh) {\n    }\n  ];\n\n  function run_inline_js() {\n    if (root.Bokeh !== undefined || force === true) {\n          for (let i = 0; i < inline_js.length; i++) {\n      inline_js[i].call(root, root.Bokeh);\n    }\n} else if (Date.now() < root._bokeh_timeout) {\n      setTimeout(run_inline_js, 100);\n    } else if (!root._bokeh_failed_load) {\n      console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n      root._bokeh_failed_load = true;\n    } else if (force !== true) {\n      const cell = $(document.getElementById(null)).parents('.cell').data().cell;\n      cell.output_area.append_execute_result(NB_LOAD_WARNING)\n    }\n  }\n\n  if (root._bokeh_is_loading === 0) {\n    console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n    run_inline_js();\n  } else {\n    load_libs(css_urls, js_urls, function() {\n      console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n      run_inline_js();\n    });\n  }\n}(window));"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import re\n",
    "import requests\n",
    "import base64\n",
    "import ipywidgets as widgets\n",
    "import bokeh.palettes\n",
    "from operator import itemgetter\n",
    "from IPython.display import display, clear_output, HTML\n",
    "from hublib.ui import Download\n",
    "from bokeh.io import show, output_notebook\n",
    "from bokeh.models import ColorBar, ColumnDataSource, CategoricalColorMapper\n",
    "from bokeh.plotting import figure\n",
    "from bokeh.transform import transform\n",
    "\n",
    "output_notebook(hide_banner=True)\n",
    "\n",
    "#API urls\n",
    "api_url='http://85.215.208.224:8983/solr/strainAPI/select?q=allele_symbol:'\n",
    "api_url_two='http://85.215.208.224:8983/solr/strainAPI/select?q=mp_ids:\\\"'\n",
    "api_url_three='http://85.215.208.224:8983/solr/strainAPI/select?q=name:'\n",
    "api_url_end='&rows=2000'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2ee417bf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2be73956f57e47a5a2ee5f81497a3504",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<h1><em><b>Infrafrontier Strains API</b></em></h1>', layout=Layout(margin='0 0 5em …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "class App():\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.tab = widgets.Tab()\n",
    "        self.tab.children = []\n",
    "        \n",
    "        #fisrt tab\n",
    "        self.table_container = widgets.Output()\n",
    "        self.send_button, send_box = self.create_send_button()\n",
    "        self.res_button = self.create_reset_button()\n",
    "        self.container = widgets.VBox([send_box, widgets.HBox([self.send_button,self.res_button])])\n",
    "        self.down_container = widgets.HBox([])\n",
    "        self.tab_one = widgets.VBox([\n",
    "            self.container,\n",
    "            self.table_container,\n",
    "            self.down_container\n",
    "        ])\n",
    "        \n",
    "        #second tab\n",
    "        self.table_container_two = widgets.Output()\n",
    "        self.send_button_two, send_box_two = self.create_send_button_two()\n",
    "        self.res_button_two = self.create_reset_button_two()\n",
    "        self.container_two = widgets.VBox([send_box_two, widgets.HBox([self.send_button_two,self.res_button_two])])\n",
    "        self.down_container_two = widgets.HBox([])\n",
    "        self.tab_two = widgets.VBox([\n",
    "            self.container_two,\n",
    "            self.table_container_two,\n",
    "            self.down_container_two\n",
    "        ])\n",
    "        \n",
    "        #third tab\n",
    "        self.table_container_three = widgets.Output()\n",
    "        self.plot_container = widgets.Output()\n",
    "        self.send_button_three, send_box_three = self.create_send_button_three()\n",
    "        self.plot_button = self.create_plot_button()\n",
    "        self.res_button_three = self.create_reset_button_three()\n",
    "        self.container_three = widgets.VBox([send_box_three, widgets.HBox([self.send_button_three,self.res_button_three])])\n",
    "        self.down_container_three = widgets.HBox([])\n",
    "        self.slider_container = widgets.HBox()\n",
    "        self.tab_three = widgets.VBox([\n",
    "            self.container_three,\n",
    "            self.table_container_three,\n",
    "            self.down_container_three,\n",
    "            self.slider_container,\n",
    "            self.plot_container\n",
    "        ])\n",
    "        \n",
    "        #final view\n",
    "        self.tab.children = [self.tab_one,self.tab_two,self.tab_three]\n",
    "        self.tab.set_title(0, 'MP terms by gene symbols')\n",
    "        self.tab.set_title(1, 'gene symbols by MP terms')\n",
    "        self.tab.set_title(2, 'common mp terms by strains')\n",
    "        self.final_container = widgets.VBox([\n",
    "            widgets.HTML(('<h1><em><b>Infrafrontier Strains API</b></em></h1>'), \n",
    "                         layout=widgets.Layout(margin='0 0 5em 0')),\n",
    "            self.tab\n",
    "        ])\n",
    "        \n",
    "    #FUNCTIONS FOR FIRST TAB PAGE\n",
    "    \n",
    "    \n",
    "    def create_send_button(self):\n",
    "        label = widgets.Label('Gene Symbol:')\n",
    "        self.text_area = widgets.Textarea(placeholder='')\n",
    "        send_b = widgets.Button(description='Submit', tooltip='submit your gene symbol', disabled=True)\n",
    "        send_b.on_click(self.on_change_s)\n",
    "        self.text_area.observe(self.on_change_text, names=['value'])\n",
    "        sub_box = widgets.HBox([label,self.text_area])\n",
    "        return(send_b, sub_box)\n",
    "        \n",
    "    def create_reset_button(self):\n",
    "        reset_b = widgets.Button(description='Reset', tooltip='reset the environment to generate a new table', disabled=True)\n",
    "        reset_b.on_click(self.on_click_r)\n",
    "        return (reset_b) \n",
    "            \n",
    "    def on_change_text(self,_):\n",
    "        if (self.text_area.value == '') | (self.text_area.value.isspace()):\n",
    "            self.send_button.disabled=True\n",
    "        else:\n",
    "            self.send_button.disabled=False\n",
    "        \n",
    "    def on_click_r(self,_):\n",
    "        try:\n",
    "            del(self.df)\n",
    "            for i in self.down_container.children:\n",
    "                remove = self.down_container.children[-1]\n",
    "                self.down_container.children = self.down_container.children[:-1]\n",
    "                remove.close()\n",
    "            for i in self.slider_container.children:\n",
    "                remove = self.slider_container.children[-1]\n",
    "                self.slider_container.children = self.slider_container.children[:-1]\n",
    "                remove.close()\n",
    "        except NameError:\n",
    "            print(\"\")\n",
    "        self.text_area.value=''\n",
    "        self.res_button.disabled=True\n",
    "        self.send_button.disabled=True\n",
    "        self.table_container.clear_output(wait=False)\n",
    "        \n",
    "    def on_change_s(self,_):\n",
    "        with self.table_container:\n",
    "            self.table_container.clear_output(wait=False)\n",
    "            self.send_button.disabled = True\n",
    "            gene = self.text_area.value\n",
    "            query = requests.get(api_url+gene+api_url_end).json()\n",
    "            if (query[\"response\"][\"numFound\"] != 0):\n",
    "                req = query[\"response\"][\"docs\"]\n",
    "                self.df = pd.DataFrame(columns=[\"Gene Symbol\",\"Strain name\",\"MP term ids\", \"MP term names\"])\n",
    "\n",
    "                sym=[]\n",
    "                names = []\n",
    "                mp_ids = []\n",
    "                mp_terms = []\n",
    "                for i in req:\n",
    "                    sym.append(i[\"allele_symbol\"])\n",
    "                    names.append(i[\"name\"])\n",
    "                    mp_ids.append(i[\"mp_ids\"])\n",
    "                    mp_terms.append(i[\"mp_terms\"])\n",
    "\n",
    "                self.df[\"Gene Symbol\"] = sym\n",
    "                self.df[\"Strain name\"] = names\n",
    "                self.df[\"MP term ids\"] = mp_ids\n",
    "                self.df[\"MP term names\"] = mp_terms\n",
    "                del(sym,names,mp_ids,mp_terms,req)\n",
    "\n",
    "                #create a copy of the dataframe to better display the table\n",
    "                df2 = self.df.copy()\n",
    "                for i in df2[\"MP term ids\"]:\n",
    "                    i[0] = i[0].replace(\",\",\", \")\n",
    "                df2 = df2.applymap(lambda x: re.sub(\"['\\[\\]]\",\"\",str(x)))\n",
    "            \n",
    "                display(HTML(df2.to_html(justify=\"left\", index=False)))\n",
    "                self.csv_file = self.df.to_csv(\"result_table.csv\",index=False)\n",
    "                self.res_button.disabled = False\n",
    "                htmlWidget = widgets.HTML(value=\"\")\n",
    "                self.create_download_link(\"result_table.csv\", htmlWidget)\n",
    "                self.down_container.children = tuple(list(self.down_container.children) + [htmlWidget])\n",
    "            else:\n",
    "                print(\"No data found for gene \"+gene)\n",
    "                self.res_button.disabled = False\n",
    "            \n",
    "    def create_download_link(self, filename, htmlWidget):  \n",
    "        title=\"Click here to download the table in csv format\"\n",
    "        \n",
    "        data = open(filename, \"rb\").read()\n",
    "        b64 = base64.b64encode(data)\n",
    "        payload = b64.decode()\n",
    "        \n",
    "        html = '<a download=\"{filename}\" href=\"data:text/csv;base64,{payload}\" target=\"_blank\"><button class=\"button-style\">Download table as csv file</button></a>'\n",
    "        htmlWidget.value = html.format(payload=payload,title=title,filename=filename)\n",
    "\n",
    "        \n",
    "    #FUNCTIONS FOR SECOND TAB PAGE\n",
    "        \n",
    "    def create_send_button_two(self):\n",
    "        label = widgets.Label('MP term id:')\n",
    "        self.text_area_two = widgets.Textarea(placeholder='')\n",
    "        send_b = widgets.Button(description='Submit', tooltip='submit your MP term id', disabled=True)\n",
    "        send_b.on_click(self.on_change_s_two)\n",
    "        self.text_area_two.observe(self.on_change_text_two, names=['value'])\n",
    "        sub_box = widgets.HBox([label,self.text_area_two])\n",
    "        return(send_b, sub_box)\n",
    "        \n",
    "    def create_reset_button_two(self):\n",
    "        reset_b = widgets.Button(description='Reset', tooltip='reset the environment to generate a new table', disabled=True)\n",
    "        reset_b.on_click(self.on_click_r_two)\n",
    "        return (reset_b) \n",
    "            \n",
    "    def on_change_text_two(self,_):\n",
    "        if (self.text_area_two.value == '') | (self.text_area_two.value.isspace()):\n",
    "            self.send_button_two.disabled=True\n",
    "        else:\n",
    "            self.send_button_two.disabled=False\n",
    "        \n",
    "    def on_click_r_two(self,_):\n",
    "        try:\n",
    "            del(self.df_two)\n",
    "            for i in self.down_container_two.children:\n",
    "                remove = self.down_container_two.children[-1]\n",
    "                self.down_container_two.children = self.down_container_two.children[:-1]\n",
    "                remove.close()\n",
    "        except NameError:\n",
    "            print(\"\")\n",
    "        self.text_area_two.value=''\n",
    "        self.res_button_two.disabled=True\n",
    "        self.send_button_two.disabled=True\n",
    "        self.table_container_two.clear_output(wait=False)\n",
    "        \n",
    "        \n",
    "    def on_change_s_two(self,_):\n",
    "        with self.table_container_two:\n",
    "            self.table_container_two.clear_output(wait=False)\n",
    "            self.send_button_two.disabled = True\n",
    "            term = self.text_area_two.value\n",
    "            query = requests.get(api_url_two+term+'\\\"'+api_url_end).json()\n",
    "            if (query[\"response\"][\"numFound\"] != 0):\n",
    "                req = query[\"response\"][\"docs\"]\n",
    "                self.df_two = pd.DataFrame(columns=[\"MP term id\", \"Genes\"])\n",
    "\n",
    "                sym=[]\n",
    "                for i in req:\n",
    "                    sym.append(i[\"allele_symbol\"][0])\n",
    "\n",
    "                sym = list(dict.fromkeys(sym))\n",
    "                self.df_two[\"MP term id\"] = [term]\n",
    "                self.df_two[\"Genes\"][0] = sym\n",
    "                del(sym,req)\n",
    "\n",
    "                #create a copy of the dataframe to better display the table\n",
    "                df2_two = self.df_two.copy()\n",
    "                df2_two = df2_two.applymap(lambda x: re.sub(\"['\\[\\]]\",\"\",str(x)))\n",
    "\n",
    "                display(HTML(df2_two.to_html(justify=\"left\", index=False)))\n",
    "                self.csv_file_two = self.df_two.to_csv(\"result_table.csv\",index=False)\n",
    "                self.res_button_two.disabled = False\n",
    "                htmlWidget_two = widgets.HTML(value=\"\")\n",
    "                self.create_download_link_two(\"result_table.csv\", htmlWidget_two)\n",
    "                self.down_container_two.children = tuple(list(self.down_container_two.children) + [htmlWidget_two])\n",
    "            else:\n",
    "                print(\"No gene found with the MP term id \"+term)\n",
    "                self.res_button_two.disabled = False\n",
    "            \n",
    "    def create_download_link_two(self, filename, htmlWidget):  \n",
    "        title=\"Click here to download the table in csv format\"\n",
    "        \n",
    "        data = open(filename, \"rb\").read()\n",
    "        b64 = base64.b64encode(data)\n",
    "        payload = b64.decode()\n",
    "        \n",
    "        html = '<a download=\"{filename}\" href=\"data:text/csv;base64,{payload}\" target=\"_blank\"><button class=\"button-style\">Download table as csv file</button></a>'\n",
    "        htmlWidget.value = html.format(payload=payload,title=title,filename=filename)\n",
    "        \n",
    "        \n",
    "    #FUNCTIONS FOR THIRD TAB\n",
    "        \n",
    "    def create_send_button_three(self):\n",
    "        label = widgets.Label('Strain names list:')\n",
    "        self.text_area_three = widgets.Textarea(placeholder='')\n",
    "        send_b = widgets.Button(description='Submit', tooltip='submit your list', disabled=True)\n",
    "        send_b.on_click(self.on_change_s_three)\n",
    "        self.text_area_three.observe(self.on_change_text_three, names=['value'])\n",
    "        sub_box = widgets.HBox([label,self.text_area_three])\n",
    "        return(send_b, sub_box)\n",
    "        \n",
    "    def create_reset_button_three(self):\n",
    "        reset_b = widgets.Button(description='Reset', tooltip='reset the environment to generate new results', disabled=True)\n",
    "        reset_b.on_click(self.on_click_r_three)\n",
    "        return (reset_b) \n",
    "            \n",
    "    def on_change_text_three(self,_):\n",
    "        if (self.text_area_three.value == '') | (self.text_area_three.value.isspace()):\n",
    "            self.send_button_three.disabled=True\n",
    "        else:\n",
    "            self.send_button_three.disabled=False\n",
    "            \n",
    "    def on_click_r_three(self,_):\n",
    "        try:\n",
    "            del(self.df_t)\n",
    "            #del(self.matr)\n",
    "            for i in self.down_container_three.children:\n",
    "                remove = self.down_container_three.children[-1]\n",
    "                self.down_container_three.children = self.down_container_three.children[:-1]\n",
    "                remove.close() \n",
    "        except NameError:\n",
    "            pass\n",
    "        self.text_area_three.value=''\n",
    "        self.res_button_three.disabled=True\n",
    "        self.send_button_three.disabled=True\n",
    "        self.table_container_three.clear_output(wait=False)\n",
    "    \n",
    "    def on_change_s_three(self,_):\n",
    "        with self.table_container_three:\n",
    "            self.table_container_three.clear_output(wait=False)\n",
    "            self.send_button_three.disabled = True\n",
    "            strains = self.text_area_three.value\n",
    "            #Commented parts regard using the strain id instead of names (here for reference, remove in final release)\n",
    "            #s = strains.split(\",\")\n",
    "            #self.df_t[\"Strain id\"] = s\n",
    "            #for i in s:\n",
    "                #try:\n",
    "                    #x = requests.get(api_url_three+i+api_url_end).json()[\"response\"][\"docs\"][0]\n",
    "                    #self.df_t.loc[self.df_t['Strain id'] == i, \"Strain name\"] = x[\"name\"]\n",
    "                    #self.df_t.loc[self.df_t['Strain id'] == i, \"MP term ids\"] = x[\"mp_ids\"]\n",
    "                    #self.df_t.loc[self.df_t['Strain id'] == i, \"MP term names\"] = x[\"mp_terms\"]\n",
    "                    #del(x)\n",
    "                #except IndexError:\n",
    "                    #self.df_t.loc[self.df_t['Strain id'] == i, \"Strain name\"] = \"nan\"\n",
    "                    #self.df_t.loc[self.df_t['Strain id'] == i, \"MP term ids\"] = \"nan\"\n",
    "                    #self.df_t.loc[self.df_t['Strain id'] == i, \"MP term names\"] = \"nan\"\n",
    "            query = requests.get(api_url_three+strains+api_url_end).json()\n",
    "            if (query[\"response\"][\"numFound\"] != 0):\n",
    "                req = query[\"response\"][\"docs\"]\n",
    "                self.df_t = pd.DataFrame(columns=[\"Strain id\",\"Strain name\",\"MP term ids\", \"MP term names\"])\n",
    "                \n",
    "                ids =[]\n",
    "                names = []\n",
    "                mp_ids = []\n",
    "                mp_terms = []\n",
    "                for i in req:\n",
    "                    ids.append(i[\"strain_id\"])\n",
    "                    names.append(i[\"name\"])\n",
    "                    mp_ids.append(i[\"mp_ids\"])\n",
    "                    mp_terms.append(i[\"mp_terms\"])\n",
    "\n",
    "                self.df_t[\"Strain id\"] = ids\n",
    "                self.df_t[\"Strain name\"] = names\n",
    "                self.df_t[\"MP term ids\"] = mp_ids\n",
    "                self.df_t[\"MP term names\"] = mp_terms\n",
    "                del(ids,names,mp_ids,mp_terms,req)\n",
    "                \n",
    "                \n",
    "                #create a copy of the dataframe to better display the table\n",
    "                df3 = self.df_t.copy()\n",
    "                df3 = df3.applymap(lambda x: re.sub(\",\",\", \",str(x)))\n",
    "                df3 = df3.applymap(lambda x: re.sub(\"['\\[\\]]\",\"\",str(x)))\n",
    "\n",
    "                display(HTML(df3.to_html(justify=\"left\", index=False)))\n",
    "                self.csv_file_three = self.df_t.to_csv(\"result_table.csv\",index=False)\n",
    "                self.res_button_three.disabled = False\n",
    "                htmlWidget_three = widgets.HTML(value=\"\")\n",
    "                self.create_download_link_three(\"result_table.csv\", htmlWidget_three)\n",
    "                self.down_container_three.children = tuple(list(self.down_container_three.children) + [htmlWidget_three])\n",
    "                #Parts to allow the plotting of the heatmap.\n",
    "                #self._slider, self.slider_box = self.create_slider()\n",
    "                #self.slider_container.children = tuple(list(self.slider_container.children) + [self.slider_box])\n",
    "                #self.update_app()\n",
    "                \n",
    "            else:\n",
    "                print(\"No strains found with the name \"+term)\n",
    "                self.res_button_three.disabled = False        \n",
    "            \n",
    "            \n",
    "    def create_download_link_three(self, filename, htmlWidget):  \n",
    "        title=\"Click here to download the table in csv format\"\n",
    "        \n",
    "        data = open(filename, \"rb\").read()\n",
    "        b64 = base64.b64encode(data)\n",
    "        payload = b64.decode()\n",
    "        \n",
    "        html = '<a download=\"{filename}\" href=\"data:text/csv;base64,{payload}\" target=\"_blank\"><button class=\"button-style\">Download table as csv file</button></a>'\n",
    "        htmlWidget.value = html.format(payload=payload,title=title,filename=filename)\n",
    "        \n",
    "    def create_slider(self):\n",
    "        slider_label = widgets.Label('Threshold: ')\n",
    "        slider = widgets.IntSlider(value=0, min=0, max = 0, step=1, orintation='horizontal', readout=True, readout_format=\"d\")\n",
    "        slider.observe(self.on_change, names=['value'])\n",
    "        slider_box = widgets.HBox([slider_label,slider])\n",
    "        return (slider, slider_box)\n",
    "    \n",
    "    def on_change(self, _):\n",
    "        self.update_app()\n",
    "    \n",
    "    def update_app(self):\n",
    "        try:\n",
    "            self._slider.max = max(list(self.matr.max()),key=itemgetter(0))[0]\n",
    "        except AttributeError:\n",
    "            self.matr = self.create_matrix()\n",
    "            self._slider.max = max(list(self.matr.max()),key=itemgetter(0))[0]\n",
    "        threshold = self._slider.value\n",
    "        try:\n",
    "            with self.plot_container:\n",
    "                p = self.create_plot(threshold)\n",
    "                self.plot_container.clear_output(wait=True)\n",
    "                show(p, notebook_handle=True)\n",
    "        except (NameError,AttributeError) as e:\n",
    "            pass\n",
    "        \n",
    "    def create_matrix(self):\n",
    "        df = self.df_t.copy().dropna()\n",
    "        t = pd.DataFrame(columns=df[\"Strain name\"].values,index=df[\"Strain name\"].values)\n",
    "\n",
    "        for i in t.index:\n",
    "            x = df.where(df[\"Strain name\"] == i).dropna()[\"MP term ids\"].values[0].split(\",\")\n",
    "            for j in t.columns:\n",
    "                y = df.where(df[\"Strain name\"] == j).dropna()[\"MP term ids\"].values[0].split(\",\")\n",
    "                s = re.sub(\"[\\[\\]']\",\"\",str(list(np.intersect1d(x,y))))\n",
    "                t.loc[i,j] = (len(np.intersect1d(x,y)),s)\n",
    "            del(x,y)\n",
    "        del(i,j,df)\n",
    "\n",
    "        t.columns.name=\"strain_col\"\n",
    "        t.index.name=\"strain_ind\"\n",
    "        return(t)\n",
    "    \n",
    "    def create_plot(self,threshold):\n",
    "        tem_mat = self.matr.copy()\n",
    "        rem = []\n",
    "        if threshold != 0:\n",
    "            for i in tem_mat.index:\n",
    "                if tem_mat.loc[i].max()[0] < threshold:\n",
    "                    rem.append(i)\n",
    "            tem_mat.drop(rem, inplace=True, axis=0)\n",
    "            tem_mat.drop(rem, inplace=True, axis=1)\n",
    "\n",
    "        # Create a custom palette and add a specific mapper to map color with values, we are converting them to strings to create a categorical color mapper to include only the\n",
    "        # values that we have in the matrix and retrieve a better representation\n",
    "\n",
    "        tmp = tem_mat.stack(dropna=False).rename(\"value\").reset_index()\n",
    "        tmp[\"terms\"] = \"\"\n",
    "        for i in range(0, len(tmp)):\n",
    "            tmp.terms[i] = tmp.value[i][1]\n",
    "            tmp.value[i] = tmp.value[i][0]\n",
    "        fact = tmp.value.unique()\n",
    "        fact.sort()\n",
    "        fact = fact.astype(str)\n",
    "        tmp.value = tmp.value.astype(str)\n",
    "        tmp.terms = tmp.terms.astype(str)\n",
    "\n",
    "        mapper = CategoricalColorMapper(palette=bokeh.palettes.inferno(len(tmp.value.unique())), factors=fact, nan_color='gray')\n",
    "\n",
    "        # Define a figure\n",
    "        p = figure(\n",
    "            width=1280,\n",
    "            height=800,\n",
    "            x_range=list(tmp.strain_col.drop_duplicates()),\n",
    "            y_range=list(tmp.strain_ind.drop_duplicates()[::-1]),\n",
    "            tooltips=[('number of common MP terms ', '@value'), ('MP term ids', '@terms')],\n",
    "            x_axis_location=\"above\",\n",
    "            output_backend=\"webgl\",\n",
    "            toolbar_location=\"right\",\n",
    "            tools=\"pan,wheel_zoom,box_zoom,reset,save\")\n",
    "\n",
    "        # Create rectangles for heatmap\n",
    "        p.rect(\n",
    "            x=\"strain_col\",\n",
    "            y=\"strain_ind\",\n",
    "            width=1,\n",
    "            height=1,\n",
    "            source=ColumnDataSource(tmp),\n",
    "            fill_color=transform('value', mapper))\n",
    "        p.xaxis.major_label_orientation = 45\n",
    "        p.yaxis.major_label_orientation = 45\n",
    "\n",
    "        # Add legend\n",
    "        color_bar = ColorBar(\n",
    "            color_mapper=mapper,\n",
    "            label_standoff=6,\n",
    "            border_line_color=None)\n",
    "        p.add_layout(color_bar, 'right')\n",
    "        del(tem_mat)\n",
    "        return(p)\n",
    "    \n",
    "    def create_plot_button(self):\n",
    "        plot_b = widgets.Button(description='Common MP heatmap', tooltip='Create an heatmap showing the common MP terms between strains', disabled=True)\n",
    "        #plot_b.on_click(self.on_click_p)\n",
    "        return (plot_b)\n",
    "    \n",
    "app = App()\n",
    "app.final_container"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}