def get_layout(self): # Set up plot plot = self.plot plot.line('x', 'y', source=self.source, line_width=3, line_alpha=0.6) plot.renderers.append(self.vline) self.trigger_plot = plot.line('x', 'trigger', source=self.source, line_width=3, line_alpha=0.6) self.trigger_plot.glyph.line_alpha = 0 self.trigger_plot.glyph.line_color = "#15bd42" self.trigger_plot.glyph.line_width = 1 trigger_slider = md.Slider(start=-2.5, end=2.5, value=2, step=0.01, title="Trigger Value") trigger_slider.on_change("value", self.on_trigger_moved) width_slider = md.Slider(start=1, end=1000, value=10, step=1, title='Width (ms)') width_slider.on_change("value", self.on_width_moved) scale_slider = md.Slider(start=0.1, end=10, value=1, step=0.01, title='Scale') scale_slider.on_change("value", self.on_scale_moved) self.trigger_button = md.buttons.Toggle(label="Trigger") self.trigger_button.on_click(self.trigger_clicked) raise_or_fall = md.RadioButtonGroup(labels=["Raising", "Falling"], active=self.raise_or_fall_value) raise_or_fall.on_change('active', self.raise_or_fall_clicked) scope = row( plot, column( row( self.trigger_button, raise_or_fall, ), trigger_slider, width_slider, scale_slider, ), ) self.layour = scope return scope
def _build_int_option(self, option_name, title): current = self.model.options[option_name] select_ui = mdl.Slider(title=title, value=current, start=1, end=30) def on_change(attr, old_state, new_state): assert attr == 'value' del old_state self.controller.set_option(option_name, new_state) select_ui.on_change('value', on_change) self.option_uis[option_name] = select_ui
def get_layout(self): step = self.parameter.step if step is None: step = (self.parameter.max - self.parameter.min) / 1000 self.slider = slider = md.Slider(start=self.parameter.min, end=self.parameter.max, title=self.parameter.name, value=self.parameter.value, step=step) slider.on_change("value", self.on_value_change) return slider
class FittedParamWidgets: """Collection of Bokeh Widgets for fitting a light-curve parameters""" top_section_div = models.Div(text=( '<h2>Fitted Parameters</h2>' '<p>Current parameter values are used as an initial guess when fitting. ' 'Note that redshift values are not varied as part of the fit.</p>')) # User input widgets for setting model parameters fit_t0_slider = models.Slider(start=-10, end=10, value=0, step=1E-4, title='t0') fit_x0_slider = models.Slider(start=0.001, end=2, value=.1, step=1E-4, title='x0') fit_x1_slider = models.Slider(start=-1, end=1, value=0, step=1E-4, title='x1') fit_c_slider = models.Slider(start=-1, end=1, value=0, step=1E-4, title='c') plot_model_button = models.Button(label='Plot Model', button_type='warning') fit_button = models.Button(label='Fit Light-Curve', button_type='success') fitted_params_widgets_list = [ top_section_div, fit_t0_slider, fit_x0_slider, fit_x1_slider, fit_c_slider, plot_model_button, fit_button ]
class SimulatedParamWidgets: """Collection of Bokeh Widgets for specifying simulation parameters""" top_section_div = models.Div(text='<h2>Simulated Parameters</h2>') # User input widgets for setting model parameters sim_z_slider = models.Slider(start=0.001, end=1, value=.55, step=.01, title='z') sim_t0_slider = models.Slider(start=-10, end=10, value=-2, step=.01, title='t0') sim_x0_slider = models.Slider(start=0.001, end=2, value=.25, step=.01, title='x0') sim_x1_slider = models.Slider(start=-1, end=1, value=0.11, step=.01, title='x1') sim_c_slider = models.Slider(start=-1, end=1, value=-.05, step=.01, title='c') sampling_input = models.TextInput(value='4', title='Sampling (Days):') sim_pwv_slider = models.Slider(start=-0, end=15, value=7, step=.1, title='PWV') plot_button = models.Button(label='Plot Light-Curve', button_type='success') snr_input = models.TextInput(value='10.0', title='SNR:', default_size=220) checkbox = models.CheckboxGroup( labels=["Plot SNR", 'Subtract Reference Star'], active=[0]) # Having all inputs as a list is useful when constructing layouts # as it establishes the default column order sim_params_widgets_list = [ top_section_div, sim_z_slider, sim_t0_slider, sim_x0_slider, sim_x1_slider, sim_c_slider, sim_pwv_slider, sampling_input, snr_input, checkbox, plot_button ]
def example_doc_modifier(): df = sea_surface_temperature.copy() source = bkm.ColumnDataSource(data=df) plot = bkp.figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = bkm.ColumnDataSource(data=data).data slider = bkm.Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) return slider, plot
def make_slider(prop, start, end, value): slider = models.Slider(title=prop, start=start, end=end, value=value) add_callback(slider, prop) return slider
def __init__(self): self.numeric_eqn = sp.lambdify(self.all_symbols, sp.Matrix(self.symbolic_eqns)) ys = np.linspace(*self.y_range, self.vector_density[0]) dys = np.linspace(*self.dy_range, self.vector_density[1]) y_grid, dy_grid = np.meshgrid(ys, dys) self._ys = y_grid.flatten() self._dys = dy_grid.flatten() self.vector_source = models.ColumnDataSource(data=dict( xs=[], ys=[], )) self.trajectories_source = models.ColumnDataSource(data=dict( xs=[], ys=[], )) self.trajectory_starts_source = models.ColumnDataSource(data=dict( x=[], y=[], )) self.plot = figure( width=FIGURE_WIDTH, height=FIGURE_HEIGHT, x_range=self.y_range, y_range=self.dy_range, title='Phase portrait', toolbar_location=None, ) self.plot.xaxis.axis_label = 'y' self.plot.yaxis.axis_label = 'ẏ' self.plot.axis.axis_label_text_font_size = AXIS_TITLE_FONT_SIZE self.plot.axis.major_label_text_font_size = AXIS_TICK_FONT_SIZE self.plot.on_event(events.Tap, self.plot_clicked) self.plot.scatter(x=self._ys, y=self._dys) self.plot.multi_line( xs='xs', ys='ys', source=self.vector_source, line_width=VECTOR_LINE_WIDTH, ) self.setup_trajectory_glyphs(self.trajectory_starts_source, self.trajectories_source) self.t_slider = models.Slider( title='Trajectory duration', width=SLIDER_WIDTH, **TIME_SLIDER_PARAMS, ) self.param_sliders = {} for param, range_, step, value in zip( self.param_symbols, self.param_ranges, self.param_steps, self.param_defaults, ): slider = models.Slider( start=range_[0], end=range_[1], step=step, value=value, title=str(param), width=SLIDER_WIDTH, ) slider.on_change('value', self.on_slider_change) self.param_sliders[param] = slider
def make_responsive_plot(prot, tag): #output_file("test_deg_def.html", title="line deg") title = tag fig_fit = get_base_plot(prot, title) #fig_fit.set(y_range=bkm.Range1d(-0.1, 1.1)) x_lim = prot.X[-1] + 0.1 X = np.arange(-0.1, x_lim, 0.1) Ys = model_syn(X, prot.N0, prot.tau, prot.offset) Yd = model_deg(X, prot.N0, prot.tau, prot.offset) params_start = [prot.N0, prot.tau, prot.offset, title] params = [prot.N0, prot.tau, prot.offset, title] diff = len(Yd) - len(params) add = [np.nan] * diff params_start += add params += add source = bkm.ColumnDataSource(data=dict( X=X, Ys=Ys, Yd=Yd, params_start=params_start, params=params, )) code = """ var data = source.get('data'); var params_start = data['params_start'] var X = data['X']; var Ys = data['Ys']; var Yd = data['Yd']; var params = data['params']; var title = params[3]; var f = cb_obj.get('value'); if (cb_obj.get('title') == 'N0') {N0 = cb_obj.get('value'); params[0] = N0;}; if (cb_obj.get('title') == 'tau') {tau = cb_obj.get('value'); params[1] = tau; }; if (cb_obj.get('title') == 'offset') {offset = cb_obj.get('value'); params[2] = offset;}; var N0 = parseFloat(params[0]); var tau = parseFloat(params[1]); var offset = parseFloat(params[2]); //console.log(params, 'here parms'); //console.log(N0, 'here N0'); //console.log(tau, 'here tau'); //console.log(offset, 'here offset'); //console.log(Ys, 'here Ys before'); //console.log(Yd, 'here Yd before'); for (i = 0; i < X.length; i++) { Ys[i] = 1 - ((N0 * Math.exp( -X[i]/tau )) + offset) ; } for (i = 0; i < X.length; i++) { Yd[i] = (N0 * Math.exp( -X[i]/tau )) + offset ; } var last_element = X[X.length - 1]; var residual = (N0 * Math.exp( -last_element/tau )) + offset //console.log(Ys, 'here Ys after'); //console.log(Yd, 'here Yd after'); source.trigger('change'); console.log(N0, 'here N0 after'); console.log(tau, 'here tau after'); console.log(offset, 'here offset after'); console.log( tau / Math.log(2) ,'here half life') //$("field_name_1").update(tau/Math.log(2)); //$("field_name_2").update(tau); //$("field_name_3").update(offset); $('#field_name_1').text(Math.round(tau/Math.log(2)* 100)/100); $('#field_name_2').text(Math.round(residual * 100)/100); //$('#field_name_3').text(offset); //document.getElementById("field_name_1").innerHTML = N0; // $( ".hello" ).remove(); //var $new = $('<div class="hello"></div>').appendTo('.insert_body'); //http://stackoverflow.com/questions/247483/http-get-request-in-javascript //function httpGet(theUrl) //{ //var xmlHttp = new XMLHttpRequest(); //xmlHttp.open( "GET", theUrl, false ); // false for synchronous request //xmlHttp.send( null ); //return xmlHttp.responseText; //} //var address = '{web_address}find_intersection?N0='+N0+'&tau='+tau+'&c='+offset //var res = httpGet(address); //console.log(res, 'test'); //if (title == 'Bloodstrem'){ //console.log('new_intersection_bs'); //$("#new_intersection_bs").html('new intersection: '+res); //} //if (title == 'Procyclic'){ // $("#new_intersection_pc").html('new intersection: '+res); //} //res = httpGet(address) //console.log(res, 'test'); //ras = $.get("address"); //req.open('GET', address, false); // //console.log(address); """ #code = code.replace('{web_address}', web_adress) callback = bkm.CustomJS(args=dict(source=source), code=code) sliderN0 = bkm.Slider(start=0, end=1, value=prot.N0, step=.01, title="N0", name='N0', callback=callback) sliderTau = bkm.Slider(start=0.1, end=50, value=prot.tau, step=.01, title="tau", name='tau', callback=callback) sliderOffSet = bkm.Slider(start=0, end=1, value=prot.offset, step=.01, title="offset", name='offset', callback=callback) syn = fig_fit.line(x='X', y='Ys', source=source, color='green') deg = fig_fit.line(x='X', y='Yd', source=source, color='red') legend = Legend(items=[("syn", [syn]), ("deg", [deg])], location=(10, -30)) #fig_fit.legend.location = (0, -30) #layout = vform(fig_fit) #script, div = components(layout) #layout = vform() #script_bar, div_bar = components(layout) #show(layout( #[[fig_fit],[sliderN0],[sliderTau],[sliderOffSet]] #)) fig_fit.add_layout(legend, 'right') #show(layouts.column(fig_fit, sliderN0, sliderTau, sliderOffSet)) script, div = components( layouts.column(fig_fit, sliderN0, sliderTau, sliderOffSet)) return script, div
# Grab the data from the file, into a pandas array bokeh_data = read_data(fname) # Create a bokeh figure p = bkp.figure(title=title, plot_width=1600, plot_height=700) # Add data to it p.scatter(x='phase', y='flux', source=bokeh_data, color=color) # Format some stuff p.xaxis.axis_label = 'Phase' p.yaxis.axis_label = 'Flux' # Plot the figure fig = p #### Lets add a slider slider = bkm.Slider(title='Flux offset', start=-1, end=1, value=0.0, width=600, step=0.01) #TODO: slider.on_change('value', alter_data) # Make a layout, and add to document layout = bkl.column([fig, slider]) bkp.curdoc().add_root(layout) bkp.curdoc().title = __name__
def generate_plot(data, df_all_prediction): COLORS = d3["Category10"][10] tooltips = f""" <div> <p> <span style="font-size: 12px; color: black;font-family:century gothic;">Nombre de cas : </span> <span style="font-size: 12px; color: {COLORS[0]}; font-weight: bold;font-family:century gothic;">@total_cases</span> <br> <span style="font-size: 12px; color: black;font-family:century gothic;">Nombre de nouveaux cas : </span> <span style="font-size: 12px; color: {COLORS[1]}; font-weight: bold;font-family:century gothic;">@new_cases</span> <br> <span style="font-size: 12px; color: black;font-family:century gothic;">Nombre de deces : </span> <span style="font-size: 12px; color: {COLORS[3]}; font-weight: bold;font-family:century gothic;">@total_deaths</span> <br> <span style="font-size: 12px; color: black;font-family:century gothic;">Nombre nouveaux deces : </span> <span style="font-size: 12px; color: {COLORS[5]}; font-weight: bold;font-family:century gothic;">@new_deaths</span> <br> <span style="font-size: 12px; color: black;font-family:century gothic;">Date : </span> <span style="font-size: 12px; color: black; font-weight: bold;font-family:century gothic;">@date_str</span> </p> </div> """ tooltips_predictions = (f""" <div> <p> <span style="font-size: 12px; color: black;font-family:century gothic;">Prédiction nombre de cas : </span> <span style="font-size: 12px; color: {COLORS[0]}; font-weight: bold;font-family:century gothic;">@median_display</span> <br> <span style="font-size: 12px; color: black;font-family:century gothic;">Date : </span> <span style="font-size: 12px; color: black; font-weight: bold;font-family:century gothic;">""" + """@date_str</span> </p> </div> """) hover = bkm.tools.HoverTool(names=["line_total"], tooltips=tooltips, mode="vline") hover_prediction = bkm.tools.HoverTool( names=["prediction"], tooltips=tooltips_predictions, ) # --- define all DataSource needed --- # source_all = bkm.ColumnDataSource(data) country = "World" source = bkm.ColumnDataSource(get_country(data, country)) source_all_prediction = bkm.ColumnDataSource(df_all_prediction) source_prediction = bkm.ColumnDataSource( get_country(df_all_prediction, country)) date_end_training = np.unique( get_country(df_all_prediction, country)["date_end_train"])[-1] source_prediction_end_date = bkm.ColumnDataSource( get_country(df_all_prediction, country)[get_country( df_all_prediction, country).date_end_train == date_end_training]) slider = bkm.Slider( start=0, end=len( np.unique( get_country(df_all_prediction, country)["date_end_train"])) - 1, value=0, step=1, title="Days dropped for prediction", ) # ----------- # p = bkp.figure( y_axis_type="linear", x_axis_type="datetime", sizing_mode="stretch_both", title=f"Covid 19 evolution: {country}", x_axis_label="date", y_axis_label="Total number of Covid 19 cases", tools=[hover, "pan", "wheel_zoom", "reset"], x_range=[ get_country(data, country).date.min(), get_country(data, country).date.max() + datetime.timedelta(days=1), ], y_range=[ -get_country(data, country).total_cases.max() * 0.05, get_country(data, country).total_cases.max() * 1.1, ], ) p.yaxis.formatter = bkm.formatters.NumeralTickFormatter(format="0,0") p.xaxis.formatter = bkm.formatters.DatetimeTickFormatter( days=["%d/%m", "%d%a"], months=["%m/%Y", "%b %Y"]) p.add_tools(hover_prediction) p.toolbar.active_drag = None # p.toolbar.active_scroll = p.select_one(bkm.WheelZoomTool) y_extra_range_max = np.max([ np.max(get_country(data, country).new_cases.values), np.max(get_country(data, country).total_deaths.values), ]) p.extra_y_ranges = { "Number of deaths": bkm.Range1d(start=-0.05 * y_extra_range_max, end=1.1 * y_extra_range_max) } p.add_layout( bkm.LinearAxis( y_range_name="Number of deaths", axis_label="New Covid 19 cases", formatter=bkm.formatters.NumeralTickFormatter(format="0,0"), ), "right", ) # --- plot total cases --- # p.line( source=source, x="date", y="total_cases", name="line_total", color=COLORS[0], legend_label="total cases", muted_alpha=0.1, ) p.circle(source=source, x="date", y="total_cases", color=COLORS[0], muted_alpha=0.1) # --- plot new cases --- # p.vbar( source=source, x="date", top="new_cases", color=COLORS[1], width=50e6, alpha=0.5, name="bar", y_range_name="Number of deaths", legend_label="new cases", muted_alpha=0.1, ) # --- plot total death --- # p.line( source=source, x="date", y="total_deaths", color=COLORS[3], y_range_name="Number of deaths", name="line_death", legend_label="total deaths", muted_alpha=0.1, ) p.circle( source=source, x="date", y="total_deaths", color=COLORS[3], y_range_name="Number of deaths", muted_alpha=0.1, ) # --- plot new death --- # p.vbar( source=source, x="date", top="new_deaths", color=COLORS[5], width=50e6, alpha=0.5, y_range_name="Number of deaths", legend_label="new deaths", muted_alpha=0.1, ) button_click_count = bkm.ColumnDataSource({"clicks": [0]}) select = bkm.Select(title="Country: ", value=country, options=list(data.location.unique())) button_log = bkm.Button(label="Log Scale", button_type="primary") # --- Predictions --- # median_prediction = p.line( source=source_prediction_end_date, x="date", y="median", line_color=COLORS[0], name="prediction", ) prediction_cases_line = p.line( source=source_prediction_end_date, x="date", y="derivative", color=COLORS[1], y_range_name="Number of deaths", ) band_low = bkm.Band( source=source_prediction_end_date, base="date", lower="25%", upper="median", fill_color=COLORS[0], level="underlay", fill_alpha=0.1, line_width=0.5, line_color="black", ) band_high = bkm.Band( source=source_prediction_end_date, base="date", lower="median", upper="75%", fill_color=COLORS[0], level="underlay", fill_alpha=0.1, line_width=0.5, line_color="black", ) median_prediction.visible = False prediction_cases_line.visible = False band_low.visible = False band_high.visible = False p.add_layout(band_low) p.add_layout(band_high) button_prediction = bkm.Button(label="Show predictions", button_type="primary") # -- Callback -- # callback = bkm.CustomJS( args=dict( source=source, source_all=source_all, select=select, x_range=p.x_range, y_range_left=p.y_range, y_range_right=p.extra_y_ranges["Number of deaths"], title=p.title, button_click_count=button_click_count, slider=slider, source_all_prediction=source_all_prediction, source_prediction=source_prediction, source_prediction_end_date=source_prediction_end_date, median_prediction=median_prediction, band_low=band_low, prediction_cases_line=prediction_cases_line, band_high=band_high, ), code=""" var country = select.value var date = source_all.data['date'] var date_str = source_all.data['date_str'] var location = source_all.data['location'] var total_cases = source_all.data['total_cases'] var new_cases = source_all.data['new_cases'] var total_deaths = source_all.data['total_deaths'] var new_deaths = source_all.data['new_deaths'] var new_date = [] var new_date_str = [] var new_total_cases = [] var new_new_cases = [] var new_total_deaths = [] var new_new_deaths = [] for(var i=0; i < date.length; i++){ if(location[i]==country){ new_date.push(date[i]); new_date_str.push(date_str[i]) new_total_cases.push(total_cases[i]); new_new_cases.push(new_cases[i]); new_total_deaths.push(total_deaths[i]); new_new_deaths.push(new_deaths[i]); } } source.data['date']=new_date; source.data['date_str']=new_date_str; source.data['total_cases']=new_total_cases; source.data['new_cases']=new_new_cases; source.data['total_deaths']=new_total_deaths; source.data['new_deaths']=new_new_deaths; const new_cases_no_Nan = new_new_cases.filter(function (value) { return !Number.isNaN(value); }); const cases_no_Nan = new_total_cases.filter(function (value) { return !Number.isNaN(value); }); y_range_right.setv({"start": -0.05*Math.max.apply(Math, new_cases_no_Nan.concat(new_total_deaths)), "end": 1.1*Math.max.apply(Math, new_cases_no_Nan.concat(new_total_deaths))}) y_range_left.setv({"start": -0.05*Math.max.apply(Math, cases_no_Nan), "end": 1.1*Math.max.apply(Math, cases_no_Nan)}) x_range.setv({"start": Math.min.apply(Math, new_date), "end": 1.0001*Math.max.apply(Math, new_date)}) title.text = "Evolution du nombre de cas en " + country source.change.emit(); // change value of predictions button_click_count.data.clicks = 0 median_prediction.visible = false band_low.visible = false band_high.visible = false prediction_cases_line.visble = false var date_end_prediction = source_all_prediction.data['date_end_train'] var location = source_all_prediction.data['location'] var date = source_all_prediction.data['date'] var date_str = source_all_prediction.data['date_str'] var quantile_1 = source_all_prediction.data['25%'] var quantile_2 = source_all_prediction.data['median'] var quantile_3 = source_all_prediction.data['75%'] var new_cases = source_all_prediction.data['derivative'] var median_prediction = source_all_prediction.data['median_display'] var new_date = [] var new_date_str = [] var new_date_end_prediction = [] var new_quantile_1 = [] var new_quantile_2 = [] var new_quantile_3 = [] var new_new_cases = [] var new_median_prediction = [] for(var i=0; i < quantile_1.length; i++){ if(location[i]==country){ new_date.push(date[i]) new_date_str.push(date_str[i]) new_date_end_prediction.push(date_end_prediction[i]) new_quantile_1.push(quantile_1[i]); new_quantile_2.push(quantile_2[i]); new_quantile_3.push(quantile_3[i]); new_new_cases.push(new_cases[i]); new_median_prediction.push(median_prediction[i]); } } source_prediction.data['date']=new_date source_prediction.data['date_str']=new_date_str source_prediction.data['date_end_train']=new_date_end_prediction source_prediction.data['25%']=new_quantile_1; source_prediction.data['median']=new_quantile_2; source_prediction.data['75%']=new_quantile_3; source_prediction.data['derivative']=new_new_cases; source_prediction.data['median_display']=new_median_prediction; var n = new_date.length var max_date = Math.max.apply(Math, new_date_end_prediction) var new_date_bis = [] var new_date_str_bis = [] var new_date_end_prediction_bis = [] var new_quantile_1_bis = [] var new_quantile_2_bis = [] var new_quantile_3_bis = [] var new_new_cases_bis = [] var new_median_prediction_bis = [] for(var i=0; i < n; i++){ if(new_date_end_prediction[i]==max_date){ new_date_bis.push(new_date[i]) new_date_str_bis.push(new_date_str[i]) new_date_end_prediction_bis.push(new_date_end_prediction[i]) new_quantile_1_bis.push(new_quantile_1[i]); new_quantile_2_bis.push(new_quantile_2[i]); new_quantile_3_bis.push(new_quantile_3[i]); new_new_cases_bis.push(new_new_cases[i]); new_median_prediction_bis.push(new_median_prediction[i]); } } var n = new_date_bis.length var max_date = Math.max.apply(Math, new_date_end_prediction_bis) source_prediction_end_date.data['date']=new_date_bis source_prediction_end_date.data['date_str']=new_date_str_bis source_prediction_end_date.data['date_end_train']=new_date_end_prediction_bis source_prediction_end_date.data['25%']=new_quantile_1_bis; source_prediction_end_date.data['median']=new_quantile_2_bis; source_prediction_end_date.data['75%']=new_quantile_3_bis; source_prediction_end_date.data['derivative']=new_new_cases_bis; source_prediction_end_date.data['median_display']=new_median_prediction_bis; source_prediction.change.emit(); source_prediction_end_date.change.emit() const unique = (value, index, self) => { return self.indexOf(value) === index } // change slider value slider.setv({"end": new_date_end_prediction.filter(unique).length - 1, "value": 0}) """, ) callback_button = bkm.CustomJS( args=dict(y_axis=p.left, title=p.title), code=""" console.log(y_axis) y_axis = LogAxis() """, ) select.js_on_change("value", callback) button_log.js_on_click(callback_button) callback_button = bkm.CustomJS( args=dict( source=source, source_prediction=source_prediction, source_all_prediction=source_all_prediction, source_prediction_end_date=source_prediction_end_date, select=select, button_prediction=button_prediction, median_prediction=median_prediction, band_low=band_low, prediction_cases_line=prediction_cases_line, band_high=band_high, button_click_count=button_click_count, x_range=p.x_range, y_range_left=p.y_range, y_range_right=p.extra_y_ranges["Number of deaths"], ), code=""" // function to get unique value of an array const unique = (value, index, self) => { return self.indexOf(value) === index } var date = source.data['date']; var total_cases = source.data['total_cases']; var new_cases = source.data['new_cases']; var total_deaths = source.data['total_deaths']; var date_prediction = source_prediction.data['date']; var total_cases_prediction = source_prediction.data['75%']; const new_cases_no_Nan = new_cases.filter(function (value) { return !Number.isNaN(value); }); const cases_no_Nan = total_cases.filter(function (value) { return !Number.isNaN(value); }); var country = select.value button_click_count.data.clicks ++ var show_prediction = (button_click_count.data.clicks % 2) == 1 var locations_predicted = source_all_prediction.data['location'].filter(unique) if (locations_predicted.includes(country) == false){ window.alert("This country doesn't have prediction: Available countries are: " + locations_predicted); } else{ if (show_prediction == true){ median_prediction.visible = true band_low.visible = true band_high.visible = true prediction_cases_line.visble = true const y_range_right_values = [].concat([].slice.call(new_cases_no_Nan), [].slice.call(total_deaths)) y_range_left.setv({"start": -0.05*Math.max.apply(Math, total_cases_prediction), "end": 1.1 * Math.max.apply(Math, total_cases_prediction)}) y_range_right.setv({"start": -0.05*Math.max.apply(Math, y_range_right_values) * Math.max.apply(Math, total_cases_prediction) / Math.max.apply(Math, cases_no_Nan), "end": 1.1*Math.max.apply(Math, y_range_right_values) * Math.max.apply(Math, total_cases_prediction) / Math.max.apply(Math, cases_no_Nan)}) x_range.setv({"start": Math.min.apply(Math, date_prediction), "end": 1.0001*Math.max.apply(Math, date_prediction)}) } else{ median_prediction.visible = false band_low.visible = false band_high.visible = false prediction_cases_line.visble = false const y_range_right_values = [].concat([].slice.call(new_cases_no_Nan), [].slice.call(total_deaths)) y_range_left.setv({"start": -0.05*Math.max.apply(Math, cases_no_Nan), "end": 1.1*Math.max.apply(Math, cases_no_Nan)}) y_range_right.setv({"start": -0.05*Math.max.apply(Math, y_range_right_values), "end": 1.1*Math.max.apply(Math, y_range_right_values)}) x_range.setv({"start": Math.min.apply(Math, date), "end": 1.0001*Math.max.apply(Math, date)}) } } """, ) button_prediction.js_on_click(callback_button) callback_slider = bkm.CustomJS( args=dict( source=source, source_prediction=source_prediction, source_all_prediction=source_all_prediction, source_prediction_end_date=source_prediction_end_date, select=select, prediction_cases_line=prediction_cases_line, slider=slider, button_click_count=button_click_count, x_range=p.x_range, y_range_left=p.y_range, y_range_right=p.extra_y_ranges["Number of deaths"], ), code=""" // function to get unique value of an array const unique = (value, index, self) => { return self.indexOf(value) === index } var slider_value = slider.value var country = select.value var date_prediction = source_prediction.data['date'] var date_str = source_prediction.data['date_str'] var date_end_prediction = source_prediction.data['date_end_train'] var quantile_1 = source_prediction.data['25%']; var quantile_2 = source_prediction.data['median'] var quantile_3 = source_prediction.data['75%'] var new_cases = source_prediction.data['derivative']; var median_prediction = source_prediction.data['median_display'] var unique_end_prediction = date_end_prediction.filter(unique) var show_prediction = (button_click_count.data.clicks % 2) == 1 var locations_predicted = source_all_prediction.data['location'].filter(unique) if (show_prediction == true && locations_predicted.includes(country)){ var new_date_prediction = [] var new_date_str = [] var new_date_end_prediction = [] var new_quantile_1 = [] var new_quantile_2 = [] var new_quantile_3 = [] var new_new_cases = [] var new_median_prediction = [] for(var i=0; i < quantile_1.length; i++){ if(date_end_prediction[i]==unique_end_prediction[slider.end - slider_value]){ new_date_prediction.push(date_prediction[i]) new_date_str.push(date_str[i]) new_date_end_prediction.push(date_end_prediction[i]) new_quantile_1.push(quantile_1[i]); new_quantile_2.push(quantile_2[i]); new_quantile_3.push(quantile_3[i]); new_new_cases.push(new_cases[i]); new_median_prediction.push(median_prediction[i]); } } source_prediction_end_date.data['date']=new_date_prediction source_prediction_end_date.data['date_str']=new_date_str source_prediction_end_date.data['date_end_train']=new_date_end_prediction source_prediction_end_date.data['25%']=new_quantile_1; source_prediction_end_date.data['median']=new_quantile_2; source_prediction_end_date.data['75%']=new_quantile_3; source_prediction_end_date.data['derivative']=new_new_cases; source_prediction_end_date.data['median_display']=new_median_prediction; source_prediction_end_date.change.emit(); var date_prediction = source_prediction_end_date.data['date']; var total_cases_prediction = source_prediction_end_date.data['75%']; const new_cases_no_Nan = new_cases.filter(function (value) { return !Number.isNaN(value); }); const cases_no_Nan = quantile_2.filter(function (value) { return !Number.isNaN(value); }); // y_range_left.setv({"start": -0.05*Math.max.apply(Math, total_cases_prediction), "end": 1.1*Math.max.apply(Math, total_cases_prediction)}) // x_range.setv({"start": Math.min.apply(Math, date_prediction), "end": 1.0001*Math.max.apply(Math, date_prediction)}) } """, ) slider.js_on_change("value", callback_slider) p.legend.location = "top_left" p.legend.click_policy = "mute" return select, button_prediction, slider, p
def add_numerical_filter(self, filter_mode='>=', title='Value', numeric_name='Altitude', step=50, height_policy='min', callback_policy='value_throttled', callback_class=None, **kwargs): """ Add a Numerical Filter to the Canvas Parameters ---------- filter_mode: str (default: >=) The operator that the filter will use on the loaded dataset (allowed operators: '<', '<=', '>', '>=', '==', '!=', 'range') title: str (default: 'Value') The title of the categorical filter numeric_name: str (default: ```'Altitude'```) The column name of the loaded dataset that contains the numeric information step: float (default: 50) The step in which the filter will move within the numeric range of the dataset. height_policy: str (default: 'min') Describes how the component should maintain its height (accepted values: 'auto', 'fixed', 'fit', 'min', 'max') From: https://docs.bokeh.org/en/1.1.0/docs/reference/models/layouts.html#bokeh.models.layouts.LayoutDOM.height_policy callback_policy: str (default: 'value_throttled') Describes when the callback will be triggered. If callback_policy == 'value', the callback will be fired with each change, while if callback_policy == 'value_throttled' the callback will be executed only when the value is set (i.e., on mouseup). callback_class: callbacks.BokehFilters (default: None) Allows custom callback methods to be set. If None, the baseline callback method is used. **kwargs: Dict Other parameters related to the filter creation """ kwargs.pop('value', None) if filter_mode not in list(ALLOWED_FILTER_OPERATORS.keys()): raise ValueError(f'filter_mode must be one of the following: {list(ALLOWED_FILTER_OPERATORS.keys())}') start, end = self.data[numeric_name].agg([np.min, np.max]) if filter_mode != 'range': # value = start if value is None else value value = start num_filter = bokeh_mdl.Slider(start=start, end=end, step=step, value=value, title=title, height_policy=height_policy, **kwargs) else: # value = (start, end) if value is None else value value = (start, end) num_filter = bokeh_mdl.RangeSlider(start=start, end=end, step=step, value=value, title=title, height_policy=height_policy, **kwargs) if callback_class is None: class Callback(callbacks.BokehFilters): def __init__(self, vsn_instance, widget): super().__init__(vsn_instance, widget) def callback(self, attr, old, new): self.callback_filter_data() num_value = new new_pts = self.get_data() if filter_mode == 'range': new_pts = new_pts.loc[new_pts[numeric_name].between(num_value[0], num_value[1], inclusive=True)] else: new_pts = new_pts.loc[ALLOWED_FILTER_OPERATORS[filter_mode](new_pts[numeric_name], num_value)] self.callback_prepare_data(new_pts, self.widget.id==self.vsn_instance.aquire_canvas_data) callback_class = Callback num_filter.on_change(callback_policy, callback_class(self, num_filter).callback) self.widgets.append(num_filter)
def __init__(self, phase_y_range=(-2.5, 2.5), potential_y_range=(-2.5, 2.5)): phi, b, d_omega = sp.symbols('phi, b, Delta_omega') self.state_symbol = phi self.param_symbols = b, d_omega self.symbolic_eqn = d_omega - sp.sin(phi) - 2 * b * sp.sin(2 * phi) self.numeric_eqn = sp.lambdify((phi, b, d_omega), self.symbolic_eqn) self.symbolic_slope = sp.diff(self.symbolic_eqn, self.state_symbol) self.numeric_slope = sp.lambdify((phi, b, d_omega), self.symbolic_slope) self.symbolic_pot = -sp.integrate(self.symbolic_eqn, self.state_symbol) self.numeric_pot = sp.lambdify((phi, b, d_omega), self.symbolic_pot) self.roots = self.get_roots() self.phase_plot, self.pot_plot = self.init_plots( phase_y_range, potential_y_range) # Set up empty DataSources. As much as possible, these are shared between the plots. self.line_source = models.ColumnDataSource(data=dict( x=[], phase=[], v=[], )) self.attractor_source = models.ColumnDataSource(data=dict( x=[], phase=[], v=[], )) self.repeller_source = models.ColumnDataSource(data=dict( x=[], phase=[], v=[], )) self.half_source = models.ColumnDataSource(data=dict( x=[], phase=[], v=[], )) self.arrow_source = models.ColumnDataSource(data=dict( x=[], angle=[], )) # Draw all the glyphs. for plot, y in [(self.phase_plot, 'phase'), (self.pot_plot, 'v')]: if y == 'v': y_circle = 'v_circle' else: y_circle = y plot.line( x='x', y=y, source=self.line_source, line_width=LINE_WIDTH, ) plot.circle( x='x', y=y_circle, source=self.attractor_source, size=CIRCLE_SIZE, ) plot.circle( x='x', y=y_circle, source=self.repeller_source, size=CIRCLE_SIZE, fill_color=None, line_width=CIRCLE_LINE_WIDTH, ) plot.circle( x='x', y=y_circle, source=self.half_source, size=CIRCLE_SIZE, fill_color=None, line_width=CIRCLE_LINE_WIDTH, ) plot.wedge( x='x', y=y_circle, source=self.half_source, radius=CIRCLE_SIZE / 2, start_angle=-np.pi / 2, end_angle=np.pi / 2, radius_units='screen', line_color=None, ) self.phase_plot.triangle( x='x', y=0, angle='angle', source=self.arrow_source, size=ARROW_SIZE, color='black', ) self.b_slider = models.Slider( start=self.b_values[0], end=self.b_values[-1], step=self.b_values[1] - self.b_values[0], value=0.5, title='b', width=FIGURE_WIDTH // 2, ) self.d_omega_slider = models.Slider( start=self.d_omega_values[0], end=self.d_omega_values[-1], step=self.d_omega_values[1] - self.d_omega_values[0], value=0, title='Δω', width=FIGURE_WIDTH // 2, ) self.b_slider.on_change('value', self.on_slider_change) self.d_omega_slider.on_change('value', self.on_slider_change) self.update_sources()