{"metadata":{"hide_input":true,"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport holoviews as hv\nhv.extension('bokeh', 'matplotlib', logo=False)\n\n# Avoid warnings to show up (trick for the final notebook on kaggle)\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"_uuid":"a2ef2622d9d982f44f73097c44a0618969909c4c","execution":{"iopub.status.busy":"2023-02-14T00:29:11.368879Z","iopub.execute_input":"2023-02-14T00:29:11.369209Z","iopub.status.idle":"2023-02-14T00:29:14.248926Z","shell.execute_reply.started":"2023-02-14T00:29:11.369151Z","shell.execute_reply":"2023-02-14T00:29:14.247959Z"},"trusted":true},"execution_count":1,"outputs":[{"output_type":"display_data","data":{"application/javascript":"\n(function(root) {\n function now() {\n return new Date();\n }\n\n var 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 var JS_MIME_TYPE = 'application/javascript';\n var HTML_MIME_TYPE = 'text/html';\n var EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n var CLASS_NAME = 'output_bokeh rendered_html';\n\n /**\n * Render data to the DOM node\n */\n function render(props, node) {\n var 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 var cell = handle.cell;\n\n var id = cell.output_area._bokeh_element_id;\n var 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 var cmd = \"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, {\n iopub: {\n output: function(msg) {\n var 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 var cmd = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n cell.notebook.kernel.execute(cmd);\n }\n }\n\n /**\n * Handle when a new output is added\n */\n function handleAddOutput(event, handle) {\n var output_area = handle.output_area;\n var output = handle.output;\n\n // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n if ((output.output_type != \"display_data\") || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n return\n }\n\n var 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 var bk_div = document.createElement(\"div\");\n bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n var script_attrs = bk_div.children[0].attributes;\n for (var i = 0; i < script_attrs.length; i++) {\n toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\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 var 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 var 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 var events = require('base/js/events');\n var 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\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 var NB_LOAD_WARNING = {'data': {'text/html':\n \"
\\n\"+\n \"

\\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 \"

\\n\"+\n \"\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"\\n\"+\n \"
\"}};\n\n function display_loaded() {\n var 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\n function run_callbacks() {\n try {\n root._bokeh_onload_callbacks.forEach(function(callback) { callback() });\n }\n finally {\n delete root._bokeh_onload_callbacks\n }\n console.info(\"Bokeh: all callbacks have finished\");\n }\n\n function load_libs(js_urls, callback) {\n root._bokeh_onload_callbacks.push(callback);\n if (root._bokeh_is_loading > 0) {\n console.log(\"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.log(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n root._bokeh_is_loading = js_urls.length;\n for (var i = 0; i < js_urls.length; i++) {\n var url = js_urls[i];\n var s = document.createElement('script');\n s.src = url;\n s.async = false;\n s.onreadystatechange = s.onload = function() {\n root._bokeh_is_loading--;\n if (root._bokeh_is_loading === 0) {\n console.log(\"Bokeh: all BokehJS libraries loaded\");\n run_callbacks()\n }\n };\n s.onerror = function() {\n console.warn(\"failed to load library \" + url);\n };\n console.log(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.getElementsByTagName(\"head\")[0].appendChild(s);\n }\n };\n\n var js_urls = [];\n\n var inline_js = [\n function(Bokeh) {\n /* BEGIN bokeh.min.js */\n /*!\n * Copyright (c) 2012 - 2018, Anaconda, Inc., and Bokeh Contributors\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of Anaconda nor the names of any contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n */\n !function(t,e){var o,s,r,a,l;t.Bokeh=(o=[function(t,e,i){var n=t(153),r=t(32);i.overrides={};var o=r.clone(n);i.Models=function(t){var e=i.overrides[t]||o[t];if(null==e)throw new Error(\"Model '\"+t+\"' does not exist. This could be due to a widget\\n or a custom model not being registered before first usage.\");return e},i.Models.register=function(t,e){i.overrides[t]=e},i.Models.unregister=function(t){delete i.overrides[t]},i.Models.register_models=function(t,e,i){if(void 0===e&&(e=!1),null!=t)for(var n in t){var r=t[n];e||!o.hasOwnProperty(n)?o[n]=r:null!=i?i(n):console.warn(\"Model '\"+n+\"' was already registered\")}},i.register_models=i.Models.register_models,i.Models.registered_names=function(){return Object.keys(o)},i.index={}},function(t,e,o){var s=t(336),a=t(14),l=t(52),h=t(282),u=t(283),c=t(2);o.DEFAULT_SERVER_WEBSOCKET_URL=\"ws://localhost:5006/ws\",o.DEFAULT_SESSION_ID=\"default\";var _=0,p=function(){function t(t,e,i,n,r){void 0===t&&(t=o.DEFAULT_SERVER_WEBSOCKET_URL),void 0===e&&(e=o.DEFAULT_SESSION_ID),void 0===i&&(i=null),void 0===n&&(n=null),void 0===r&&(r=null),this.url=t,this.id=e,this.args_string=i,this._on_have_session_hook=n,this._on_closed_permanently_hook=r,this._number=_++,this.socket=null,this.session=null,this.closed_permanently=!1,this._current_handler=null,this._pending_ack=null,this._pending_replies={},this._receiver=new u.Receiver,a.logger.debug(\"Creating websocket \"+this._number+\" to '\"+this.url+\"' session '\"+this.id+\"'\")}return t.prototype.connect=function(){var i=this;if(this.closed_permanently)return s.Promise.reject(new Error(\"Cannot connect() a closed ClientConnection\"));if(null!=this.socket)return s.Promise.reject(new Error(\"Already connected\"));this._pending_replies={},this._current_handler=null;try{var t=this.url+\"?bokeh-protocol-version=1.0&bokeh-session-id=\"+this.id;return null!=this.args_string&&0=this.x0&&t<=this.x1&&e>=this.y0&&e<=this.y1},e.prototype.clip=function(t,e){return tthis.x1&&(t=this.x1),ethis.y1&&(e=this.y1),[t,e]},e.prototype.union=function(t){return new e({x0:n(this.x0,t.x0),y0:n(this.y0,t.y0),x1:r(this.x1,t.x1),y1:r(this.y1,t.y1)})},e}();i.BBox=o},function(t,e,i){i.delay=function(t,e){return setTimeout(t,e)};var n=\"function\"==typeof requestAnimationFrame?requestAnimationFrame:setImmediate;i.defer=function(t){return n(t)},i.throttle=function(i,n,r){void 0===r&&(r={});var o,s,a,l=null,h=0,u=function(){h=!1===r.leading?0:Date.now(),l=null,a=i.apply(o,s),l||(o=s=null)};return function(){var t=Date.now();h||!1!==r.leading||(h=t);var e=n-(t-h);return o=this,s=arguments,e<=0||n2*Math.PI;)t-=2*Math.PI;return t}function l(t,e){return Math.abs(a(t-e))}function o(){return Math.random()}i.angle_norm=a,i.angle_dist=l,i.angle_between=function(t,e,i,n){var r=a(t),o=l(e,i),s=l(e,r)<=o&&l(r,i)<=o;return 1==n?!s:s},i.random=o,i.randomIn=function(t,e){return null==e&&(e=t,t=0),t+Math.floor(Math.random()*(e-t+1))},i.atan2=function(t,e){return Math.atan2(e[1]-t[1],e[0]-t[0])},i.rnorm=function(t,e){for(var i,n;i=o(),n=(2*(n=o())-1)*Math.sqrt(1/Math.E*2),!(-4*i*i*Math.log(i)>=n*n););var r=n/i;return r=t+e*r},i.clamp=function(t,e,i){return ia[e][0]&&t\"'`])/g,function(t){switch(t){case\"&\":return\"&\";case\"<\":return\"<\";case\">\":return\">\";case'\"':return\""\";case\"'\":return\"'\";case\"`\":return\"`\";default:return t}})},i.unescape=function(t){return t.replace(/&(amp|lt|gt|quot|#x27|#x60);/g,function(t,e){switch(e){case\"amp\":return\"&\";case\"lt\":return\"<\";case\"gt\":return\">\";case\"quot\":return'\"';case\"#x27\":return\"'\";case\"#x60\":return\"`\";default:return e}})},i.use_strict=function(t){return\"'use strict';\\n\"+t}},function(t,e,i){i.svg_colors={indianred:\"#CD5C5C\",lightcoral:\"#F08080\",salmon:\"#FA8072\",darksalmon:\"#E9967A\",lightsalmon:\"#FFA07A\",crimson:\"#DC143C\",red:\"#FF0000\",firebrick:\"#B22222\",darkred:\"#8B0000\",pink:\"#FFC0CB\",lightpink:\"#FFB6C1\",hotpink:\"#FF69B4\",deeppink:\"#FF1493\",mediumvioletred:\"#C71585\",palevioletred:\"#DB7093\",coral:\"#FF7F50\",tomato:\"#FF6347\",orangered:\"#FF4500\",darkorange:\"#FF8C00\",orange:\"#FFA500\",gold:\"#FFD700\",yellow:\"#FFFF00\",lightyellow:\"#FFFFE0\",lemonchiffon:\"#FFFACD\",lightgoldenrodyellow:\"#FAFAD2\",papayawhip:\"#FFEFD5\",moccasin:\"#FFE4B5\",peachpuff:\"#FFDAB9\",palegoldenrod:\"#EEE8AA\",khaki:\"#F0E68C\",darkkhaki:\"#BDB76B\",lavender:\"#E6E6FA\",thistle:\"#D8BFD8\",plum:\"#DDA0DD\",violet:\"#EE82EE\",orchid:\"#DA70D6\",fuchsia:\"#FF00FF\",magenta:\"#FF00FF\",mediumorchid:\"#BA55D3\",mediumpurple:\"#9370DB\",blueviolet:\"#8A2BE2\",darkviolet:\"#9400D3\",darkorchid:\"#9932CC\",darkmagenta:\"#8B008B\",purple:\"#800080\",indigo:\"#4B0082\",slateblue:\"#6A5ACD\",darkslateblue:\"#483D8B\",mediumslateblue:\"#7B68EE\",greenyellow:\"#ADFF2F\",chartreuse:\"#7FFF00\",lawngreen:\"#7CFC00\",lime:\"#00FF00\",limegreen:\"#32CD32\",palegreen:\"#98FB98\",lightgreen:\"#90EE90\",mediumspringgreen:\"#00FA9A\",springgreen:\"#00FF7F\",mediumseagreen:\"#3CB371\",seagreen:\"#2E8B57\",forestgreen:\"#228B22\",green:\"#008000\",darkgreen:\"#006400\",yellowgreen:\"#9ACD32\",olivedrab:\"#6B8E23\",olive:\"#808000\",darkolivegreen:\"#556B2F\",mediumaquamarine:\"#66CDAA\",darkseagreen:\"#8FBC8F\",lightseagreen:\"#20B2AA\",darkcyan:\"#008B8B\",teal:\"#008080\",aqua:\"#00FFFF\",cyan:\"#00FFFF\",lightcyan:\"#E0FFFF\",paleturquoise:\"#AFEEEE\",aquamarine:\"#7FFFD4\",turquoise:\"#40E0D0\",mediumturquoise:\"#48D1CC\",darkturquoise:\"#00CED1\",cadetblue:\"#5F9EA0\",steelblue:\"#4682B4\",lightsteelblue:\"#B0C4DE\",powderblue:\"#B0E0E6\",lightblue:\"#ADD8E6\",skyblue:\"#87CEEB\",lightskyblue:\"#87CEFA\",deepskyblue:\"#00BFFF\",dodgerblue:\"#1E90FF\",cornflowerblue:\"#6495ED\",royalblue:\"#4169E1\",blue:\"#0000FF\",mediumblue:\"#0000CD\",darkblue:\"#00008B\",navy:\"#000080\",midnightblue:\"#191970\",cornsilk:\"#FFF8DC\",blanchedalmond:\"#FFEBCD\",bisque:\"#FFE4C4\",navajowhite:\"#FFDEAD\",wheat:\"#F5DEB3\",burlywood:\"#DEB887\",tan:\"#D2B48C\",rosybrown:\"#BC8F8F\",sandybrown:\"#F4A460\",goldenrod:\"#DAA520\",darkgoldenrod:\"#B8860B\",peru:\"#CD853F\",chocolate:\"#D2691E\",saddlebrown:\"#8B4513\",sienna:\"#A0522D\",brown:\"#A52A2A\",maroon:\"#800000\",white:\"#FFFFFF\",snow:\"#FFFAFA\",honeydew:\"#F0FFF0\",mintcream:\"#F5FFFA\",azure:\"#F0FFFF\",aliceblue:\"#F0F8FF\",ghostwhite:\"#F8F8FF\",whitesmoke:\"#F5F5F5\",seashell:\"#FFF5EE\",beige:\"#F5F5DC\",oldlace:\"#FDF5E6\",floralwhite:\"#FFFAF0\",ivory:\"#FFFFF0\",antiquewhite:\"#FAEBD7\",linen:\"#FAF0E6\",lavenderblush:\"#FFF0F5\",mistyrose:\"#FFE4E1\",gainsboro:\"#DCDCDC\",lightgray:\"#D3D3D3\",lightgrey:\"#D3D3D3\",silver:\"#C0C0C0\",darkgray:\"#A9A9A9\",darkgrey:\"#A9A9A9\",gray:\"#808080\",grey:\"#808080\",dimgray:\"#696969\",dimgrey:\"#696969\",lightslategray:\"#778899\",lightslategrey:\"#778899\",slategray:\"#708090\",slategrey:\"#708090\",darkslategray:\"#2F4F4F\",darkslategrey:\"#2F4F4F\",black:\"#000000\"},i.is_svg_color=function(t){return t in i.svg_colors}},function(t,e,s){var r=t(389),n=t(361),o=t(390),_=t(38),a=t(44);function l(t,e,i){if(a.isNumber(t)){var n=function(){switch(!1){case Math.floor(t)!=t:return\"%d\";case!(.1\");if(\"SCRIPT\"==e.tagName){var i=r.div({class:n.BOKEH_ROOT});r.replaceWith(e,i),e=i}return e}n.BOKEH_ROOT=\"bk-root\",n.inject_css=function(t){var e=r.link({href:t,rel:\"stylesheet\",type:\"text/css\"});document.body.appendChild(e)},n.inject_raw_css=function(t){var e=r.style({},t);document.body.appendChild(e)},n._resolve_element=function(t){var e=t.elementid;return null!=e?o(e):document.body},n._resolve_root_elements=function(t){var e={};if(null!=t.roots)for(var i in t.roots)e[i]=o(t.roots[i]);return e}},function(t,e,i){var d=t(52),f=t(14),a=t(25),v=t(38),m=t(44),g=t(57),y=t(56),b=t(53),n=t(57);i.add_document_standalone=n.add_document_standalone;var r=t(56);i.add_document_from_session=r.add_document_from_session;var o=t(55);i.embed_items_notebook=o.embed_items_notebook,i.kernels=o.kernels;var s=t(53);function l(t,e,i,n){m.isString(t)&&(t=JSON.parse(v.unescape(t)));var r={};for(var o in t){var s=t[o];r[o]=d.Document.from_json(s)}for(var a=0,l=e;athis.sleft&&tthis.stop&&el||(_[r].push(u[d]),_[o].push(0));for(var d=0,f=c.length;dl||(p[r].push(c[d]),p[o].push(0));var v={major:this._format_major_labels(_[r],u)},m={major:[[],[]],minor:[[],[]]};return m.major[r]=i.v_compute(_[r]),m.minor[r]=i.v_compute(p[r]),m.major[o]=_[o],m.minor[o]=p[o],\"vertical\"==this.orientation&&(m.major[r]=g.map(m.major[r],function(t){return e-t}),m.minor[r]=g.map(m.minor[r],function(t){return e-t})),{coords:m,labels:v}},t}(r.Annotation);(i.ColorBar=m).initClass()},function(t,e,i){var n=t(60);i.Annotation=n.Annotation;var r=t(61);i.Arrow=r.Arrow;var o=t(62);i.ArrowHead=o.ArrowHead;var s=t(62);i.OpenHead=s.OpenHead;var a=t(62);i.NormalHead=a.NormalHead;var l=t(62);i.TeeHead=l.TeeHead;var h=t(62);i.VeeHead=h.VeeHead;var u=t(63);i.Band=u.Band;var c=t(64);i.BoxAnnotation=c.BoxAnnotation;var _=t(65);i.ColorBar=_.ColorBar;var p=t(67);i.Label=p.Label;var d=t(68);i.LabelSet=d.LabelSet;var f=t(69);i.Legend=f.Legend;var v=t(70);i.LegendItem=v.LegendItem;var m=t(71);i.PolyAnnotation=m.PolyAnnotation;var g=t(72);i.Slope=g.Slope;var y=t(73);i.Span=y.Span;var b=t(74);i.TextAnnotation=b.TextAnnotation;var x=t(75);i.Title=x.Title;var w=t(76);i.ToolbarPanel=w.ToolbarPanel;var k=t(77);i.Tooltip=k.Tooltip;var S=t(78);i.Whisker=S.Whisker},function(t,e,i){var n=t(391),r=t(74),a=t(5),o=t(15),s=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return n.__extends(t,e),t.prototype.initialize=function(t){e.prototype.initialize.call(this,t),this.visuals.warm_cache()},t.prototype._get_size=function(){var t=this.plot_view.canvas_view.ctx;if(this.visuals.text.set_value(t),this.model.panel.is_horizontal){var e=t.measureText(this.model.text).ascent;return e}var i=t.measureText(this.model.text).width;return i},t.prototype.render=function(){if(this.model.visible||\"css\"!=this.model.render_mode||a.hide(this.el),this.model.visible){var t;switch(this.model.angle_units){case\"rad\":t=-this.model.angle;break;case\"deg\":t=-this.model.angle*Math.PI/180;break;default:throw new Error(\"unreachable code\")}var e=null!=this.model.panel?this.model.panel:this.plot_view.frame,i=this.plot_view.frame.xscales[this.model.x_range_name],n=this.plot_view.frame.yscales[this.model.y_range_name],r=\"data\"==this.model.x_units?i.compute(this.model.x):e.xview.compute(this.model.x),o=\"data\"==this.model.y_units?n.compute(this.model.y):e.yview.compute(this.model.y);r+=this.model.x_offset,o-=this.model.y_offset;var s=\"canvas\"==this.model.render_mode?this._canvas_text.bind(this):this._css_text.bind(this);s(this.plot_view.canvas_view.ctx,this.model.text,r,o,t)}},t}(r.TextAnnotationView);i.LabelView=s;var l=function(e){function t(t){return e.call(this,t)||this}return n.__extends(t,e),t.initClass=function(){this.prototype.type=\"Label\",this.prototype.default_view=s,this.mixins([\"text\",\"line:border_\",\"fill:background_\"]),this.define({x:[o.Number],x_units:[o.SpatialUnits,\"data\"],y:[o.Number],y_units:[o.SpatialUnits,\"data\"],text:[o.String],angle:[o.Angle,0],angle_units:[o.AngleUnits,\"rad\"],x_offset:[o.Number,0],y_offset:[o.Number,0],x_range_name:[o.String,\"default\"],y_range_name:[o.String,\"default\"]}),this.override({background_fill_color:null,border_line_color:null})},t}(r.TextAnnotation);(i.Label=l).initClass()},function(t,e,i){var n=t(391),r=t(74),o=t(200),u=t(5),s=t(15),a=function(r){function t(){return null!==r&&r.apply(this,arguments)||this}return n.__extends(t,r),t.prototype.initialize=function(t){if(r.prototype.initialize.call(this,t),this.set_data(this.model.source),\"css\"==this.model.render_mode)for(var e=0,i=this._text.length;eh(a-l)?(n=c(u(o,s),a),r=u(c(o,s),l)):(n=u(o,s),r=c(o,s)),[n,r]}throw new Error(\"user bounds '\"+e+\"' not understood\")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"rule_coords\",{get:function(){var t=this.dimension,e=(t+1)%2,i=this.ranges[0],n=this.computed_bounds,r=n[0],o=n[1],s=new Array(2),a=new Array(2),l=[s,a];return l[t][0]=Math.max(r,i.min),l[t][1]=Math.min(o,i.max),l[t][0]>l[t][1]&&(l[t][0]=l[t][1]=NaN),l[e][0]=this.loc,l[e][1]=this.loc,l},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"tick_coords\",{get:function(){for(var t=this.dimension,e=(t+1)%2,i=this.ranges[0],n=this.computed_bounds,r=n[0],o=n[1],s=this.ticker.get_ticks(r,o,i,this.loc,{}),a=s.major,l=s.minor,h=[[],[]],u=[[],[]],c=[i.min,i.max],_=c[0],p=c[1],d=0;dp||(h[t].push(a[d]),h[e].push(this.loc));for(var d=0;dp||(u[t].push(l[d]),u[e].push(this.loc));return{major:h,minor:u}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"loc\",{get:function(){if(null!=this.fixed_location){if(T.isNumber(this.fixed_location))return this.fixed_location;var t=this.ranges,e=t[1];if(e instanceof a.FactorRange)return e.synthetic(this.fixed_location);throw new Error(\"unexpected\")}var i=this.ranges,n=i[1];switch(this.panel.side){case\"left\":case\"below\":return n.start;case\"right\":case\"above\":return n.end}},enumerable:!0,configurable:!0}),t}(r.GuideRenderer);(i.Axis=p).initClass()},function(t,e,i){var n=t(391),r=t(79),o=t(208),s=t(105),a=t(15),l=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n.__extends(e,t),e.prototype._render=function(t,e,i){this._draw_group_separators(t,e,i)},e.prototype._draw_group_separators=function(t,e,i){var n,r=this.model.ranges[0],o=this.model.computed_bounds,s=o[0],a=o[1];if(r.tops&&!(r.tops.length<2)&&this.visuals.separator_line.doit){for(var l=this.model.dimension,h=(l+1)%2,u=[[],[]],c=0,_=0;_=this.scientific_limit_high||a<=this.scientific_limit_low)){n=!0;break}}var l=new Array(t.length),h=this.precision;if(null==h||f.isNumber(h))if(n)for(var u=0,c=t.length;ut.maxX&&(t.maxX=r.maxX)}for(var o=this.index.search(h.positive_y()),s=0,a=o;st.maxY&&(t.maxY=l.maxY)}return this._bounds(t)},t.prototype.get_anchor_point=function(t,e,i){var n=i[0],r=i[1];switch(t){case\"center\":return{x:this.scenterx(e,n,r),y:this.scentery(e,n,r)};default:return null}},t.prototype.sdist=function(t,e,i,n,r){var o,s;void 0===n&&(n=\"edge\"),void 0===r&&(r=!1);var a=e.length;if(\"center\"==n){var l=b.map(i,function(t){return t/2});o=new Float64Array(a);for(var h=0;h=a.length?c:a[n],l[t]=r},e=0,i=o.length;e=h.end&&(r=!0,h.end=_,(e||i)&&(h.start=_+d)),null!=p&&p<=h.start&&(r=!0,h.start=p,(e||i)&&(h.end=p-d))):(null!=_&&_>=h.start&&(r=!0,h.start=_,(e||i)&&(h.end=_+d)),null!=p&&p<=h.end&&(r=!0,h.end=p,(e||i)&&(h.start=p-d)))}}if(!(i&&r&&n))for(var f=0,v=t;fn.lod_timeout&&e.interactive_stop(n),t.request_render()},n.lod_timeout):e.interactive_stop(n)}for(var r in this.renderer_views){var o=this.renderer_views[r];if(null==this.range_update_timestamp||o instanceof T.GlyphRendererView&&o.set_data_timestamp>this.range_update_timestamp){this.update_dataranges();break}}this.model.frame.update_scales();var s=this.canvas_view.ctx,a=this.canvas.pixel_ratio;s.save(),s.scale(a,a),s.translate(.5,.5);var l=[this.frame._left.value,this.frame._top.value,this.frame._width.value,this.frame._height.value];if(this._map_hook(s,l),this._paint_empty(s,l),this.prepare_webgl(a,l),s.save(),this.visuals.outline_line.doit){this.visuals.outline_line.set_value(s);var h=l[0],u=l[1],c=l[2],_=l[3];h+c==this.canvas._width.value&&(c-=1),u+_==this.canvas._height.value&&(_-=1),s.strokeRect(h,u,c,_)}s.restore(),this._paint_levels(s,[\"image\",\"underlay\",\"glyph\"],l,!0),this.blit_webgl(a),this._paint_levels(s,[\"annotation\"],l,!0),this._paint_levels(s,[\"overlay\"],l,!1),null==this._initial_state_info.range&&this.set_initial_range(),s.restore(),this._has_finished||(this._has_finished=!0,this.notify_finished())}},t.prototype._paint_levels=function(t,e,i,n){t.save(),n&&(t.beginPath(),t.rect.apply(t,i),t.clip());for(var r={},o=0;oc&&(\"start\"==this.follow?r=n+u*c:\"end\"==this.follow&&(n=r-u*c)),[n,r]},t.prototype.update=function(t,e,i,n){if(!this.have_updated_interactively){var r=this.computed_renderers(),o=this._compute_plot_bounds(r,t);null!=n&&(o=this.adjust_bounds_for_aspect(o,n)),this._plot_bounds[i]=o;var s=this._compute_min_max(this._plot_bounds,e),a=s[0],l=s[1],h=this._compute_range(a,l),u=h[0],c=h[1];null!=this._initial_start&&(\"log\"==this.scale_hint?0this.end},enumerable:!0,configurable:!0}),t}(r.Model);(i.Range=a).initClass()},function(t,e,i){var n=t(391),r=t(183),o=t(15),s=function(e){function t(t){return e.call(this,t)||this}return n.__extends(t,e),t.initClass=function(){this.prototype.type=\"Range1d\",this.define({start:[o.Number,0],end:[o.Number,1],reset_start:[o.Number],reset_end:[o.Number]})},t.prototype._set_auto_bounds=function(){if(\"auto\"==this.bounds){var t=Math.min(this.reset_start,this.reset_end),e=Math.max(this.reset_start,this.reset_end);this.setv({bounds:[t,e]},{silent:!0})}},t.prototype.initialize=function(){e.prototype.initialize.call(this),null==this.reset_start&&(this.reset_start=this.start),null==this.reset_end&&(this.reset_end=this.end),this._set_auto_bounds()},Object.defineProperty(t.prototype,\"min\",{get:function(){return Math.min(this.start,this.end)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"max\",{get:function(){return Math.max(this.start,this.end)},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this._set_auto_bounds(),this.start!=this.reset_start||this.end!=this.reset_end?this.setv({start:this.reset_start,end:this.reset_end}):this.change.emit()},t}(r.Range);(i.Range1d=s).initClass()},function(t,e,i){var n=t(391),r=t(189),P=t(130),o=t(199),j=t(14),s=t(15),a=t(22),N=t(21),_=t(32),l=t(181),p={fill:{},line:{}},d={fill:{fill_alpha:.3,fill_color:\"grey\"},line:{line_alpha:.3,line_color:\"grey\"}},f={fill:{fill_alpha:.2},line:{}},h=function(c){function t(){return null!==c&&c.apply(this,arguments)||this}return n.__extends(t,c),t.prototype.initialize=function(t){c.prototype.initialize.call(this,t);var i=this.model.glyph,n=N.includes(i.mixins,\"fill\"),r=N.includes(i.mixins,\"line\"),o=_.clone(i.attributes);function e(t){var e=_.clone(o);return n&&_.extend(e,t.fill),r&&_.extend(e,t.line),new i.constructor(e)}delete o.id,this.glyph=this.build_glyph_view(i);var s=this.model.selection_glyph;null==s?s=e({fill:{},line:{}}):\"auto\"===s&&(s=e(p)),this.selection_glyph=this.build_glyph_view(s);var a=this.model.nonselection_glyph;null==a?a=e({fill:{},line:{}}):\"auto\"===a&&(a=e(f)),this.nonselection_glyph=this.build_glyph_view(a);var l=this.model.hover_glyph;null!=l&&(this.hover_glyph=this.build_glyph_view(l));var h=this.model.muted_glyph;null!=h&&(this.muted_glyph=this.build_glyph_view(h));var u=e(d);this.decimated_glyph=this.build_glyph_view(u),this.xscale=this.plot_view.frame.xscales[this.model.x_range_name],this.yscale=this.plot_view.frame.yscales[this.model.y_range_name],this.set_data(!1)},t.prototype.build_glyph_view=function(t){return new t.default_view({model:t,renderer:this,plot_view:this.plot_view,parent:this})},t.prototype.connect_signals=function(){var e=this;c.prototype.connect_signals.call(this),this.connect(this.model.change,function(){return e.request_render()}),this.connect(this.model.glyph.change,function(){return e.set_data()}),this.connect(this.model.data_source.change,function(){return e.set_data()}),this.connect(this.model.data_source.streaming,function(){return e.set_data()}),this.connect(this.model.data_source.patching,function(t){return e.set_data(!0,t)}),this.connect(this.model.data_source.selected.change,function(){return e.request_render()}),this.connect(this.model.data_source._select,function(){return e.request_render()}),null!=this.hover_glyph&&this.connect(this.model.data_source.inspect,function(){return e.request_render()}),this.connect(this.model.properties.view.change,function(){return e.set_data()}),this.connect(this.model.view.change,function(){return e.set_data()});var t=this.plot_model.frame,i=t.x_ranges,n=t.y_ranges;for(var r in i){var o=i[r];o instanceof l.FactorRange&&this.connect(o.change,function(){return e.set_data()})}for(var s in n){var o=n[s];o instanceof l.FactorRange&&this.connect(o.change,function(){return e.set_data()})}this.connect(this.model.glyph.transformchange,function(){return e.set_data()})},t.prototype.have_selection_glyphs=function(){return null!=this.selection_glyph&&null!=this.nonselection_glyph},t.prototype.set_data=function(t,e){void 0===t&&(t=!0),void 0===e&&(e=null);var i=Date.now(),n=this.model.data_source;this.all_indices=this.model.view.indices,this.glyph.model.setv({x_range_name:this.model.x_range_name,y_range_name:this.model.y_range_name},{silent:!0}),this.glyph.set_data(n,this.all_indices,e),this.glyph.set_visuals(n),this.decimated_glyph.set_visuals(n),this.have_selection_glyphs()&&(this.selection_glyph.set_visuals(n),this.nonselection_glyph.set_visuals(n)),null!=this.hover_glyph&&this.hover_glyph.set_visuals(n),null!=this.muted_glyph&&this.muted_glyph.set_visuals(n);var r=this.plot_model.plot.lod_factor;this.decimated=[];for(var o=0,s=Math.floor(this.all_indices.length/r);ov?(o=this.decimated,_=this.decimated_glyph,p=this.decimated_glyph):(_=this.model.muted&&null!=this.muted_glyph?this.muted_glyph:this.glyph,p=this.nonselection_glyph),d=this.selection_glyph,null!=this.hover_glyph&&f.length&&(o=N.difference(o,f));var m,g=null;if(l.length&&this.have_selection_glyphs()){for(var y=Date.now(),b={},x=0,w=l;xi?n.slice(-i):n}if(S.isTypedArray(t)){var r=t.length+e.length;if(null!=i&&i=Math.pow(2,i))||e<0||e>=Math.pow(2,i))},t.prototype.parent_by_tile_xyz=function(t,e,i){var n=this.tile_xyz_to_quadkey(t,e,i),r=n.substring(0,n.length-1);return this.quadkey_to_tile_xyz(r)},t.prototype.get_resolution=function(t){return this._computed_initial_resolution()/Math.pow(2,t)},t.prototype.get_resolution_by_extent=function(t,e,i){var n=(t[2]-t[0])/i,r=(t[3]-t[1])/e;return[n,r]},t.prototype.get_level_by_extent=function(t,e,i){for(var n=(t[2]-t[0])/i,r=(t[3]-t[1])/e,o=Math.max(n,r),s=0,a=0,l=this._resolutions;ar.end)&&(this.v_axis_only=!0),(io.end)&&(this.h_axis_only=!0)}null!=this.model.document&&this.model.document.interactive_start(this.plot_model.plot)},e.prototype._pan=function(t){this._update(t.deltaX,t.deltaY),null!=this.model.document&&this.model.document.interactive_start(this.plot_model.plot)},e.prototype._pan_end=function(t){this.h_axis_only=!1,this.v_axis_only=!1,null!=this.pan_info&&this.plot_view.push_state(\"pan\",{range:this.pan_info})},e.prototype._update=function(t,e){var i,n,r,o,s,a,l=this.plot_model.frame,h=t-this.last_dx,u=e-this.last_dy,c=l.bbox.h_range,_=c.start-h,p=c.end-h,d=l.bbox.v_range,f=d.start-u,v=d.end-u,m=this.model.dimensions;\"width\"!=m&&\"both\"!=m||this.v_axis_only?(i=c.start,n=c.end,r=0):(i=_,n=p,r=-h),\"height\"!=m&&\"both\"!=m||this.h_axis_only?(o=d.start,s=d.end,a=0):(o=f,s=v,a=-u),this.last_dx=t,this.last_dy=e;var g=l.xscales,y=l.yscales,b={};for(var x in g){var w=g[x],k=w.r_invert(i,n),S=k[0],C=k[1];b[x]={start:S,end:C}}var T={};for(var A in y){var w=y[A],E=w.r_invert(o,s),S=E[0],C=E[1];T[A]={start:S,end:C}}this.pan_info={xrs:b,yrs:T,sdx:r,sdy:a},this.plot_view.update_range(this.pan_info,!0)},e}(r.GestureToolView);i.PanToolView=s;var a=function(i){function t(t){var e=i.call(this,t)||this;return e.tool_name=\"Pan\",e.event_type=\"pan\",e.default_order=10,e}return n.__extends(t,i),t.initClass=function(){this.prototype.type=\"PanTool\",this.prototype.default_view=s,this.define({dimensions:[o.Dimensions,\"both\"]})},Object.defineProperty(t.prototype,\"tooltip\",{get:function(){return this._get_dim_tooltip(\"Pan\",this.dimensions)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"icon\",{get:function(){switch(this.dimensions){case\"both\":return\"bk-tool-icon-pan\";case\"width\":return\"bk-tool-icon-xpan\";case\"height\":return\"bk-tool-icon-ypan\"}},enumerable:!0,configurable:!0}),t}(r.GestureTool);(i.PanTool=a).initClass()},function(t,e,i){var l=t(391),n=t(256),r=t(71),o=t(5),s=t(15),a=t(21),h=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.__extends(t,e),t.prototype.initialize=function(t){e.prototype.initialize.call(this,t),this.data={sx:[],sy:[]}},t.prototype.connect_signals=function(){var t=this;e.prototype.connect_signals.call(this),this.connect(this.model.properties.active.change,function(){return t._active_change()})},t.prototype._active_change=function(){this.model.active||this._clear_data()},t.prototype._keyup=function(t){t.keyCode==o.Keys.Enter&&this._clear_data()},t.prototype._doubletap=function(t){var e=t.shiftKey;this._do_select(this.data.sx,this.data.sy,!0,e),this.plot_view.push_state(\"poly_select\",{selection:this.plot_view.get_selection()}),this._clear_data()},t.prototype._clear_data=function(){this.data={sx:[],sy:[]},this.model.overlay.update({xs:[],ys:[]})},t.prototype._tap=function(t){var e=t.sx,i=t.sy,n=this.plot_model.frame;n.bbox.contains(e,i)&&(this.data.sx.push(e),this.data.sy.push(i),this.model.overlay.update({xs:a.copy(this.data.sx),ys:a.copy(this.data.sy)}))},t.prototype._do_select=function(t,e,i,n){var r={type:\"poly\",sx:t,sy:e};this._select(r,i,n)},t.prototype._emit_callback=function(t){var e=this.computed_renderers[0],i=this.plot_model.frame,n=i.xscales[e.x_range_name],r=i.yscales[e.y_range_name],o=n.v_invert(t.sx),s=r.v_invert(t.sy),a=l.__assign({x:o,y:s},t);this.model.callback.execute(this.model,{geometry:a})},t}(n.SelectToolView);i.PolySelectToolView=h;var u=function(){return new r.PolyAnnotation({level:\"overlay\",xs_units:\"screen\",ys_units:\"screen\",fill_color:{value:\"lightgrey\"},fill_alpha:{value:.5},line_color:{value:\"black\"},line_alpha:{value:1},line_width:{value:2},line_dash:{value:[4,4]}})},c=function(i){function t(t){var e=i.call(this,t)||this;return e.tool_name=\"Poly Select\",e.icon=\"bk-tool-icon-polygon-select\",e.event_type=\"tap\",e.default_order=11,e}return l.__extends(t,i),t.initClass=function(){this.prototype.type=\"PolySelectTool\",this.prototype.default_view=h,this.define({callback:[s.Instance],overlay:[s.Instance,u]})},t}(n.SelectTool);(i.PolySelectTool=c).initClass()},function(t,e,i){var n=t(391),_=t(64),r=t(14),o=t(15),s=t(251);function p(t,e,i,n){if(null==e)return!1;var r=i.compute(e);return Math.abs(t-r)r.right)&&(o=!1)}if(null!=r.bottom&&null!=r.top){var a=n.invert(e);(ar.top)&&(o=!1)}return o}function l(t,e,i,n){var r=e.compute(t),o=e.invert(r+i);return o>=n.start&&o<=n.end?o:t}function h(t,e,i,n){var r=e.r_compute(t.start,t.end),o=r[0],s=r[1],a=e.r_invert(o+i,s+i),l=a[0],h=a[1];l>=n.start&&l<=n.end&&h>=n.start&&h<=n.end&&(t.start=l,t.end=h)}i.is_near=p,i.is_inside=d,i.compute_value=l,i.update_range=h;var a=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return n.__extends(t,e),t.prototype.initialize=function(t){e.prototype.initialize.call(this,t),this.side=0,this.model.update_overlay_from_ranges()},t.prototype.connect_signals=function(){var t=this;e.prototype.connect_signals.call(this),null!=this.model.x_range&&this.connect(this.model.x_range.change,function(){return t.model.update_overlay_from_ranges()}),null!=this.model.y_range&&this.connect(this.model.y_range.change,function(){return t.model.update_overlay_from_ranges()})},t.prototype._pan_start=function(t){this.last_dx=0,this.last_dy=0;var e=this.model.x_range,i=this.model.y_range,n=this.plot_model.frame,r=n.xscales.default,o=n.yscales.default,s=this.model.overlay,a=s.left,l=s.right,h=s.top,u=s.bottom,c=this.model.overlay.properties.line_width.value()+_.EDGE_TOLERANCE;null!=e&&this.model.x_interaction&&(p(t.sx,a,r,c)?this.side=1:p(t.sx,l,r,c)?this.side=2:d(t.sx,t.sy,r,o,s)&&(this.side=3)),null!=i&&this.model.y_interaction&&(0==this.side&&p(t.sy,u,o,c)&&(this.side=4),0==this.side&&p(t.sy,h,o,c)?this.side=5:d(t.sx,t.sy,r,o,this.model.overlay)&&(3==this.side?this.side=7:this.side=6))},t.prototype._pan=function(t){var e=this.plot_model.frame,i=t.deltaX-this.last_dx,n=t.deltaY-this.last_dy,r=this.model.x_range,o=this.model.y_range,s=e.xscales.default,a=e.yscales.default;null!=r&&(3==this.side||7==this.side?h(r,s,i,e.x_range):1==this.side?r.start=l(r.start,s,i,e.x_range):2==this.side&&(r.end=l(r.end,s,i,e.x_range))),null!=o&&(6==this.side||7==this.side?h(o,a,n,e.y_range):4==this.side?o.start=l(o.start,a,n,e.y_range):5==this.side&&(o.end=l(o.end,a,n,e.y_range))),this.last_dx=t.deltaX,this.last_dy=t.deltaY},t.prototype._pan_end=function(t){this.side=0},t}(s.GestureToolView);i.RangeToolView=a;var u=function(){return new _.BoxAnnotation({level:\"overlay\",render_mode:\"css\",fill_color:\"lightgrey\",fill_alpha:{value:.5},line_color:{value:\"black\"},line_alpha:{value:1},line_width:{value:.5},line_dash:[2,2]})},c=function(i){function t(t){var e=i.call(this,t)||this;return e.tool_name=\"Range Tool\",e.icon=\"bk-tool-icon-range\",e.event_type=\"pan\",e.default_order=1,e}return n.__extends(t,i),t.initClass=function(){this.prototype.type=\"RangeTool\",this.prototype.default_view=a,this.define({x_range:[o.Instance,null],x_interaction:[o.Bool,!0],y_range:[o.Instance,null],y_interaction:[o.Bool,!0],overlay:[o.Instance,u]})},t.prototype.initialize=function(){i.prototype.initialize.call(this),this.overlay.in_cursor=\"grab\",this.overlay.ew_cursor=null!=this.x_range&&this.x_interaction?\"ew-resize\":null,this.overlay.ns_cursor=null!=this.y_range&&this.y_interaction?\"ns-resize\":null},t.prototype.update_overlay_from_ranges=function(){null==this.x_range&&null==this.y_range&&(this.overlay.left=null,this.overlay.right=null,this.overlay.bottom=null,this.overlay.top=null,r.logger.warn(\"RangeTool not configured with any Ranges.\")),null==this.x_range?(this.overlay.left=null,this.overlay.right=null):(this.overlay.left=this.x_range.start,this.overlay.right=this.x_range.end),null==this.y_range?(this.overlay.bottom=null,this.overlay.top=null):(this.overlay.bottom=this.y_range.start,this.overlay.top=this.y_range.end)},t}(s.GestureTool);(i.RangeTool=c).initClass()},function(t,e,i){var y=t(391),n=t(251),o=t(186),r=t(271),s=t(15),a=t(5),b=t(3),l=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return y.__extends(e,t),Object.defineProperty(e.prototype,\"computed_renderers\",{get:function(){var t=this.model.renderers,e=this.plot_model.plot.renderers,i=this.model.names;return r.compute_renderers(t,e,i)},enumerable:!0,configurable:!0}),e.prototype._computed_renderers_by_data_source=function(){for(var t={},e=0,i=this.computed_renderers;ee.x?-1:t.x==e.x?0:1}):r.sort(function(t,e){return t.xthis._x_sorted[this._x_sorted.length-1])return NaN}else{if(ethis._x_sorted[this._x_sorted.length-1])return this._y_sorted[this._y_sorted.length-1]}if(e==this._x_sorted[0])return this._y_sorted[0];var t=s.findLastIndex(this._x_sorted,function(t){return tthis._x_sorted[this._x_sorted.length-1])return NaN}else{if(ethis._x_sorted[this._x_sorted.length-1])return this._y_sorted[this._y_sorted.length-1]}var t;switch(this.mode){case\"after\":t=s.findLastIndex(this._x_sorted,function(t){return t<=e});break;case\"before\":t=s.findIndex(this._x_sorted,function(t){return e<=t});break;case\"center\":var i=this._x_sorted.map(function(t){return Math.abs(t-e)}),n=s.min(i);t=s.findIndex(i,function(t){return n===t});break;default:throw new Error(\"unknown mode: \"+this.mode)}return-1!=t?this._y_sorted[t]:NaN},t}(r.Interpolator);(i.StepInterpolator=a).initClass()},function(t,e,i){var n=t(391),r=t(59),o=function(e){function t(t){return e.call(this,t)||this}return n.__extends(t,e),t.initClass=function(){this.prototype.type=\"Transform\"},t}(r.Model);(i.Transform=o).initClass()},function(t,e,i){\"function\"!=typeof WeakMap&&t(342),Number.isInteger||(Number.isInteger=function(t){return\"number\"==typeof t&&isFinite(t)&&Math.floor(t)===t});var n,l,r,h,o=String.prototype;o.repeat||(o.repeat=function(t){if(null==this)throw new TypeError(\"can't convert \"+this+\" to object\");var e=\"\"+this;if((t=+t)!=t&&(t=0),t<0)throw new RangeError(\"repeat count must be non-negative\");if(t==1/0)throw new RangeError(\"repeat count must be less than infinity\");if(t=Math.floor(t),0==e.length||0==t)return\"\";if(e.length*t>=1<<28)throw new RangeError(\"repeat count must not overflow maximum string size\");for(var i=\"\";1==(1&t)&&(i+=e),0!=(t>>>=1);)e+=e;return i}),Array.from||(Array.from=(n=Object.prototype.toString,l=function(t){return\"function\"==typeof t||\"[object Function]\"===n.call(t)},r=Math.pow(2,53)-1,h=function(t){var e,i=(e=Number(t),isNaN(e)?0:0!==e&&isFinite(e)?(0Math.PI?0:1:_>Math.PI?1:0,this.lineTo(l,h),this.__addPathCommand(f(\"A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}\",{rx:i,ry:i,xAxisRotation:0,largeArcFlag:c,sweepFlag:u,endX:s,endY:a})),this.__currentPosition={x:s,y:a}}},x.prototype.clip=function(){var t=this.__closestGroupOrSvg(),e=this.__createElement(\"clipPath\"),i=l(this.__ids),n=this.__createElement(\"g\");this.__applyCurrentDefaultPath(),t.removeChild(this.__currentElement),e.setAttribute(\"id\",i),e.appendChild(this.__currentElement),this.__defs.appendChild(e),t.setAttribute(\"clip-path\",f(\"url(#{id})\",{id:i})),t.appendChild(n),this.__currentElement=n},x.prototype.drawImage=function(){var t,e,i,n,r,o,s,a,l,h,u,c,_,p,d=Array.prototype.slice.call(arguments),f=d[0],v=0,m=0;if(3===d.length)t=d[1],e=d[2],r=f.width,o=f.height,i=r,n=o;else if(5===d.length)t=d[1],e=d[2],i=d[3],n=d[4],r=f.width,o=f.height;else{if(9!==d.length)throw new Error(\"Inavlid number of arguments passed to drawImage: \"+arguments.length);v=d[1],m=d[2],r=d[3],o=d[4],t=d[5],e=d[6],i=d[7],n=d[8]}s=this.__closestGroupOrSvg(),this.__currentElement;var g=\"translate(\"+t+\", \"+e+\")\";if(f instanceof x){if((a=f.getSvg().cloneNode(!0)).childNodes&&1=this.__nextIndex__||(++this.__nextIndex__,this.__redo__?(this.__redo__.forEach(function(t,e){i<=t&&(this.__redo__[e]=++t)},this),this.__redo__.push(i)):c(this,\"__redo__\",l(\"c\",[i])))}),_onDelete:l(function(i){var t;i>=this.__nextIndex__||(--this.__nextIndex__,this.__redo__&&(-1!==(t=this.__redo__.indexOf(i))&&this.__redo__.splice(t,1),this.__redo__.forEach(function(t,e){i>1,a=i>>1^i,l=r>>1^n&o>>1^r,h=i&r>>1^o>>1^o;a=(i=s)&(n=a)>>2^n&(i^n)>>2,l^=i&(r=l)>>2^n&(o=h)>>2,h^=n&r>>2^(i^n)&o>>2,a=(i=s=i&i>>2^n&n>>2)&(n=a)>>4^n&(i^n)>>4,l^=i&(r=l)>>4^n&(o=h)>>4,h^=n&r>>4^(i^n)&o>>4,l^=(i=s=i&i>>4^n&n>>4)&(r=l)>>8^(n=a)&(o=h)>>8;var u=t^e,c=(n=(h^=n&r>>8^(i^n)&o>>8)^h>>1)|65535^(u|(i=l^l>>1));return((c=1431655765&((c=858993459&((c=252645135&((c=16711935&(c|c<<8))|c<<4))|c<<2))|c<<1))<<1|(u=1431655765&((u=858993459&((u=252645135&((u=16711935&(u|u<<8))|u<<4))|u<<2))|u<<1)))>>>0}return h.from=function(t){if(!(t instanceof ArrayBuffer))throw new Error(\"Data must be an instance of ArrayBuffer.\");var e=new Uint8Array(t,0,2),i=e[0],n=e[1];if(251!==i)throw new Error(\"Data does not appear to be in a Flatbush format.\");if(n>>4!=3)throw new Error(\"Got v\"+(n>>4)+\" data when expected v3.\");var r=new Uint16Array(t,2,1),o=r[0],s=new Uint32Array(t,4,1),a=s[0];return new h(a,o,l[15&n],t)},h.prototype.add=function(t,e,i,n){var r=this._pos>>2;this._indices[r]=r,this._boxes[this._pos++]=t,this._boxes[this._pos++]=e,this._boxes[this._pos++]=i,this._boxes[this._pos++]=n,tthis.maxX&&(this.maxX=i),n>this.maxY&&(this.maxY=n)},h.prototype.finish=function(){var t=this;if(this._pos>>2!==this.numItems)throw new Error(\"Added \"+(this._pos>>2)+\" items when expected \"+this.numItems+\".\");for(var e=this.maxX-this.minX,i=this.maxY-this.minY,n=new Uint32Array(this.numItems),r=0;r>1],a=r-1,l=o+1;;){for(;e[++a]s;);if(l<=a)break;C(e,i,n,a,l)}t(e,i,n,r,l),t(e,i,n,l+1,o)}}(n,this._boxes,this._indices,0,this.numItems-1);for(var _=0,p=0;_>2]=y,t._boxes[t._pos++]=f,t._boxes[t._pos++]=v,t._boxes[t._pos++]=m,t._boxes[t._pos++]=g}},h.prototype.search=function(t,e,i,n,r){if(this._pos!==this._boxes.length)throw new Error(\"Data not yet indexed - call index.finish().\");for(var o=this._boxes.length-4,s=this._levelBounds.length-1,a=[],l=[];void 0!==o;){for(var h=Math.min(o+4*this.nodeSize,this._levelBounds[s]),u=o;u>2];ithis._boxes[u+2]||e>this._boxes[u+3]||(o<4*this.numItems?(void 0===r||r(c))&&l.push(c):(a.push(c),a.push(s-1)))}s=a.pop(),o=a.pop()}return l},h},\"object\"==typeof i&&void 0!==e?e.exports=r():n.Flatbush=r()},function(t,Yt,e){\n /*! Hammer.JS - v2.0.7 - 2016-04-22\n * http://hammerjs.github.io/\n *\n * Copyright (c) 2016 Jorik Tangelder;\n * Licensed under the MIT license */\n !function(o,a,t,x){\"use strict\";var s,l=[\"\",\"webkit\",\"Moz\",\"MS\",\"ms\",\"o\"],e=a.createElement(\"div\"),i=\"function\",h=Math.round,w=Math.abs,k=Date.now;function u(t,e,i){return setTimeout(f(t,i),e)}function n(t,e,i){return!!Array.isArray(t)&&(c(t,i[e],i),!0)}function c(t,e,i){var n;if(t)if(t.forEach)t.forEach(e,i);else if(t.length!==x)for(n=0;n\\s*\\(/gm,\"{anonymous}()@\"):\"Unknown Stack Trace\",i=o.console&&(o.console.warn||o.console.log);return i&&i.call(o.console,r,e),n.apply(this,arguments)}}s=\"function\"!=typeof Object.assign?function(t){if(t===x||null===t)throw new TypeError(\"Cannot convert undefined or null to object\");for(var e=Object(t),i=1;ie[i]}):n.sort()),n}function M(t,e){for(var i,n,r=e[0].toUpperCase()+e.slice(1),o=0;ow(y.y)?y.x:y.y,e.scale=_?(m=_.pointers,it((g=n)[0],g[1],J)/it(m[0],m[1],J)):1,e.rotation=_?(f=_.pointers,nt((v=n)[1],v[0],J)+nt(f[1],f[0],J)):0,e.maxPointers=i.prevInput?e.pointers.length>i.prevInput.maxPointers?e.pointers.length:i.prevInput.maxPointers:e.pointers.length,function(t,e){var i,n,r,o,s=t.lastInterval||e,a=e.timeStamp-s.timeStamp;if(e.eventType!=B&&(Dw(u.y)?u.x:u.y,o=et(l,h),t.lastInterval=e}else i=s.velocity,n=s.velocityX,r=s.velocityY,o=s.direction;e.velocity=i,e.velocityX=n,e.velocityY=r,e.direction=o}(i,e);var b=t.element;S(e.srcEvent.target,b)&&(b=e.srcEvent.target),e.target=b}(t,i),t.emit(\"hammer.input\",i),t.recognize(i),t.session.prevInput=i}function K(t){for(var e=[],i=0;i=w(e)?t<0?V:G:e<0?U:q}function it(t,e,i){i||(i=W);var n=e[i[0]]-t[i[0]],r=e[i[1]]-t[i[1]];return Math.sqrt(n*n+r*r)}function nt(t,e,i){i||(i=W);var n=e[i[0]]-t[i[0]],r=e[i[1]]-t[i[1]];return 180*Math.atan2(r,n)/Math.PI}Q.prototype={handler:function(){},init:function(){this.evEl&&g(this.element,this.evEl,this.domHandler),this.evTarget&&g(this.target,this.evTarget,this.domHandler),this.evWin&&g(z(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&y(this.element,this.evEl,this.domHandler),this.evTarget&&y(this.target,this.evTarget,this.domHandler),this.evWin&&y(z(this.element),this.evWin,this.domHandler)}};var rt={mousedown:I,mousemove:2,mouseup:R},ot=\"mousedown\",st=\"mousemove mouseup\";function at(){this.evEl=ot,this.evWin=st,this.pressed=!1,Q.apply(this,arguments)}d(at,Q,{handler:function(t){var e=rt[t.type];e&I&&0===t.button&&(this.pressed=!0),2&e&&1!==t.which&&(e=R),this.pressed&&(e&R&&(this.pressed=!1),this.callback(this.manager,e,{pointers:[t],changedPointers:[t],pointerType:\"mouse\",srcEvent:t}))}});var lt={pointerdown:I,pointermove:2,pointerup:R,pointercancel:B,pointerout:B},ht={2:F,3:\"pen\",4:\"mouse\",5:\"kinect\"},ut=\"pointerdown\",ct=\"pointermove pointerup pointercancel\";function _t(){this.evEl=ut,this.evWin=ct,Q.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}o.MSPointerEvent&&!o.PointerEvent&&(ut=\"MSPointerDown\",ct=\"MSPointerMove MSPointerUp MSPointerCancel\"),d(_t,Q,{handler:function(t){var e=this.store,i=!1,n=t.type.toLowerCase().replace(\"ms\",\"\"),r=lt[n],o=ht[t.pointerType]||t.pointerType,s=o==F,a=T(e,t.pointerId,\"pointerId\");r&I&&(0===t.button||s)?a<0&&(e.push(t),a=e.length-1):r&(R|B)&&(i=!0),a<0||(e[a]=t,this.callback(this.manager,r,{pointers:e,changedPointers:[t],pointerType:o,srcEvent:t}),i&&e.splice(a,1))}});var pt={touchstart:I,touchmove:2,touchend:R,touchcancel:B};function dt(){this.evTarget=\"touchstart\",this.evWin=\"touchstart touchmove touchend touchcancel\",this.started=!1,Q.apply(this,arguments)}d(dt,Q,{handler:function(t){var e=pt[t.type];if(e===I&&(this.started=!0),this.started){var i=function(t,e){var i=A(t.touches),n=A(t.changedTouches);return e&(R|B)&&(i=E(i.concat(n),\"identifier\",!0)),[i,n]}.call(this,t,e);e&(R|B)&&i[0].length-i[1].length==0&&(this.started=!1),this.callback(this.manager,e,{pointers:i[0],changedPointers:i[1],pointerType:F,srcEvent:t})}}});var ft={touchstart:I,touchmove:2,touchend:R,touchcancel:B},vt=\"touchstart touchmove touchend touchcancel\";function mt(){this.evTarget=vt,this.targetIds={},Q.apply(this,arguments)}d(mt,Q,{handler:function(t){var e=ft[t.type],i=function(t,e){var i=A(t.touches),n=this.targetIds;if(e&(2|I)&&1===i.length)return n[i[0].identifier]=!0,[i,i];var r,o,s=A(t.changedTouches),a=[],l=this.target;if(o=i.filter(function(t){return S(t.target,l)}),e===I)for(r=0;re.threshold&&r&e.direction},attrTest:function(t){return Nt.prototype.attrTest.call(this,t)&&(2&this.state||!(2&this.state)&&this.directionTest(t))},emit:function(t){this.pX=t.deltaX,this.pY=t.deltaY;var e=Pt(t.direction);e&&(t.additionalEvent=this.options.event+e),this._super.emit.call(this,t)}}),d(Dt,Nt,{defaults:{event:\"pinch\",threshold:0,pointers:2},getTouchAction:function(){return[St]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.scale-1)>this.options.threshold||2&this.state)},emit:function(t){if(1!==t.scale){var e=t.scale<1?\"in\":\"out\";t.additionalEvent=this.options.event+e}this._super.emit.call(this,t)}}),d(It,Ot,{defaults:{event:\"press\",pointers:1,time:251,threshold:9},getTouchAction:function(){return[\"auto\"]},process:function(t){var e=this.options,i=t.pointers.length===e.pointers,n=t.distancee.time;if(this._input=t,!n||!i||t.eventType&(R|B)&&!r)this.reset();else if(t.eventType&I)this.reset(),this._timer=u(function(){this.state=8,this.tryEmit()},e.time,this);else if(t.eventType&R)return 8;return 32},reset:function(){clearTimeout(this._timer)},emit:function(t){8===this.state&&(t&&t.eventType&R?this.manager.emit(this.options.event+\"up\",t):(this._input.timeStamp=k(),this.manager.emit(this.options.event,this._input)))}}),d(Rt,Nt,{defaults:{event:\"rotate\",threshold:0,pointers:2},getTouchAction:function(){return[St]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.rotation)>this.options.threshold||2&this.state)}}),d(Bt,Nt,{defaults:{event:\"swipe\",threshold:10,velocity:.3,direction:Y|X,pointers:1},getTouchAction:function(){return Ft.prototype.getTouchAction.call(this)},attrTest:function(t){var e,i=this.options.direction;return i&(Y|X)?e=t.overallVelocity:i&Y?e=t.overallVelocityX:i&X&&(e=t.overallVelocityY),this._super.attrTest.call(this,t)&&i&t.offsetDirection&&t.distance>this.options.threshold&&t.maxPointers==this.options.pointers&&w(e)>this.options.velocity&&t.eventType&R},emit:function(t){var e=Pt(t.offsetDirection);e&&this.manager.emit(this.options.event+e,t),this.manager.emit(this.options.event,t)}}),d(Lt,Ot,{defaults:{event:\"tap\",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[kt]},process:function(t){var e=this.options,i=t.pointers.length===e.pointers,n=t.distance=\";case n.Eq:return\"==\"}}()+\" 0\"},Object.defineProperty(t.prototype,\"id\",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"expression\",{get:function(){return this._expression},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"op\",{get:function(){return this._operator},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,\"strength\",{get:function(){return this._strength},enumerable:!0,configurable:!0}),t}();i.Constraint=s;var a=0},function(t,e,i){var h=t(357),u=t(360),c=t(351),n=function(){function t(){var t=function(t){for(var e=0,i=function(){return 0},n=c.createMap(u.Variable.Compare),r=0,o=t.length;r>1)],e)<0?(o=r+1,s-=n+1):s=n;return o}i.lowerBound=o,i.binarySearch=function(t,e,i){var n=o(t,e,i);if(n===t.length)return-1;var r=t[n];return 0!==i(r,e)?-1:n},i.binaryFind=function(t,e,i){var n=o(t,e,i);if(n!==t.length){var r=t[n];if(0===i(r,e))return r}},i.asSet=function(t,e){var i=l.asArray(t),n=i.length;if(n<=1)return i;i.sort(e);for(var r=[i[0]],o=1,s=0;o=Math.pow(10,12)&&!z||O?(T+=U[q].abbreviations.trillion,t/=Math.pow(10,12)):N=Math.pow(10,9)&&!z||M?(T+=U[q].abbreviations.billion,t/=Math.pow(10,9)):N=Math.pow(10,6)&&!z||E?(T+=U[q].abbreviations.million,t/=Math.pow(10,6)):(N=Math.pow(10,3)&&!z||A)&&(T+=U[q].abbreviations.thousand,t/=Math.pow(10,3)))}if(-1Math.PI&&(a-=2*Math.PI),r=Math.sin(l),s=Math.cos(l),o=r*r,{x:((n=i/Math.sqrt(1-e*o))+h)*s*Math.cos(a),y:(n+h)*s*Math.sin(a),z:(n*(1-e)+h)*r}},i.geocentricToGeodetic=function(t,e,i,n){var r,o,s,a,l,h,u,c,_,p,d,f,v,m,g,y,b=t.x,x=t.y,w=t.z?t.z:0;if(r=Math.sqrt(b*b+x*x),o=Math.sqrt(b*b+x*x+w*w),r/i<1e-12){if(m=0,o/i<1e-12)return g=k,y=-n,{x:t.x,y:t.y,z:t.z}}else m=Math.atan2(x,b);for(s=w/o,a=r/o,l=1/Math.sqrt(1-e*(2-e)*a*a),c=a*(1-e)*l,_=s*l,v=0;v++,u=i/Math.sqrt(1-e*_*_),h=e*u/(u+(y=r*c+w*_-u*(1-e*_*_))),l=1/Math.sqrt(1-h*(2-h)*a*a),f=(d=s*l)*c-(p=a*(1-h)*l)*_,c=p,_=d,1e-24>>0).toString(8);break;case\"s\":i=String(i),i=o[7]?i.substring(0,o[7]):i;break;case\"t\":i=String(!!i),i=o[7]?i.substring(0,o[7]):i;break;case\"T\":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=o[7]?i.substring(0,o[7]):i;break;case\"u\":i=parseInt(i,10)>>>0;break;case\"v\":i=i.valueOf(),i=o[7]?i.substring(0,o[7]):i;break;case\"x\":i=(parseInt(i,10)>>>0).toString(16);break;case\"X\":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}d.json.test(o[8])?p+=i:(!d.number.test(o[8])||h&&!o[3]?u=\"\":(u=h?\"+\":\"-\",i=i.toString().replace(d.sign,\"\")),a=o[4]?\"0\"===o[4]?\"0\":o[4].charAt(1):\" \",l=o[6]-(u+i).length,s=o[6]&&0=c[n][e]&&c[n][c[n].clock]>o[c[n].clock]&&(s=c[n])}return s&&((a=/^(.*)\\/(.*)$/.exec(o.format))?s.abbrev=a[s.save?2:1]:s.abbrev=o.format.replace(/%s/,s.rule.letter)),s||o}function a(t,e){return\"UTC\"==t.zone?e:(t.entry=r(t,\"posix\",e),e+t.entry.offset+t.entry.save)}function c(t,e){return\"UTC\"==t.zone?e:(t.entry=i=r(t,\"wallclock\",e),0<(n=e-i.wallclock)&&ns[0]&&e[1]=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}}},p=function(t,e){var i=\"function\"==typeof Symbol&&t[Symbol.iterator];if(!i)return t;var n,r,o=i.call(t),s=[];try{for(;(void 0===e||0=t&&(this.model.active=t-1);var o=this.model.tabs.map(function(t,e){return h.li({},h.span({data:{index:e}},t.title))});o[this.model.active].classList.add(\"bk-bs-active\");var e=h.ul({class:[\"bk-bs-nav\",\"bk-bs-nav-tabs\"]},o);this.el.appendChild(e);var s=this.model.tabs.map(function(t){return h.div({class:\"bk-bs-tab-pane\"})});s[this.model.active].classList.add(\"bk-bs-active\");var n=h.div({class:\"bk-bs-tab-content\"},s);this.el.appendChild(n),e.addEventListener(\"click\",function(t){if(t.preventDefault(),t.target!=t.currentTarget){var e=t.target,n=r.model.active,i=parseInt(e.dataset.index);n!=i&&(o[n].classList.remove(\"bk-bs-active\"),s[n].classList.remove(\"bk-bs-active\"),o[i].classList.add(\"bk-bs-active\"),s[i].classList.add(\"bk-bs-active\"),r.model.active=i,null!=r.model.callback&&r.model.callback.execute(r.model))}});for(var i=0,a=p.zip(this.model.children,s);i=e[n];)n+=1;return n}function n(t,e,n){if(n>=t.slice(-1)[0])return 100;var i,r,o,s,a,l,u=h(n,t);return i=t[u-1],r=t[u],o=e[u-1],s=e[u],o+(l=n,d(a=[i,r],a[0]<0?l+Math.abs(a[0]):l-a[0])/c(o,s))}function i(t,e,n,i){if(100===i)return i;var r,o,s,a,l=h(i,t);return n?(r=t[l-1],((o=t[l])-r)/2n.stepAfter.startValue&&(r=n.stepAfter.startValue-i),o=i>n.thisStep.startValue?n.thisStep.step:!1!==n.stepBefore.step&&i-n.stepBefore.highestStep,100===t?r=null:0===t&&(o=null);var s=w.countStepDecimals();return null!==r&&!1!==r&&(r=Number(r.toFixed(s))),null!==o&&!1!==o&&(o=Number(o.toFixed(s))),[o,r]})},on:J,off:function(t){var i=t&&t.split(\".\")[0],r=i&&t.substring(i.length);Object.keys(b).forEach(function(t){var e=t.split(\".\")[0],n=t.substring(e.length);i&&i!==e||r&&r!==n||delete b[t]})},get:K,set:X,reset:function(t){X(d.start,t)},__moveHandles:function(t,e,n){T(t,e,m,n)},options:o,updateOptions:function(e,t){var n=K(),i=[\"margin\",\"limit\",\"padding\",\"range\",\"animate\",\"snap\",\"step\",\"format\"];i.forEach(function(t){void 0!==e[t]&&(o[t]=e[t])});var r=rt(o);i.forEach(function(t){void 0!==e[t]&&(d[t]=r[t])}),w=r.spectrum,d.margin=r.margin,d.limit=r.limit,d.padding=r.padding,d.pips&&N(d.pips),m=[],X(e.start||n,t)},target:_,removePips:A,pips:N},(c=d.events).fixed||l.forEach(function(t,e){V(p.start,t.children[0],B,{handleNumbers:[e]})}),c.tap&&V(p.start,u,U,{}),c.hover&&V(p.move,u,j,{hover:!0}),c.drag&&s.forEach(function(t,e){if(!1!==t&&0!==e&&e!==s.length-1){var n=l[e-1],i=l[e],r=[t];et(t,d.cssClasses.draggable),c.fixed&&(r.push(n.children[0]),r.push(i.children[0])),r.forEach(function(t){V(p.start,t,B,{handles:[n,i],handleNumbers:[e-1,e]})})}}),X(d.start),d.pips&&N(d.pips),d.tooltips&&(r=l.map(D),J(\"update\",function(t,e,n){if(r[e]){var i=t[e];!0!==d.tooltips[e]&&(i=d.tooltips[e].to(n[e])),r[e].innerHTML=i}})),J(\"update\",function(t,e,s,n,a){v.forEach(function(t){var e=l[t],n=z(m,t,0,!0,!0,!0),i=z(m,t,100,!0,!0,!0),r=a[t],o=d.ariaFormat.to(s[t]);e.children[0].setAttribute(\"aria-valuemin\",n.toFixed(1)),e.children[0].setAttribute(\"aria-valuemax\",i.toFixed(1)),e.children[0].setAttribute(\"aria-valuenow\",r.toFixed(1)),e.children[0].setAttribute(\"aria-valuetext\",o)})}),a}return{version:$,create:function(t,e){if(!t||!t.nodeName)throw new Error(\"noUiSlider (\"+$+\"): create requires a single element, got: \"+t);var n=rt(e),i=P(t,n,e);return t.noUiSlider=i}}},\"object\"==typeof n?e.exports=i():window.noUiSlider=i()},433:function(i,r,o){\n /*!\n * Pikaday\n *\n * Copyright © 2014 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday\n */\n !function(t,e){\"use strict\";var n;if(\"object\"==typeof o){try{n=i(\"moment\")}catch(t){}r.exports=e(n)}else t.Pikaday=e(t.moment)}(this,function(n){\"use strict\";var o=\"function\"==typeof n,s=!!window.addEventListener,c=window.document,u=window.setTimeout,a=function(t,e,n,i){s?t.addEventListener(e,n,!!i):t.attachEvent(\"on\"+e,n)},i=function(t,e,n,i){s?t.removeEventListener(e,n,!!i):t.detachEvent(\"on\"+e,n)},l=function(t,e){return-1!==(\" \"+t.className+\" \").indexOf(\" \"+e+\" \")},g=function(t){return/Array/.test(Object.prototype.toString.call(t))},B=function(t){return/Date/.test(Object.prototype.toString.call(t))&&!isNaN(t.getTime())},U=function(t,e){return[31,(n=t,n%4==0&&n%100!=0||n%400==0?29:28),31,30,31,30,31,31,30,31,30,31][e];var n},j=function(t){B(t)&&t.setHours(0,0,0,0)},z=function(t,e){return t.getTime()===e.getTime()},d=function(t,e,n){var i,r;for(i in e)(r=void 0!==t[i])&&\"object\"==typeof e[i]&&null!==e[i]&&void 0===e[i].nodeName?B(e[i])?n&&(t[i]=new Date(e[i].getTime())):g(e[i])?n&&(t[i]=e[i].slice(0)):t[i]=d({},e[i],n):!n&&r||(t[i]=e[i]);return t},r=function(t,e,n){var i;c.createEvent?((i=c.createEvent(\"HTMLEvents\")).initEvent(e,!0,!1),i=d(i,n),t.dispatchEvent(i)):c.createEventObject&&(i=c.createEventObject(),i=d(i,n),t.fireEvent(\"on\"+e,i))},e=function(t){return t.month<0&&(t.year-=Math.ceil(Math.abs(t.month)/12),t.month+=12),11';e.push(\"is-outside-current-month\"),t.enableSelectionDaysInNextAndPreviousMonths||e.push(\"is-selection-disabled\")}return t.isDisabled&&e.push(\"is-disabled\"),t.isToday&&e.push(\"is-today\"),t.isSelected&&(e.push(\"is-selected\"),n=\"true\"),t.hasEvent&&e.push(\"has-event\"),t.isInRange&&e.push(\"is-inrange\"),t.isStartRange&&e.push(\"is-startrange\"),t.isEndRange&&e.push(\"is-endrange\"),'\"},f=function(t,e,n,i,r,o){var s,a,l,u,c,d=t._o,h=n===d.minYear,p=n===d.maxYear,f='
',m=!0,v=!0;for(l=[],s=0;s<12;s++)l.push('\");for(u='
'+d.i18n.months[i]+'
\",g(d.yearRange)?(s=d.yearRange[0],a=d.yearRange[1]+1):(s=n-d.yearRange,a=1+n+d.yearRange),l=[];s=d.minYear&&l.push('\");return c='
'+n+d.yearSuffix+'
\",d.showMonthAfterYear?f+=c+u:f+=u+c,h&&(0===i||d.minMonth>=i)&&(m=!1),p&&(11===i||d.maxMonth<=i)&&(v=!1),0===e&&(f+='\"),e===t._o.numberOfMonths-1&&(f+='\"),f+=\"
\"},Y=function(t,e,n){return''+function(t){var e,n=[];for(t.showWeekNumber&&n.push(\"\"),e=0;e<7;e++)n.push('\");return\"\"+(t.isRTL?n.reverse():n).join(\"\")+\"\"}(t)+\"\"+e.join(\"\")+\"
'+p(t,e,!0)+\"
\"},t=function(t){var i=this,r=i.config(t);i._onMouseDown=function(t){if(i._v){var e=(t=t||window.event).target||t.srcElement;if(e)if(l(e,\"is-disabled\")||(!l(e,\"pika-button\")||l(e,\"is-empty\")||l(e.parentNode,\"is-disabled\")?l(e,\"pika-prev\")?i.prevMonth():l(e,\"pika-next\")&&i.nextMonth():(i.setDate(new Date(e.getAttribute(\"data-pika-year\"),e.getAttribute(\"data-pika-month\"),e.getAttribute(\"data-pika-day\"))),r.bound&&u(function(){i.hide(),r.blurFieldOnSelect&&r.field&&r.field.blur()},100))),l(e,\"pika-select\"))i._c=!0;else{if(!t.preventDefault)return t.returnValue=!1;t.preventDefault()}}},i._onChange=function(t){var e=(t=t||window.event).target||t.srcElement;e&&(l(e,\"pika-select-month\")?i.gotoMonth(e.value):l(e,\"pika-select-year\")&&i.gotoYear(e.value))},i._onKeyChange=function(t){if(t=t||window.event,i.isVisible())switch(t.keyCode){case 13:case 27:r.field&&r.field.blur();break;case 37:t.preventDefault(),i.adjustDate(\"subtract\",1);break;case 38:i.adjustDate(\"subtract\",7);break;case 39:i.adjustDate(\"add\",1);break;case 40:i.adjustDate(\"add\",7)}},i._onInputChange=function(t){var e;t.firedBy!==i&&(e=r.parse?r.parse(r.field.value,r.format):o?(e=n(r.field.value,r.format,r.formatStrict))&&e.isValid()?e.toDate():null:new Date(Date.parse(r.field.value)),B(e)&&i.setDate(e),i._v||i.show())},i._onInputFocus=function(){i.show()},i._onInputClick=function(){i.show()},i._onInputBlur=function(){var t=c.activeElement;do{if(l(t,\"pika-single\"))return}while(t=t.parentNode);i._c||(i._b=u(function(){i.hide()},50)),i._c=!1},i._onClick=function(t){var e=(t=t||window.event).target||t.srcElement,n=e;if(e){!s&&l(e,\"pika-select\")&&(e.onchange||(e.setAttribute(\"onchange\",\"return;\"),a(e,\"change\",i._onChange)));do{if(l(n,\"pika-single\")||n===r.trigger)return}while(n=n.parentNode);i._v&&e!==r.trigger&&n!==r.trigger&&i.hide()}},i.el=c.createElement(\"div\"),i.el.className=\"pika-single\"+(r.isRTL?\" is-rtl\":\"\")+(r.theme?\" \"+r.theme:\"\"),a(i.el,\"mousedown\",i._onMouseDown,!0),a(i.el,\"touchend\",i._onMouseDown,!0),a(i.el,\"change\",i._onChange),r.keyboardInput&&a(c,\"keydown\",i._onKeyChange),r.field&&(r.container?r.container.appendChild(i.el):r.bound?c.body.appendChild(i.el):r.field.parentNode.insertBefore(i.el,r.field.nextSibling),a(r.field,\"change\",i._onInputChange),r.defaultDate||(o&&r.field.value?r.defaultDate=n(r.field.value,r.format).toDate():r.defaultDate=new Date(Date.parse(r.field.value)),r.setDefaultDate=!0));var e=r.defaultDate;B(e)?r.setDefaultDate?i.setDate(e,!0):i.gotoDate(e):i.gotoDate(new Date),r.bound?(this.hide(),i.el.className+=\" is-bound\",a(r.trigger,\"click\",i._onInputClick),a(r.trigger,\"focus\",i._onInputFocus),a(r.trigger,\"blur\",i._onInputBlur)):this.show()};return t.prototype={config:function(t){this._o||(this._o=d({},h,!0));var e=d(this._o,t,!0);e.isRTL=!!e.isRTL,e.field=e.field&&e.field.nodeName?e.field:null,e.theme=\"string\"==typeof e.theme&&e.theme?e.theme:null,e.bound=!!(void 0!==e.bound?e.field&&e.bound:e.field),e.trigger=e.trigger&&e.trigger.nodeName?e.trigger:e.field,e.disableWeekends=!!e.disableWeekends,e.disableDayFn=\"function\"==typeof e.disableDayFn?e.disableDayFn:null;var n=parseInt(e.numberOfMonths,10)||1;if(e.numberOfMonths=4=r&&(this._y=r,!isNaN(s)&&this._m>s&&(this._m=s)),e=\"pika-title-\"+Math.random().toString(36).replace(/[^a-z]+/g,\"\").substr(0,2);for(var l=0;l'+f(this,l,this.calendars[l].year,this.calendars[l].month,this.calendars[0].year,e)+this.render(this.calendars[l].year,this.calendars[l].month,e)+\"\";this.el.innerHTML=a,n.bound&&\"hidden\"!==n.field.type&&u(function(){n.trigger.focus()},1),\"function\"==typeof this._o.onDraw&&this._o.onDraw(this),n.bound&&n.field.setAttribute(\"aria-label\",\"Use the arrow keys to pick a date\")}},adjustPosition:function(){var t,e,n,i,r,o,s,a,l,u;if(!this._o.container){if(this.el.style.position=\"absolute\",t=this._o.trigger,e=t,n=this.el.offsetWidth,i=this.el.offsetHeight,r=window.innerWidth||c.documentElement.clientWidth,o=window.innerHeight||c.documentElement.clientHeight,s=window.pageYOffset||c.body.scrollTop||c.documentElement.scrollTop,\"function\"==typeof t.getBoundingClientRect)u=t.getBoundingClientRect(),a=u.left+window.pageXOffset,l=u.bottom+window.pageYOffset;else for(a=e.offsetLeft,l=e.offsetTop+e.offsetHeight;e=e.offsetParent;)a+=e.offsetLeft,l+=e.offsetTop;(this._o.reposition&&ri.maxDate||i.disableWeekends&&(0===(x=E.getDay())||6===x)||i.disableDayFn&&i.disableDayFn(E);N&&(S'+Math.ceil(((new Date(_,b,y)-w)/864e5+w.getDay()+1)/7)+\"\")),a.push((v=l,g=i.isRTL,''+(g?v.reverse():v).join(\"\")+\"\")),C=0,k=!(l=[]))}return Y(i,a,n)},isVisible:function(){return this._v},show:function(){var t,e,n;this.isVisible()||(this._v=!0,this.draw(),t=this.el,e=\"is-hidden\",t.className=(n=(\" \"+t.className+\" \").replace(\" \"+e+\" \",\" \")).trim?n.trim():n.replace(/^\\s+|\\s+$/g,\"\"),this._o.bound&&(a(c,\"click\",this._onClick),this.adjustPosition()),\"function\"==typeof this._o.onOpen&&this._o.onOpen.call(this))},hide:function(){var t,e,n=this._v;!1!==n&&(this._o.bound&&i(c,\"click\",this._onClick),this.el.style.position=\"static\",this.el.style.left=\"auto\",this.el.style.top=\"auto\",t=this.el,l(t,e=\"is-hidden\")||(t.className=\"\"===t.className?e:t.className+\" \"+e),this._v=!1,void 0!==n&&\"function\"==typeof this._o.onClose&&this._o.onClose.call(this))},destroy:function(){var t=this._o;this.hide(),i(this.el,\"mousedown\",this._onMouseDown,!0),i(this.el,\"touchend\",this._onMouseDown,!0),i(this.el,\"change\",this._onChange),t.keyboardInput&&i(c,\"keydown\",this._onKeyChange),t.field&&(i(t.field,\"change\",this._onInputChange),t.bound&&(i(t.trigger,\"click\",this._onInputClick),i(t.trigger,\"focus\",this._onInputFocus),i(t.trigger,\"blur\",this._onInputBlur))),this.el.parentNode&&this.el.parentNode.removeChild(this.el)}},t})}})}(this);\n //# sourceMappingURL=bokeh-widgets.min.js.map\n /* END bokeh-widgets.min.js */\n },\n \n function(Bokeh) {\n /* BEGIN bokeh-tables.min.js */\n /*!\n * Copyright (c) 2012 - 2018, Anaconda, Inc., and Bokeh Contributors\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of Anaconda nor the names of any contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n */\n !function(a,b){!function(Bokeh){var define;(function(e,t,n){if(null!=Bokeh)return Bokeh.register_plugin(e,{\"models/widgets/tables/cell_editors\":434,\"models/widgets/tables/cell_formatters\":435,\"models/widgets/tables/data_table\":436,\"models/widgets/tables/index\":437,\"models/widgets/tables/main\":438,\"models/widgets/tables/table_column\":439,\"models/widgets/tables/table_widget\":440,\"models/widgets/widget\":441},438);throw new Error(\"Cannot find Bokeh. You have to load it prior to loading plugins.\")})({434:function(e,t,n){var o=e(391),r=e(15),i=e(5),l=e(6),a=e(59),s=e(436),c=function(t){function e(e){return t.call(this,o.__assign({model:e.column.model},e))||this}return o.__extends(e,t),Object.defineProperty(e.prototype,\"emptyValue\",{get:function(){return null},enumerable:!0,configurable:!0}),e.prototype.initialize=function(e){t.prototype.initialize.call(this,e),this.inputEl=this._createInput(),this.defaultValue=null,this.args=e,this.render()},e.prototype.css_classes=function(){return t.prototype.css_classes.call(this).concat(\"bk-cell-editor\")},e.prototype.render=function(){t.prototype.render.call(this),this.args.container.appendChild(this.el),this.el.appendChild(this.inputEl),this.renderEditor(),this.disableNavigation()},e.prototype.renderEditor=function(){},e.prototype.disableNavigation=function(){this.inputEl.addEventListener(\"keydown\",function(e){switch(e.keyCode){case i.Keys.Left:case i.Keys.Right:case i.Keys.Up:case i.Keys.Down:case i.Keys.PageUp:case i.Keys.PageDown:e.stopImmediatePropagation()}})},e.prototype.destroy=function(){this.remove()},e.prototype.focus=function(){this.inputEl.focus()},e.prototype.show=function(){},e.prototype.hide=function(){},e.prototype.position=function(){},e.prototype.getValue=function(){return this.inputEl.value},e.prototype.setValue=function(e){this.inputEl.value=e},e.prototype.serializeValue=function(){return this.getValue()},e.prototype.isValueChanged=function(){return!(\"\"==this.getValue()&&null==this.defaultValue)&&this.getValue()!==this.defaultValue},e.prototype.applyValue=function(e,t){var n=this.args.grid.getData(),o=n.index.indexOf(e[s.DTINDEX_NAME]);n.setField(o,this.args.column.field,t)},e.prototype.loadValue=function(e){var t=e[this.args.column.field];this.defaultValue=null!=t?t:this.emptyValue,this.setValue(this.defaultValue)},e.prototype.validateValue=function(e){if(this.args.column.validator){var t=this.args.column.validator(e);if(!t.valid)return t}return{valid:!0,msg:null}},e.prototype.validate=function(){return this.validateValue(this.getValue())},e}(l.DOMView);n.CellEditorView=c;var u=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o.__extends(t,e),t.initClass=function(){this.prototype.type=\"CellEditor\"},t}(a.Model);(n.CellEditor=u).initClass();var d=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o.__extends(e,t),Object.defineProperty(e.prototype,\"emptyValue\",{get:function(){return\"\"},enumerable:!0,configurable:!0}),e.prototype._createInput=function(){return i.input({type:\"text\"})},e.prototype.renderEditor=function(){this.inputEl.focus(),this.inputEl.select()},e.prototype.loadValue=function(e){t.prototype.loadValue.call(this,e),this.inputEl.defaultValue=this.defaultValue,this.inputEl.select()},e}(c);n.StringEditorView=d;var p=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o.__extends(t,e),t.initClass=function(){this.prototype.type=\"StringEditor\",this.prototype.default_view=d,this.define({completions:[r.Array,[]]})},t}(u);(n.StringEditor=p).initClass();var f=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o.__extends(t,e),t.prototype._createInput=function(){return i.textarea()},t}(c);n.TextEditorView=f;var h=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o.__extends(t,e),t.initClass=function(){this.prototype.type=\"TextEditor\",this.prototype.default_view=f},t}(u);(n.TextEditor=h).initClass();var g=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o.__extends(t,e),t.prototype._createInput=function(){return i.select()},t.prototype.renderEditor=function(){for(var e=0,t=this.model.options;e/g,\">\")},e}(r.Model),l=function(t){function e(e){return t.call(this,e)||this}return s.__extends(e,t),e.initClass=function(){this.prototype.type=\"StringFormatter\",this.define({font_style:[o.FontStyle,\"normal\"],text_align:[o.TextAlign,\"left\"],text_color:[o.Color]})},e.prototype.doFormat=function(e,t,n,o,r){var i=this.font_style,l=this.text_align,a=this.text_color,s=d.div({},null==n?\"\":\"\"+n);switch(i){case\"bold\":s.style.fontWeight=\"bold\";break;case\"italic\":s.style.fontStyle=\"italic\"}return null!=l&&(s.style.textAlign=l),null!=a&&(s.style.color=a),s.outerHTML},e}(n.CellFormatter=i);(n.StringFormatter=l).initClass();var f=function(c){function e(e){return c.call(this,e)||this}return s.__extends(e,c),e.initClass=function(){this.prototype.type=\"NumberFormatter\",this.define({format:[o.String,\"0,0\"],language:[o.String,\"en\"],rounding:[o.String,\"round\"]})},e.prototype.doFormat=function(e,t,n,o,r){var i=this,l=this.format,a=this.language,s=function(){switch(i.rounding){case\"round\":case\"nearest\":return Math.round;case\"floor\":case\"rounddown\":return Math.floor;case\"ceil\":case\"roundup\":return Math.ceil}}();return n=u.format(n,l,a,s),c.prototype.doFormat.call(this,e,t,n,o,r)},e}(l);(n.NumberFormatter=f).initClass();var h=function(t){function e(e){return t.call(this,e)||this}return s.__extends(e,t),e.initClass=function(){this.prototype.type=\"BooleanFormatter\",this.define({icon:[o.String,\"check\"]})},e.prototype.doFormat=function(e,t,n,o,r){return n?d.i({class:this.icon}).outerHTML:\"\"},e}(i);(n.BooleanFormatter=h).initClass();var g=function(l){function e(e){return l.call(this,e)||this}return s.__extends(e,l),e.initClass=function(){this.prototype.type=\"DateFormatter\",this.define({format:[o.String,\"ISO-8601\"]})},e.prototype.getFormat=function(){switch(this.format){case\"ATOM\":case\"W3C\":case\"RFC-3339\":case\"ISO-8601\":return\"%Y-%m-%d\";case\"COOKIE\":return\"%a, %d %b %Y\";case\"RFC-850\":return\"%A, %d-%b-%y\";case\"RFC-1123\":case\"RFC-2822\":return\"%a, %e %b %Y\";case\"RSS\":case\"RFC-822\":case\"RFC-1036\":return\"%a, %e %b %y\";case\"TIMESTAMP\":return;default:return this.format}},e.prototype.doFormat=function(e,t,n,o,r){n=p.isString(n)?parseInt(n,10):n;var i=a(n,this.getFormat());return l.prototype.doFormat.call(this,e,t,i,o,r)},e}(i);(n.DateFormatter=g).initClass();var m=function(t){function e(e){return t.call(this,e)||this}return s.__extends(e,t),e.initClass=function(){this.prototype.type=\"HTMLTemplateFormatter\",this.define({template:[o.String,\"<%= value %>\"]})},e.prototype.doFormat=function(e,t,n,o,r){var i=this.template;if(null==n)return\"\";var l=c(i),a=s.__assign({},r,{value:n});return l(a)},e}(i);(n.HTMLTemplateFormatter=m).initClass()},436:function(e,t,i){var o=e(391),s=e(449).Grid,c=e(447).RowSelectionModel,u=e(446).CheckboxSelectColumn,d=e(445).CellExternalCopyManager,r=e(15),n=e(38),p=e(44),l=e(21),a=e(32),f=e(14),h=e(440),g=e(441);i.DTINDEX_NAME=\"__bkdt_internal_index__\";var m=function(){function e(e,t){if(this.source=e,this.view=t,i.DTINDEX_NAME in this.source.data)throw new Error(\"special name \"+i.DTINDEX_NAME+\" cannot be used as a data table column\");this.index=this.view.indices}return e.prototype.getLength=function(){return this.index.length},e.prototype.getItem=function(e){for(var t={},n=0,o=a.keys(this.source.data);n+~]|\"+F+\")\"+F+\"*\"),q=new RegExp(\"=\"+F+\"*([^\\\\]'\\\"]*?)\"+F+\"*\\\\]\",\"g\"),z=new RegExp(W),X=new RegExp(\"^\"+_+\"$\"),K={ID:new RegExp(\"^#(\"+_+\")\"),CLASS:new RegExp(\"^\\\\.(\"+_+\")\"),TAG:new RegExp(\"^(\"+_+\"|[*])\"),ATTR:new RegExp(\"^\"+M),PSEUDO:new RegExp(\"^\"+W),CHILD:new RegExp(\"^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\\\(\"+F+\"*(even|odd|(([+-]|)(\\\\d*)n|)\"+F+\"*(?:([+-]|)\"+F+\"*(\\\\d+)|))\"+F+\"*\\\\)|)\",\"i\"),bool:new RegExp(\"^(?:\"+L+\")$\",\"i\"),needsContext:new RegExp(\"^\"+F+\"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\\\(\"+F+\"*((?:-\\\\d)?\\\\d*)\"+F+\"*\\\\)|)(?=[^-]|$)\",\"i\")},U=/^(?:input|select|textarea|button)$/i,G=/^h\\d$/i,Y=/^[^{]+\\{\\s*\\[native \\w/,Q=/^(?:#([\\w-]+)|(\\w+)|\\.([\\w-]+))$/,J=/[+~]/,Z=new RegExp(\"\\\\\\\\([\\\\da-f]{1,6}\"+F+\"?|(\"+F+\")|.)\",\"ig\"),ee=function(e,t,n){var o=\"0x\"+t-65536;return o!=o||n?t:o<0?String.fromCharCode(o+65536):String.fromCharCode(o>>10|55296,1023&o|56320)},te=/([\\0-\\x1f\\x7f]|^-?\\d)|^-$|[^\\0-\\x1f\\x7f-\\uFFFF\\w-]/g,ne=function(e,t){return t?\"\\0\"===e?\"�\":e.slice(0,-1)+\"\\\\\"+e.charCodeAt(e.length-1).toString(16)+\" \":\"\\\\\"+e},oe=function(){x()},re=we(function(e){return!0===e.disabled&&(\"form\"in e||\"label\"in e)},{dir:\"parentNode\",next:\"legend\"});try{H.apply(t=$.call(w.childNodes),w.childNodes),t[w.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){N.apply(e,$.call(t))}:function(e,t){for(var n=e.length,o=0;e[n++]=t[o++];);e.length=n-1}}}function ie(e,t,n,o){var r,i,l,a,s,c,u,d=t&&t.ownerDocument,p=t?t.nodeType:9;if(n=n||[],\"string\"!=typeof e||!e||1!==p&&9!==p&&11!==p)return n;if(!o&&((t?t.ownerDocument||t:w)!==R&&x(t),t=t||R,S)){if(11!==p&&(s=Q.exec(e)))if(r=s[1]){if(9===p){if(!(l=t.getElementById(r)))return n;if(l.id===r)return n.push(l),n}else if(d&&(l=d.getElementById(r))&&v(t,l)&&l.id===r)return n.push(l),n}else{if(s[2])return H.apply(n,t.getElementsByTagName(e)),n;if((r=s[3])&&f.getElementsByClassName&&t.getElementsByClassName)return H.apply(n,t.getElementsByClassName(r)),n}if(f.qsa&&!T[e+\" \"]&&(!m||!m.test(e))){if(1!==p)d=t,u=e;else if(\"object\"!==t.nodeName.toLowerCase()){for((a=t.getAttribute(\"id\"))?a=a.replace(te,ne):t.setAttribute(\"id\",a=E),c=h(e),i=c.length;i--;)c[i]=\"#\"+a+\" \"+ve(c[i]);u=c.join(\",\"),d=J.test(e)&&ge(t.parentNode)||t}if(u)try{return H.apply(n,d.querySelectorAll(u)),n}catch(e){}finally{a===E&&t.removeAttribute(\"id\")}}}return g(e.replace(j,\"$1\"),t,n,o)}function le(){var o=[];return function e(t,n){o.push(t+\" \")>y.cacheLength&&delete e[o.shift()];return e[t+\" \"]=n}}function ae(e){return e[E]=!0,e}function se(e){var t=R.createElement(\"fieldset\");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ce(e,t){for(var n=e.split(\"|\"),o=n.length;o--;)y.attrHandle[n[o]]=t}function ue(e,t){var n=t&&e,o=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(o)return o;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function de(n){return function(e){var t=e.nodeName.toLowerCase();return\"input\"===t&&e.type===n}}function pe(n){return function(e){var t=e.nodeName.toLowerCase();return(\"input\"===t||\"button\"===t)&&e.type===n}}function fe(t){return function(e){return\"form\"in e?e.parentNode&&!1===e.disabled?\"label\"in e?\"label\"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&re(e)===t:e.disabled===t:\"label\"in e&&e.disabled===t}}function he(l){return ae(function(i){return i=+i,ae(function(e,t){for(var n,o=l([],e.length,i),r=o.length;r--;)e[n=o[r]]&&(e[n]=!(t[n]=e[n]))})})}function ge(e){return e&&void 0!==e.getElementsByTagName&&e}for(e in f=ie.support={},r=ie.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&\"HTML\"!==t.nodeName},x=ie.setDocument=function(e){var t,n,o=e?e.ownerDocument||e:w;return o!==R&&9===o.nodeType&&o.documentElement&&(l=(R=o).documentElement,S=!r(R),w!==R&&(n=R.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener(\"unload\",oe,!1):n.attachEvent&&n.attachEvent(\"onunload\",oe)),f.attributes=se(function(e){return e.className=\"i\",!e.getAttribute(\"className\")}),f.getElementsByTagName=se(function(e){return e.appendChild(R.createComment(\"\")),!e.getElementsByTagName(\"*\").length}),f.getElementsByClassName=Y.test(R.getElementsByClassName),f.getById=se(function(e){return l.appendChild(e).id=E,!R.getElementsByName||!R.getElementsByName(E).length}),f.getById?(y.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute(\"id\")===t}},y.find.ID=function(e,t){if(void 0!==t.getElementById&&S){var n=t.getElementById(e);return n?[n]:[]}}):(y.filter.ID=function(e){var n=e.replace(Z,ee);return function(e){var t=void 0!==e.getAttributeNode&&e.getAttributeNode(\"id\");return t&&t.value===n}},y.find.ID=function(e,t){if(void 0!==t.getElementById&&S){var n,o,r,i=t.getElementById(e);if(i){if((n=i.getAttributeNode(\"id\"))&&n.value===e)return[i];for(r=t.getElementsByName(e),o=0;i=r[o++];)if((n=i.getAttributeNode(\"id\"))&&n.value===e)return[i]}return[]}}),y.find.TAG=f.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):f.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,o=[],r=0,i=t.getElementsByTagName(e);if(\"*\"===e){for(;n=i[r++];)1===n.nodeType&&o.push(n);return o}return i},y.find.CLASS=f.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&S)return t.getElementsByClassName(e)},a=[],m=[],(f.qsa=Y.test(R.querySelectorAll))&&(se(function(e){l.appendChild(e).innerHTML=\"\",e.querySelectorAll(\"[msallowcapture^='']\").length&&m.push(\"[*^$]=\"+F+\"*(?:''|\\\"\\\")\"),e.querySelectorAll(\"[selected]\").length||m.push(\"\\\\[\"+F+\"*(?:value|\"+L+\")\"),e.querySelectorAll(\"[id~=\"+E+\"-]\").length||m.push(\"~=\"),e.querySelectorAll(\":checked\").length||m.push(\":checked\"),e.querySelectorAll(\"a#\"+E+\"+*\").length||m.push(\".#.+[+~]\")}),se(function(e){e.innerHTML=\"\";var t=R.createElement(\"input\");t.setAttribute(\"type\",\"hidden\"),e.appendChild(t).setAttribute(\"name\",\"D\"),e.querySelectorAll(\"[name=d]\").length&&m.push(\"name\"+F+\"*[*^$|!~]?=\"),2!==e.querySelectorAll(\":enabled\").length&&m.push(\":enabled\",\":disabled\"),l.appendChild(e).disabled=!0,2!==e.querySelectorAll(\":disabled\").length&&m.push(\":enabled\",\":disabled\"),e.querySelectorAll(\"*,:x\"),m.push(\",.*:\")})),(f.matchesSelector=Y.test(u=l.matches||l.webkitMatchesSelector||l.mozMatchesSelector||l.oMatchesSelector||l.msMatchesSelector))&&se(function(e){f.disconnectedMatch=u.call(e,\"*\"),u.call(e,\"[s!='']:x\"),a.push(\"!=\",W)}),m=m.length&&new RegExp(m.join(\"|\")),a=a.length&&new RegExp(a.join(\"|\")),t=Y.test(l.compareDocumentPosition),v=t||Y.test(l.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,o=t&&t.parentNode;return e===o||!(!o||1!==o.nodeType||!(n.contains?n.contains(o):e.compareDocumentPosition&&16&e.compareDocumentPosition(o)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},P=t?function(e,t){if(e===t)return c=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!f.sortDetached&&t.compareDocumentPosition(e)===n?e===R||e.ownerDocument===w&&v(w,e)?-1:t===R||t.ownerDocument===w&&v(w,t)?1:s?I(s,e)-I(s,t):0:4&n?-1:1)}:function(e,t){if(e===t)return c=!0,0;var n,o=0,r=e.parentNode,i=t.parentNode,l=[e],a=[t];if(!r||!i)return e===R?-1:t===R?1:r?-1:i?1:s?I(s,e)-I(s,t):0;if(r===i)return ue(e,t);for(n=e;n=n.parentNode;)l.unshift(n);for(n=t;n=n.parentNode;)a.unshift(n);for(;l[o]===a[o];)o++;return o?ue(l[o],a[o]):l[o]===w?-1:a[o]===w?1:0}),R},ie.matches=function(e,t){return ie(e,null,null,t)},ie.matchesSelector=function(e,t){if((e.ownerDocument||e)!==R&&x(e),t=t.replace(q,\"='$1']\"),f.matchesSelector&&S&&!T[t+\" \"]&&(!a||!a.test(t))&&(!m||!m.test(t)))try{var n=u.call(e,t);if(n||f.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){}return 0\":{dir:\"parentNode\",first:!0},\" \":{dir:\"parentNode\"},\"+\":{dir:\"previousSibling\",first:!0},\"~\":{dir:\"previousSibling\"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||\"\").replace(Z,ee),\"~=\"===e[2]&&(e[3]=\" \"+e[3]+\" \"),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),\"nth\"===e[1].slice(0,3)?(e[3]||ie.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*(\"even\"===e[3]||\"odd\"===e[3])),e[5]=+(e[7]+e[8]||\"odd\"===e[3])):e[3]&&ie.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||\"\":n&&z.test(n)&&(t=h(n,!0))&&(t=n.indexOf(\")\",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return\"*\"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+\" \"];return t||(t=new RegExp(\"(^|\"+F+\")\"+e+\"(\"+F+\"|$)\"))&&p(e,function(e){return t.test(\"string\"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute(\"class\")||\"\")})},ATTR:function(n,o,r){return function(e){var t=ie.attr(e,n);return null==t?\"!=\"===o:!o||(t+=\"\",\"=\"===o?t===r:\"!=\"===o?t!==r:\"^=\"===o?r&&0===t.indexOf(r):\"*=\"===o?r&&-1\",\"#\"===e.firstChild.getAttribute(\"href\")})||ce(\"type|href|height|width\",function(e,t,n){if(!n)return e.getAttribute(t,\"type\"===t.toLowerCase()?1:2)}),f.attributes&&se(function(e){return e.innerHTML=\"\",e.firstChild.setAttribute(\"value\",\"\"),\"\"===e.firstChild.getAttribute(\"value\")})||ce(\"value\",function(e,t,n){if(!n&&\"input\"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute(\"disabled\")})||ce(L,function(e,t,n){var o;if(!n)return!0===e[t]?t.toLowerCase():(o=e.getAttributeNode(t))&&o.specified?o.value:null}),ie}(R);E.find=C,E.expr=C.selectors,E.expr[\":\"]=E.expr.pseudos,E.uniqueSort=E.unique=C.uniqueSort,E.text=C.getText,E.isXMLDoc=C.isXML,E.contains=C.contains,E.escapeSelector=C.escape;var y=function(e,t,n){for(var o=[],r=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(r&&E(e).is(n))break;o.push(e)}return o},b=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},x=E.expr.match.needsContext;function k(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var T=/^<([a-z][^\\/\\0>:\\x20\\t\\r\\n\\f]*)[\\x20\\t\\r\\n\\f]*\\/?>(?:<\\/\\1>|)$/i,P=/^.[^:#\\[\\.,]*$/;function D(e,n,o){return E.isFunction(n)?E.grep(e,function(e,t){return!!n.call(e,t,e)!==o}):n.nodeType?E.grep(e,function(e){return e===n!==o}):\"string\"!=typeof n?E.grep(e,function(e){return-1)[^>]*|#([\\w-]+))$/,H=E.fn.init=function(e,t,n){var o,r;if(!e)return this;if(n=n||A,\"string\"==typeof e){if(!(o=\"<\"===e[0]&&\">\"===e[e.length-1]&&3<=e.length?[null,e,null]:N.exec(e))||!o[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(o[1]){if(t=t instanceof E?t[0]:t,E.merge(this,E.parseHTML(o[1],t&&t.nodeType?t.ownerDocument||t:S,!0)),T.test(o[1])&&E.isPlainObject(t))for(o in t)E.isFunction(this[o])?this[o](t[o]):this.attr(o,t[o]);return this}return(r=S.getElementById(o[2]))&&(this[0]=r,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):E.isFunction(e)?void 0!==n.ready?n.ready(e):e(E):E.makeArray(e,this)};H.prototype=E.fn,A=E(S);var $=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};function L(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}E.fn.extend({has:function(e){var t=E(e,this),n=t.length;return this.filter(function(){for(var e=0;e\\x20\\t\\r\\n\\f]+)/i,se=/^$|\\/(?:java|ecma)script/i,ce={option:[1,\"\"],thead:[1,\"\",\"
\"],col:[2,\"\",\"
\"],tr:[2,\"\",\"
\"],td:[3,\"\",\"
\"],_default:[0,\"\",\"\"]};function ue(e,t){var n;return n=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||\"*\"):void 0!==e.querySelectorAll?e.querySelectorAll(t||\"*\"):[],void 0===t||t&&k(e,t)?E.merge([e],n):n}function de(e,t){for(var n=0,o=e.length;nx\",m.noCloneChecked=!!fe.cloneNode(!0).lastChild.defaultValue;var ve=S.documentElement,we=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ye=/^([^.]*)(?:\\.(.+)|)/;function be(){return!0}function xe(){return!1}function Re(){try{return S.activeElement}catch(e){}}function Se(e,t,n,o,r,i){var l,a;if(\"object\"==typeof t){for(a in\"string\"!=typeof n&&(o=o||n,n=void 0),t)Se(e,a,n,o,t[a],i);return e}if(null==o&&null==r?(r=n,o=n=void 0):null==r&&(\"string\"==typeof n?(r=o,o=void 0):(r=o,o=n,n=void 0)),!1===r)r=xe;else if(!r)return e;return 1===i&&(l=r,(r=function(e){return E().off(e),l.apply(this,arguments)}).guid=l.guid||(l.guid=E.guid++)),e.each(function(){E.event.add(this,t,r,o,n)})}E.event={global:{},add:function(t,e,n,o,r){var i,l,a,s,c,u,d,p,f,h,g,m=X.get(t);if(m)for(n.handler&&(n=(i=n).handler,r=i.selector),r&&E.find.matchesSelector(ve,r),n.guid||(n.guid=E.guid++),(s=m.events)||(s=m.events={}),(l=m.handle)||(l=m.handle=function(e){return void 0!==E&&E.event.triggered!==e.type?E.event.dispatch.apply(t,arguments):void 0}),e=(e||\"\").match(F)||[\"\"],c=e.length;c--;)a=ye.exec(e[c])||[],f=g=a[1],h=(a[2]||\"\").split(\".\").sort(),f&&(d=E.event.special[f]||{},f=(r?d.delegateType:d.bindType)||f,d=E.event.special[f]||{},u=E.extend({type:f,origType:g,data:o,handler:n,guid:n.guid,selector:r,needsContext:r&&E.expr.match.needsContext.test(r),namespace:h.join(\".\")},i),(p=s[f])||((p=s[f]=[]).delegateCount=0,d.setup&&!1!==d.setup.call(t,o,h,l)||t.addEventListener&&t.addEventListener(f,l)),d.add&&(d.add.call(t,u),u.handler.guid||(u.handler.guid=n.guid)),r?p.splice(p.delegateCount++,0,u):p.push(u),E.event.global[f]=!0)},remove:function(e,t,n,o,r){var i,l,a,s,c,u,d,p,f,h,g,m=X.hasData(e)&&X.get(e);if(m&&(s=m.events)){for(t=(t||\"\").match(F)||[\"\"],c=t.length;c--;)if(a=ye.exec(t[c])||[],f=g=a[1],h=(a[2]||\"\").split(\".\").sort(),f){for(d=E.event.special[f]||{},f=(o?d.delegateType:d.bindType)||f,p=s[f]||[],a=a[2]&&new RegExp(\"(^|\\\\.)\"+h.join(\"\\\\.(?:.*\\\\.|)\")+\"(\\\\.|$)\"),l=i=p.length;i--;)u=p[i],!r&&g!==u.origType||n&&n.guid!==u.guid||a&&!a.test(u.namespace)||o&&o!==u.selector&&(\"**\"!==o||!u.selector)||(p.splice(i,1),u.selector&&p.delegateCount--,d.remove&&d.remove.call(e,u));l&&!p.length&&(d.teardown&&!1!==d.teardown.call(e,h,m.handle)||E.removeEvent(e,f,m.handle),delete s[f])}else for(f in s)E.event.remove(e,f+t[c],n,o,!0);E.isEmptyObject(s)&&X.remove(e,\"handle events\")}},dispatch:function(e){var t,n,o,r,i,l,a=E.event.fix(e),s=new Array(arguments.length),c=(X.get(this,\"events\")||{})[a.type]||[],u=E.event.special[a.type]||{};for(s[0]=a,t=1;t\\x20\\t\\r\\n\\f]*)[^>]*)\\/>/gi,ke=/\\s*$/g;function Ae(e,t){return k(e,\"table\")&&k(11!==t.nodeType?t:t.firstChild,\"tr\")&&E(\">tbody\",e)[0]||e}function Ne(e){return e.type=(null!==e.getAttribute(\"type\"))+\"/\"+e.type,e}function He(e){var t=Pe.exec(e.type);return t?e.type=t[1]:e.removeAttribute(\"type\"),e}function $e(e,t){var n,o,r,i,l,a,s,c;if(1===t.nodeType){if(X.hasData(e)&&(i=X.access(e),l=X.set(t,i),c=i.events))for(r in delete l.handle,l.events={},c)for(n=0,o=c[r].length;n\")},clone:function(e,t,n){var o,r,i,l,a=e.cloneNode(!0),s=E.contains(e.ownerDocument,e);if(!(m.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||E.isXMLDoc(e)))for(l=ue(a),i=ue(e),o=0,r=i.length;o\").prop({charset:n.scriptCharset,src:n.url}).on(\"load error\",r=function(e){o.remove(),r=null,e&&t(\"error\"===e.type?404:200,e.type)}),S.head.appendChild(o[0])},abort:function(){r&&r()}}});var Ot,Bt=[],qt=/(=)\\?(?=&|$)|\\?\\?/;E.ajaxSetup({jsonp:\"callback\",jsonpCallback:function(){var e=Bt.pop()||E.expando+\"_\"+yt++;return this[e]=!0,e}}),E.ajaxPrefilter(\"json jsonp\",function(e,t,n){var o,r,i,l=!1!==e.jsonp&&(qt.test(e.url)?\"url\":\"string\"==typeof e.data&&0===(e.contentType||\"\").indexOf(\"application/x-www-form-urlencoded\")&&qt.test(e.data)&&\"data\");if(l||\"jsonp\"===e.dataTypes[0])return o=e.jsonpCallback=E.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,l?e[l]=e[l].replace(qt,\"$1\"+o):!1!==e.jsonp&&(e.url+=(bt.test(e.url)?\"&\":\"?\")+e.jsonp+\"=\"+o),e.converters[\"script json\"]=function(){return i||E.error(o+\" was not called\"),i[0]},e.dataTypes[0]=\"json\",r=R[o],R[o]=function(){i=arguments},n.always(function(){void 0===r?E(R).removeProp(o):R[o]=r,e[o]&&(e.jsonpCallback=t.jsonpCallback,Bt.push(o)),i&&E.isFunction(r)&&r(i[0]),i=r=void 0}),\"script\"}),m.createHTMLDocument=((Ot=S.implementation.createHTMLDocument(\"\").body).innerHTML=\"
\",2===Ot.childNodes.length),E.parseHTML=function(e,t,n){return\"string\"!=typeof e?[]:(\"boolean\"==typeof t&&(n=t,t=!1),t||(m.createHTMLDocument?(t=S.implementation.createHTMLDocument(\"\"),(o=t.createElement(\"base\")).href=S.location.href,t.head.appendChild(o)):t=S),r=T.exec(e),i=!n&&[],r?[t.createElement(r[1])]:(r=me([e],t,i),i&&i.length&&E(i).remove(),E.merge([],r.childNodes)));var o,r,i},E.fn.load=function(e,t,n){var o,r,i,l=this,a=e.indexOf(\" \");return-1\").append(E.parseHTML(e)).find(o):e)}).always(n&&function(e,t){l.each(function(){n.apply(this,i||[e.responseText,t,e])})}),this},E.each([\"ajaxStart\",\"ajaxStop\",\"ajaxComplete\",\"ajaxError\",\"ajaxSuccess\",\"ajaxSend\"],function(e,t){E.fn[t]=function(e){return this.on(t,e)}}),E.expr.pseudos.animated=function(t){return E.grep(E.timers,function(e){return t===e.elem}).length},E.offset={setOffset:function(e,t,n){var o,r,i,l,a,s,c=E.css(e,\"position\"),u=E(e),d={};\"static\"===c&&(e.style.position=\"relative\"),a=u.offset(),i=E.css(e,\"top\"),s=E.css(e,\"left\"),(\"absolute\"===c||\"fixed\"===c)&&-1<(i+s).indexOf(\"auto\")?(o=u.position(),l=o.top,r=o.left):(l=parseFloat(i)||0,r=parseFloat(s)||0),E.isFunction(t)&&(t=t.call(e,n,E.extend({},a))),null!=t.top&&(d.top=t.top-a.top+l),null!=t.left&&(d.left=t.left-a.left+r),\"using\"in t?t.using.call(e,d):u.css(d)}},E.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){E.offset.setOffset(this,t,e)});var e,n,o,r,i=this[0];return i?i.getClientRects().length?(o=i.getBoundingClientRect(),e=i.ownerDocument,n=e.documentElement,r=e.defaultView,{top:o.top+r.pageYOffset-n.clientTop,left:o.left+r.pageXOffset-n.clientLeft}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n=this[0],o={top:0,left:0};return\"fixed\"===E.css(n,\"position\")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),k(e[0],\"html\")||(o=e.offset()),o={top:o.top+E.css(e[0],\"borderTopWidth\",!0),left:o.left+E.css(e[0],\"borderLeftWidth\",!0)}),{top:t.top-o.top-E.css(n,\"marginTop\",!0),left:t.left-o.left-E.css(n,\"marginLeft\",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&\"static\"===E.css(e,\"position\");)e=e.offsetParent;return e||ve})}}),E.each({scrollLeft:\"pageXOffset\",scrollTop:\"pageYOffset\"},function(t,r){var i=\"pageYOffset\"===r;E.fn[t]=function(e){return B(this,function(e,t,n){var o;if(E.isWindow(e)?o=e:9===e.nodeType&&(o=e.defaultView),void 0===n)return o?o[r]:e[t];o?o.scrollTo(i?o.pageXOffset:n,i?n:o.pageYOffset):e[t]=n},t,e,arguments.length)}}),E.each([\"top\",\"left\"],function(e,n){E.cssHooks[n]=je(m.pixelPosition,function(e,t){if(t)return t=Ve(e,n),Me.test(t)?E(e).position()[n]+\"px\":t})}),E.each({Height:\"height\",Width:\"width\"},function(l,a){E.each({padding:\"inner\"+l,content:a,\"\":\"outer\"+l},function(o,i){E.fn[i]=function(e,t){var n=arguments.length&&(o||\"boolean\"!=typeof e),r=o||(!0===e||!0===t?\"margin\":\"border\");return B(this,function(e,t,n){var o;return E.isWindow(e)?0===i.indexOf(\"outer\")?e[\"inner\"+l]:e.document.documentElement[\"client\"+l]:9===e.nodeType?(o=e.documentElement,Math.max(e.body[\"scroll\"+l],o[\"scroll\"+l],e.body[\"offset\"+l],o[\"offset\"+l],o[\"client\"+l])):void 0===n?E.css(e,t,r):E.style(e,t,n,r)},a,n?e:void 0,n)}})}),E.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,o){return this.on(t,e,n,o)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,\"**\"):this.off(t,e||\"**\",n)}}),E.holdReady=function(e){e?E.readyWait++:E.ready(!0)},E.isArray=Array.isArray,E.parseJSON=JSON.parse,E.nodeName=k,\"function\"==typeof define&&define.amd&&define(\"jquery\",[],function(){return E});var zt=R.jQuery,Xt=R.$;return E.noConflict=function(e){return R.$===E&&(R.$=Xt),e&&R.jQuery===E&&(R.jQuery=zt),E},e||(R.jQuery=R.$=E),E})},443:function(e,t,n){\n /*!\n * jquery.event.drag - v 2.3.0\n * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com\n * Open Source MIT License - http://threedubmedia.com/code/license\n */\n var f=e(450);f.fn.drag=function(e,t,n){var o=\"string\"==typeof e?e:\"\",r=f.isFunction(e)?e:f.isFunction(t)?t:null;return 0!==o.indexOf(\"drag\")&&(o=\"drag\"+o),n=(e==r?t:n)||{},r?this.on(o,n,r):this.trigger(o)};var h=f.event,o=h.special,g=o.drag={defaults:{which:1,distance:0,not:\":input\",handle:null,relative:!1,drop:!0,click:!1},datakey:\"dragdata\",noBubble:!0,add:function(e){var n=f.data(this,g.datakey),o=e.data||{};n.related+=1,f.each(g.defaults,function(e,t){void 0!==o[e]&&(n[e]=o[e])})},remove:function(){f.data(this,g.datakey).related-=1},setup:function(){if(!f.data(this,g.datakey)){var e=f.extend({related:0},g.defaults);f.data(this,g.datakey,e),h.add(this,\"touchstart mousedown\",g.init,e),this.attachEvent&&this.attachEvent(\"ondragstart\",g.dontstart)}},teardown:function(){var e=f.data(this,g.datakey)||{};e.related||(f.removeData(this,g.datakey),h.remove(this,\"touchstart mousedown\",g.init),g.textselect(!0),this.detachEvent&&this.detachEvent(\"ondragstart\",g.dontstart))},init:function(e){if(!g.touched){var t,n=e.data;if(!(0!=e.which&&0=e.left&&(t[0]||t.right)<=e.right&&(t[1]||t.top)>=e.top&&(t[1]||t.bottom)<=e.bottom},modes:{intersect:function(e,t,n){return this.contains(n,[e.pageX,e.pageY])?1e9:this.modes.overlap.apply(this,arguments)},overlap:function(e,t,n){return Math.max(0,Math.min(n.bottom,t.bottom)-Math.max(n.top,t.top))*Math.max(0,Math.min(n.right,t.right)-Math.max(n.left,t.left))},fit:function(e,t,n){return this.contains(n,t)?1:0},middle:function(e,t,n){return this.contains(n,[t.left+.5*t.width,t.top+.5*t.height])?1:0}},sort:function(e,t){return t.winner-e.winner||e.index-t.index},tolerate:function(e){var t,n,o,r,i,l,a,s,c=0,u=e.interactions.length,d=[g.event.pageX,g.event.pageY],p=g.tolerance||g.modes[g.mode];do{if(s=e.interactions[c]){if(!s)return;s.drop=[],i=[],l=s.droppable.length,p&&(o=g.locate(s.proxy)),t=0;do{if(a=s.droppable[t]){if(r=f.data(a,g.datakey),!(n=r.location))continue;r.winner=p?p.call(g,g.event,o,n):g.contains(n,d)?1:0,i.push(r)}}while(++t\"),column:t,position:{top:0,left:0},grid:m,event:n},l=new t.editor(i);l.loadValue(e),r=l.serializeValue(),l.destroy()}else r=e[t.field];return r}function E(e,t,n){if(x.dataItemColumnValueSetter)return x.dataItemColumnValueSetter(e,t,n);if(t.editor){var o={container:c(\"body\"),column:t,position:{top:0,left:0},grid:m},r=new t.editor(o);r.loadValue(e),r.applyValue(e,n),r.destroy()}else e[t.field]=n}function k(e){var t=document.createElement(\"textarea\");return t.style.position=\"absolute\",t.style.left=\"-1000px\",t.style.top=document.body.scrollTop+\"px\",t.value=e,R.appendChild(t),t.select(),t}function n(e,t){var n;if(!m.getEditorLock().isActive()||m.getOptions().autoEdit){if(e.which==D.ESC&&v&&(e.preventDefault(),P(),b.onCopyCancelled.notify({ranges:v}),v=null),(e.which===D.C||e.which===D.INSERT)&&(e.ctrlKey||e.metaKey)&&!e.shiftKey&&(w&&w.call(),0!=(n=m.getSelectionModel().getSelectedRanges()).length)){T(v=n),b.onCopyCells.notify({ranges:n});for(var o=m.getColumns(),r=\"\",i=0;ia.getDataLength();if(x.newRowCreator&&w){var C=u+f-a.getDataLength();x.newRowCreator(C)}var y={isClipboardCommand:!0,clippedRange:l,oldValues:[],cellExternalCopyManager:b,_options:x,setDataItemValueForColumn:E,markCopySelection:T,oneCellToMultiple:p,activeRow:u,activeCell:d,destH:f,destW:h,maxDestY:a.getDataLength(),maxDestX:a.getColumns().length,h:0,w:0,execute:function(){for(var e=this.h=0;e\",d.toolTip):a.updateColumnHeader(d.columnId,\"\",d.toolTip)),!d.hideInFilterHeaderRow){var l=v(\"#header-filter-selector\"+s);l.prop(\"checked\",u)}}function i(e,t){32==e.which&&a.getColumns()[t.cell].id===d.columnId&&(a.getEditorLock().isActive()&&!a.getEditorLock().commitCurrentEdit()||p(t.row),e.preventDefault(),e.stopImmediatePropagation())}function l(e,t){if(a.getColumns()[t.cell].id===d.columnId&&v(e.target).is(\":checkbox\")){if(a.getEditorLock().isActive()&&!a.getEditorLock().commitCurrentEdit())return e.preventDefault(),void e.stopImmediatePropagation();p(t.row),e.stopPropagation(),e.stopImmediatePropagation()}}function p(t){c[t]?a.setSelectedRows(v.grep(a.getSelectedRows(),function(e){return e!=t})):a.setSelectedRows(a.getSelectedRows().concat(t)),a.setActiveCell(t,function(){if(null===h){h=0;for(var e=a.getColumns(),t=0;t\":\"\":null}v.extend(this,{init:function(e){a=e,n.subscribe(a.onSelectedRowsChanged,t).subscribe(a.onClick,l).subscribe(a.onKeyDown,i),d.hideInFilterHeaderRow||e.onHeaderRowCellRendered.subscribe(function(e,t){\"sel\"===t.column.field&&(v(t.node).empty(),v(\"\").appendTo(t.node).on(\"click\",function(e){f(e,t)}))});d.hideInColumnTitleRow||n.subscribe(a.onHeaderClick,f)},destroy:function(){n.unsubscribeAll()},deSelectRows:function(e){var t,n=e.length,o=[];for(t=0;t\",toolTip:d.toolTip,field:\"sel\",width:d.width,resizable:!1,sortable:!1,cssClass:d.cssClass,hideSelectAllCheckbox:d.hideSelectAllCheckbox,formatter:m}},getOptions:function(){return d},setOptions:function(e){if((d=v.extend(!0,{},d,e)).hideSelectAllCheckbox)o(),r();else if(d.hideInColumnTitleRow?o():(u?a.updateColumnHeader(d.columnId,\"\",d.toolTip):a.updateColumnHeader(d.columnId,\"\",d.toolTip),n.subscribe(a.onHeaderClick,f)),d.hideInFilterHeaderRow)r();else{var t=v(\"#filter-checkbox-selectall-container\");t.show(),t.find('input[type=\"checkbox\"]').prop(\"checked\",u)}}})}}},447:function(e,t,n){var v=e(450),w=e(448);t.exports={RowSelectionModel:function(t){var c,n,o,u=[],r=this,i=new w.EventHandler,l={selectActiveRow:!0};function a(e){return function(){n||(n=!0,e.apply(this,arguments),n=!1)}}function d(e){for(var t=[],n=0;n=this.fromRow&&e<=this.toRow&&t>=this.fromCell&&t<=this.toCell},this.toString=function(){return this.isSingleCell()?\"(\"+this.fromRow+\":\"+this.fromCell+\")\":\"(\"+this.fromRow+\":\"+this.fromCell+\" - \"+this.toRow+\":\"+this.toCell+\")\"}},NonDataRow:o,Group:r,GroupTotals:i,EditorLock:a,GlobalEditorLock:new a,keyCode:{BACKSPACE:8,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,ESC:27,HOME:36,INSERT:45,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,RIGHT:39,TAB:9,UP:38,C:67,V:86},preClickClassName:\"slick-edit-preclick\"}},449:function _(require,module,exports){\n /**\n * @license\n * (c) 2009-2016 Michael Leibman\n * michael{dot}leibman{at}gmail{dot}com\n * http://github.com/mleibman/slickgrid\n *\n * Distributed under MIT license.\n * All rights reserved.\n *\n * SlickGrid v2.3\n *\n * NOTES:\n * Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.\n * This increases the speed dramatically, but can only be done safely because there are no event handlers\n * or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy()\n * and do proper cleanup.\n */\n var $=require(450),Slick=require(448),scrollbarDimensions,maxSupportedCssHeight;function SlickGrid(container,data,columns,options){$.fn.drag||require(443),$.fn.drop||require(444);var defaults={alwaysShowVerticalScroll:!1,explicitInitialization:!1,rowHeight:25,defaultColumnWidth:80,enableAddRow:!1,leaveSpaceForNewRows:!1,editable:!1,autoEdit:!0,suppressActiveCellChangeOnEdit:!1,enableCellNavigation:!0,enableColumnReorder:!0,asyncEditorLoading:!1,asyncEditorLoadDelay:100,forceFitColumns:!1,enableAsyncPostRender:!1,asyncPostRenderDelay:50,enableAsyncPostRenderCleanup:!1,asyncPostRenderCleanupDelay:40,autoHeight:!1,editorLock:Slick.GlobalEditorLock,showHeaderRow:!1,headerRowHeight:25,createFooterRow:!1,showFooterRow:!1,footerRowHeight:25,createPreHeaderPanel:!1,showPreHeaderPanel:!1,preHeaderPanelHeight:25,showTopPanel:!1,topPanelHeight:25,formatterFactory:null,editorFactory:null,cellFlashingCssClass:\"flashing\",selectedCellCssClass:\"selected\",multiSelect:!0,enableTextSelectionOnCells:!1,dataItemColumnValueExtractor:null,fullWidthRows:!1,multiColumnSort:!1,numberedMultiColumnSort:!1,tristateMultiColumnSort:!1,sortColNumberInSeparateSpan:!1,defaultFormatter:defaultFormatter,forceSyncScrolling:!1,addNewRowCssClass:\"new-row\",preserveCopiedSelectionOnPaste:!1,showCellSelection:!0,viewportClass:null,minRowBuffer:3,emulatePagingWhenScrolling:!0,editorCellNavOnLRKeys:!1},columnDefaults={name:\"\",resizable:!0,sortable:!1,minWidth:30,rerenderOnResize:!1,headerCssClass:null,defaultSortAsc:!0,focusable:!0,selectable:!0},th,h,ph,n,cj,page=0,offset=0,vScrollDir=1,initialized=!1,$container,uid=\"slickgrid_\"+Math.round(1e6*Math.random()),self=this,$focusSink,$focusSink2,$headerScroller,$headers,$headerRow,$headerRowScroller,$headerRowSpacer,$footerRow,$footerRowScroller,$footerRowSpacer,$preHeaderPanel,$preHeaderPanelScroller,$preHeaderPanelSpacer,$topPanelScroller,$topPanel,$viewport,$canvas,$style,$boundAncestors,stylesheet,columnCssRulesL,columnCssRulesR,viewportH,viewportW,canvasWidth,viewportHasHScroll,viewportHasVScroll,headerColumnWidthDiff=0,headerColumnHeightDiff=0,cellWidthDiff=0,cellHeightDiff=0,jQueryNewWidthBehaviour=!1,absoluteColumnMinWidth,tabbingDirection=1,activePosX,activeRow,activeCell,activeCellNode=null,currentEditor=null,serializedEditorValue,editController,rowsCache={},renderedRows=0,numVisibleRows,prevScrollTop=0,scrollTop=0,lastRenderedScrollTop=0,lastRenderedScrollLeft=0,prevScrollLeft=0,scrollLeft=0,selectionModel,selectedRows=[],plugins=[],cellCssClasses={},columnsById={},sortColumns=[],columnPosLeft=[],columnPosRight=[],pagingActive=!1,pagingIsLastPage=!1,scrollThrottle=ActionThrottle(render,50),h_editorLoader=null,h_render=null,h_postrender=null,h_postrenderCleanup=null,postProcessedRows={},postProcessToRow=null,postProcessFromRow=null,postProcessedCleanupQueue=[],postProcessgroupId=0,counter_rows_rendered=0,counter_rows_removed=0,rowNodeFromLastMouseWheelEvent,zombieRowNodeFromLastMouseWheelEvent,zombieRowCacheFromLastMouseWheelEvent,zombieRowPostProcessedFromLastMouseWheelEvent,cssShow={position:\"absolute\",visibility:\"hidden\",display:\"block\"},$hiddenParents,oldProps=[],columnResizeDragging=!1;function init(){if(($container=container instanceof $?container:$(container)).length<1)throw new Error(\"SlickGrid requires a valid container, \"+container+\" does not exist in the DOM.\");cacheCssForHiddenInit(),maxSupportedCssHeight=maxSupportedCssHeight||getMaxSupportedCssHeight(),options=$.extend({},defaults,options),validateAndEnforceOptions(),columnDefaults.width=options.defaultColumnWidth,columnsById={};for(var e=0;et.maxWidth&&(t.width=t.maxWidth)}if(options.enableColumnReorder&&!$.fn.sortable)throw new Error(\"SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded\");editController={commitCurrentEdit:commitCurrentEdit,cancelCurrentEdit:cancelCurrentEdit},$container.empty().css(\"overflow\",\"hidden\").css(\"outline\",0).addClass(uid).addClass(\"ui-widget\"),/relative|absolute|fixed/.test($container.css(\"position\"))||$container.css(\"position\",\"relative\"),$focusSink=$(\"
\").appendTo($container),options.createPreHeaderPanel&&($preHeaderPanelScroller=$(\"
\").appendTo($container),$preHeaderPanel=$(\"
\").appendTo($preHeaderPanelScroller),$preHeaderPanelSpacer=$(\"
\").appendTo($preHeaderPanelScroller),options.showPreHeaderPanel||$preHeaderPanelScroller.hide()),$headerScroller=$(\"
\").appendTo($container),$headers=$(\"
\").appendTo($headerScroller),$headerRowScroller=$(\"
\").appendTo($container),$headerRow=$(\"
\").appendTo($headerRowScroller),$headerRowSpacer=$(\"
\").appendTo($headerRowScroller),$topPanelScroller=$(\"
\").appendTo($container),$topPanel=$(\"
\").appendTo($topPanelScroller),options.showTopPanel||$topPanelScroller.hide(),options.showHeaderRow||$headerRowScroller.hide(),($viewport=$(\"
\").appendTo($container)).css(\"overflow-y\",options.alwaysShowVerticalScroll?\"scroll\":options.autoHeight?\"hidden\":\"auto\"),$viewport.css(\"overflow-x\",options.forceFitColumns?\"hidden\":\"auto\"),options.viewportClass&&$viewport.toggleClass(options.viewportClass,!0),$canvas=$(\"
\").appendTo($viewport),scrollbarDimensions=scrollbarDimensions||measureScrollbar(),$preHeaderPanelSpacer&&$preHeaderPanelSpacer.css(\"width\",getCanvasWidth()+scrollbarDimensions.width+\"px\"),$headers.width(getHeadersWidth()),$headerRowSpacer.css(\"width\",getCanvasWidth()+scrollbarDimensions.width+\"px\"),options.createFooterRow&&($footerRowScroller=$(\"
\").appendTo($container),$footerRow=$(\"
\").appendTo($footerRowScroller),$footerRowSpacer=$(\"
\").css(\"width\",getCanvasWidth()+scrollbarDimensions.width+\"px\").appendTo($footerRowScroller),options.showFooterRow||$footerRowScroller.hide()),$focusSink2=$focusSink.clone().appendTo($container),options.explicitInitialization||finishInitialization()}function finishInitialization(){initialized||(initialized=!0,viewportW=parseFloat($.css($container[0],\"width\",!0)),measureCellPaddingAndBorder(),disableSelection($headers),options.enableTextSelectionOnCells||$viewport.on(\"selectstart.ui\",function(e){return $(e.target).is(\"input,textarea\")}),updateColumnCaches(),createColumnHeaders(),setupColumnSort(),createCssRules(),resizeCanvas(),bindAncestorScrollEvents(),$container.on(\"resize.slickgrid\",resizeCanvas),$viewport.on(\"scroll\",handleScroll),$headerScroller.on(\"contextmenu\",handleHeaderContextMenu).on(\"click\",handleHeaderClick).on(\"mouseenter\",\".slick-header-column\",handleHeaderMouseEnter).on(\"mouseleave\",\".slick-header-column\",handleHeaderMouseLeave),$headerRowScroller.on(\"scroll\",handleHeaderRowScroll),options.createFooterRow&&$footerRowScroller.on(\"scroll\",handleFooterRowScroll),options.createPreHeaderPanel&&$preHeaderPanelScroller.on(\"scroll\",handlePreHeaderPanelScroll),$focusSink.add($focusSink2).on(\"keydown\",handleKeyDown),$canvas.on(\"keydown\",handleKeyDown).on(\"click\",handleClick).on(\"dblclick\",handleDblClick).on(\"contextmenu\",handleContextMenu).on(\"draginit\",handleDragInit).on(\"dragstart\",{distance:3},handleDragStart).on(\"drag\",handleDrag).on(\"dragend\",handleDragEnd).on(\"mouseenter\",\".slick-cell\",handleMouseEnter).on(\"mouseleave\",\".slick-cell\",handleMouseLeave),navigator.userAgent.toLowerCase().match(/webkit/)&&navigator.userAgent.toLowerCase().match(/macintosh/)&&$canvas.on(\"mousewheel\",handleMouseWheel),restoreCssFromHiddenInit())}function cacheCssForHiddenInit(){($hiddenParents=$container.parents().addBack().not(\":visible\")).each(function(){var e={};for(var t in cssShow)e[t]=this.style[t],this.style[t]=cssShow[t];oldProps.push(e)})}function restoreCssFromHiddenInit(){$hiddenParents.each(function(e){var t=oldProps[e];for(var n in cssShow)this.style[n]=t[n]})}function registerPlugin(e){plugins.unshift(e),e.init(self)}function unregisterPlugin(e){for(var t=plugins.length;0<=t;t--)if(plugins[t]===e){plugins[t].destroy&&plugins[t].destroy(),plugins.splice(t,1);break}}function setSelectionModel(e){selectionModel&&(selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged),selectionModel.destroy&&selectionModel.destroy()),(selectionModel=e)&&(selectionModel.init(self),selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged))}function getSelectionModel(){return selectionModel}function getCanvasNode(){return $canvas[0]}function measureScrollbar(){var e=$('
').appendTo($viewport),t=$('
').appendTo(e),n={width:e[0].offsetWidth-e[0].clientWidth,height:e[0].offsetHeight-e[0].clientHeight};return t.remove(),e.remove(),n}function getColumnTotalWidth(e){for(var t=0,n=0,o=columns.length;nviewportW-scrollbarDimensions.width);var n=canvasWidth+(viewportHasVScroll?scrollbarDimensions.width:0);$headerRowSpacer.width(n),options.createFooterRow&&$footerRowSpacer.width(n),options.createPreHeaderPanel&&$preHeaderPanelSpacer.width(n),(canvasWidth!=t||e)&&applyColumnWidths()}function disableSelection(e){e&&e.jquery&&e.attr(\"unselectable\",\"on\").css(\"MozUserSelect\",\"none\").on(\"selectstart.ui\",function(){return!1})}function getMaxSupportedCssHeight(){for(var e=1e6,t=navigator.userAgent.toLowerCase().match(/firefox/)?6e6:1e9,n=$(\"
\").appendTo(document.body);;){var o=2*e;if(n.css(\"height\",o),t\").html(\"\"+o.name+\"\").width(o.width-headerColumnWidthDiff).attr(\"id\",\"\"+uid+o.id).attr(\"title\",o.toolTip||\"\").data(\"column\",o).addClass(o.headerCssClass||\"\").appendTo($headers);if((options.enableColumnReorder||o.sortable)&&r.on(\"mouseenter\",e).on(\"mouseleave\",t),o.sortable&&(r.addClass(\"slick-header-sortable\"),r.append(\"\"),options.numberedMultiColumnSort&&options.sortColNumberInSeparateSpan&&r.append(\"\")),trigger(self.onHeaderCellRendered,{node:r[0],column:o,grid:self}),options.showHeaderRow){var i=$(\"
\").data(\"column\",o).appendTo($headerRow);trigger(self.onHeaderRowCellRendered,{node:i[0],column:o,grid:self})}if(options.createFooterRow&&options.showFooterRow){var l=$(\"
\").data(\"column\",o).appendTo($footerRow);trigger(self.onFooterRowCellRendered,{node:l[0],column:o})}}setSortColumns(sortColumns),setupColumnResize(),options.enableColumnReorder&&(\"function\"==typeof options.enableColumnReorder?options.enableColumnReorder(self,$headers,headerColumnWidthDiff,setColumns,setupColumnResize,columns,getColumnIndex,uid,trigger):setupColumnReorder())}function setupColumnSort(){$headers.click(function(e){if(!columnResizeDragging&&(e.metaKey=e.metaKey||e.ctrlKey,!$(e.target).hasClass(\"slick-resizable-handle\"))){var t=$(e.target).closest(\".slick-header-column\");if(t.length){var n=t.data(\"column\");if(n.sortable){if(!getEditorLock().commitCurrentEdit())return;for(var o=null,r=0;r=columns.length||columns[e].resizable&&(void 0===n&&(n=e),o=e)}),void 0!==n&&u.each(function(l,e){l>=columns.length||l\").appendTo(e).on(\"dragstart\",function(e,t){if(!getEditorLock().commitCurrentEdit())return!1;c=e.pageX,$(this).parent().addClass(\"slick-header-column-active\");var n=null,o=null;if(u.each(function(e,t){e>=columns.length||(columns[e].previousWidth=$(t).outerWidth())}),options.forceFitColumns)for(o=n=0,a=l+1;a
\").appendTo($headers),headerColumnWidthDiff=headerColumnHeightDiff=0,\"border-box\"!=n.css(\"box-sizing\")&&\"border-box\"!=n.css(\"-moz-box-sizing\")&&\"border-box\"!=n.css(\"-webkit-box-sizing\")&&($.each(e,function(e,t){headerColumnWidthDiff+=parseFloat(n.css(t))||0}),$.each(t,function(e,t){headerColumnHeightDiff+=parseFloat(n.css(t))||0})),n.remove();var r=$(\"
\").appendTo($canvas);n=$(\"\").appendTo(r),cellWidthDiff=cellHeightDiff=0,\"border-box\"!=n.css(\"box-sizing\")&&\"border-box\"!=n.css(\"-moz-box-sizing\")&&\"border-box\"!=n.css(\"-webkit-box-sizing\")&&($.each(e,function(e,t){cellWidthDiff+=parseFloat(n.css(t))||0}),$.each(t,function(e,t){cellHeightDiff+=parseFloat(n.css(t))||0})),r.remove(),absoluteColumnMinWidth=Math.max(headerColumnWidthDiff,cellWidthDiff)}function createCssRules(){$style=$(\"\n\n"},"metadata":{}},{"output_type":"display_data","data":{"application/javascript":"function HoloViewsWidget() {\n}\n\nHoloViewsWidget.prototype.init_slider = function(init_val){\n if(this.load_json) {\n this.from_json()\n } else {\n this.update_cache();\n }\n}\n\nHoloViewsWidget.prototype.populate_cache = function(idx){\n this.cache[idx].innerHTML = this.frames[idx];\n if (this.embed) {\n delete this.frames[idx];\n }\n}\n\nHoloViewsWidget.prototype.process_error = function(msg){\n}\n\nHoloViewsWidget.prototype.from_json = function() {\n var data_url = this.json_path + this.id + '.json';\n $.getJSON(data_url, $.proxy(function(json_data) {\n this.frames = json_data;\n this.update_cache();\n this.update(0);\n }, this));\n}\n\nHoloViewsWidget.prototype.dynamic_update = function(current){\n if (current === undefined) {\n return\n }\n this.current = current;\n if (this.comm) {\n var msg = {comm_id: this.id+'_client', content: current}\n this.comm.send(msg);\n }\n}\n\nHoloViewsWidget.prototype.update_cache = function(force){\n var frame_len = Object.keys(this.frames).length;\n for (var i=0; i 0) {\n that.time = Date.now();\n that.dynamic_update(that.queue[that.queue.length-1]);\n that.queue = [];\n } else {\n that.wait = false;\n }\n if ((msg.msg_type == \"Ready\") && msg.content) {\n console.log(\"Python callback returned following output:\", msg.content);\n } else if (msg.msg_type == \"Error\") {\n console.log(\"Python failed with the following traceback:\", msg.traceback)\n }\n }\n var comm = HoloViews.comm_manager.get_client_comm(this.plot_id, this.id+'_client', ack_callback);\n return comm\n }\n}\n\nHoloViewsWidget.prototype.msg_handler = function(msg) {\n var metadata = msg.metadata;\n if ((metadata.msg_type == \"Ready\")) {\n if (metadata.content) {\n console.log(\"Python callback returned following output:\", metadata.content);\n }\n\treturn;\n } else if (metadata.msg_type == \"Error\") {\n console.log(\"Python failed with the following traceback:\", metadata.traceback)\n return\n }\n this.process_msg(msg)\n}\n\nHoloViewsWidget.prototype.process_msg = function(msg) {\n}\n\nfunction SelectionWidget(frames, id, slider_ids, keyMap, dim_vals, notFound, load_json, mode, cached, json_path, dynamic, plot_id){\n this.frames = frames;\n this.id = id;\n this.plot_id = plot_id;\n this.slider_ids = slider_ids;\n this.keyMap = keyMap\n this.current_frame = 0;\n this.current_vals = dim_vals;\n this.load_json = load_json;\n this.mode = mode;\n this.notFound = notFound;\n this.cached = cached;\n this.dynamic = dynamic;\n this.cache = {};\n this.json_path = json_path;\n this.init_slider(this.current_vals[0]);\n this.queue = [];\n this.wait = false;\n if (!this.cached || this.dynamic) {\n this.comm = this.init_comms();\n }\n}\n\nSelectionWidget.prototype = new HoloViewsWidget;\n\n\nSelectionWidget.prototype.get_key = function(current_vals) {\n var key = \"(\";\n for (var i=0; i Date.now()))) {\n this.queue.push(key);\n return\n }\n this.queue = [];\n this.time = Date.now();\n this.current_frame = key;\n this.wait = true;\n this.dynamic_update(key)\n } else if (key !== undefined) {\n this.update(key)\n }\n}\n\n\n/* Define the ScrubberWidget class */\nfunction ScrubberWidget(frames, num_frames, id, interval, load_json, mode, cached, json_path, dynamic, plot_id){\n this.slider_id = \"_anim_slider\" + id;\n this.loop_select_id = \"_anim_loop_select\" + id;\n this.id = id;\n this.plot_id = plot_id;\n this.interval = interval;\n this.current_frame = 0;\n this.direction = 0;\n this.dynamic = dynamic;\n this.timer = null;\n this.load_json = load_json;\n this.mode = mode;\n this.cached = cached;\n this.frames = frames;\n this.cache = {};\n this.length = num_frames;\n this.json_path = json_path;\n document.getElementById(this.slider_id).max = this.length - 1;\n this.init_slider(0);\n this.wait = false;\n this.queue = [];\n if (!this.cached || this.dynamic) {\n this.comm = this.init_comms()\n }\n}\n\nScrubberWidget.prototype = new HoloViewsWidget;\n\nScrubberWidget.prototype.set_frame = function(frame){\n this.current_frame = frame;\n var widget = document.getElementById(this.slider_id);\n if (widget === null) {\n this.pause_animation();\n return\n }\n widget.value = this.current_frame;\n if (this.dynamic || !this.cached) {\n if ((this.time !== undefined) && ((this.wait) && ((this.time + 10000) > Date.now()))) {\n this.queue.push(frame);\n return\n }\n this.queue = [];\n this.time = Date.now();\n this.wait = true;\n this.dynamic_update(frame)\n } else {\n this.update(frame)\n }\n}\n\nScrubberWidget.prototype.get_loop_state = function(){\n var button_group = document[this.loop_select_id].state;\n for (var i = 0; i < button_group.length; i++) {\n var button = button_group[i];\n if (button.checked) {\n return button.value;\n }\n }\n return undefined;\n}\n\n\nScrubberWidget.prototype.next_frame = function() {\n this.set_frame(Math.min(this.length - 1, this.current_frame + 1));\n}\n\nScrubberWidget.prototype.previous_frame = function() {\n this.set_frame(Math.max(0, this.current_frame - 1));\n}\n\nScrubberWidget.prototype.first_frame = function() {\n this.set_frame(0);\n}\n\nScrubberWidget.prototype.last_frame = function() {\n this.set_frame(this.length - 1);\n}\n\nScrubberWidget.prototype.slower = function() {\n this.interval /= 0.7;\n if(this.direction > 0){this.play_animation();}\n else if(this.direction < 0){this.reverse_animation();}\n}\n\nScrubberWidget.prototype.faster = function() {\n this.interval *= 0.7;\n if(this.direction > 0){this.play_animation();}\n else if(this.direction < 0){this.reverse_animation();}\n}\n\nScrubberWidget.prototype.anim_step_forward = function() {\n if(this.current_frame < this.length - 1){\n this.next_frame();\n }else{\n var loop_state = this.get_loop_state();\n if(loop_state == \"loop\"){\n this.first_frame();\n }else if(loop_state == \"reflect\"){\n this.last_frame();\n this.reverse_animation();\n }else{\n this.pause_animation();\n this.last_frame();\n }\n }\n}\n\nScrubberWidget.prototype.anim_step_reverse = function() {\n if(this.current_frame > 0){\n this.previous_frame();\n } else {\n var loop_state = this.get_loop_state();\n if(loop_state == \"loop\"){\n this.last_frame();\n }else if(loop_state == \"reflect\"){\n this.first_frame();\n this.play_animation();\n }else{\n this.pause_animation();\n this.first_frame();\n }\n }\n}\n\nScrubberWidget.prototype.pause_animation = function() {\n this.direction = 0;\n if (this.timer){\n clearInterval(this.timer);\n this.timer = null;\n }\n}\n\nScrubberWidget.prototype.play_animation = function() {\n this.pause_animation();\n this.direction = 1;\n var t = this;\n if (!this.timer) this.timer = setInterval(function(){t.anim_step_forward();}, this.interval);\n}\n\nScrubberWidget.prototype.reverse_animation = function() {\n this.pause_animation();\n this.direction = -1;\n var t = this;\n if (!this.timer) this.timer = setInterval(function(){t.anim_step_reverse();}, this.interval);\n}\n\nfunction extend(destination, source) {\n for (var k in source) {\n if (source.hasOwnProperty(k)) {\n destination[k] = source[k];\n }\n }\n return destination;\n}\n\nfunction update_widget(widget, values) {\n if (widget.hasClass(\"ui-slider\")) {\n widget.slider('option', {\n min: 0,\n max: values.length-1,\n dim_vals: values,\n value: 0,\n dim_labels: values\n })\n widget.slider('option', 'slide').call(widget, event, {value: 0})\n } else {\n widget.empty();\n for (var i=0; i\", {\n value: i,\n text: values[i]\n }))\n };\n widget.data('values', values);\n widget.data('value', 0);\n widget.trigger(\"change\");\n };\n}\n\nfunction init_slider(id, plot_id, dim, values, next_vals, labels, dynamic, step, value, next_dim,\n dim_idx, delay, jQueryUI_CDN, UNDERSCORE_CDN) {\n // Slider JS Block START\n function loadcssfile(filename){\n var fileref=document.createElement(\"link\")\n fileref.setAttribute(\"rel\", \"stylesheet\")\n fileref.setAttribute(\"type\", \"text/css\")\n fileref.setAttribute(\"href\", filename)\n document.getElementsByTagName(\"head\")[0].appendChild(fileref)\n }\n loadcssfile(\"https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css\");\n /* Check if jQuery and jQueryUI have been loaded\n otherwise load with require.js */\n var jQuery = window.jQuery,\n // check for old versions of jQuery\n oldjQuery = jQuery && !!jQuery.fn.jquery.match(/^1\\.[0-4](\\.|$)/),\n jquery_path = '',\n paths = {},\n noConflict;\n var jQueryUI = jQuery.ui;\n // check for jQuery\n if (!jQuery || oldjQuery) {\n // load if it's not available or doesn't meet min standards\n paths.jQuery = jQuery;\n noConflict = !!oldjQuery;\n } else {\n // register the current jQuery\n define('jquery', [], function() { return jQuery; });\n }\n if (!jQueryUI) {\n paths.jQueryUI = jQueryUI_CDN.slice(null, -3);\n } else {\n define('jQueryUI', [], function() { return jQuery.ui; });\n }\n paths.underscore = UNDERSCORE_CDN.slice(null, -3);\n var jquery_require = {\n paths: paths,\n shim: {\n \"jQueryUI\": {\n exports:\"$\",\n deps: ['jquery']\n },\n \"underscore\": {\n exports: '_'\n }\n }\n }\n require.config(jquery_require);\n require([\"jQueryUI\", \"underscore\"], function(jUI, _){\n if (noConflict) $.noConflict(true);\n var vals = values;\n if (dynamic && vals.constructor === Array) {\n var default_value = parseFloat(value);\n var min = parseFloat(vals[0]);\n var max = parseFloat(vals[vals.length-1]);\n var wstep = step;\n var wlabels = [default_value];\n var init_label = default_value;\n } else {\n var min = 0;\n if (dynamic) {\n var max = Object.keys(vals).length - 1;\n var init_label = labels[value];\n var default_value = values[value];\n } else {\n var max = vals.length - 1;\n var init_label = labels[value];\n var default_value = value;\n }\n var wstep = 1;\n var wlabels = labels;\n }\n function adjustFontSize(text) {\n var width_ratio = (text.parent().width()/8)/text.val().length;\n var size = Math.min(0.9, Math.max(0.6, width_ratio))+'em';\n text.css('font-size', size);\n }\n var slider = $('#_anim_widget'+id+'_'+dim);\n slider.slider({\n animate: \"fast\",\n min: min,\n max: max,\n step: wstep,\n value: default_value,\n dim_vals: vals,\n dim_labels: wlabels,\n next_vals: next_vals,\n slide: function(event, ui) {\n var vals = slider.slider(\"option\", \"dim_vals\");\n var next_vals = slider.slider(\"option\", \"next_vals\");\n var dlabels = slider.slider(\"option\", \"dim_labels\");\n if (dynamic) {\n var dim_val = ui.value;\n if (vals.constructor === Array) {\n var label = ui.value;\n } else {\n var label = dlabels[ui.value];\n }\n } else {\n var dim_val = vals[ui.value];\n var label = dlabels[ui.value];\n }\n var text = $('#textInput'+id+'_'+dim);\n text.val(label);\n adjustFontSize(text);\n HoloViews.index[plot_id].set_frame(dim_val, dim_idx);\n if (Object.keys(next_vals).length > 0) {\n var new_vals = next_vals[dim_val];\n var next_widget = $('#_anim_widget'+id+'_'+next_dim);\n update_widget(next_widget, new_vals);\n }\n }\n });\n slider.keypress(function(event) {\n if (event.which == 80 || event.which == 112) {\n var start = slider.slider(\"option\", \"value\");\n var stop = slider.slider(\"option\", \"max\");\n for (var i=start; i<=stop; i++) {\n var delay = i*delay;\n $.proxy(function doSetTimeout(i) { setTimeout($.proxy(function() {\n var val = {value:i};\n slider.slider('value',i);\n slider.slider(\"option\", \"slide\")(null, val);\n }, slider), delay);}, slider)(i);\n }\n }\n if (event.which == 82 || event.which == 114) {\n var start = slider.slider(\"option\", \"value\");\n var stop = slider.slider(\"option\", \"min\");\n var count = 0;\n for (var i=start; i>=stop; i--) {\n var delay = count*delay;\n count = count + 1;\n $.proxy(function doSetTimeout(i) { setTimeout($.proxy(function() {\n var val = {value:i};\n slider.slider('value',i);\n slider.slider(\"option\", \"slide\")(null, val);\n }, slider), delay);}, slider)(i);\n }\n }\n });\n var textInput = $('#textInput'+id+'_'+dim)\n textInput.val(init_label);\n adjustFontSize(textInput);\n });\n}\n\nfunction init_dropdown(id, plot_id, dim, vals, value, next_vals, labels, next_dim, dim_idx, dynamic) {\n var widget = $(\"#_anim_widget\"+id+'_'+dim);\n widget.data('values', vals)\n for (var i=0; i\", {\n value: val,\n text: labels[i]\n }));\n };\n widget.data(\"next_vals\", next_vals);\n widget.val(value);\n widget.on('change', function(event, ui) {\n if (dynamic) {\n var dim_val = parseInt(this.value);\n } else {\n var dim_val = $.data(this, 'values')[this.value];\n }\n var next_vals = $.data(this, \"next_vals\");\n if (Object.keys(next_vals).length > 0) {\n var new_vals = next_vals[dim_val];\n var next_widget = $('#_anim_widget'+id+'_'+next_dim);\n update_widget(next_widget, new_vals);\n }\n var widgets = HoloViews.index[plot_id]\n if (widgets) {\n widgets.set_frame(dim_val, dim_idx);\n }\n });\n}\n\n\nif (window.HoloViews === undefined) {\n window.HoloViews = {}\n window.PyViz = window.HoloViews\n} else if (window.PyViz === undefined) {\n window.PyViz = window.HoloViews\n}\n\n\nvar _namespace = {\n init_slider: init_slider,\n init_dropdown: init_dropdown,\n comms: {},\n comm_status: {},\n index: {},\n plot_index: {},\n kernels: {},\n receivers: {}\n}\n\nfor (var k in _namespace) {\n if (!(k in window.HoloViews)) {\n window.HoloViews[k] = _namespace[k];\n }\n}\n\n// Define MPL specific subclasses\nfunction MPLSelectionWidget() {\n SelectionWidget.apply(this, arguments);\n}\n\nfunction MPLScrubberWidget() {\n ScrubberWidget.apply(this, arguments);\n}\n\n// Let them inherit from the baseclasses\nMPLSelectionWidget.prototype = Object.create(SelectionWidget.prototype);\nMPLScrubberWidget.prototype = Object.create(ScrubberWidget.prototype);\n\n// Define methods to override on widgets\nvar MPLMethods = {\n init_slider : function(init_val){\n if(this.load_json) {\n this.from_json()\n } else {\n this.update_cache();\n }\n if (this.dynamic | !this.cached | (this.current_vals === undefined)) {\n this.update(0)\n } else {\n this.set_frame(this.current_vals[0], 0)\n }\n },\n process_msg : function(msg) {\n var data = msg.content.data;\n this.frames[this.current] = data;\n this.update_cache(true);\n this.update(this.current);\n }\n}\n// Extend MPL widgets with backend specific methods\nextend(MPLSelectionWidget.prototype, MPLMethods);\nextend(MPLScrubberWidget.prototype, MPLMethods);\n\nwindow.HoloViews.MPLSelectionWidget = MPLSelectionWidget\nwindow.HoloViews.MPLScrubberWidget = MPLScrubberWidget\n\n// Define Bokeh specific subclasses\nfunction BokehSelectionWidget() {\n SelectionWidget.apply(this, arguments);\n}\n\nfunction BokehScrubberWidget() {\n ScrubberWidget.apply(this, arguments);\n}\n\n// Let them inherit from the baseclasses\nBokehSelectionWidget.prototype = Object.create(SelectionWidget.prototype);\nBokehScrubberWidget.prototype = Object.create(ScrubberWidget.prototype);\n\n// Define methods to override on widgets\nvar BokehMethods = {\n update_cache : function(){\n for (var index in this.frames) {\n this.frames[index] = JSON.parse(this.frames[index]);\n }\n },\n update : function(current){\n if (current === undefined) {\n return;\n }\n var data = this.frames[current];\n if (data !== undefined) {\n if (data.root in HoloViews.plot_index) {\n var doc = HoloViews.plot_index[data.root].model.document;\n } else {\n var doc = Bokeh.index[data.root].model.document;\n }\n doc.apply_json_patch(data.content);\n }\n },\n init_comms: function() {\n if (Bokeh.protocol !== undefined) {\n this.receiver = new Bokeh.protocol.Receiver()\n } else {\n this.receiver = null;\n }\n return HoloViewsWidget.prototype.init_comms.call(this);\n },\n process_msg : function(msg) {\n if (this.plot_id in HoloViews.plot_index) {\n var doc = HoloViews.plot_index[this.plot_id].model.document;\n } else {\n var doc = Bokeh.index[this.plot_id].model.document;\n }\n if (this.receiver === null) { return }\n var receiver = this.receiver;\n if (msg.buffers.length > 0) {\n receiver.consume(msg.buffers[0].buffer)\n } else {\n receiver.consume(msg.content.data)\n }\n const comm_msg = receiver.message;\n if ((comm_msg != null) && (doc != null)) {\n doc.apply_json_patch(comm_msg.content, comm_msg.buffers)\n }\n }\n}\n\n// Extend Bokeh widgets with backend specific methods\nextend(BokehSelectionWidget.prototype, BokehMethods);\nextend(BokehScrubberWidget.prototype, BokehMethods);\n\nwindow.HoloViews.BokehSelectionWidget = BokehSelectionWidget\nwindow.HoloViews.BokehScrubberWidget = BokehScrubberWidget\n\n function JupyterCommManager() {\n }\n\n JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {\n if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n comm_manager.register_target(comm_id, function(comm) {\n comm.on_msg(msg_handler);\n });\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {\n comm.onMsg = msg_handler;\n });\n }\n }\n\n JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {\n if (comm_id in window.PyViz.comms) {\n return window.PyViz.comms[comm_id];\n } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);\n if (msg_handler) {\n comm.on_msg(msg_handler);\n }\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);\n comm.open();\n if (msg_handler) {\n comm.onMsg = msg_handler;\n }\n }\n\n window.PyViz.comms[comm_id] = comm;\n return comm;\n }\n\n window.PyViz.comm_manager = new JupyterCommManager();\n \n\nvar JS_MIME_TYPE = 'application/javascript';\nvar HTML_MIME_TYPE = 'text/html';\nvar EXEC_MIME_TYPE = 'application/vnd.holoviews_exec.v0+json';\nvar CLASS_NAME = 'output';\n\n/**\n * Render data to the DOM node\n */\nfunction render(props, node) {\n var div = document.createElement(\"div\");\n var script = document.createElement(\"script\");\n node.appendChild(div);\n node.appendChild(script);\n}\n\n/**\n * Handle when a new output is added\n */\nfunction handle_add_output(event, handle) {\n var output_area = handle.output_area;\n var output = handle.output;\n if ((output.data == undefined) || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n return\n }\n var id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n if (id !== undefined) {\n var nchildren = toinsert.length;\n toinsert[nchildren-1].children[0].innerHTML = output.data[HTML_MIME_TYPE];\n toinsert[nchildren-1].children[1].textContent = output.data[JS_MIME_TYPE];\n output_area._hv_plot_id = id;\n if ((window.Bokeh !== undefined) && (id in Bokeh.index)) {\n window.PyViz.plot_index[id] = Bokeh.index[id];\n } else {\n window.PyViz.plot_index[id] = null;\n }\n }\n}\n\n/**\n * Handle when an output is cleared or removed\n */\nfunction handle_clear_output(event, handle) {\n var id = handle.cell.output_area._hv_plot_id;\n if ((id === undefined) || !(id in PyViz.plot_index)) { return; }\n var comm = window.PyViz.comm_manager.get_client_comm(\"hv-extension-comm\", \"hv-extension-comm\", function () {});\n if (comm !== null) {\n comm.send({event_type: 'delete', 'id': id});\n }\n delete PyViz.plot_index[id];\n if ((window.Bokeh !== undefined) & (id in window.Bokeh.index)) {\n var doc = window.Bokeh.index[id].model.document\n doc.clear();\n const i = window.Bokeh.documents.indexOf(doc);\n if (i > -1) {\n window.Bokeh.documents.splice(i, 1);\n }\n }\n}\n\n/**\n * Handle kernel restart event\n */\nfunction handle_kernel_cleanup(event, handle) {\n delete PyViz.comms[\"hv-extension-comm\"];\n window.PyViz.plot_index = {}\n}\n\n/**\n * Handle update_display_data messages\n */\nfunction handle_update_output(event, handle) {\n handle_clear_output(event, {cell: {output_area: handle.output_area}})\n handle_add_output(event, handle)\n}\n\nfunction register_renderer(events, OutputArea) {\n function append_mime(data, metadata, element) {\n // create a DOM node to render to\n var 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 var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n render(props, toinsert[0]);\n element.append(toinsert);\n return toinsert\n }\n\n events.on('output_added.OutputArea', handle_add_output);\n events.on('output_updated.OutputArea', handle_update_output);\n events.on('clear_output.CodeCell', handle_clear_output);\n events.on('delete.Cell', handle_clear_output);\n events.on('kernel_ready.Kernel', handle_kernel_cleanup);\n\n OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n safe: true,\n index: 0\n });\n}\n\nif (window.Jupyter !== undefined) {\n try {\n var events = require('base/js/events');\n var OutputArea = require('notebook/js/outputarea').OutputArea;\n if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n register_renderer(events, OutputArea);\n }\n } catch(err) {\n }\n}\n","application/vnd.holoviews_load.v0+json":"function HoloViewsWidget() {\n}\n\nHoloViewsWidget.prototype.init_slider = function(init_val){\n if(this.load_json) {\n this.from_json()\n } else {\n this.update_cache();\n }\n}\n\nHoloViewsWidget.prototype.populate_cache = function(idx){\n this.cache[idx].innerHTML = this.frames[idx];\n if (this.embed) {\n delete this.frames[idx];\n }\n}\n\nHoloViewsWidget.prototype.process_error = function(msg){\n}\n\nHoloViewsWidget.prototype.from_json = function() {\n var data_url = this.json_path + this.id + '.json';\n $.getJSON(data_url, $.proxy(function(json_data) {\n this.frames = json_data;\n this.update_cache();\n this.update(0);\n }, this));\n}\n\nHoloViewsWidget.prototype.dynamic_update = function(current){\n if (current === undefined) {\n return\n }\n this.current = current;\n if (this.comm) {\n var msg = {comm_id: this.id+'_client', content: current}\n this.comm.send(msg);\n }\n}\n\nHoloViewsWidget.prototype.update_cache = function(force){\n var frame_len = Object.keys(this.frames).length;\n for (var i=0; i 0) {\n that.time = Date.now();\n that.dynamic_update(that.queue[that.queue.length-1]);\n that.queue = [];\n } else {\n that.wait = false;\n }\n if ((msg.msg_type == \"Ready\") && msg.content) {\n console.log(\"Python callback returned following output:\", msg.content);\n } else if (msg.msg_type == \"Error\") {\n console.log(\"Python failed with the following traceback:\", msg.traceback)\n }\n }\n var comm = HoloViews.comm_manager.get_client_comm(this.plot_id, this.id+'_client', ack_callback);\n return comm\n }\n}\n\nHoloViewsWidget.prototype.msg_handler = function(msg) {\n var metadata = msg.metadata;\n if ((metadata.msg_type == \"Ready\")) {\n if (metadata.content) {\n console.log(\"Python callback returned following output:\", metadata.content);\n }\n\treturn;\n } else if (metadata.msg_type == \"Error\") {\n console.log(\"Python failed with the following traceback:\", metadata.traceback)\n return\n }\n this.process_msg(msg)\n}\n\nHoloViewsWidget.prototype.process_msg = function(msg) {\n}\n\nfunction SelectionWidget(frames, id, slider_ids, keyMap, dim_vals, notFound, load_json, mode, cached, json_path, dynamic, plot_id){\n this.frames = frames;\n this.id = id;\n this.plot_id = plot_id;\n this.slider_ids = slider_ids;\n this.keyMap = keyMap\n this.current_frame = 0;\n this.current_vals = dim_vals;\n this.load_json = load_json;\n this.mode = mode;\n this.notFound = notFound;\n this.cached = cached;\n this.dynamic = dynamic;\n this.cache = {};\n this.json_path = json_path;\n this.init_slider(this.current_vals[0]);\n this.queue = [];\n this.wait = false;\n if (!this.cached || this.dynamic) {\n this.comm = this.init_comms();\n }\n}\n\nSelectionWidget.prototype = new HoloViewsWidget;\n\n\nSelectionWidget.prototype.get_key = function(current_vals) {\n var key = \"(\";\n for (var i=0; i Date.now()))) {\n this.queue.push(key);\n return\n }\n this.queue = [];\n this.time = Date.now();\n this.current_frame = key;\n this.wait = true;\n this.dynamic_update(key)\n } else if (key !== undefined) {\n this.update(key)\n }\n}\n\n\n/* Define the ScrubberWidget class */\nfunction ScrubberWidget(frames, num_frames, id, interval, load_json, mode, cached, json_path, dynamic, plot_id){\n this.slider_id = \"_anim_slider\" + id;\n this.loop_select_id = \"_anim_loop_select\" + id;\n this.id = id;\n this.plot_id = plot_id;\n this.interval = interval;\n this.current_frame = 0;\n this.direction = 0;\n this.dynamic = dynamic;\n this.timer = null;\n this.load_json = load_json;\n this.mode = mode;\n this.cached = cached;\n this.frames = frames;\n this.cache = {};\n this.length = num_frames;\n this.json_path = json_path;\n document.getElementById(this.slider_id).max = this.length - 1;\n this.init_slider(0);\n this.wait = false;\n this.queue = [];\n if (!this.cached || this.dynamic) {\n this.comm = this.init_comms()\n }\n}\n\nScrubberWidget.prototype = new HoloViewsWidget;\n\nScrubberWidget.prototype.set_frame = function(frame){\n this.current_frame = frame;\n var widget = document.getElementById(this.slider_id);\n if (widget === null) {\n this.pause_animation();\n return\n }\n widget.value = this.current_frame;\n if (this.dynamic || !this.cached) {\n if ((this.time !== undefined) && ((this.wait) && ((this.time + 10000) > Date.now()))) {\n this.queue.push(frame);\n return\n }\n this.queue = [];\n this.time = Date.now();\n this.wait = true;\n this.dynamic_update(frame)\n } else {\n this.update(frame)\n }\n}\n\nScrubberWidget.prototype.get_loop_state = function(){\n var button_group = document[this.loop_select_id].state;\n for (var i = 0; i < button_group.length; i++) {\n var button = button_group[i];\n if (button.checked) {\n return button.value;\n }\n }\n return undefined;\n}\n\n\nScrubberWidget.prototype.next_frame = function() {\n this.set_frame(Math.min(this.length - 1, this.current_frame + 1));\n}\n\nScrubberWidget.prototype.previous_frame = function() {\n this.set_frame(Math.max(0, this.current_frame - 1));\n}\n\nScrubberWidget.prototype.first_frame = function() {\n this.set_frame(0);\n}\n\nScrubberWidget.prototype.last_frame = function() {\n this.set_frame(this.length - 1);\n}\n\nScrubberWidget.prototype.slower = function() {\n this.interval /= 0.7;\n if(this.direction > 0){this.play_animation();}\n else if(this.direction < 0){this.reverse_animation();}\n}\n\nScrubberWidget.prototype.faster = function() {\n this.interval *= 0.7;\n if(this.direction > 0){this.play_animation();}\n else if(this.direction < 0){this.reverse_animation();}\n}\n\nScrubberWidget.prototype.anim_step_forward = function() {\n if(this.current_frame < this.length - 1){\n this.next_frame();\n }else{\n var loop_state = this.get_loop_state();\n if(loop_state == \"loop\"){\n this.first_frame();\n }else if(loop_state == \"reflect\"){\n this.last_frame();\n this.reverse_animation();\n }else{\n this.pause_animation();\n this.last_frame();\n }\n }\n}\n\nScrubberWidget.prototype.anim_step_reverse = function() {\n if(this.current_frame > 0){\n this.previous_frame();\n } else {\n var loop_state = this.get_loop_state();\n if(loop_state == \"loop\"){\n this.last_frame();\n }else if(loop_state == \"reflect\"){\n this.first_frame();\n this.play_animation();\n }else{\n this.pause_animation();\n this.first_frame();\n }\n }\n}\n\nScrubberWidget.prototype.pause_animation = function() {\n this.direction = 0;\n if (this.timer){\n clearInterval(this.timer);\n this.timer = null;\n }\n}\n\nScrubberWidget.prototype.play_animation = function() {\n this.pause_animation();\n this.direction = 1;\n var t = this;\n if (!this.timer) this.timer = setInterval(function(){t.anim_step_forward();}, this.interval);\n}\n\nScrubberWidget.prototype.reverse_animation = function() {\n this.pause_animation();\n this.direction = -1;\n var t = this;\n if (!this.timer) this.timer = setInterval(function(){t.anim_step_reverse();}, this.interval);\n}\n\nfunction extend(destination, source) {\n for (var k in source) {\n if (source.hasOwnProperty(k)) {\n destination[k] = source[k];\n }\n }\n return destination;\n}\n\nfunction update_widget(widget, values) {\n if (widget.hasClass(\"ui-slider\")) {\n widget.slider('option', {\n min: 0,\n max: values.length-1,\n dim_vals: values,\n value: 0,\n dim_labels: values\n })\n widget.slider('option', 'slide').call(widget, event, {value: 0})\n } else {\n widget.empty();\n for (var i=0; i\", {\n value: i,\n text: values[i]\n }))\n };\n widget.data('values', values);\n widget.data('value', 0);\n widget.trigger(\"change\");\n };\n}\n\nfunction init_slider(id, plot_id, dim, values, next_vals, labels, dynamic, step, value, next_dim,\n dim_idx, delay, jQueryUI_CDN, UNDERSCORE_CDN) {\n // Slider JS Block START\n function loadcssfile(filename){\n var fileref=document.createElement(\"link\")\n fileref.setAttribute(\"rel\", \"stylesheet\")\n fileref.setAttribute(\"type\", \"text/css\")\n fileref.setAttribute(\"href\", filename)\n document.getElementsByTagName(\"head\")[0].appendChild(fileref)\n }\n loadcssfile(\"https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css\");\n /* Check if jQuery and jQueryUI have been loaded\n otherwise load with require.js */\n var jQuery = window.jQuery,\n // check for old versions of jQuery\n oldjQuery = jQuery && !!jQuery.fn.jquery.match(/^1\\.[0-4](\\.|$)/),\n jquery_path = '',\n paths = {},\n noConflict;\n var jQueryUI = jQuery.ui;\n // check for jQuery\n if (!jQuery || oldjQuery) {\n // load if it's not available or doesn't meet min standards\n paths.jQuery = jQuery;\n noConflict = !!oldjQuery;\n } else {\n // register the current jQuery\n define('jquery', [], function() { return jQuery; });\n }\n if (!jQueryUI) {\n paths.jQueryUI = jQueryUI_CDN.slice(null, -3);\n } else {\n define('jQueryUI', [], function() { return jQuery.ui; });\n }\n paths.underscore = UNDERSCORE_CDN.slice(null, -3);\n var jquery_require = {\n paths: paths,\n shim: {\n \"jQueryUI\": {\n exports:\"$\",\n deps: ['jquery']\n },\n \"underscore\": {\n exports: '_'\n }\n }\n }\n require.config(jquery_require);\n require([\"jQueryUI\", \"underscore\"], function(jUI, _){\n if (noConflict) $.noConflict(true);\n var vals = values;\n if (dynamic && vals.constructor === Array) {\n var default_value = parseFloat(value);\n var min = parseFloat(vals[0]);\n var max = parseFloat(vals[vals.length-1]);\n var wstep = step;\n var wlabels = [default_value];\n var init_label = default_value;\n } else {\n var min = 0;\n if (dynamic) {\n var max = Object.keys(vals).length - 1;\n var init_label = labels[value];\n var default_value = values[value];\n } else {\n var max = vals.length - 1;\n var init_label = labels[value];\n var default_value = value;\n }\n var wstep = 1;\n var wlabels = labels;\n }\n function adjustFontSize(text) {\n var width_ratio = (text.parent().width()/8)/text.val().length;\n var size = Math.min(0.9, Math.max(0.6, width_ratio))+'em';\n text.css('font-size', size);\n }\n var slider = $('#_anim_widget'+id+'_'+dim);\n slider.slider({\n animate: \"fast\",\n min: min,\n max: max,\n step: wstep,\n value: default_value,\n dim_vals: vals,\n dim_labels: wlabels,\n next_vals: next_vals,\n slide: function(event, ui) {\n var vals = slider.slider(\"option\", \"dim_vals\");\n var next_vals = slider.slider(\"option\", \"next_vals\");\n var dlabels = slider.slider(\"option\", \"dim_labels\");\n if (dynamic) {\n var dim_val = ui.value;\n if (vals.constructor === Array) {\n var label = ui.value;\n } else {\n var label = dlabels[ui.value];\n }\n } else {\n var dim_val = vals[ui.value];\n var label = dlabels[ui.value];\n }\n var text = $('#textInput'+id+'_'+dim);\n text.val(label);\n adjustFontSize(text);\n HoloViews.index[plot_id].set_frame(dim_val, dim_idx);\n if (Object.keys(next_vals).length > 0) {\n var new_vals = next_vals[dim_val];\n var next_widget = $('#_anim_widget'+id+'_'+next_dim);\n update_widget(next_widget, new_vals);\n }\n }\n });\n slider.keypress(function(event) {\n if (event.which == 80 || event.which == 112) {\n var start = slider.slider(\"option\", \"value\");\n var stop = slider.slider(\"option\", \"max\");\n for (var i=start; i<=stop; i++) {\n var delay = i*delay;\n $.proxy(function doSetTimeout(i) { setTimeout($.proxy(function() {\n var val = {value:i};\n slider.slider('value',i);\n slider.slider(\"option\", \"slide\")(null, val);\n }, slider), delay);}, slider)(i);\n }\n }\n if (event.which == 82 || event.which == 114) {\n var start = slider.slider(\"option\", \"value\");\n var stop = slider.slider(\"option\", \"min\");\n var count = 0;\n for (var i=start; i>=stop; i--) {\n var delay = count*delay;\n count = count + 1;\n $.proxy(function doSetTimeout(i) { setTimeout($.proxy(function() {\n var val = {value:i};\n slider.slider('value',i);\n slider.slider(\"option\", \"slide\")(null, val);\n }, slider), delay);}, slider)(i);\n }\n }\n });\n var textInput = $('#textInput'+id+'_'+dim)\n textInput.val(init_label);\n adjustFontSize(textInput);\n });\n}\n\nfunction init_dropdown(id, plot_id, dim, vals, value, next_vals, labels, next_dim, dim_idx, dynamic) {\n var widget = $(\"#_anim_widget\"+id+'_'+dim);\n widget.data('values', vals)\n for (var i=0; i\", {\n value: val,\n text: labels[i]\n }));\n };\n widget.data(\"next_vals\", next_vals);\n widget.val(value);\n widget.on('change', function(event, ui) {\n if (dynamic) {\n var dim_val = parseInt(this.value);\n } else {\n var dim_val = $.data(this, 'values')[this.value];\n }\n var next_vals = $.data(this, \"next_vals\");\n if (Object.keys(next_vals).length > 0) {\n var new_vals = next_vals[dim_val];\n var next_widget = $('#_anim_widget'+id+'_'+next_dim);\n update_widget(next_widget, new_vals);\n }\n var widgets = HoloViews.index[plot_id]\n if (widgets) {\n widgets.set_frame(dim_val, dim_idx);\n }\n });\n}\n\n\nif (window.HoloViews === undefined) {\n window.HoloViews = {}\n window.PyViz = window.HoloViews\n} else if (window.PyViz === undefined) {\n window.PyViz = window.HoloViews\n}\n\n\nvar _namespace = {\n init_slider: init_slider,\n init_dropdown: init_dropdown,\n comms: {},\n comm_status: {},\n index: {},\n plot_index: {},\n kernels: {},\n receivers: {}\n}\n\nfor (var k in _namespace) {\n if (!(k in window.HoloViews)) {\n window.HoloViews[k] = _namespace[k];\n }\n}\n\n// Define MPL specific subclasses\nfunction MPLSelectionWidget() {\n SelectionWidget.apply(this, arguments);\n}\n\nfunction MPLScrubberWidget() {\n ScrubberWidget.apply(this, arguments);\n}\n\n// Let them inherit from the baseclasses\nMPLSelectionWidget.prototype = Object.create(SelectionWidget.prototype);\nMPLScrubberWidget.prototype = Object.create(ScrubberWidget.prototype);\n\n// Define methods to override on widgets\nvar MPLMethods = {\n init_slider : function(init_val){\n if(this.load_json) {\n this.from_json()\n } else {\n this.update_cache();\n }\n if (this.dynamic | !this.cached | (this.current_vals === undefined)) {\n this.update(0)\n } else {\n this.set_frame(this.current_vals[0], 0)\n }\n },\n process_msg : function(msg) {\n var data = msg.content.data;\n this.frames[this.current] = data;\n this.update_cache(true);\n this.update(this.current);\n }\n}\n// Extend MPL widgets with backend specific methods\nextend(MPLSelectionWidget.prototype, MPLMethods);\nextend(MPLScrubberWidget.prototype, MPLMethods);\n\nwindow.HoloViews.MPLSelectionWidget = MPLSelectionWidget\nwindow.HoloViews.MPLScrubberWidget = MPLScrubberWidget\n\n// Define Bokeh specific subclasses\nfunction BokehSelectionWidget() {\n SelectionWidget.apply(this, arguments);\n}\n\nfunction BokehScrubberWidget() {\n ScrubberWidget.apply(this, arguments);\n}\n\n// Let them inherit from the baseclasses\nBokehSelectionWidget.prototype = Object.create(SelectionWidget.prototype);\nBokehScrubberWidget.prototype = Object.create(ScrubberWidget.prototype);\n\n// Define methods to override on widgets\nvar BokehMethods = {\n update_cache : function(){\n for (var index in this.frames) {\n this.frames[index] = JSON.parse(this.frames[index]);\n }\n },\n update : function(current){\n if (current === undefined) {\n return;\n }\n var data = this.frames[current];\n if (data !== undefined) {\n if (data.root in HoloViews.plot_index) {\n var doc = HoloViews.plot_index[data.root].model.document;\n } else {\n var doc = Bokeh.index[data.root].model.document;\n }\n doc.apply_json_patch(data.content);\n }\n },\n init_comms: function() {\n if (Bokeh.protocol !== undefined) {\n this.receiver = new Bokeh.protocol.Receiver()\n } else {\n this.receiver = null;\n }\n return HoloViewsWidget.prototype.init_comms.call(this);\n },\n process_msg : function(msg) {\n if (this.plot_id in HoloViews.plot_index) {\n var doc = HoloViews.plot_index[this.plot_id].model.document;\n } else {\n var doc = Bokeh.index[this.plot_id].model.document;\n }\n if (this.receiver === null) { return }\n var receiver = this.receiver;\n if (msg.buffers.length > 0) {\n receiver.consume(msg.buffers[0].buffer)\n } else {\n receiver.consume(msg.content.data)\n }\n const comm_msg = receiver.message;\n if ((comm_msg != null) && (doc != null)) {\n doc.apply_json_patch(comm_msg.content, comm_msg.buffers)\n }\n }\n}\n\n// Extend Bokeh widgets with backend specific methods\nextend(BokehSelectionWidget.prototype, BokehMethods);\nextend(BokehScrubberWidget.prototype, BokehMethods);\n\nwindow.HoloViews.BokehSelectionWidget = BokehSelectionWidget\nwindow.HoloViews.BokehScrubberWidget = BokehScrubberWidget\n\n function JupyterCommManager() {\n }\n\n JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {\n if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n comm_manager.register_target(comm_id, function(comm) {\n comm.on_msg(msg_handler);\n });\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {\n comm.onMsg = msg_handler;\n });\n }\n }\n\n JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {\n if (comm_id in window.PyViz.comms) {\n return window.PyViz.comms[comm_id];\n } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);\n if (msg_handler) {\n comm.on_msg(msg_handler);\n }\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);\n comm.open();\n if (msg_handler) {\n comm.onMsg = msg_handler;\n }\n }\n\n window.PyViz.comms[comm_id] = comm;\n return comm;\n }\n\n window.PyViz.comm_manager = new JupyterCommManager();\n \n\nvar JS_MIME_TYPE = 'application/javascript';\nvar HTML_MIME_TYPE = 'text/html';\nvar EXEC_MIME_TYPE = 'application/vnd.holoviews_exec.v0+json';\nvar CLASS_NAME = 'output';\n\n/**\n * Render data to the DOM node\n */\nfunction render(props, node) {\n var div = document.createElement(\"div\");\n var script = document.createElement(\"script\");\n node.appendChild(div);\n node.appendChild(script);\n}\n\n/**\n * Handle when a new output is added\n */\nfunction handle_add_output(event, handle) {\n var output_area = handle.output_area;\n var output = handle.output;\n if ((output.data == undefined) || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n return\n }\n var id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n if (id !== undefined) {\n var nchildren = toinsert.length;\n toinsert[nchildren-1].children[0].innerHTML = output.data[HTML_MIME_TYPE];\n toinsert[nchildren-1].children[1].textContent = output.data[JS_MIME_TYPE];\n output_area._hv_plot_id = id;\n if ((window.Bokeh !== undefined) && (id in Bokeh.index)) {\n window.PyViz.plot_index[id] = Bokeh.index[id];\n } else {\n window.PyViz.plot_index[id] = null;\n }\n }\n}\n\n/**\n * Handle when an output is cleared or removed\n */\nfunction handle_clear_output(event, handle) {\n var id = handle.cell.output_area._hv_plot_id;\n if ((id === undefined) || !(id in PyViz.plot_index)) { return; }\n var comm = window.PyViz.comm_manager.get_client_comm(\"hv-extension-comm\", \"hv-extension-comm\", function () {});\n if (comm !== null) {\n comm.send({event_type: 'delete', 'id': id});\n }\n delete PyViz.plot_index[id];\n if ((window.Bokeh !== undefined) & (id in window.Bokeh.index)) {\n var doc = window.Bokeh.index[id].model.document\n doc.clear();\n const i = window.Bokeh.documents.indexOf(doc);\n if (i > -1) {\n window.Bokeh.documents.splice(i, 1);\n }\n }\n}\n\n/**\n * Handle kernel restart event\n */\nfunction handle_kernel_cleanup(event, handle) {\n delete PyViz.comms[\"hv-extension-comm\"];\n window.PyViz.plot_index = {}\n}\n\n/**\n * Handle update_display_data messages\n */\nfunction handle_update_output(event, handle) {\n handle_clear_output(event, {cell: {output_area: handle.output_area}})\n handle_add_output(event, handle)\n}\n\nfunction register_renderer(events, OutputArea) {\n function append_mime(data, metadata, element) {\n // create a DOM node to render to\n var 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 var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n render(props, toinsert[0]);\n element.append(toinsert);\n return toinsert\n }\n\n events.on('output_added.OutputArea', handle_add_output);\n events.on('output_updated.OutputArea', handle_update_output);\n events.on('clear_output.CodeCell', handle_clear_output);\n events.on('delete.Cell', handle_clear_output);\n events.on('kernel_ready.Kernel', handle_kernel_cleanup);\n\n OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n safe: true,\n index: 0\n });\n}\n\nif (window.Jupyter !== undefined) {\n try {\n var events = require('base/js/events');\n var OutputArea = require('notebook/js/outputarea').OutputArea;\n if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n register_renderer(events, OutputArea);\n }\n } catch(err) {\n }\n}\n"},"metadata":{}}]},{"cell_type":"markdown","source":"# Credit risk case study\n*DISCLAIMER: This is not 100% my own code*\n\n## Table of content\n\n* [Dataset overview](#ds)\n* [Exploratory analysis](#explo)\n * [Descritive statistics for PAID loans](#descp)\n * [Descritive statistics for DEFAULT loans](#descd)\n * [DEFAULT as a function of reason for aquiring the loans](#reason)\n * [DEFAULT as a function of occupation](#occupation)\n * [Graphical overview](#graph)\n * [Violin plot](#violin)\n * [Correlation matrix](#corr)\n* [Test of default classifiers](#classification)\n* [Model evaluation](#eval)\n * [Precision & recall](#per)\n * [F1](#f1)\n * [Receiver operating characteristic](#roc)\n * [Confusion matrix](#confusion)\n * [Classification probability](#prob)\n* [Logistic regression](#logit)\n* [SGD classifier](#sgd)\n* [Supporting vector classifier](#svc)\n* [Gradient boosting classifier](#gbrt)\n* [Forest of randomized tree](#frt)\n * [Randm forest classifier](#rfc)\n * [Extremely randomized tree](#ert)\n* [Model comparison and conclusion](#conclusion)\n\n## Dataset overview\n\n\nThe dataset contains baseline and loan performance information for 5,960 recent home equity loans. A home equity loan is a loan where the obligor uses the equity of his or her home as the underlying collateral. The target (BAD) is a binary variable indicating whether an applicant eventually defaulted or was seriously delinquent. This adverse outcome occurred in 1,189 cases (20%). \n\nFor each applicant, 11 input variables were recorded:\n\n* BAD: 1 = applicant defaulted on loan or seriously delinquent; 0 = applicant paid loan\n* LOAN: Amount of the loan request\n* MORTDUE: Amount due on existing mortgage\n* VALUE: Value of current property\n* REASON: DebtCon = debt consolidation; HomeImp = home improvement\n* JOB: Occupational categories\n* YOJ: Years at present job\n* DEROG: Number of major derogatory reports\n* DELINQ: Number of delinquent credit lines\n* CLAGE: Age of oldest credit line in months\n* NINQ: Number of recent credit inquiries\n* CLNO: Number of credit lines","metadata":{"_uuid":"043e78ba82baf8748dcc07876d7b2f4a8a0678ee"}},{"cell_type":"code","source":"df=pd.read_csv('/kaggle/input/hmeq-data/hmeq.csv')\ndf.head()","metadata":{"_uuid":"99f7547021739168db64988549a9535a5bc06a72","execution":{"iopub.status.busy":"2023-02-14T00:30:25.487260Z","iopub.execute_input":"2023-02-14T00:30:25.487839Z","iopub.status.idle":"2023-02-14T00:30:25.536426Z","shell.execute_reply.started":"2023-02-14T00:30:25.487777Z","shell.execute_reply":"2023-02-14T00:30:25.535269Z"},"trusted":true},"execution_count":6,"outputs":[{"execution_count":6,"output_type":"execute_result","data":{"text/plain":" BAD LOAN MORTDUE VALUE ... CLAGE NINQ CLNO DEBTINC\n0 1 1100 25860.0 39025.0 ... 94.366667 1.0 9.0 NaN\n1 1 1300 70053.0 68400.0 ... 121.833333 0.0 14.0 NaN\n2 1 1500 13500.0 16700.0 ... 149.466667 1.0 10.0 NaN\n3 1 1500 NaN NaN ... NaN NaN NaN NaN\n4 0 1700 97800.0 112000.0 ... 93.333333 0.0 14.0 NaN\n\n[5 rows x 13 columns]","text/html":"
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
BADLOANMORTDUEVALUEREASONJOBYOJDEROGDELINQCLAGENINQCLNODEBTINC
01110025860.039025.0HomeImpOther10.50.00.094.3666671.09.0NaN
11130070053.068400.0HomeImpOther7.00.02.0121.8333330.014.0NaN
21150013500.016700.0HomeImpOther4.00.00.0149.4666671.010.0NaN
311500NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
40170097800.0112000.0HomeImpOffice3.00.00.093.3333330.014.0NaN
\n
"},"metadata":{}}]},{"cell_type":"markdown","source":"## Exploratory analysis\n\n\nI summarize the main characteristics of the dataset with visual methods and summary statistics. I use the target variable (BAD) to divide the data set into sub-samples and I specifically look for variables, features and correlation which contain classification power.\n\n### Descritive statistics for PAID loans\n","metadata":{"_uuid":"689f230ab38b172609ebbf62c0810b6403b2cb14"}},{"cell_type":"code","source":"df[df['BAD']==0].drop('BAD', axis=1).describe().style.format(\"{:.2f}\")","metadata":{"_uuid":"7714ab305dd9e853ab266438144d91dc857d38c1","execution":{"iopub.status.busy":"2023-02-14T00:30:26.341154Z","iopub.execute_input":"2023-02-14T00:30:26.341838Z","iopub.status.idle":"2023-02-14T00:30:26.433883Z","shell.execute_reply.started":"2023-02-14T00:30:26.341465Z","shell.execute_reply":"2023-02-14T00:30:26.432942Z"},"trusted":true},"execution_count":7,"outputs":[{"execution_count":7,"output_type":"execute_result","data":{"text/plain":"","text/html":" \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
LOANMORTDUEVALUEYOJDEROGDELINQCLAGENINQCLNODEBTINC
count4771.004359.004764.004321.004150.004263.004541.004336.004602.004290.00
mean19028.1174829.25102595.929.150.130.25187.001.0321.3233.25
std11115.7643584.9952748.397.680.510.6784.471.539.686.95
min1700.002619.008000.000.000.000.000.490.000.000.72
25%11700.0047484.0067297.753.000.000.00120.220.0015.0028.91
50%16900.0066839.0090659.007.000.000.00180.421.0020.0034.54
75%23500.0093068.00120615.5013.000.000.00240.162.0026.0038.74
max89900.00371003.00471827.0036.006.005.00649.7511.0056.0045.57
"},"metadata":{}}]},{"cell_type":"markdown","source":"### Descritive statistics for DEFAULT loans\n","metadata":{"_uuid":"bf50d833946ba558c3a5a85b9a02a7b08b60f068"}},{"cell_type":"code","source":"df[df['BAD']==1].drop('BAD', axis=1).describe().style.format(\"{:.2f}\")","metadata":{"_uuid":"7ae114f0450eb4ca523d9dfb4b548d37e07bd769","execution":{"iopub.status.busy":"2023-02-14T00:30:27.839251Z","iopub.execute_input":"2023-02-14T00:30:27.840011Z","iopub.status.idle":"2023-02-14T00:30:27.892289Z","shell.execute_reply.started":"2023-02-14T00:30:27.839547Z","shell.execute_reply":"2023-02-14T00:30:27.891359Z"},"trusted":true},"execution_count":8,"outputs":[{"execution_count":8,"output_type":"execute_result","data":{"text/plain":"","text/html":" \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
LOANMORTDUEVALUEYOJDEROGDELINQCLAGENINQCLNODEBTINC
count1189.001083.001084.001124.001102.001117.001111.001114.001136.00403.00
mean16922.1269460.4598172.858.030.711.23150.191.7821.2139.39
std11418.4647588.1974339.827.101.471.9084.952.2511.8117.72
min1100.002063.008800.000.000.000.000.000.000.000.52
25%9200.0039946.5059368.252.000.000.0096.030.0013.0032.38
50%14900.0060279.0082000.006.000.000.00132.871.0020.0038.08
75%21700.0085864.50116000.0012.001.002.00193.283.0028.0043.29
max77400.00399550.00855909.0041.0010.0015.001168.2317.0071.00203.31
"},"metadata":{}}]},{"cell_type":"markdown","source":"1. From the descriptive statistics above I can draw the following consideration:\n\n* The amount of requested loan, the amount of due mortgage and the value of the underlying collateral are statistically consistent for both loans that been PAID and that resulted in a DEFAULT. This suggests that those variables may not provide significant discrimination power to separate the two classes.\n\n\n* The number of years at the present job (YOJ) seems to discriminate the two classes as DEFAULTs seem more frequent in contractors which have a shorter seniority. This tendency is supported by the correspoding average value quantiles which indicate a distribution skewed toward shorter seniority.\n\n* A similar considerations apply to variables related to the contractor credit history such as: the number of major derogatory reports (DEROG), the number of delinquent credit lines (DELINQ), the age of oldest credit line in months (CLAGE), and the number of recent credit inquiries (NINQ). In the case of DEFAULT the distribution of these variables is skewed toward values that suggest a credit hystory that is worse than the corresponding distribution for PAID loan contractors.\n\n\n* Finally, the number of open credit line (CLNO) seems statistically consistent in both case, suggesting that this variable has no significant discrimination power.","metadata":{"_uuid":"15b6b46578e4bf2999ef1a750d086f8824809d28"}},{"cell_type":"code","source":"df.loc[df.BAD == 1, 'STATUS'] = 'DEFAULT'\ndf.loc[df.BAD == 0, 'STATUS'] = 'PAID'","metadata":{"_uuid":"f8539626c720ae398e548fa3ae509317aa8b5bf1","execution":{"iopub.status.busy":"2023-02-14T00:30:29.895514Z","iopub.execute_input":"2023-02-14T00:30:29.896064Z","iopub.status.idle":"2023-02-14T00:30:29.912013Z","shell.execute_reply.started":"2023-02-14T00:30:29.895990Z","shell.execute_reply":"2023-02-14T00:30:29.911291Z"},"trusted":true},"execution_count":9,"outputs":[]},{"cell_type":"markdown","source":"### DEFAULT as a function of the reason for aquiring the loans\n\nThe fraction of PAID and DEFAULT loans do not seem to depend strongly on the reason for acquiring the loan. On average, 80% of the loans have been payed while about the 20% DEFAULT. The 2% discrepancy observed is not statistically significant given the amount of loans in the dataset.","metadata":{"_uuid":"cd6a0d12befc4ce3733c3f0c340e393bd512da9f"}},{"cell_type":"code","source":"g = df.groupby('REASON')\ng['STATUS'].value_counts(normalize=True).to_frame().style.format(\"{:.1%}\")","metadata":{"_uuid":"b6ea91d888b48ee9274cd26f85456665fb293ce1","execution":{"iopub.status.busy":"2023-02-14T00:30:32.223550Z","iopub.execute_input":"2023-02-14T00:30:32.224034Z","iopub.status.idle":"2023-02-14T00:30:32.239315Z","shell.execute_reply.started":"2023-02-14T00:30:32.223986Z","shell.execute_reply":"2023-02-14T00:30:32.238323Z"},"trusted":true},"execution_count":10,"outputs":[{"execution_count":10,"output_type":"execute_result","data":{"text/plain":"","text/html":" \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
STATUS
REASONSTATUS
DebtConPAID81.0%
DEFAULT19.0%
HomeImpPAID77.8%
DEFAULT22.2%
"},"metadata":{}}]},{"cell_type":"markdown","source":"### DEFAULT as a function of the occupation\n\nThe fraction of PAID and DEFAULT loans show some dependence on the occupation of the contractor. Office worker and professional executives have the highest probability to pay their loans while sales and self employed have the highest probability to default. The occupation shows a good discriminating power and it will most likely be an important feature of our classification model.","metadata":{"_uuid":"4ae118a39513b77d1748e7c0aaeefd5f693e801b"}},{"cell_type":"code","source":"g = df.groupby('JOB')\ng['STATUS'].value_counts(normalize=True).to_frame().style.format(\"{:.1%}\")","metadata":{"_uuid":"14c58774c8872b1e0a932d70dd121eebbbbac460","execution":{"iopub.status.busy":"2023-02-14T00:52:26.321447Z","iopub.execute_input":"2023-02-14T00:52:26.321779Z","iopub.status.idle":"2023-02-14T00:52:26.336967Z","shell.execute_reply.started":"2023-02-14T00:52:26.321738Z","shell.execute_reply":"2023-02-14T00:52:26.336097Z"},"trusted":true},"execution_count":11,"outputs":[{"execution_count":11,"output_type":"execute_result","data":{"text/plain":"","text/html":" \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
STATUS
JOBSTATUS
MgrPAID76.7%
DEFAULT23.3%
OfficePAID86.8%
DEFAULT13.2%
OtherPAID76.8%
DEFAULT23.2%
ProfExePAID83.4%
DEFAULT16.6%
SalesPAID65.1%
DEFAULT34.9%
SelfPAID69.9%
DEFAULT30.1%
"},"metadata":{}}]},{"cell_type":"code","source":"%%opts Bars[width=700 height=400 tools=['hover'] xrotation=45]{+axiswise +framewise}\n\n# Categorical\n\ncols = ['REASON', 'JOB']\n\ndd={}\n\nfor col in cols:\n\n counts=df.groupby(col)['STATUS'].value_counts(normalize=True).to_frame('val').reset_index()\n dd[col] = hv.Bars(counts, [col, 'STATUS'], 'val') \n \nvar = [*dd]\nkdims=hv.Dimension(('var', 'Variable'), values=var) \nhv.HoloMap(dd, kdims=kdims)","metadata":{"_uuid":"62bc0016776d966c4b7069677998f6cd634da494","execution":{"iopub.status.busy":"2023-02-14T00:53:41.486074Z","iopub.execute_input":"2023-02-14T00:53:41.486446Z","iopub.status.idle":"2023-02-14T00:53:41.818567Z","shell.execute_reply.started":"2023-02-14T00:53:41.486393Z","shell.execute_reply":"2023-02-14T00:53:41.817589Z"},"trusted":true},"execution_count":13,"outputs":[{"execution_count":13,"output_type":"execute_result","data":{"text/html":"
\n
\n
\n \n
\n\n\n\n\n\n
\n
\n \n
\n
\n
\n
\n \n \n
\n \n \n
\n \n \n
\n
\n
","application/javascript":"\n// Ugly hack - see HoloViews #2574 for more information\nif (!(document.getElementById('1139')) && !(document.getElementById('_anim_img5f6395d998454af4959be02a4ca5b51c'))) {\n console.log(\"Creating DOM nodes dynamically for assumed nbconvert export. To generate clean HTML output set HV_DOC_HTML as an environment variable.\")\n var htmlObject = document.createElement('div');\n htmlObject.innerHTML = `
\n
\n
\n \n
\n\n\n\n\n\n
\n
\n \n
\n
\n
\n
\n \n \n
\n \n \n
\n \n \n
\n
\n
`;\n var scriptTags = document.getElementsByTagName('script');\n var parentTag = scriptTags[scriptTags.length-1].parentNode;\n if (parentTag.attributes.length && (parentTag.attributes[0].name == 'data-shell-mode')) {\n alert('Displaying PyViz objects in JupyterLab requires the jupyterlab_pyviz extension to be installed, install it with:\\n\\n\\tjupyter labextension install @pyviz/jupyterlab_pyviz');\n } else {\n parentTag.append(htmlObject)\n }\n}\n/* Instantiate the BokehSelectionWidget class. */\n/* The IDs given should match those used in the template above. */\nvar widget_ids = new Array(1);\n\n\nwidget_ids[0] = \"_anim_widget5f6395d998454af4959be02a4ca5b51c_Variable\";\n\n\nfunction create_widget() {\n var frame_data = {\"0\": \"{\\\"content\\\":{\\\"events\\\":[{\\\"attr\\\":\\\"data\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1171\\\",\\\"type\\\":\\\"ColumnDataSource\\\"},\\\"new\\\":{\\\"JOB\\\":[],\\\"STATUS\\\":[],\\\"val\\\":[],\\\"xoffsets\\\":[]}},{\\\"attr\\\":\\\"factors\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1135\\\",\\\"type\\\":\\\"FactorRange\\\"},\\\"new\\\":[[\\\"DebtCon\\\",\\\"DEFAULT\\\"],[\\\"DebtCon\\\",\\\"PAID\\\"],[\\\"HomeImp\\\",\\\"DEFAULT\\\"],[\\\"HomeImp\\\",\\\"PAID\\\"]]},{\\\"attr\\\":\\\"end\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1136\\\",\\\"type\\\":\\\"Range1d\\\"},\\\"new\\\":0.810336048879837},{\\\"attr\\\":\\\"reset_end\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1136\\\",\\\"type\\\":\\\"Range1d\\\"},\\\"new\\\":0.810336048879837},{\\\"attr\\\":\\\"axis_label\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1147\\\",\\\"type\\\":\\\"CategoricalAxis\\\"},\\\"new\\\":\\\"REASON, STATUS\\\"},{\\\"attr\\\":\\\"text\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1138\\\",\\\"type\\\":\\\"Title\\\"},\\\"new\\\":\\\"Variable: REASON\\\"},{\\\"attr\\\":\\\"data\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1171\\\",\\\"type\\\":\\\"ColumnDataSource\\\"},\\\"new\\\":{\\\"REASON\\\":[],\\\"STATUS\\\":[],\\\"val\\\":[],\\\"xoffsets\\\":[]}},{\\\"cols\\\":null,\\\"column_source\\\":{\\\"id\\\":\\\"1171\\\",\\\"type\\\":\\\"ColumnDataSource\\\"},\\\"kind\\\":\\\"ColumnDataChanged\\\",\\\"new\\\":{\\\"REASON\\\":[\\\"DebtCon\\\",\\\"HomeImp\\\",\\\"DebtCon\\\",\\\"HomeImp\\\"],\\\"STATUS\\\":[\\\"PAID\\\",\\\"PAID\\\",\\\"DEFAULT\\\",\\\"DEFAULT\\\"],\\\"val\\\":{\\\"__ndarray__\\\":\\\"JK6W3UXu6T+OPbmWguHoP25HpYnoRsg/yAkbpfV5zD8=\\\",\\\"dtype\\\":\\\"float64\\\",\\\"shape\\\":[4]},\\\"xoffsets\\\":[[\\\"DebtCon\\\",\\\"PAID\\\"],[\\\"HomeImp\\\",\\\"PAID\\\"],[\\\"DebtCon\\\",\\\"DEFAULT\\\"],[\\\"HomeImp\\\",\\\"DEFAULT\\\"]]}},{\\\"attr\\\":\\\"data\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1171\\\",\\\"type\\\":\\\"ColumnDataSource\\\"},\\\"new\\\":{\\\"JOB\\\":[],\\\"STATUS\\\":[],\\\"val\\\":[],\\\"xoffsets\\\":[]}},{\\\"cols\\\":null,\\\"column_source\\\":{\\\"id\\\":\\\"1171\\\",\\\"type\\\":\\\"ColumnDataSource\\\"},\\\"kind\\\":\\\"ColumnDataChanged\\\",\\\"new\\\":{\\\"REASON\\\":[\\\"DebtCon\\\",\\\"HomeImp\\\",\\\"DebtCon\\\",\\\"HomeImp\\\"],\\\"STATUS\\\":[\\\"PAID\\\",\\\"PAID\\\",\\\"DEFAULT\\\",\\\"DEFAULT\\\"],\\\"val\\\":{\\\"__ndarray__\\\":\\\"JK6W3UXu6T+OPbmWguHoP25HpYnoRsg/yAkbpfV5zD8=\\\",\\\"dtype\\\":\\\"float64\\\",\\\"shape\\\":[4]},\\\"xoffsets\\\":[[\\\"DebtCon\\\",\\\"PAID\\\"],[\\\"HomeImp\\\",\\\"PAID\\\"],[\\\"DebtCon\\\",\\\"DEFAULT\\\"],[\\\"HomeImp\\\",\\\"DEFAULT\\\"]]}}],\\\"references\\\":[]},\\\"root\\\":\\\"1139\\\"}\", \"1\": \"{\\\"content\\\":{\\\"events\\\":[{\\\"attr\\\":\\\"factors\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1135\\\",\\\"type\\\":\\\"FactorRange\\\"},\\\"new\\\":[[\\\"Mgr\\\",\\\"DEFAULT\\\"],[\\\"Mgr\\\",\\\"PAID\\\"],[\\\"Office\\\",\\\"DEFAULT\\\"],[\\\"Office\\\",\\\"PAID\\\"],[\\\"Other\\\",\\\"DEFAULT\\\"],[\\\"Other\\\",\\\"PAID\\\"],[\\\"ProfExe\\\",\\\"DEFAULT\\\"],[\\\"ProfExe\\\",\\\"PAID\\\"],[\\\"Sales\\\",\\\"DEFAULT\\\"],[\\\"Sales\\\",\\\"PAID\\\"],[\\\"Self\\\",\\\"DEFAULT\\\"],[\\\"Self\\\",\\\"PAID\\\"]]},{\\\"attr\\\":\\\"end\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1136\\\",\\\"type\\\":\\\"Range1d\\\"},\\\"new\\\":0.8681434599156118},{\\\"attr\\\":\\\"reset_end\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1136\\\",\\\"type\\\":\\\"Range1d\\\"},\\\"new\\\":0.8681434599156118},{\\\"attr\\\":\\\"axis_label\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1147\\\",\\\"type\\\":\\\"CategoricalAxis\\\"},\\\"new\\\":\\\"JOB, STATUS\\\"},{\\\"attr\\\":\\\"text\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1138\\\",\\\"type\\\":\\\"Title\\\"},\\\"new\\\":\\\"Variable: JOB\\\"},{\\\"attr\\\":\\\"data\\\",\\\"kind\\\":\\\"ModelChanged\\\",\\\"model\\\":{\\\"id\\\":\\\"1171\\\",\\\"type\\\":\\\"ColumnDataSource\\\"},\\\"new\\\":{\\\"REASON\\\":[],\\\"STATUS\\\":[],\\\"val\\\":[],\\\"xoffsets\\\":[]}},{\\\"cols\\\":null,\\\"column_source\\\":{\\\"id\\\":\\\"1171\\\",\\\"type\\\":\\\"ColumnDataSource\\\"},\\\"kind\\\":\\\"ColumnDataChanged\\\",\\\"new\\\":{\\\"JOB\\\":[\\\"Mgr\\\",\\\"Office\\\",\\\"Other\\\",\\\"ProfExe\\\",\\\"Sales\\\",\\\"Self\\\",\\\"Mgr\\\",\\\"Office\\\",\\\"Other\\\",\\\"ProfExe\\\",\\\"Sales\\\",\\\"Self\\\"],\\\"STATUS\\\":[\\\"PAID\\\",\\\"PAID\\\",\\\"PAID\\\",\\\"PAID\\\",\\\"PAID\\\",\\\"PAID\\\",\\\"DEFAULT\\\",\\\"DEFAULT\\\",\\\"DEFAULT\\\",\\\"DEFAULT\\\",\\\"DEFAULT\\\",\\\"DEFAULT\\\"],\\\"val\\\":{\\\"__ndarray__\\\":\\\"RtJ2ZC2I6D/lXBLL1MfrP4CBismCk+g/g2N8W/Ku6j+BTfvJEtjkP8po8conYuY/6LYkbkrfzT9sjLbTrODAP//51dn0sc0/9XEOkjZExT/+ZAls2k/WP20uHWqwO9M/\\\",\\\"dtype\\\":\\\"float64\\\",\\\"shape\\\":[12]},\\\"xoffsets\\\":[[\\\"Mgr\\\",\\\"PAID\\\"],[\\\"Office\\\",\\\"PAID\\\"],[\\\"Other\\\",\\\"PAID\\\"],[\\\"ProfExe\\\",\\\"PAID\\\"],[\\\"Sales\\\",\\\"PAID\\\"],[\\\"Self\\\",\\\"PAID\\\"],[\\\"Mgr\\\",\\\"DEFAULT\\\"],[\\\"Office\\\",\\\"DEFAULT\\\"],[\\\"Other\\\",\\\"DEFAULT\\\"],[\\\"ProfExe\\\",\\\"DEFAULT\\\"],[\\\"Sales\\\",\\\"DEFAULT\\\"],[\\\"Self\\\",\\\"DEFAULT\\\"]]}}],\\\"references\\\":[]},\\\"root\\\":\\\"1139\\\"}\"};\n var dim_vals = ['REASON'];\n var keyMap = {\"('REASON',)\": 0, \"('JOB',)\": 1};\n var notFound = \"

\n\n\n\n\n\n
\n

`;\n var scriptTags = document.getElementsByTagName('script');\n var parentTag = scriptTags[scriptTags.length-1].parentNode;\n if (parentTag.attributes.length && (parentTag.attributes[0].name == 'data-shell-mode')) {\n alert('Displaying PyViz objects in JupyterLab requires the jupyterlab_pyviz extension to be installed, install it with:\\n\\n\\tjupyter labextension install @pyviz/jupyterlab_pyviz');\n } else {\n parentTag.append(htmlObject)\n }\n}\n(function(root) {\n function embed_document(root) {\n \n var docs_json = {\"344b48e6-1bb8-4218-8d5d-fc04af08cf70\":{\"roots\":{\"references\":[{\"attributes\":{\"below\":[{\"id\":\"1147\",\"type\":\"CategoricalAxis\"}],\"left\":[{\"id\":\"1151\",\"type\":\"LinearAxis\"}],\"min_border_bottom\":10,\"min_border_left\":10,\"min_border_right\":10,\"min_border_top\":10,\"plot_height\":400,\"plot_width\":700,\"renderers\":[{\"id\":\"1147\",\"type\":\"CategoricalAxis\"},{\"id\":\"1150\",\"type\":\"Grid\"},{\"id\":\"1151\",\"type\":\"LinearAxis\"},{\"id\":\"1155\",\"type\":\"Grid\"},{\"id\":\"1165\",\"type\":\"BoxAnnotation\"},{\"id\":\"1177\",\"type\":\"GlyphRenderer\"}],\"title\":{\"id\":\"1138\",\"type\":\"Title\"},\"toolbar\":{\"id\":\"1161\",\"type\":\"Toolbar\"},\"x_range\":{\"id\":\"1135\",\"type\":\"FactorRange\"},\"x_scale\":{\"id\":\"1143\",\"type\":\"CategoricalScale\"},\"y_range\":{\"id\":\"1136\",\"type\":\"Range1d\"},\"y_scale\":{\"id\":\"1145\",\"type\":\"LinearScale\"}},\"id\":\"1139\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"dimension\":1,\"grid_line_color\":{\"value\":null},\"plot\":{\"id\":\"1139\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"1152\",\"type\":\"BasicTicker\"}},\"id\":\"1155\",\"type\":\"Grid\"},{\"attributes\":{\"factors\":[\"PAID\",\"DEFAULT\"],\"palette\":[\"#30a2da\",\"#fc4f30\"]},\"id\":\"1170\",\"type\":\"CategoricalColorMapper\"},{\"attributes\":{\"axis_label\":\"val\",\"bounds\":\"auto\",\"formatter\":{\"id\":\"1181\",\"type\":\"BasicTickFormatter\"},\"major_label_orientation\":\"horizontal\",\"plot\":{\"id\":\"1139\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"1152\",\"type\":\"BasicTicker\"}},\"id\":\"1151\",\"type\":\"LinearAxis\"},{\"attributes\":{\"bottom_units\":\"screen\",\"fill_alpha\":{\"value\":0.5},\"fill_color\":{\"value\":\"lightgrey\"},\"left_units\":\"screen\",\"level\":\"overlay\",\"line_alpha\":{\"value\":1.0},\"line_color\":{\"value\":\"black\"},\"line_dash\":[4,4],\"line_width\":{\"value\":2},\"plot\":null,\"render_mode\":\"css\",\"right_units\":\"screen\",\"top_units\":\"screen\"},\"id\":\"1165\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"1148\",\"type\":\"CategoricalTicker\"},{\"attributes\":{\"grid_line_color\":{\"value\":null},\"plot\":{\"id\":\"1139\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"1148\",\"type\":\"CategoricalTicker\"}},\"id\":\"1150\",\"type\":\"Grid\"},{\"attributes\":{\"overlay\":{\"id\":\"1165\",\"type\":\"BoxAnnotation\"}},\"id\":\"1159\",\"type\":\"BoxZoomTool\"},{\"attributes\":{},\"id\":\"1160\",\"type\":\"ResetTool\"},{\"attributes\":{\"callback\":null,\"renderers\":[{\"id\":\"1177\",\"type\":\"GlyphRenderer\"}],\"tooltips\":[[\"JOB\",\"@{JOB}\"],[\"STATUS\",\"@{STATUS}\"],[\"val\",\"@{val}\"]]},\"id\":\"1137\",\"type\":\"HoverTool\"},{\"attributes\":{\"axis_label\":\"REASON, STATUS\",\"bounds\":\"auto\",\"formatter\":{\"id\":\"1179\",\"type\":\"CategoricalTickFormatter\"},\"major_label_orientation\":0.7853981633974483,\"plot\":{\"id\":\"1139\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"1148\",\"type\":\"CategoricalTicker\"}},\"id\":\"1147\",\"type\":\"CategoricalAxis\"},{\"attributes\":{\"callback\":null,\"data\":{\"REASON\":[\"DebtCon\",\"HomeImp\",\"DebtCon\",\"HomeImp\"],\"STATUS\":[\"PAID\",\"PAID\",\"DEFAULT\",\"DEFAULT\"],\"val\":{\"__ndarray__\":\"JK6W3UXu6T+OPbmWguHoP25HpYnoRsg/yAkbpfV5zD8=\",\"dtype\":\"float64\",\"shape\":[4]},\"xoffsets\":[[\"DebtCon\",\"PAID\"],[\"HomeImp\",\"PAID\"],[\"DebtCon\",\"DEFAULT\"],[\"HomeImp\",\"DEFAULT\"]]},\"selected\":{\"id\":\"1172\",\"type\":\"Selection\"},\"selection_policy\":{\"id\":\"1198\",\"type\":\"UnionRenderers\"}},\"id\":\"1171\",\"type\":\"ColumnDataSource\"},{\"attributes\":{},\"id\":\"1143\",\"type\":\"CategoricalScale\"},{\"attributes\":{},\"id\":\"1157\",\"type\":\"PanTool\"},{\"attributes\":{\"callback\":null,\"end\":0.810336048879837,\"reset_end\":0.810336048879837,\"reset_start\":0,\"tags\":[[[\"val\",\"val\",null]]]},\"id\":\"1136\",\"type\":\"Range1d\"},{\"attributes\":{},\"id\":\"1158\",\"type\":\"WheelZoomTool\"},{\"attributes\":{},\"id\":\"1172\",\"type\":\"Selection\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_multi\":null,\"active_scroll\":\"auto\",\"active_tap\":\"auto\",\"tools\":[{\"id\":\"1137\",\"type\":\"HoverTool\"},{\"id\":\"1156\",\"type\":\"SaveTool\"},{\"id\":\"1157\",\"type\":\"PanTool\"},{\"id\":\"1158\",\"type\":\"WheelZoomTool\"},{\"id\":\"1159\",\"type\":\"BoxZoomTool\"},{\"id\":\"1160\",\"type\":\"ResetTool\"}]},\"id\":\"1161\",\"type\":\"Toolbar\"},{\"attributes\":{},\"id\":\"1179\",\"type\":\"CategoricalTickFormatter\"},{\"attributes\":{\"callback\":null,\"factors\":[[\"DebtCon\",\"DEFAULT\"],[\"DebtCon\",\"PAID\"],[\"HomeImp\",\"DEFAULT\"],[\"HomeImp\",\"PAID\"]],\"tags\":[[[\"JOB\",\"JOB\",null],[\"STATUS\",\"STATUS\",null]]]},\"id\":\"1135\",\"type\":\"FactorRange\"},{\"attributes\":{},\"id\":\"1156\",\"type\":\"SaveTool\"},{\"attributes\":{\"fill_color\":{\"field\":\"STATUS\",\"transform\":{\"id\":\"1170\",\"type\":\"CategoricalColorMapper\"}},\"top\":{\"field\":\"val\"},\"width\":{\"value\":0.8},\"x\":{\"field\":\"xoffsets\"}},\"id\":\"1174\",\"type\":\"VBar\"},{\"attributes\":{},\"id\":\"1145\",\"type\":\"LinearScale\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.1},\"fill_color\":{\"field\":\"STATUS\",\"transform\":{\"id\":\"1170\",\"type\":\"CategoricalColorMapper\"}},\"line_alpha\":{\"value\":0.1},\"line_color\":{\"value\":\"black\"},\"top\":{\"field\":\"val\"},\"width\":{\"value\":0.8},\"x\":{\"field\":\"xoffsets\"}},\"id\":\"1175\",\"type\":\"VBar\"},{\"attributes\":{\"fill_alpha\":{\"value\":0.2},\"fill_color\":{\"field\":\"STATUS\",\"transform\":{\"id\":\"1170\",\"type\":\"CategoricalColorMapper\"}},\"line_alpha\":{\"value\":0.2},\"line_color\":{\"value\":\"black\"},\"top\":{\"field\":\"val\"},\"width\":{\"value\":0.8},\"x\":{\"field\":\"xoffsets\"}},\"id\":\"1176\",\"type\":\"VBar\"},{\"attributes\":{\"data_source\":{\"id\":\"1171\",\"type\":\"ColumnDataSource\"},\"glyph\":{\"id\":\"1174\",\"type\":\"VBar\"},\"hover_glyph\":null,\"muted_glyph\":{\"id\":\"1176\",\"type\":\"VBar\"},\"nonselection_glyph\":{\"id\":\"1175\",\"type\":\"VBar\"},\"selection_glyph\":null,\"view\":{\"id\":\"1178\",\"type\":\"CDSView\"}},\"id\":\"1177\",\"type\":\"GlyphRenderer\"},{\"attributes\":{},\"id\":\"1198\",\"type\":\"UnionRenderers\"},{\"attributes\":{\"source\":{\"id\":\"1171\",\"type\":\"ColumnDataSource\"}},\"id\":\"1178\",\"type\":\"CDSView\"},{\"attributes\":{\"plot\":null,\"text\":\"Variable: REASON\",\"text_color\":{\"value\":\"black\"},\"text_font_size\":{\"value\":\"12pt\"}},\"id\":\"1138\",\"type\":\"Title\"},{\"attributes\":{},\"id\":\"1181\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"1152\",\"type\":\"BasicTicker\"}],\"root_ids\":[\"1139\"]},\"title\":\"Bokeh Application\",\"version\":\"1.0.4\"}};\n var render_items = [{\"docid\":\"344b48e6-1bb8-4218-8d5d-fc04af08cf70\",\"roots\":{\"1139\":\"40cb2b4e-36ff-437d-8ab8-c3186426cd7e\"}}];\n root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n\n }\n if (root.Bokeh !== undefined) {\n embed_document(root);\n } else {\n var attempts = 0;\n var timer = setInterval(function(root) {\n if (root.Bokeh !== undefined) {\n embed_document(root);\n clearInterval(timer);\n }\n attempts++;\n if (attempts > 100) {\n console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\");\n clearInterval(timer);\n }\n }, 10, root)\n }\n})(window);","application/vnd.holoviews_exec.v0+json":"","text/plain":":HoloMap [var]\n :Bars [JOB,STATUS] (val)"},"metadata":{"application/vnd.holoviews_exec.v0+json":{"id":"1139"}}}]},{"cell_type":"markdown","source":"### Graphical overview\n\nA coherent graphical overview of the dataset is shown below. For each variable I show an histogram for the whole dataset, for the PAID, and DEFUALT loans, respectively. The correlations among variables are also sumamrized in 2-dimensinal scatter plots.","metadata":{"_uuid":"145c45f430d806214a84bf90a0855bd0fb97d937"}},{"cell_type":"code","source":"%%opts Histogram[width=700 height=400 tools=['hover'] xrotation=0]{+axiswise +framewise}\n\ng = df.groupby('STATUS')\n\ncols = ['LOAN',\n 'MORTDUE', \n 'VALUE',\n 'YOJ',\n 'DEROG',\n 'DELINQ',\n 'CLAGE',\n 'NINQ',\n 'CLNO']\ndd={}\n\n# Histograms\nfor col in cols:\n \n freq, edges = np.histogram(df[col].values)\n dd[col] = hv.Histogram((edges, freq), label='ALL Loans').redim.label(x=' ')\n \n freq, edges = np.histogram(g.get_group('PAID')[col].values, bins=edges)\n dd[col] *= hv.Histogram((edges, freq), label='PAID Loans').redim.label(x=' ')\n \n freq, edges = np.histogram(g.get_group('DEFAULT')[col].values, bins=edges)\n dd[col] *= hv.Histogram((edges, freq), label='DEFAULT Loans' ).redim.label(x=' ') \n \nvar = [*dd]\nkdims=hv.Dimension(('var', 'Variable'), values=var) \nhv.HoloMap(dd, kdims=kdims)","metadata":{"_uuid":"e6b5c5ed3ca124dfa07a73cd3137e845b6539f5d","execution":{"iopub.status.busy":"2023-02-14T00:54:01.565746Z","iopub.execute_input":"2023-02-14T00:54:01.566453Z","iopub.status.idle":"2023-02-14T00:54:01.819990Z","shell.execute_reply.started":"2023-02-14T00:54:01.566008Z","shell.execute_reply":"2023-02-14T00:54:01.819175Z"},"trusted":true},"execution_count":14,"outputs":[{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mcol\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcols\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 17\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 18\u001b[0;31m \u001b[0mfreq\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0medges\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mhistogram\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdf\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mcol\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 19\u001b[0m \u001b[0mdd\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mcol\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mhv\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mHistogram\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0medges\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfreq\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabel\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'ALL Loans'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mredim\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlabel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m' '\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/opt/conda/lib/python3.6/site-packages/numpy/lib/histograms.py\u001b[0m in \u001b[0;36mhistogram\u001b[0;34m(a, bins, range, normed, weights, density)\u001b[0m\n\u001b[1;32m 778\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweights\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_ravel_and_check_weights\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweights\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 779\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 780\u001b[0;31m \u001b[0mbin_edges\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0muniform_bins\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_get_bin_edges\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbins\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweights\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 781\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 782\u001b[0m \u001b[0;31m# Histogram is an integer or a float array depending on the weights.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/opt/conda/lib/python3.6/site-packages/numpy/lib/histograms.py\u001b[0m in \u001b[0;36m_get_bin_edges\u001b[0;34m(a, bins, range, weights)\u001b[0m\n\u001b[1;32m 415\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'`bins` must be positive, when an integer'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 416\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 417\u001b[0;31m \u001b[0mfirst_edge\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlast_edge\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_get_outer_edges\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 418\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 419\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mndim\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbins\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/opt/conda/lib/python3.6/site-packages/numpy/lib/histograms.py\u001b[0m in \u001b[0;36m_get_outer_edges\u001b[0;34m(a, range)\u001b[0m\n\u001b[1;32m 313\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0misfinite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfirst_edge\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0misfinite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlast_edge\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 314\u001b[0m raise ValueError(\n\u001b[0;32m--> 315\u001b[0;31m \"autodetected range of [{}, {}] is not finite\".format(first_edge, last_edge))\n\u001b[0m\u001b[1;32m 316\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 317\u001b[0m \u001b[0;31m# expand empty range to avoid divide by zero\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mValueError\u001b[0m: autodetected range of [nan, nan] is not finite"],"ename":"ValueError","evalue":"autodetected range of [nan, nan] is not finite","output_type":"error"}]},{"cell_type":"code","source":"%%opts Scatter[width=500 height=500 tools=['hover'] xrotation=0]{+axiswise +framewise}\n\ng = df.groupby('STATUS')\n\ncols = ['LOAN',\n 'MORTDUE',\n 'VALUE',\n 'YOJ',\n 'DEROG',\n 'DELINQ',\n 'CLAGE',\n 'NINQ',\n 'CLNO']\n\nimport itertools\nprod = list(itertools.combinations(cols,2))\n\ndd = {}\n\nfor p in prod:\n dd['_'.join(p)] = hv.Scatter(g.get_group('PAID')[list(p)], label='PAID Loans').options(size=5)\n dd['_'.join(p)] *= hv.Scatter(g.get_group('DEFAULT')[list(p)], label='DEFAULT Loans').options(size=5, marker='x')\n \nvar = [*dd]\nkdims=hv.Dimension(('var', 'Variable'), values=var) \nhv.HoloMap(dd, kdims=kdims).collate()","metadata":{"_uuid":"bba53af90d733c7a8593cbe8e76538dce6a013e0","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"g=sns.PairGrid(df.drop('BAD',axis=1), hue='STATUS', diag_sharey=False, palette={'PAID': 'C0', 'DEFAULT':'C1'})\ng.map_lower(sns.kdeplot)\ng.map_upper(sns.scatterplot)\ng.map_diag(sns.kdeplot, lw=3)\ng.add_legend()\nplt.show()","metadata":{"_uuid":"48f49cd93a8b662849f10842b907eaff97c61213","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Violin plot\n\nViolin plot shows the different shapes of the probability density function for some of the variables discussed previously that seem the most promising for the classification task. The plot shows, in different colors, the PAID and the DEFAULT loans. The horizontal dashed lines indecate the position of the mean and the quantiles of the different distributions. Since there is a dependency of the DEFAULT probability on the occupation categories, the \"violins\" are shown for each of them.","metadata":{"_uuid":"7351e8abefcfcf52ffb2da6d4dc11de6c9147f5f"}},{"cell_type":"code","source":"cols=['YOJ', 'CLAGE', 'NINQ']\n\nfor col in cols:\n \n plt.figure(figsize=(15,5))\n\n sns.violinplot(x='JOB', y=col, hue='STATUS',\n split=True, inner=\"quart\", palette={'PAID': 'C0', 'DEFAULT':'C1'},\n data=df)\n \n sns.despine(left=True)","metadata":{"_uuid":"c3f2d2b3a9d2d10120b9655b3b7b6fc6158bd20b","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Correlation matrix\n\nFinally I show the correlation matrix among the variables discussed so far. Correlations are useful because they can indicate a predictive relationship that can be exploited in the classification task. \n\nThe plot is color coded: colder colors correspond to low correlation while warmer color correspond to high correlation. The variables are also grouped according to their correlation, i.e. variables with higher correlation are close to each other.\n\nVariables related to the credit history (DELINQ, DEROG, NINQ) are the most correlated with the loan status (BAD), suggesting that these will be the most discriminating variables. These variables are also slightly correlated among them, suggesting that some of the information might be redoundant.\n\nAs already discussed, the amount of the loan or the underlying collateral do not seem related to the loan status. They anyhow form another correlation cluster with other variables such as the age of oldest credit line (CLAGE) and the number of credit lines (CLNO). This is expected since those variables are clearly related.","metadata":{"_uuid":"8204474b9c4bf0681597d41b6f7a84733854ec27"}},{"cell_type":"code","source":"def compute_corr(df,size=10):\n '''Function plots a graphical correlation matrix for each pair of columns in the dataframe.\n\n Input:\n df: pandas DataFrame\n size: vertical and horizontal size of the plot'''\n import scipy\n import scipy.cluster.hierarchy as sch\n \n corr = df.corr()\n \n # Clustering\n d = sch.distance.pdist(corr) # vector of ('55' choose 2) pairwise distances\n L = sch.linkage(d, method='complete')\n ind = sch.fcluster(L, 0.5*d.max(), 'distance')\n columns = [df.select_dtypes(include=[np.number]).columns.tolist()[i] for i in list((np.argsort(ind)))]\n \n # Reordered df upon custering results\n df = df.reindex(columns, axis=1)\n \n # Recompute correlation matrix w/ clustering\n corr = df.corr()\n #corr.dropna(axis=0, how='all', inplace=True)\n #corr.dropna(axis=1, how='all', inplace=True)\n #corr.fillna(0, inplace=True)\n \n #fig, ax = plt.subplots(figsize=(size, size))\n #img = ax.matshow(corr)\n #plt.xticks(range(len(corr.columns)), corr.columns, rotation=45);\n #plt.yticks(range(len(corr.columns)), corr.columns);\n #fig.colorbar(img)\n \n return corr","metadata":{"_uuid":"62dcf0c50169195a204178098de9043005fc9b4d","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%opts HeatMap [tools=['hover'] colorbar=True width=500 height=500 toolbar='above', xrotation=45, yrotation=45]\n\ncorr=compute_corr(df)\ncorr=corr.stack(level=0).to_frame('value').reset_index()\nhv.HeatMap(corr).options(cmap='Viridis')","metadata":{"_uuid":"d5e9979ed5d368f2c877b2ac70c13d709e6ae9e2","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n# Test of default classifiers\nThe exploratory analysis described above provides good insights on the dataset and higlights the most promising variables with good discrimination power to identify loans resulting in DEFAULT. In this section I develop and investigate supervided machine learning classifiers to predict the outcome of loans. Given the large amount of algorithms available in literature, I begin from the simple methods, such as logistc regression, and gradually increase the model complexity up to randomized trees techniques. Finally I compare the performance of each model and discuss the most appropriate for this loan classification task. In this section, the following models are developed:\n* [Logistic regression](#logit)\n* [SGD classifier](#sgd)\n* [Supporting vector classifier](#svc)\n* [Gradient boosting classifier](#gbrt)\n* [Forest of randomized tree](#frt)\n * [Randm forest classifier](#rfc)\n * [Extremely randomized tree](#ert)\n* [Model comparison and conclusion](#conclusion)\n\n\n## Model Evaluation\nThe evaluation of classifiers performance is relatively complex and depenends on many factors, some of which are model dependent. In order to indetify the best model for our classification task, I adopt different evaluation metrics that are briefly summarized in the following.\n\nTo avoid overtraining, the performance of our classification model are evaluated using cross-validation. The training set is randomly splited in $N$ distinct subsets called folds, then the model is trained and evaluated $N$ times by using a different fold for the evaluation of a model that is trained on the other $N-1$ folds. The results of the procedure consist in $N$ evaluation scores for each metric that are then averaged. These averages are fianlly used to compare the different techniques considered in this study.\n\n\n### Precision & recall\nPrecision-Recall is a useful performance metric to evaluate a models in those cases when the classes are very imbalanced. In information retrieval, precision is a measure of result relevancy, while recall is a measure of how many truly relevant results are returned. Intuitively, precision is the ability of the classifier not to label as positive a sample that is negative, and recall is the ability of the classifier to find all the positive samples. \n\nA system with high recall but low precision returns many labels that tend to be predicted incorrectly when compared to the training labels. A system with high precision but low recall is just the opposite, returning very few results, but most of its predicted labels are correct when compared to the training labels. An ideal system with high precision and high recall will return many results, with many results labeled correctly.\n\nPrecision ($P$) is defined as the number of true positives ($T_{p}$) over the number of true positives plus the number of false positives ($T_{p}+F_{p}$):\n\n$P = \\frac{T_{p}}{T_{p}+F_{p}}$ \n\nRecall ($R$) is defined as the number of true positives ($T_{p}$) over the number of true positives plus the number of false negatives ($T_{p}+F_{n}$):\n\n$R = \\frac{T_{p}}{T_{p}+F_{n}}$\n\n\n### F1 measure\nIt is often convenient to combine precision and recall into a single metric called the $F_{1}$ score, defined as a weighted harmonic mean of the precision and recall:\n\n$F_{1} = 2\\times \\frac{P \\times R}{P+R}$\n\nWhereas the regular mean treats all values equally, the harmonic mean gives much more weight to low values. As a result, the classifier will only get a high F1 score if both recall and precision are high.\nThe $F_{1}$ score favors classifiers that have similar precision and recall. This is not always what you want: in some contexts you mostly care about precision, and in other contexts you really care about recall.\n\n\n### Receiver operating characteristic\nA receiver operating characteristic (ROC), or simply ROC curve, is a graphical plot which illustrates the performance of a binary classifier system as its discrimination threshold is varied. It is created by plotting the fraction of true positives out of the positives (TPR = true positive rate) vs. the fraction of false positives out of the negatives (FPR = false positive rate), at various threshold settings. TPR is also known as sensitivity, and FPR is one minus the specificity or true negative rate.\nThere is a tradeoff: the higher the recall (TPR), the more false positives (FPR) the classifier produces. The dotted line represents the ROC curve of a purely random classifier; a good classifier stays as far away from that line as possible (toward the top-left corner). \n\nThe area under the ROC curve, which is also denoted by AUC, summarise the curve information in one number. The AUC should be interpreted as the probability that a classifier will rank a randomly chosen positive istance higher than a randomly chosen negative one. A perfect classifier will have a ROC AUC equal to 1, whereas a purely random classifier will have a ROC AUC equal to 0.5.\n\n\n### Confusion matrix\nThe confusion matrix evaluates classification accuracy by computing the confusion matrix with each row corresponding to the true class. By definition, entry $i,j$ in a confusion matrix is the number of observations actually in group $i$, but predicted to be in group $j$. The confusion matrix is not used for model evaluation but it provide a good grasp on the overall model performance.\n\n\n### Classification probability\nThe classification probability provides an estimation of the probability that a given instance of the data belongs to the given class. In a binary classification problem like the one being considered, the histogram of the classification probability for the two class provide a good visual grasp on the model performance. The more the peak of the classification probability are far from each other, the higher the separation power of the model.","metadata":{"_uuid":"b5e8db9cd86ea60f3b63cfe9a0c758ad611a138f"}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import classification_report","metadata":{"_uuid":"5ce7c5a234213bbcaa3ece610a34ec4ebf437b35","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_csv('../input/hmeq.csv', low_memory=False) # No duplicated columns, no highly correlated columns\ndf=pd.get_dummies(df, columns=['REASON','JOB'])\ndf.drop('DEBTINC', axis=1, inplace=True)\ndf.dropna(axis=0, how='any', inplace=True)\ny = df['BAD']\nX = df.drop(['BAD'], axis=1)","metadata":{"_uuid":"c5efc75e35bcb100cfb18af07653ebb4e2640b04","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def cross_validate_model(model, X, y, \n scoring=['f1', 'precision', 'recall', 'roc_auc'], \n cv=12, n_jobs=-1, verbose=True):\n \n scores = cross_validate(pipe, \n X, y, \n scoring=scoring,\n cv=cv, n_jobs=n_jobs, \n verbose=verbose,\n return_train_score=False)\n\n #sorted(scores.keys())\n dd={}\n \n for key, val in scores.items():\n if key in ['fit_time', 'score_time']:\n continue\n #print('{:>30}: {:>6.5f} +/- {:.5f}'.format(key, np.mean(val), np.std(val)) )\n name = \" \".join(key.split('_')[1:]).capitalize()\n \n dd[name] = {'value' : np.mean(val), 'error' : np.std(val)}\n \n return pd.DataFrame(dd) \n #print()\n #pprint(scores)\n #print()","metadata":{"_uuid":"ac954ae9704fb17b42b548fb0ade5e91ca917c3c","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_roc(model, X_test ,y_test, n_classes=0):\n \n from sklearn.metrics import roc_curve, auc\n \n \"\"\"\n Target scores, can either be probability estimates \n of the positive class, confidence values, or \n non-thresholded measure of decisions (as returned \n by “decision_function” on some classifiers).\n \"\"\"\n try:\n y_score = model.decision_function(X_test)\n except Exception as e:\n y_score = model.predict_proba(X_test)[:,1]\n \n \n fpr, tpr, _ = roc_curve(y_test.ravel(), y_score.ravel())\n roc_auc = auc(fpr, tpr)\n\n # Compute micro-average ROC curve and ROC area\n #fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score.ravel())\n #roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n \n #plt.figure()\n lw = 2\n plt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\n\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example')\n plt.legend(loc=\"lower right\")\n #plt.show()\n \n# shuffle and split training and test sets\n#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,\n# random_state=0)","metadata":{"_uuid":"8bc2942ce77db1e02bb570bd7613afaba51a75bb","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_confusion_matrix(model, X_test ,y_test,\n classes=[0,1],\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \n import itertools\n from sklearn.metrics import confusion_matrix\n \n y_pred = model.predict(X_test)\n \n # Compute confusion matrix\n cm = confusion_matrix(y_test, y_pred)\n np.set_printoptions(precision=2)\n \n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n # print(\"Normalized confusion matrix\")\n #else:\n # print('Confusion matrix, without normalization')\n\n #print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')","metadata":{"_uuid":"c321fe50f6eb4498dd30597623f996803dc741aa","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feature_importance(coef, names, verbose=False, plot=True):\n \n #importances = model.feature_importances_\n\n \n \n #std = np.std([tree.feature_importances_ for tree in model.estimators_],\n # axis=0)\n indices = np.argsort(coef)[::-1]\n \n if verbose:\n \n # Print the feature ranking\n print(\"Feature ranking:\")\n \n for f in range(len(names)):\n print(\"{:>2d}. {:>15}: {:.5f}\".format(f + 1, names[indices[f]], coef[indices[f]]))\n \n if plot:\n \n # Plot the feature importances of the forest\n #plt.figure(figsize=(5,10))\n plt.title(\"Feature importances\")\n plt.barh(range(len(names)), coef[indices][::-1], align=\"center\")\n #plt.barh(range(X.shape[1]), importances[indices][::-1],\n # xerr=std[indices][::-1], align=\"center\")\n plt.yticks(range(len(names)), names[indices][::-1])\n #plt.xlim([-0.001, 1.1])\n #plt.show()","metadata":{"_uuid":"8395e8a2f03ef68d865d6a58dfa8924c143448b6","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_proba(model, X, y, bins=40, show_class = 1):\n \n from sklearn.calibration import CalibratedClassifierCV\n \n model = CalibratedClassifierCV(model)#, cv='prefit')\n \n model.fit(X, y)\n \n proba=model.predict_proba(X)\n \n if show_class == 0:\n sns.kdeplot(proba[y==0,0], shade=True, color=\"r\", label='True class')\n sns.kdeplot(proba[y==0,1], shade=True, color=\"b\", label='Wrong class')\n plt.title('Classification probability: Class 0')\n elif show_class == 1:\n sns.kdeplot(proba[y==1,1], shade=True, color=\"r\", label='True class')\n sns.kdeplot(proba[y==1,0], shade=True, color=\"b\", label='Wrong class')\n plt.title('Classification probability: Class 1')\n plt.legend()","metadata":{"_uuid":"4b82915abe9c07f603d19a0a4bdd2cd4279cbdd8","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Logistic regression\n\n\nLogistic regression is the simplest linear model for classification. Logistic regression is also known in the literature as logit regression, maximum-entropy classification (MaxEnt) or the log-linear classifier. In this model, the probabilities describing the possible outcomes of a single trial are modeled using a logistic function. The optimization problem is solved minimizing a cost function using an highly optimized coordinate descent algorithm.","metadata":{"_uuid":"e940ba20f513b744d2fa5132d7c14206b7901680"}},{"cell_type":"code","source":"from sklearn.linear_model import LogisticRegression\n\nsteps = [('scaler', StandardScaler(copy=True, with_mean=True, with_std=True)),\n ('model', LogisticRegression(random_state=0))]\n\npipe = Pipeline(steps)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)\npipe.fit(X_train, y_train)","metadata":{"_uuid":"d526e2619034ae819155db168a52baa4db11545e","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,10))\n\nplt.subplot(221)\nplot_roc(pipe, X_test ,y_test)\n\nplt.subplot(222)\nplot_confusion_matrix(pipe, X_test ,y_test, normalize=True)\n\nplt.subplot(223)\nplot_proba(pipe, X_test, y_test)\n\nplt.subplot(224)\nfeature_importance(pipe.named_steps['model'].coef_[0], X.columns)\n\nplt.tight_layout()","metadata":{"_uuid":"1238203218684c84f0435627e32531a58af94807","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"logit_xval_res = cross_validate_model(pipe, X, y, verbose=False)\nlogit_xval_res.T[['value','error']].style.format(\"{:.2f}\")","metadata":{"_uuid":"9b7e4bdcf812f7851e5022ad91c9645cbad26ba3","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n### Forests of randomized trees\nDecision Trees (DTs) are a non-parametric supervised learning method used for classification and regression. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features.\n\nThe forest of randomized tree technique includes two averaging algorithms based on randomized decision trees: the RandomForest algorithm and the Extra-Trees method. Both algorithms are perturb-and-combine techniques specifically designed for trees. This means a diverse set of classifiers is created by introducing randomness in the classifier construction. The prediction of the ensemble is given as the averaged prediction of the individual classifiers.\n\n\n#### Random Forest Classifier\nIn random forests, each tree in the ensemble is built from a sample drawn with replacement (i.e., a bootstrap sample) from the training set. In addition, when splitting a node during the construction of the tree, the split that is chosen is no longer the best split among all features. Instead, the split that is picked is the best split among a random subset of the features. As a result of this randomness, the bias of the forest usually slightly increases (with respect to the bias of a single non-random tree) but, due to averaging, its variance also decreases, usually more than compensating for the increase in bias, hence yielding an overall better model.","metadata":{"_uuid":"2a57986faf29fb12dfe52cf38e48588a85f1329e"}},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\n\nsteps = [('scaler', StandardScaler(copy=True, with_mean=True, with_std=True)),\n ('model', RandomForestClassifier(n_estimators=250, n_jobs=-1, random_state=0))]\n\npipe = Pipeline(steps)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)\npipe.fit(X_train, y_train)","metadata":{"scrolled":true,"_uuid":"6f98e2f06aea23bbcd54a7d110ada03a5b4f1d24","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,10))\n\nplt.subplot(221)\nplot_roc(pipe, X_test ,y_test)\n\nplt.subplot(222)\nplot_confusion_matrix(pipe, X_test ,y_test, normalize=True)\n\nplt.subplot(223)\nplot_proba(pipe, X_test, y_test)\n\nplt.subplot(224)\nfeature_importance(pipe.named_steps['model'].feature_importances_, X.columns)\n\nplt.tight_layout()","metadata":{"_uuid":"bdb13c15335b04789b591de91dd606a57ac755a9","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rfc_xval_res = cross_validate_model(pipe, X, y, verbose=False)\nrfc_xval_res.T[['value','error']].style.format(\"{:.2f}\")","metadata":{"_uuid":"4bb62c9ba333c45f9d6e58a28c4e6a27c0d0e8ff","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n#### Extremely Randomized Trees\nIn extremely randomized trees, randomness goes one step further in the way splits are computed. As in random forests, a random subset of candidate features is used, but instead of looking for the most discriminative thresholds, thresholds are drawn at random for each candidate feature and the best of these randomly-generated thresholds is picked as the splitting rule. This usually allows to reduce the variance of the model a bit more, at the expense of a slightly greater increase in bias","metadata":{"_uuid":"32fac0f2dc0970d4c7b60cb02229b97df5897bc1"}},{"cell_type":"code","source":"from sklearn.ensemble import ExtraTreesClassifier\n\nsteps = [('scaler', StandardScaler(copy=True, with_mean=True, with_std=True)),\n ('model', ExtraTreesClassifier(n_estimators=250, n_jobs=-1, random_state=0, class_weight='balanced'))]\n\npipe = Pipeline(steps)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)\npipe.fit(X_train, y_train)","metadata":{"_uuid":"687c336968c42abd165a735641f5cfbd9de03be9","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,10))\n\nplt.subplot(221)\nplot_roc(pipe, X_test ,y_test)\n\nplt.subplot(222)\nplot_confusion_matrix(pipe, X_test ,y_test, normalize=True)\n\nplt.subplot(223)\nplot_proba(pipe, X_test, y_test)\n\nplt.subplot(224)\nfeature_importance(pipe.named_steps['model'].feature_importances_, X.columns)\n\nplt.tight_layout()","metadata":{"_uuid":"97a8c723c30fdcdf7d040989c5094d7c762ba85b","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ert_xval_res = cross_validate_model(pipe, X, y, verbose=False)\nert_xval_res.T[['value','error']].style.format(\"{:.2f}\")","metadata":{"_uuid":"eb13d68e18139ed3ca7fe282547d99838f7f2d8b","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## Model comparison and conclusions\nThe table below summarizes the performance of the classification models that I considered in this study. Performances are ordered by increasing value of $F_{1}$. The best performances are obtained by the **extremely randomized tree**, followed by the **random forest** and the **logistic regression**. \n\nThe extremely randomized tree allow to identify up to 66% of loans which would cause a DEFAULT while retaining 91% of loans which would be PAID in time. The ROC AUC value is as high as 96%, indicating that the probabilty that the classifier would perform better by random choice is as low as 4%.","metadata":{"_uuid":"59ebb7aa871678f1f7cda4bd66c081e56012fd29"}},{"cell_type":"code","source":"from collections import OrderedDict\n\nres_comp = OrderedDict([\n ('Logistic regression' , logit_xval_res[1:]),\n ('SGD classifier' , sgd_xval_res[1:] ),\n ('Supporting vector classifier' , svc_xval_res[1:] ),\n ('Random forest classifier' , rfc_xval_res[1:] ),\n ('Extermely random tree classifier' , ert_xval_res[1:] ),\n ('Gradient boost classifier' , gbc_xval_res[1:] ),\n])\n\nnew_columns = {'level_0' : 'Model'}\n\npd.concat(res_comp).reset_index().drop('level_1', axis=1).rename(columns=new_columns).set_index('Model').sort_values('F1', ascending=False).style.format(\"{:.2f}\")","metadata":{"_uuid":"5dd30c501a228b91bb34fd8f04aeee7ebd9918f4","trusted":true},"execution_count":null,"outputs":[]}]}