class radiobutton(): def __init__(self, widget_lst, default_value, label, inline=True): self.widget_lst = widget_lst self.radiobutton = None self.initialize(default_value, label, inline) def initialize(self, default_value, label, inline): self.radiobutton = RadioGroup(active=default_value, labels=label, inline=inline) self.widget_lst.append(self.radiobutton) def add_callback(self, callback): self.radiobutton.on_click(callback)
def file_callback(attr, old, new): global raw_df, hist_df loaded_file_div.text = '<font color=#006699>' + "Loaded file" + ': </font>' + \ file_source.data['file_name'][0] raw_contents = file_source.data['file_contents'][0] # remove the prefix that JS adds prefix, b64_contents = raw_contents.split(",", 1) file_contents = base64.b64decode(b64_contents).decode() # read in new rawdata raw_df = esp8266_aux.preprocess_csv_string(file_contents) MAC_list = esp8266_aux.get_MAC_list(raw_df) # replace old MAC list by a new list. mac_radio_group_column.children.pop() mac_radio_group = RadioGroup(labels=MAC_list, active=0) mac_radio_group.on_click(mac_radio_group_callback) mac_radio_group_column.children.append(mac_radio_group) # calculate histogram for the first MAC hist_df = time_series_histogram.histogram_of_time( raw_df, MAC_list[0], time_window_length=time_window) histogram_line.data_source.data = ColumnDataSource(hist_df).data
class radiobutton(): def __init__(self, widget_lst, default_value, label, inline=True): self.label = label self.default_value = default_value self.inline = inline self.radiobutton = None self.callback = None # self.initialize(default_value, label, inline) widget_lst.append(self) def initialize(self, widget_lst): self.radiobutton = RadioGroup(active=self.default_value, labels=self.label, inline=self.inline) widget_lst.append(self.radiobutton) if self.callback is not None: self.radiobutton.on_click(self.callback) def add_callback(self, callback): self.callback = callback if self.radiobutton is not None: self.radiobutton.on_click(self.callback)
for i in range(100): line3.append( p.line(x, [obj**2 + np.random.normal() for obj in x], name='line3')) line1.glyph.line_alpha = 0 line2.glyph.line_alpha = 0 for line in line3: line.glyph.line_alpha = 0 def my_radio_handler(new): line1.glyph.line_alpha = 0 line2.glyph.line_alpha = 0 for line in line3: line.glyph.line_alpha = 0 if new == 0: line1.glyph.line_alpha = 100 elif new == 1: line2.glyph.line_alpha = 100 elif new == 2: for line in line3: time.sleep(0.1) line.glyph.line_alpha = 1 else: print('Error') radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(my_radio_handler) curdoc().add_root(column(widgetbox(radio_group), p))
''' Created on 29 May 2017 @author: jermz ''' from bokeh.plotting import Figure from bokeh.models.layouts import VBox from bokeh.models.widgets import RadioGroup from bokeh.io import curdoc fig1 = Figure() fig1.circle(x=[1,2], y=[3,4]) fig2 = Figure() fig2.circle(x=[100,200], y=[200, 1000]) def switch_plots(selected_plot): main_box.children = layouts[selected_plot] layout_picker = RadioGroup(labels=['Layout1', 'Layout2']) layout_picker.on_click(switch_plots) layout1 = VBox(children=[fig1]) layout2 = VBox(children=[fig2]) layouts = [[layout1], [layout2]] main_box = VBox(children=[layout1]) curdoc().add_root(main_box) curdoc().add_root(layout_picker)
dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())")) dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", menu=menu) dropdown_disabled.on_click(lambda value: print('dropdown_disabled: %s' % value)) dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())")) #dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default") #dropdown_split.on_click(lambda value: print('dropdown_split: %s' % value)) #dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())")) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(lambda value: print('checkbox_group: %s' % value)) checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())")) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(lambda value: print('radio_group: %s' % value)) radio_group.js_on_click(CustomJS(code="console.log('radio_group: ' + this.active, this.toString())")) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(lambda value: print('checkbox_button_group: %s' % value)) checkbox_button_group.js_on_click(CustomJS(code="console.log('checkbox_button_group: ' + this.active, this.toString())")) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click(lambda value: print('radio_button_group: %s' % value)) radio_button_group.js_on_click(CustomJS(code="console.log('radio_button_group: ' + this.active, this.toString())")) widgetBox = WidgetBox(children=[ button, button_disabled, toggle_inactive, toggle_active, dropdown, dropdown_disabled, #dropdown_split, checkbox_group, radio_group,
t_selected = bool(active) update_conf_levels(0, 0, 0) ################################################ update_text_button_sample_CLT(0, 0, 0) update_text_button_sample_population(0, 0, 0) update_text_button_sample_bootstrap(0, 0, 0) update_distribution_type(0, 0, 0) ################################################ select_distribution.on_change('value', update_distribution_type) button_sample_population.on_click(take_single_sample_population) button_sample_bootstrap.on_click(take_bootstrap_samples) button_sample_CLT.on_click(take_many_samples_for_CLT) z_vs_t_group.on_click(update_zt) slider_bandwidth.on_change('value', draw_kde) slider_CL_CLT.on_change('value', update_conf_levels) slider_CL_bootstrap.on_change('value', update_conf_levels_boot) slider_sample_size_population.on_change('value', update_text_button_sample_population) slider_sample_size_population.on_change('value', update_text_button_sample_CLT) slider_repetitions_CLT.on_change('value', update_text_button_sample_CLT) slider_sample_size_bootstrap.on_change('value', update_text_button_sample_bootstrap) for slider in [slider_param1, slider_param2]: slider.on_change('value', update_distribution_type) ################################################ p_comparison = figure(title="Normal vs t-distribution",
"Whole year", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], active=0) def monthSel(active): if active == 0: p2.x_range.start = MonthTimestamps[0] p2.x_range.end = MonthTimestamps[12] else: p2.x_range.start = MonthTimestamps[active - 1] p2.x_range.end = MonthTimestamps[active] radio_group.on_click(monthSel) dPickWidget = widgetbox(button) blank = widgetbox(radio_group, width=400) p1Widget = widgetbox(checkbox1) p2Widget = widgetbox(checkbox2) l = layout([[ column(slider, row(datePickStart, datePickEnd, height=210), dPickWidget, width=400), p1, p1Widget ], [blank, p2, p2Widget]]) legend1 = Legend(legends=[("Mon", [l_mon]), ("Tue", [l_tue]), ("Wed", [l_wed]), ("Thu", [l_thu]), ("Fri", [l_fri]), ("Sat", [l_sat]), ("Sun", [l_sun]), ("Deviation", [l_std])], location=(0, -5))
# allow for playing and pausing duing the animations and pre animation if play_button.label == '► Play': play_button.label = '❚❚ Pause' curdoc().add_periodic_callback( play_update, play_speed_vals[play_speed_radiogroup.active]) else: play_button.label = '► Play' curdoc().remove_periodic_callback(play_update) # add widgets time_gran_radio_title = Div(text="""<b>Time Granularity:</b>""") time_gran_radio = RadioGroup(labels=['Per Email', 'Per Hour', 'Per Day'], active=0, width=100) # MUST START AT 0 FOR GLBL time_gran_radio.on_click(change_time_gran) slider_titles = ['Chronological Email Number:', 'Hour:', 'Day:'] time_slider = Slider(start=1, end=20, value=1, step=1, title=slider_titles[time_gran_radio.active], width=500) time_slider.on_change('value', update_arrows) play_speeds_radio_title = Div(text="""<b>Play Speed:</b>""") play_speed_vals = [750, 500, 250] play_speeds = [ 'Slow ({}ms delay)'.format(play_speed_vals[0]), 'Medium ({}ms delay)'.format(play_speed_vals[1]),
def tab_learning(): config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) select_data = Select(title="Data:", value="", options=[]) select_model = Select(title="Model script:", value="", options=[]) data_descriptor = Paragraph(text=""" Data descriptor """, width=250, height=250) model_descriptor = Paragraph(text=""" Model descriptor """, width=250, height=250) select_grid = gridplot([[select_data, select_model], [data_descriptor, model_descriptor]]) problem_type = RadioGroup(labels=["Classification", "Regression"], active=0) def problem_handler(new): if(new == 0): select_data.options = glob.glob('./np/Classification/*.npy') select_model.options = list(filter(lambda x: 'model_' in x, dir(classification))) elif(new == 1): select_data.options = glob.glob('./np/Regression/*.npy') select_model.options = list(filter(lambda x: 'model_' in x, dir(regression))) problem_type.on_click(problem_handler) learning_rate = TextInput(value="0.01", title="Learning rate") epoch_size = Slider(start=2, end=200, value=5, step=1, title="Epoch") batch_size = Slider(start=16, end=256, value=64, step=1, title="Batch") model_insert = TextInput(value="model", title="Model name") opeimizer = Select(title="Optimizer:", value="", options=["SGD", "ADAM", "RMS"]) hyper_param = gridplot([[learning_rate], [epoch_size], [batch_size], [opeimizer], [model_insert]]) xs = [[1], [1]] ys = [[1], [1]] label = [['Train loss'], ['Validation loss']] color = [['blue'], ['green']] total_loss_src = ColumnDataSource(data=dict(xs=xs, ys=ys, label=label, color=color)) plot2 = Figure(plot_width=500, plot_height=300) plot2.multi_line('xs', 'ys', color='color', source=total_loss_src, line_width=3, line_alpha=0.6) TOOLTIPS = [("loss type", "@label"), ("loss value", "$y")] plot2.add_tools(HoverTool(tooltips=TOOLTIPS)) t = Title() t.text = 'Loss' plot2.title = t acc_src = ColumnDataSource(data=dict(x=[1], y=[1], label=['R^2 score'])) plot_acc = Figure(plot_width=500, plot_height=300, title="Accuracy") plot_acc.line('x', 'y', source=acc_src, line_width=3, line_alpha=0.7, color='red') TOOLTIPS = [("Type ", "@label"), ("Accuracy value", "$y")] plot_acc.add_tools(HoverTool(tooltips=TOOLTIPS)) acc_list = [] notifier = Paragraph(text=""" Notification """, width=200, height=100) def learning_handler(): print("Start learning") del acc_list[:] tf.reset_default_graph() K.clear_session() data = np.load(select_data.value) data = data.item() print("data load complete") time_window = data.get('x').shape[-2] model_name = model_insert.value model_name = '(' + str(time_window) + ')' + model_name if (problem_type.active == 0): sub_path = 'Classification/' elif (problem_type.active == 1): sub_path = 'Regression/' model_save_dir = './model/' + sub_path + model_name + '/' if not os.path.exists(model_save_dir): os.makedirs(model_save_dir) x_shape = list(data.get('x').shape) print("Optimizer: " + str(opeimizer.value)) print(select_model.value) if (problem_type.active == 0): target_model = getattr(classification, select_model.value) model = target_model(x_shape[-3], x_shape[-2], float(learning_rate.value), str(opeimizer.value), data.get('y').shape[-1]) elif (problem_type.active == 1): target_model = getattr(regression, select_model.value) model = target_model(x_shape[-3], x_shape[-2], float(learning_rate.value), str(opeimizer.value), data.get('y').shape[-1]) notifier.text = """ get model """ training_epochs = int(epoch_size.value) batch = int(batch_size.value) loss_train = [] loss_val = [] train_ratio = 0.8 train_x = data.get('x') train_y = data.get('y') length = train_x.shape[0] print(train_x.shape) data_descriptor.text = "Data shape: " + str(train_x.shape) # model_descriptor.text = "Model layer: " + str(model.model.summary()) val_x = train_x[int(length * train_ratio):] if(val_x.shape[-1] == 1 and not 'cnn' in select_model.value): val_x = np.squeeze(val_x, -1) val_y = train_y[int(length * train_ratio):] train_x = train_x[:int(length * train_ratio)] if (train_x.shape[-1] == 1 and not 'cnn' in select_model.value): train_x = np.squeeze(train_x, -1) train_y = train_y[:int(length * train_ratio)] print(train_x.shape) if('model_dl' in select_model.value): for epoch in range(training_epochs): notifier.text = """ learning -- epoch: """ + str(epoch) hist = model.fit(train_x, train_y, epochs=1, batch_size=batch, validation_data=(val_x, val_y), verbose=1) print("%d epoch's cost: %f" % (epoch, hist.history['loss'][0])) loss_train.append(hist.history['loss'][0]) loss_val.append(hist.history['val_loss'][0]) xs_temp = [] xs_temp.append([i for i in range(epoch + 1)]) xs_temp.append([i for i in range(epoch + 1)]) ys_temp = [] ys_temp.append(loss_train) ys_temp.append(loss_val) total_loss_src.data['xs'] = xs_temp total_loss_src.data['ys'] = ys_temp if (problem_type.active == 0): r2 = hist.history['val_acc'][0] label_str = 'Class accuracy' elif (problem_type.active == 1): pred_y = model.predict(val_x) r2 = r2_score(val_y, pred_y) label_str = 'R^2 score' print("%d epoch's acc: %f" % (epoch, r2)) acc_list.append(np.max([r2, 0])) acc_src.data['x'] = [i for i in range(epoch+1)] acc_src.data['y'] = acc_list acc_src.data['label'] = [label_str for _ in range(epoch + 1)] print(acc_src.data) notifier.text = """ learning complete """ model.save(model_save_dir + model_name + '.h5') notifier.text = """ model save complete """ K.clear_session() elif('model_ml' in select_model.value): notifier.text = """ Machine learning model """ if(train_x.shape[-2] != 1): notifier.text = """ Data include more then one time-frame. \n\n Data will automatically be flatten""" train_x = train_x.reshape([train_x.shape[0], -1]) val_x = val_x.reshape([val_x.shape[0], -1]) ##### shit if (problem_type.active == 0): train_y = np.argmax(train_y, axis=-1).astype(float) print(train_x.shape) print(train_y.shape) model.fit(train_x, train_y) notifier.text = """ Training done """ pred_y = model.predict(val_x) print(pred_y) pickle.dump(model, open(model_save_dir + model_name + '.sav', 'wb')) notifier.text = """ Machine learning model saved """ button_learning = Button(label="Run model") button_learning.on_click(learning_handler) learning_grid = gridplot( [[problem_type], [select_grid, hyper_param, button_learning, notifier], [plot2, plot_acc]]) tab = Panel(child=learning_grid, title='Learning') return tab
def make_document(doc): doc.title = "Hello, world!" df = pd.read_csv(fileName_csv_source) # return dataframe if False: df = df.set_index('date') ''' make a copy of df. therefor changing the source will not affect df. using df in update() will ~reset the source to original values ''' source = ColumnDataSource(data=df) # dict()) columns = [ TableColumn(field="name", title="Employee Name"), TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")), TableColumn(field="years_experience", title="Experience (years)") ] data_table = DataTable(source=source, columns=columns, width=800) # ,row_headers=None) table = widgetbox(data_table, width=880) # def slider_table_update(attr, old, new): # print(attr) # print(old) # print(new) def slider_table_update(): print ("slider update") # adjustment by https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/fPAoHTyMcuQ current = df[df['salary'] <= slider.value].dropna() # df ## source.data = { 'name' : list(current.name), 'salary' : list(current.salary), 'years_experience' : list(current.years_experience) } return None slider = Slider(title="values range", start=0, end=100000, value=21000, step=1, width=800) # slider.on_change('value', lambda attr, old, new: slider_table_update(attr, old, new)) slider.on_change('value', lambda attr, old, new: slider_table_update()) # fig1 = figure(title='Line plot!') #, sizing_mode='scale_width') # fig1.line(x=[1, 2, 3], y=[1, 4, 9]) #, sizing_mode='scale_width') ) # , y_range=(00000, 100000), # fig2.scatter(x=source.data['years_experience'], y=source.data['salary']) # title="scatter example") #, xlabel="xlable", ylabel="ylabel") # plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) selected_tools = 'pan,wheel_zoom,xbox_select,reset' fig2 = figure(title='salary - vs years scatter plot', width=500, height=400, tools='pan, wheel_zoom') fig2.scatter(x='years_experience', y='salary', source=source) # https://stackoverflow.com/questions/34646270/how-do-i-work-with-images-in-bokeh-python # img_path = 'https://bokeh.pydata.org/en/latest/_static/images/logo.png' img_path = join(rel_DATA_DIR,'logoScrnSht.png') # img_path = r'C:\Users\Ran_the_User\Documents\GitHub\TAILOR\bokeh\bokeh_pages\static\logoScrnSht.png' my_print(img_path) x_range = (-20,10) # could be anything - e.g.(0,1) y_range = (20,30) factor = 1.2 figImg = figure(x_range=x_range, y_range=y_range) # figImg = figure(x_range=x_range, y_range=y_range, width=500, height=400) print (img_path) figImg.image_url(url=[img_path], x=x_range[0], y=y_range[1], w=x_range[1]-x_range[0], h=y_range[1]-y_range[0]) # figImg.image_url(url=[img_path], x=x_range[0]/factor, y=(y_range[0]+y_range[1])/2, w=(x_range[1]-x_range[0])/factor, h=(y_range[1]-y_range[0])/factor, anchor="bottom_left") toggle_callback = CustomJS(args=dict(source=source), code=""" var data = source.data; var A = a.value; var k = b.value; var phi = c.value; var B = d.value; var x = data['years_experience'] var y = data['salary'] for (var i = 0; i < x.length; i++) { y[i] =i*2.; } source.change.emit(); """) def isToggleActive(status): print("toggle case") print(status) def on_chkbx_clicked(list_of_checked_options): print("chkbx case") print(list_of_checked_options) def on_radio_clicked(checked_option_ndx): print("cradio case") print(checked_option_ndx) def on_text_input_change(attr, old, new): print("Previous label: " + old) print("attribute : ", attr) print("Updated label: " + new) # check if new is path. if sow - get files list # print(base_path_text_Input.value, file_attr_text_Input.value) ret = fH.list_files_in_path(base_path=base_path_text_Input.value, filter=file_attr_text_Input.value) col1 = [itm[0] for itm in ret] col2 = [itm[1] for itm in ret] col3 = [itm[2] for itm in ret] sourceFilteredFiles.data ={ 'name' : list(col1), 'path' : list(col2), 'mod date' : list(col3) } return None def fTable_clicked(attr, old, new): # print("fTAble clicked", attr) # print(old) # print(new) # https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/jGHbTWVqH6U # https: // github.com / bokeh / bokeh / wiki / Filterable - Data - Source try: selected_rows_indeces = sourceFilteredFiles.selected["1d"]["indices"] print("selected_rows_indeces",selected_rows_indeces) # print(sourceFilteredFiles.data) for ndx in selected_rows_indeces: selected_files_str = sourceFilteredFiles.data['mod date'][ndx] print (selected_files_str) except IndexError: print("index error") pass # relevant output is : selected_rows_indeces template = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>""" sourceFilteredFiles = ColumnDataSource(data=pd.DataFrame()) # dict()) files_table_columns = [ TableColumn(field="name", title="Name"), TableColumn(field="path", title="Path"), TableColumn(field="mod date", title="modification date", formatter=HTMLTemplateFormatter(template=template)) ] # edit dataTable: https://stackoverflow.com/questions/32321841/how-to-add-a-callback-to-bokeh-datatable # https://bokeh.pydata.org/en/latest/docs/reference/model.html#bokeh.model.Model # https: // bokeh.pydata.org / en / latest / docs / reference / models / widgets.tables.html files_table = DataTable(source=sourceFilteredFiles, columns=files_table_columns, width=900, fit_columns=True) # files_table.on_click(fTable_clicked) print(sourceFilteredFiles.to_json(include_defaults=True)) print(files_table.to_json(include_defaults=True)) fTable = widgetbox(files_table, width=980) sourceFilteredFiles.on_change('selected', fTable_clicked) # toggle = Toggle(label='Some on/off', button_type='success') toggle = Button(label='change table by source', button_type='success', callback=toggle_callback) # toggleLayout = layout([toggle]) # base_path_str = os.path.curdir # relative path base_path_str = os.path.abspath(os.path.curdir) # absolute format base_path_text_Input = TextInput(value=base_path_str, title="base path for files:") base_path_text_Input.on_change("value", on_text_input_change) file_attr_str = '.csv' file_attr_text_Input = TextInput(value=file_attr_str, title="files attribute for search") file_attr_text_Input.on_change("value", on_text_input_change) checkbox = CheckboxGroup(labels=['foo', 'bar', 'baz']) radio = RadioGroup(labels=['2000', '2010', '2020']) # toggle.on_click(isToggleActive) checkbox.on_click(on_chkbx_clicked) radio.on_click(on_chkbx_clicked) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) def set_vbar(): fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] fig3 = figure(x_range=fruits, plot_height=250, title="Fruit Counts", toolbar_location=None, tools="") fig3.vbar(x=fruits, top=[5, 3, 4, 2, 4, 6], width=0.9) fig3.xgrid.grid_line_color = None fig3.y_range.start = 0 return fig3 def event_chart(): factors = ["a","b","c,","d"] x = [24.3, -22.3, -25, 6] LineColor=["green" if a>=0 else "red" for a in x] Tooltips = [ ("index", "$index"), ("(x,y)", "($x, $y)") # ("radius", "@radius"), # ("fill color", "$color[hex, swatch]:fill_color"), # ("x", "@x"), # ("bar", "@bar"), ] dots_fig = figure(title="exapmple", y_range = factors, x_range = [-30,30], toolbar_location="below", toolbar_sticky=False, \ tools='lasso_select, poly_select, undo, redo, reset') # , \ # tooltips=Tooltips) dots_fig.segment(0, factors, x, factors, line_width=2, line_color=LineColor) c1 = dots_fig.circle(x, factors, size=15, fill_color="orange", line_width=3, line_color=LineColor) # tool = BoxEditTool(renderers=[c1]) # ERROR:bokeh.core.validation.check:E-1014 (INCOMPATIBLE_BOX_EDIT_RENDERER): BoxEditTool renderers may only reference Rect glyph models: Circle glyph type(s) found. tool2 = BoxSelectTool(dimensions="width") # To make a multiple selection, press the SHIFT key. To clear the selection, press the ESC key # dots_fig.add_tools(tool) # disappears the points.. dots_fig.add_tools(tool2) dots_fig.add_tools(CrosshairTool(dimensions='height')) return dots_fig # fig2.axis.visible = False # fig2.image phase1 = column(table, slider) phase2 = row(phase1, fig2) phase3 = row(event_chart(), set_vbar()) phase4 = column(phase2, phase3 , checkbox, radio) # phase5 = bk_example.bk_example() # doc.add_root(phase5) # doc.add_root(phase4) tab1 = Panel(child=phase4, title="phase4 part") # doc.add_root(toggle) # doc.add_root(figImg) # secPanelLy = column(toggle, figImg, checkbox_button_group, base_path_text_Input, file_attr_text_Input, fTable) secPanelLy = column(base_path_text_Input, file_attr_text_Input, fTable) tab2 = Panel(child=secPanelLy, title="other parts", closable=False) tabs = Tabs(tabs=[ tab2, tab1 ]) doc_add_root(doc, tabs) # if __name__!='__main__': # print("doc : ", str(doc)) # print("name : ",__name__) # doc().add_root(tabs) # else: # print("doc : ", str(doc)) # doc.add_root(tabs) toggle_callback.args['a']=slider toggle_callback.args['b']=toggle toggle_callback.args['c']=checkbox toggle_callback.args['d']=radio slider_table_update()
], active=5) def callback_radio(new): vars = ['Age', 'Height'] ps = [ 'Extra-Lightweight', 'Half-Middleweight', 'Lightweight', 'Heavyweight', 'Half-Heavyweight', 'Middleweight', 'Half-Lightweight' ] var = vars[radio_var.active] p = ps[radio_poid.active] data1.data.update(dataset_graphe1(df_judo, var, p)) radio_var.on_click(callback_radio) radio_poid.on_click(callback_radio) # Création du jeu de données pour le graphe df_graphe1 = dataset_graphe1(df_judo, "Age", "Middleweight") data1 = ColumnDataSource(data=df_graphe1) # Graphique 1 p1 = figure(title="Fréquence", y_axis_label="Count", x_axis_label="Variable") p1.title.text_color = "Blue" p1.title.border_line_color = "green" l0 = p1.line(x='Var', y='Density', source=data1, color='black') l1 = p1.line(x='Var', y='Density_H', source=data1, color='blue') l2 = p1.line(x='Var', y='Density_F', source=data1, color='red')
print(new) # Get a distribution plot together for distances distances = figure(plot_height=300, plot_width=800, title="Distribution of Distances for All Hikes") distance_counts, distance_bins = ufunc.update_distances( list(trail_stats.find())) dist_source = ColumnDataSource( data=dict(bins=distance_bins, counts=distance_counts)) distances.vbar(x='bins', bottom=0, top='counts', width=0.5, source=dist_source) # Set up the radio buttons for switching between data sets buttons = RadioGroup(labels=['All', 'Solo', 'Group', 'After Work'], active=0) buttons.on_click(change_data_set) # Read trail stats into pandas dataframe for text description ts_frame = pd.DataFrame(list(trail_stats.find())) stats_box = PreText(name="Summary", text=ts_frame.describe().to_string(), width=1200) # Data source for all line_graphs lg_source = ColumnDataSource(data=dict( distances=[trail['Distance'] for trail in list(trail_stats.find())], dates=sorted([ datetime.strptime(trail['Date'], '%Y/%m/%d %H:%M') for trail in list(trail_stats.find()) ]), energy=[trail['Energy'] for trail in list(trail_stats.find())],
select_chrg_type = Select(title="Charge Type", value="Charge", options=["Charge", "Discharge", "Cycle", "Re-Peak", "AutoCharge", "Balance Charge", "Fast Charge", "Storage"]) def select_chrg_type_handler(attr, old, new): settings['chrg_type'] = new select_chrg_type.on_change('value', select_chrg_type_handler) maxmah_slider = Slider(start=50, end=24000, value=1, step=50, title="Bat. Specified Capacity, mah") def maxmah_handler(attr, old, new): settings['nominal_mah'] = new maxmah_slider.on_change('value', maxmah_handler) DC_radio_group = RadioGroup(labels=["Discharge/Charge", "Charge/Discharge"], active=0) def DC_radio_handler(new): settings['DC'] = new DC_radio_group.on_click(DC_radio_handler) select_cells = Select(title = "No. of Cells", value ="4", options = [str(i) for i in range(1,13)]) def select_cells_handler(attr, old, new): settings['cells'] = new select_cells.on_change('value', select_cells_handler) #imax discharge/charge # of cycles; imax limit is 5 #no way to read this from imax only shows up in set up packet select_cycles = Select(title = "Cycles", value ="1", options = [str(i) for i in range(1,6)]) def select_cycles_handler(attr, old, new): settings['cycles'] = new select_cycles.on_change('value', select_cycles_handler) text_input = TextInput(value="Enter run information", title="Run Info::") def text_input_handler(attr, old, new):
# image_stack = hv.DynamicMap(load_image, kdims=['time', 'p'], streams=[Param()]) #plot = regrid(image_stack)# * gf.coastline(plot=dict(scale='10m')) #.redim.range(time=(0,3)) gf.coastline.set_param("extents", (90, -18, 154, 30)) coastline = gf.coastline(plot=dict(scale='50m')) #regridded_map = regrid(load_image(0, params[0])) data_map = hv.DynamicMap(load_image, streams=[Param()]) regridded_map = regrid(data_map) print("coastline: %s, regridded_map %s" % (coastline, regridded_map)) plot = regridded_map * coastline print("plot: %s" % (plot)) print(plot.id) def select_param(param=params[0]): data_map.event(p=param) def select_param_handler(index): select_param(params[index]) radio_group = RadioGroup(labels=params, active=0) radio_group.on_click(select_param_handler) if not is_notebook: hvplot = renderer.get_plot(plot) curdoc().add_root(column(hvplot.state, radio_group)) plot
toggle = Toggle(label="Toggle button", type="success") toggle.on_click(toggle_handler) menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu) dropdown.on_click(dropdown_handler) menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")] split = Dropdown(label="Split button", type="danger", menu=menu, default_action="baz") split.on_click(split_handler) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(checkbox_group_handler) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(radio_group_handler) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(checkbox_button_group_handler) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click(radio_button_group_handler) vbox = VBox(children=[button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group]) document.add(vbox) session.store_document(document) if __name__ == "__main__": link = session.object_link(document.context) print("Please visit %s to see the plots" % link)
def make_document(doc): doc.title = "Hello, world!" df = pd.read_csv(fileName) # return dataframe if False: df = df.set_index('date') ''' make a copy of df. therefor changing the source will not affect df. using df in update() will ~reset the source to original values ''' source = ColumnDataSource(data=df) # dict()) columns = [ TableColumn(field="name", title="Employee Name"), TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")), TableColumn(field="years_experience", title="Experience (years)") ] data_table = DataTable(source=source, columns=columns, width=800) # ,row_headers=None) table = widgetbox(data_table, width=880) def slider_table_update(attr, old, new): print ("slider update") print(attr) print(old) print(new) current = df[df['salary'] <= slider.value].dropna() # df ## source.data = { 'name' : current.name, 'salary' : current.salary, 'years_experience' : current.years_experience } return None slider = Slider(title="values range", start=0, end=100000, value=21000, step=1, width=800) slider.on_change('value', lambda attr, old, new: slider_table_update(attr, old, new)) # fig1 = figure(title='Line plot!') #, sizing_mode='scale_width') # fig1.line(x=[1, 2, 3], y=[1, 4, 9]) #, sizing_mode='scale_width') ) # , y_range=(00000, 100000), # fig2.scatter(x=source.data['years_experience'], y=source.data['salary']) # title="scatter example") #, xlabel="xlable", ylabel="ylabel") # plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) selected_tools = 'pan,wheel_zoom,xbox_select,reset' fig2 = figure(title='salary - vs years scatter plot', width=500, height=400, tools='pan, wheel_zoom') fig2.scatter(x='years_experience', y='salary', source=source) # https://stackoverflow.com/questions/34646270/how-do-i-work-with-images-in-bokeh-python # img_path = 'https://bokeh.pydata.org/en/latest/_static/images/logo.png' img_path = join(DATA_DIR,'logoScrnSht.png') # img_path = r'C:\Users\Ran_the_User\Documents\GitHub\TAILOR\bokeh\bokeh_pages\static\logoScrnSht.png' x_range = (-20,10) # could be anything - e.g.(0,1) y_range = (20,30) factor = 1.2 figImg = figure(x_range=x_range, y_range=y_range) # figImg = figure(x_range=x_range, y_range=y_range, width=500, height=400) print (img_path) figImg.image_url(url=[img_path], x=x_range[0], y=y_range[1], w=x_range[1]-x_range[0], h=y_range[1]-y_range[0]) # figImg.image_url(url=[img_path], x=x_range[0]/factor, y=(y_range[0]+y_range[1])/2, w=(x_range[1]-x_range[0])/factor, h=(y_range[1]-y_range[0])/factor, anchor="bottom_left") toggle_callback = CustomJS(args=dict(source=source), code=""" var data = source.data; var A = a.value; var k = b.value; var phi = c.value; var B = d.value; var x = data['years_experience'] var y = data['salary'] for (var i = 0; i < x.length; i++) { y[i] =i*2.; } source.change.emit(); """) def isToggleActive(status): print("toggle case") print(status) def on_chkbx_clicked(list_of_checked_options): print("chkbx case") print(list_of_checked_options) def on_radio_clicked(checked_option_ndx): print("cradio case") print(checked_option_ndx) # toggle = Toggle(label='Some on/off', button_type='success') toggle = Button(label='change table by source', button_type='success', callback=toggle_callback) # toggleLayout = layout([toggle]) checkbox = CheckboxGroup(labels=['foo', 'bar', 'baz']) radio = RadioGroup(labels=['2000', '2010', '2020']) # toggle.on_click(isToggleActive) checkbox.on_click(on_chkbx_clicked) radio.on_click(on_chkbx_clicked) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) def set_vbar(): fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] fig3 = figure(x_range=fruits, plot_height=250, title="Fruit Counts", toolbar_location=None, tools="") fig3.vbar(x=fruits, top=[5, 3, 4, 2, 4, 6], width=0.9) fig3.xgrid.grid_line_color = None fig3.y_range.start = 0 return fig3 def event_chart(): factors = ["a","b","c,","d"] x = [24.3, -22.3, -25, 6] LineColor=["green" if a>=0 else "red" for a in x] Tooltips = [ ("index", "$index"), ("(x,y)", "($x, $y)") # ("radius", "@radius"), # ("fill color", "$color[hex, swatch]:fill_color"), # ("x", "@x"), # ("bar", "@bar"), ] dots_fig = figure(title="exapmple", y_range = factors, x_range = [-30,30], toolbar_location="below", toolbar_sticky=False, \ tools='lasso_select, poly_select, undo, redo, reset') # , \ # tooltips=Tooltips) dots_fig.segment(0, factors, x, factors, line_width=2, line_color=LineColor) c1 = dots_fig.circle(x, factors, size=15, fill_color="orange", line_width=3, line_color=LineColor) # tool = BoxEditTool(renderers=[c1]) tool2 = BoxSelectTool(dimensions="width") # To make a multiple selection, press the SHIFT key. To clear the selection, press the ESC key # dots_fig.add_tools(tool) # disappears the points.. dots_fig.add_tools(tool2) dots_fig.add_tools(CrosshairTool(dimensions='height')) return dots_fig # fig2.axis.visible = False # fig2.image phase1 = column(table, slider) phase2 = row(phase1, fig2) phase3 = row(event_chart(), set_vbar()) phase4 = column(phase2, phase3 , checkbox, radio) # phase5 = bk_example.bk_example() # doc.add_root(phase5) # doc.add_root(phase4) tab1 = Panel(child=phase4, title="phase4 part") # doc.add_root(toggle) # doc.add_root(figImg) secPanelLy = column(toggle, figImg, checkbox_button_group) tab2 = Panel(child=secPanelLy, title="other parts", closable=False) tabs = Tabs(tabs=[ tab1, tab2 ]) if __name__!='__main__': print("doc : ", doc) print("name : ",__name__) doc().add_root(tabs) else: doc.add_root(tabs) # doc.add_root(event_chart_example()) toggle_callback.args['a']=slider toggle_callback.args['b']=toggle toggle_callback.args['c']=checkbox toggle_callback.args['d']=radio
dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu) dropdown.on_click(dropdown_handler) menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")] split = Dropdown(label="Split button", type="danger", menu=menu, default_value="baz") split.on_click(split_handler) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(checkbox_group_handler) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(radio_group_handler) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click(checkbox_button_group_handler) radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) radio_button_group.on_click(radio_button_group_handler) vbox = VBox(children=[ button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group ]) document = Document()
} else { alert('FileReader is not supported in this browser'); } } input.click(); """ load_file_button = Button(label="Load Data From CSV File", button_type='success', callback=CustomJS(args=dict(file_source=file_source), code=load_file_js)) loaded_file_div = Div(text="Loaded file: None") mac_radio_group = RadioGroup(labels=MAC_list, active=0) mac_radio_group.on_click(mac_radio_group_callback) time_window_text_input = TextInput(title="Time Window", value=str(time_window)) time_window_text_input.on_change('value', time_window_text_input_callback) # --- Layouts mac_radio_group_column = column(mac_radio_group) input_widgets = column(load_file_button, loaded_file_div, time_window_text_input) figure_widgets = column(histogram) column1 = row(figure_widgets, mac_radio_group_column, input_widgets)
code="console.log('dropdown_disabled: ' + this.value, this.toString())" )) #dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default") #dropdown_split.on_click(lambda value: print('dropdown_split: %s' % value)) #dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())")) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_group.on_click(lambda value: print('checkbox_group: %s' % value)) checkbox_group.js_on_click( CustomJS( code="console.log('checkbox_group: ' + this.active, this.toString())")) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) radio_group.on_click(lambda value: print('radio_group: %s' % value)) radio_group.js_on_click( CustomJS( code="console.log('radio_group: ' + this.active, this.toString())")) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) checkbox_button_group.on_click( lambda value: print('checkbox_button_group: %s' % value)) checkbox_button_group.js_on_click( CustomJS( code= "console.log('checkbox_button_group: ' + this.active, this.toString())" )) radio_button_group = RadioButtonGroup(
def main(): name = '' sex = '' years = [i for i in range(1880, 2018)] if "HI" in us_states.keys(): del us_states["HI"] if "AK" in us_states.keys(): del us_states["AK"] state_xs = [us_states[code]["lons"] for code in us_states] state_ys = [us_states[code]["lats"] for code in us_states] states = [state for state in us_states.keys()] """Begin formatting data for popularity trend model. Once data is formatted, build the model and add labels""" data_sources = create_dataset(name, sex, years, states, state_xs, state_ys) #adding layout tools and color pallete name_field = TextInput(value="", title="Name") sex_selection = RadioGroup(labels=["Male", "Female"], active=0) sub_button = Button(label="Submit", button_type="success", disabled=False) directions = Paragraph( text="""Type in any name and select the sex you would like to query. Then press Submit to display your results.""", width=250, height=60) palette.reverse() color_mapper = LogColorMapper(palette=palette) #create popularity trend model pop_plt = figure(title="Popularity Trend", x_axis_label='Year', y_axis_label="Quantity") pop_plt.line('x', 'y', source=data_sources['line_source'], legend="Qty", line_width=2) pop_plt.circle('year', 'qty', source=data_sources['circ_source'], size=14, color="navy", alpha=0.5) labels = LabelSet(x='year', y='qty', text='value', level='glyph', x_offset=5, y_offset=5, source=data_sources['label_source']) pop_plt.add_layout(labels) #create the choropleth model TOOLS = "pan,wheel_zoom,reset,hover,save" choro_plt = figure(title="US Name Distribution", tools=TOOLS, x_axis_location=None, plot_width=850, y_axis_location=None, plot_height=565, tooltips=[("State", "@state_names"), ("Quantity", "@rate")]) choro_plt.grid.grid_line_color = None choro_plt.hover.point_policy = "follow_mouse" choro_plt.patches('x', 'y', source=data_sources['choropleth_source'], fill_color={ 'field': 'rate', 'transform': color_mapper }, line_color="white", fill_alpha=.8, line_width=0.5) year_slider = Slider(start=1880, end=2017, value=1880, step=1, title="Year") color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(), label_standoff=12, border_line_color=None, location=(0, 0)) choro_plt.add_layout(color_bar, 'right') #handlers and callbacks def slider_callback(attr, old, new): """Called by year_slider to cause interactive changes on the popularity trend and choropleth models""" yr = str(year_slider.value) #x is a pandas series xlist = data_sources['line_source'].data['x'].tolist() # x~year y~qty if year_slider.value in xlist: new_circ_data = dict( year=[ data_sources['line_source'].data['x'][xlist.index( year_slider.value)] ], qty=[ data_sources['line_source'].data['y'][xlist.index( year_slider.value)] ]) new_label_data = dict(year=new_circ_data['year'], qty=new_circ_data['qty'], value=new_circ_data['qty']) data_sources['label_source'].data = new_label_data data_sources['circ_source'].data = new_circ_data choro_data = dict(x=state_xs, y=state_ys, state_names=states, rate=data_sources['matrix'][str(yr)]) data_sources['choropleth_source'].data = choro_data def text_input_handler(attr, old, new): new_name = new.strip() try: name_validation(new_name) try: new_name = new_name.capitalize() check_tables(new_name) new_query_data = dict( name=[new_name], sex=[data_sources["query_source"].data["sex"][0]]) query_data = ColumnDataSource(new_query_data) data_sources['query_source'] = query_data except ValueError: name_field.value = f"Sorry, {new_name} doesn't exist in the database" except ValueError: name_field.value = "Enter a name with valid letters only." def radio_handler(new): #value based on radio button index: 0-Male 1-Female if new == 0: sex = 'M' else: sex = 'F' new_query_data = dict( name=[data_sources["query_source"].data["name"][0]], sex=[sex]) query_data = ColumnDataSource(new_query_data) data_sources['query_source'] = query_data def replot(): new_name = str(name_field.value).strip() new_name = new_name.capitalize() if sex_selection.active == 0: new_sex = 'M' else: new_sex = 'F' data_dict = get_data(new_name, new_sex, years, states) new_query_data = dict(name=[new_name], sex=[new_sex]) data_sources['query_source'].data = new_query_data new_line_data = dict(x=data_dict['pop_df']['Year'], y=data_dict['pop_df']['Qty']) data_sources['line_source'].data = new_line_data xlist = data_sources['line_source'].data['x'].tolist() if year_slider.value not in xlist: new_circ_data = dict( year=[data_sources['line_source'].data['x'][0]], qty=[data_sources['line_source'].data['y'][0]]) else: new_circ_data = dict( year=[ data_sources['line_source'].data['x'][xlist.index( year_slider.value)] ], qty=[ data_sources['line_source'].data['y'][xlist.index( year_slider.value)] ]) new_label_data = dict(year=new_circ_data['year'], qty=new_circ_data['qty'], value=new_circ_data['qty']) new_choropleth_data = dict(x=state_xs, y=state_ys, state_names=states, rate=data_dict['matrix'][str( year_slider.value)]) data_sources['circ_source'].data = new_circ_data data_sources['label_source'].data = new_label_data data_sources['choropleth_source'].data = new_choropleth_data data_sources['matrix'] = data_dict['matrix'] year_slider.on_change('value', slider_callback) sex_selection.on_click(radio_handler) name_field.on_change('value', text_input_handler) sub_button.on_click(replot) layout = row(column(directions, name_field, sex_selection, sub_button), row(pop_plt, column(choro_plt, widgetbox(year_slider)))) curdoc().add_root(layout)