def buildVendorsTab(): defaultGfxVendors = [ gfxVendors.index('NVIDIA Corporation'), gfxVendors.index('Advanced Micro Devices, Inc. [AMD/ATI]'), gfxVendors.index('Intel Corporation') ] gfxVendorCheckbox = CheckboxGroup(labels=gfxVendors, active=defaultGfxVendors) source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title="GFX Vendors", x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update(selected): vendors = [gfxVendors[i] for i in range(len(gfxVendors)) if i in selected] releaseUsers = 100 * getUsersForVendors('release', vendors) / gfxTotalReleaseUsers betaUsers = 100 * getUsersForVendors('beta', vendors) / gfxTotalBetaUsers fig.x_range.factors = vendors fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in vendors], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in vendors], y=betaUsers / 2, height=betaUsers, ) gfxVendorCheckbox.on_click(update) update(gfxVendorCheckbox.active) vendorComparison = HBox(HBox(VBoxForm(*[gfxVendorCheckbox]), width=300), fig, width=1100) return Panel(child=vendorComparison, title="GFX Vendor Comparison")
def buildOSesTab(): osesCheckbox = CheckboxGroup(labels=oses, active=[i for i in range(len(oses))]) source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title='OS', x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update(selected): cur_oses = [oses[i] for i in range(len(oses)) if i in selected] releaseUsers = 100 * getUsersForOses('release', cur_oses) / osTotalReleaseUsers betaUsers = 100 * getUsersForOses('beta', cur_oses) / osTotalBetaUsers fig.x_range.factors = cur_oses fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in cur_oses], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in cur_oses], y=betaUsers / 2, height=betaUsers, ) osesCheckbox.on_click(update) update(osesCheckbox.active) osesComparison = HBox(HBox(VBoxForm(*[osesCheckbox]), width=300), fig, width=1100) return Panel(child=osesComparison, title="OS Comparison")
class checkbox(): def __init__(self, widget_lst, default_value, label, inline=True): self.widget_lst = widget_lst self.checkbox = None self.initialize(default_value, label, inline) def initialize(self, default_value, label, inline): self.checkbox = CheckboxGroup(active=default_value, labels=[label], inline=inline) self.widget_lst.append(self.checkbox) def add_callback(self, callback): self.checkbox.on_click(callback)
def init_axis_checkboxes(view, callback): """Generates a group of checkboxes whose function is to activate or deactivate the visibility of the axis of the view """ # Get a zipped list of [(element_id, isVisible), ..] axis_visibility_list = view.get_axis_status() _ = zip(*axis_visibility_list) axis_id_l = [element_id for element_id in _[0]] CheckboxGroupWidget.LOGGER.debug("Axis visibility: %s", _[1]) axis_visibility_l = [i for i in xrange(0, len(_[1])) if _[1][i]] cb_group = CheckboxGroup(labels=axis_id_l, active=axis_visibility_l) cb_group.on_click(lambda active_list: CheckboxGroupWidget._checkbox_update_element\ (active_list, cb_group.labels, callback)) return cb_group
class checkbox(): def __init__(self, widget_lst, default_value, label, inline=True): self.label = label self.default_value = default_value self.inline = inline self.checkbox = None self.callback = None # self.initialize(default_value, label, inline) widget_lst.append(self) def initialize(self, widget_lst): self.checkbox = CheckboxGroup(active=self.default_value, labels=[self.label], inline=self.inline) widget_lst.append(self.checkbox) if self.callback is not None: self.checkbox.on_click(self.callback) def add_callback(self, callback): self.callback = callback if self.checkbox is not None: self.checkbox.on_click(self.callback)
def category_options(self): """Returns gridplot (bokeh layout or Element) defining elements for the User to manipulate Data shown in other views. Function first checks if the category variables are initialized and if not, initializes them. Then two bokeh widgets are created: Radio Group and Checbox Group and both are put into the column layout. Category Type Radio Group allows to choose which category column will be used in dataframes (either .category or .all) and if the categories will be extracted as they are (either in "simple" or "extended" options) or if the "combinations" of categories will be created for User's choosing (e.g. Expenses:Family:Grocery:Fruits will provide 4 different categories: - "Expenses" - "Expenses:Family" - "Expenses:Family:Grocery" - "Expenses:Family:Grocery:Fruits". Checkbox Group will then provide all choosable categories (from chosen category type) for the User to check and uncheck and therefore filter/unfilter them from the dataframes. Elements on creation take data from respective instance attributes - this way navigating between different views and then coming back to Settings view will "remember" previous choice of the User. Callbacks are defined for each Element so that it will be responsive to User choosing. Additionally, Checkbox Group is set into .checkbox_group attribute so that change in Category Type can also trigger change in Checkbox Group. Returns column layout. """ if self.are_categories_initialized is False: self.__initialize_categories() chosen_index = self.chosen_category_type category_type_chooser = RadioGroup( labels=self.category_type_labels, active=chosen_index, css_classes=["category_types_buttons"], inline=True ) checkbox_group = CheckboxGroup( labels=self.all_categories, active=[self.all_categories.index(x) for x in self.chosen_categories], css_classes=["category_checkbox"] ) # set as attribute for RadioGroup Buttons Updates to have access to it self.checkbox_group = checkbox_group # Callbacks def callback_on_category_type_change(attr, old, new): if new != old: self.__update_categories_on_category_type_change(new) category_type_chooser.on_change("active", callback_on_category_type_change) def callback_on_checkbox_change(new): self.__update_chosen_categories_on_new(new) checkbox_group.on_click(callback_on_checkbox_change) # Grid grid = column( category_type_chooser, checkbox_group ) return grid
source.data = dict( x=df[x_name], y=df[y_name], color=df["color"], user_vector=df["user_vector"], content_vector=df["content_vector"], alg_type=df["alg_type"], dataset = df["dataset"], num_run = df["N"], #alpha = df["alpha"], ) controls = [alg_type, num_preds, x_axis, y_axis, dataset_type, u_button, checkbox_button_group, c_button, checkbox_button_group_content] for control in controls: if control==dataset_type: control.on_change('value', update_dataset) else: control.on_change('value', update) checkbox_button_group.on_click(checkbox_handler) checkbox_button_group_content.on_click(checkbox_handler) inputs = HBox(VBoxForm(*controls), width=300) update(None, None, None) # initial load of the data curdoc().add_root(HBox(inputs, p, width=1100))
# initialize data source for line plot source_curve = ColumnDataSource(data=dict(x=[], y=[])) # plotting for normal parametrization source_point_normal = ColumnDataSource(data=dict(x=[], y=[])) # plotting for arc length parametrization source_point_arc = ColumnDataSource(data=dict(x=[], y=[])) # initialize controls # choose between original and arc length parametrization parametrization_input = CheckboxGroup(labels=['show original parametrization', 'show arc length parametrization'], active=[0, 1]) parametrization_input.on_click(parametrization_change) # slider controlling the current parameter t t_value_input = Slider(title="parameter t", name='parameter t', value=arc_settings.t_value_init, start=arc_settings.t_value_min, end=arc_settings.t_value_max, step=arc_settings.t_value_step) t_value_input.on_change('value', t_value_change) # text input for the x component of the curve x_component_input = TextInput(value=arc_settings.x_component_input_msg, title="curve x") x_component_input.on_change('value', curve_change) # text input for the y component of the curve y_component_input = TextInput(value=arc_settings.y_component_input_msg, title="curve y") y_component_input.on_change('value', curve_change) # dropdown menu for selecting one of the sample curves sample_curve_input = Dropdown(label="choose a sample function pair or enter one below", menu=arc_settings.sample_curve_names) sample_curve_input.on_click(sample_curve_change)
#Nouveau CallBackn box_group checkbox_group = CheckboxGroup( labels=['Mains Stations', 'Stations', 'Lines'], active=[0, 1, 2]) def callback_check(attr, old, new) : if checkbox_group.active == [0] : temp_p2.visible = True temp_p3.visible = False temp_p4.visible = False elif checkbox_group.active == [0,1] : temp_p2.visible = True temp_p3.visible = True temp_p4.visible = False elif checkbox_group.active == [0,2] : temp_p2.visible = True temp_p3.visible = False temp_p4.visible = True elif checkbox_group.active == [0,1,2] : temp_p2.visible = True temp_p3.visible = True temp_p4.visible = True checkbox_group.on_click(callback_check) temp_f.add_tile(CARTODBPOSITRON) layout_map = column(select_line, widgetbox(checkbox_group),temp_f)
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(
def tabledetails_tab(df_all_nfolds, old_to_new_regions, new_to_old_regions, old_to_new_sources, new_to_old_sources): # Transpose dataframe df_all_t = df_all_nfolds.copy().T # Replace values in dataframe region_replace = dict(old_to_new_sources) del region_replace['Colombia'] df_all_t.replace(to_replace={ 'Column': { 'id': 'Predictor', 'objective_values': 'R2 Training', 'OOS_R_squared': 'R2 OOS' }, 'SourcesSet': region_replace, 'Region': old_to_new_regions }, inplace=True) # Define columns between selector and results (2nd column is for width) select_cols = { 'NbFolds': ['Nb Folds', 60], 'Region': ['Region', 100], 'SourcesSet': ['Predictors Set', 150], 'Column': ['Result Type', 80], 'Score': ['Score', 80] } result_cols = sorted([x for x in df_all_t.columns.tolist() if x.isdigit()], key=lambda x: float(x)) # Transform number entries into numbers and round them nb_rows = ['R2 Training', 'R2 OOS'] df_all_t.loc[df_all_t.Column.isin(nb_rows),result_cols] = \ df_all_t.loc[df_all_t.Column.isin(nb_rows),result_cols].applymap(\ lambda x: np.float(x)).round(3) # Get final value for each row df_all_t.loc[:, 'Score'] = df_all_t.loc[:, result_cols].apply( lambda x: x.fillna(method='ffill')[-1], axis=1) df_all_t.loc[:, 'Score'] = df_all_t.apply(lambda x: x['Score'] if x['Column'] in nb_rows else '', axis=1) df_all_t.fillna(value='', inplace=True) ## Define checkboxes to select data to display # Get possible values for each column nb_folds_list = sorted(np.unique(df_all_t['NbFolds']), key=lambda x: float(x)) region_list = sorted(np.unique(df_all_t['Region'])) sources_set_list = sorted(np.unique(df_all_t['SourcesSet'])) result_type_list = sorted(np.unique(df_all_t['Column'])) # Define boxes nb_folds_box = CheckboxGroup(labels=[np.str(x) for x in nb_folds_list], active=[0, 1]) region_box = CheckboxGroup(labels=region_list, active=[0, 1]) sources_set_box = CheckboxGroup(labels=sources_set_list, active=[0, 1]) result_type_box = CheckboxGroup(labels=result_type_list, active=[0, 1, 2]) # Divs to contain each checkbox's name nb_folds_div = Div(text='<b>Nb Folds</b>') region_div = Div(text='<b>Region</b>') sources_set_div = Div(text='<b>Sources Set</b>') result_type_div = Div(text='<b>Result Type</b>') # Buttons to select all/none regions or sources at once select_all_regions_button = Button(label="Select All") select_all_sources_button = Button(label="Select All") select_no_region_button = Button(label="Unselect All") select_no_source_button = Button(label="Unselect All") ########################################################################### # Update function def boxes_update(attr): #attr, old, new): # Get list of selected items for each button nb_folds_selected = [nb_folds_list[x] for x in nb_folds_box.active] result_type_selected = [ result_type_list[x] for x in result_type_box.active ] region_selected = [region_list[x] for x in region_box.active] sources_set_selected = [ sources_set_list[x] for x in sources_set_box.active ] # Update source data conditions = { 'NbFolds': nb_folds_selected, 'Column': result_type_selected, 'Region': region_selected, 'SourcesSet': sources_set_selected } new_data = data_to_show(df_all_t, result_cols, conditions) # new_source = ColumnDataSource(data) source.data = new_data def update_all_regions(): region_box.active = list(range(len(region_list))) def update_all_sources(): sources_set_box.active = list(range(len(sources_set_list))) def update_no_region(): region_box.active = [] def update_all_source(): sources_set_box.active = [] ########################################################################### # Callback / Update function events nb_folds_box.on_click(boxes_update) result_type_box.on_click(boxes_update) region_box.on_click(boxes_update) sources_set_box.on_click(boxes_update) select_all_regions_button.on_click(update_all_regions) select_all_sources_button.on_click(update_all_sources) select_no_region_button.on_click(update_no_region) select_no_source_button.on_click(update_all_source) ## Create table and get data to display when opening the page starting_cond = { 'NbFolds': [nb_folds_list[x] for x in nb_folds_box.active], 'Region': [region_list[x] for x in region_box.active], 'SourcesSet': [sources_set_list[x] for x in sources_set_box.active] } data_start = data_to_show(df_all_t, result_cols, conditions=starting_cond) source = ColumnDataSource(data_start) # Define table columns columns = [] for k in select_cols.keys(): columns.append( TableColumn(field=k, title=select_cols[k][0], width=select_cols[k][1])) # Add the actual result columns (column names are numbers) for c in result_cols: columns.append( TableColumn(field=c, title=np.str(np.int(c) + 1), width=200)) # Create data table, fit_columns=False ensures we have a scrolling bar data_table = DataTable(source=source, columns=columns, width=1000, height=700, fit_columns=False) # Put controls in a single element controls = row( column(nb_folds_div, nb_folds_box, width=60), column(region_div, select_all_regions_button, select_no_region_button, region_box, width=140), column(sources_set_div, select_all_sources_button, select_no_source_button, sources_set_box, width=200), column(result_type_div, result_type_box, width=100)) # Create a row layout layout = row(controls, data_table) # Make a tab with the layout tab = Panel(child=layout, title='Detailed Results - Table') return tab ###############################################################################
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_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
class BenchmarkApp(HBox): """An example of a browser-based, interactive plot with slider controls.""" extra_generated_classes = [["BenchmarkApp", "BenchmarkApp", "HBox"]] inputs = Instance(VBoxForm) # widgets benchmarks = Instance(Select) x_axis_options = Instance(Select) y_axis_options = Instance(Select) # TODO: Convert this to a MultiSelect once it is fixed # https://github.com/bokeh/bokeh/issues/2495 device_names = Instance(CheckboxGroup) platform_names = Instance(CheckboxButtonGroup) # data displays, not enabled by default data_display0 = Instance(DataTable) data_display1 = Instance(DataTable) # plot and interaction plot = Instance(Plot) hover = Instance(HoverTool) # data source0 = Instance(ColumnDataSource) source1 = Instance(ColumnDataSource) source2 = Instance(ColumnDataSource) source3 = Instance(ColumnDataSource) source4 = Instance(ColumnDataSource) source5 = Instance(ColumnDataSource) source6 = Instance(ColumnDataSource) source7 = Instance(ColumnDataSource) source8 = Instance(ColumnDataSource) source9 = Instance(ColumnDataSource) def make_source(self): # set up the data source self.source0 = ColumnDataSource(data=dict()) self.source1 = ColumnDataSource(data=dict()) self.source2 = ColumnDataSource(data=dict()) self.source3 = ColumnDataSource(data=dict()) self.source4 = ColumnDataSource(data=dict()) self.source5 = ColumnDataSource(data=dict()) self.source6 = ColumnDataSource(data=dict()) self.source7 = ColumnDataSource(data=dict()) self.source8 = ColumnDataSource(data=dict()) self.source9 = ColumnDataSource(data=dict()) def make_inputs(self): columns = [ TableColumn(field='x', title='x'), TableColumn(field='y', title='y'), TableColumn(field='device', title='device'), TableColumn(field='platform', title='platform') ] # obj.data_display0 = DataTable(source=obj.source2, columns=columns) # obj.data_display1 = DataTable(source=obj.source3, columns=columns) # setup user input self.x_axis_options = Select(title="X:", value='size', options=axis_options) self.y_axis_options = Select(title="Y:", value='throughput [1/sec]', options=axis_options) self.benchmarks = Select(title="Benchmark:", value=benchmark_names[0], options=benchmark_names) self.device_names = CheckboxGroup(labels=device_names, active=[0]) self.platform_names = CheckboxButtonGroup(labels=platform_names, active=[0]) @classmethod def create(cls): """One-time creation of app's objects. This function is called once, and is responsible for creating all objects (plots, datasources, etc) """ obj = cls() obj.make_source() obj.make_inputs() obj.make_plot() obj.update_data() obj.set_children() return obj def plot_data(self, source, linecolor, symbolfill): self.plot.line( 'x', 'y', source=source, line_color=linecolor, line_width=3, line_alpha=0.6) self.plot.scatter('x', 'y', source=source, fill_color=symbolfill, size=8) def make_plot(self): # configure the toolset toolset = ['wheel_zoom,save,box_zoom,resize,reset'] self.hover = BenchmarkApp.make_hovertool() toolset.append(self.hover) title = self.benchmarks.value + " " + \ "(" + self.y_axis_options.value + " vs." + self.x_axis_options.value + ")" self.plot = figure(title_text_font_size="12pt", plot_height=400, plot_width=400, tools=toolset, title=title, ) # remove the logo self.plot.logo = None # Generate a figure container # Plot the line by the x,y values in the source property self.plot_data(self.source0, "#F0A3FF", "white") self.plot_data(self.source1, "#0075DC", "white") self.plot_data(self.source2, "#993F00", "white") self.plot_data(self.source3, "#4C005C", "white") self.plot_data(self.source4, "#191919", "white") self.plot_data(self.source5, "#005C31", "white") self.plot_data(self.source6, "#2BCE48", "white") self.plot_data(self.source7, "#FFCC99", "white") self.plot_data(self.source8, "#808080", "white") self.plot_data(self.source9, "#94FFB5", "white") # set the x/y axis labels # plot.xaxis.axis_label = self.x_axis_options.value # plot.yaxis.axis_label = self.y_axis_options.value def set_children(self): self.inputs = VBoxForm( children=[self.benchmarks, self.device_names, self.platform_names, self.x_axis_options, self.y_axis_options, # self.data_display0, self.data_display1 ] ) self.children.append(self.inputs) self.children.append(self.plot) @classmethod def make_hovertool(self): hover = HoverTool( tooltips = [ ("Device", "@device"), ("Backend", "@platform"), ("(x,y)", "(@x,@y)") ] ) return hover def setup_events(self): """Attaches the on_change event to the value property of the widget. The callback is set to the input_change method of this app. """ super(BenchmarkApp, self).setup_events() if not self.benchmarks: return # Event registration for everything except checkboxes self.benchmarks.on_change('value', self, 'benchmark_changed') self.x_axis_options.on_change('value', self, 'input_change') self.y_axis_options.on_change('value', self, 'input_change') # Event registration for checkboxes self.device_names.on_click(self.checkbox_handler) self.platform_names.on_click(self.checkbox_handler) def checkbox_handler(self, active): self.update_data() def benchmark_changed(self, obj, attrname, old, new): self.update_data() self.make_plot() curdoc().add(self) def input_change(self, obj, attrname, old, new): """Executes whenever the input form changes. It is responsible for updating the plot, or anything else you want. Args: obj : the object that changed attrname : the attr that changed old : old value of attr new : new value of attr """ self.update_data() self.make_plot() curdoc().add(self) def getXY(self, celero_result, axis_filter): """Returns the X or Y value as specified by axis_filter""" # TODO: Remove the baseline measurement from the timing results if axis_filter == 'size': return celero_result['data_sizes'] elif axis_filter == 'log2(size)': return np.log2(celero_result['data_sizes']) elif axis_filter == 'log10(size)': return np.log10(celero_result['data_sizes']) elif axis_filter == 'time [ms]': return celero_result['times'] * 1E-3 elif axis_filter == 'throughput [1/sec]': return 1.0 / (celero_result['times'] * 1E-6) elif axis_filter == 'throughput [log2(1/sec)]': return np.log2(1.0 / (celero_result['times'] * 1E-6)) elif axis_filter == 'throughput [log10(1/sec)]': return np.log10(1.0 / (celero_result['times'] * 1E-6)) @classmethod def make_field_ids(self, id_number): """Creates a unique set of named fields for the y, device, and platform""" i = str(id_number) y_id = 'y' + i device_id = 'device' + i platform_id = 'platform' + i return [y_id, device_id, platform_id] def update_data(self): """Called each time that any watched property changes. This updates the sin wave data with the most recent values of the sliders. This is stored as two numpy arrays in a dict into the app's data source property. """ # extract the user's input benchmark = self.benchmarks.value devices = list(device_names[i] for i in self.device_names.active) platforms = list(platform_names[i] for i in self.platform_names.active) x_axis_label = self.x_axis_options.value y_axis_label = self.y_axis_options.value # extract only the results which match this group filtered_results = filter(lambda x: x['benchmark_name'] == benchmark, celero_results) # remove the baseline measurements from the plots filtered_results = filter(lambda x: x['benchmark_name'] != "Baseline", filtered_results) # select the desired devices filtered_results = filter(lambda x: x['extra_data']['AF_DEVICE'] in devices, filtered_results) filtered_results = filter(lambda x: x['extra_data']['AF_PLATFORM'] in platforms, filtered_results) # extract the data sources = dict() result_number = 0 for result in filtered_results: # ensure we don't plot too many results if result_number > MAX_PLOTS: break y_id, device_id, platform_id = self.make_field_ids(result_number) # Extract the results from the benchmark platform = result['extra_data']['AF_PLATFORM'] device = result['extra_data']['AF_DEVICE'] x = self.getXY(result, x_axis_label) y = self.getXY(result, y_axis_label) # store the benchmark results in the self.source object # NOTE: we replicate the device and platform data here so that # it works correctly with the mouseover/hover sources['x'] = x sources[y_id] = y sources[device_id] = [device] * len(x) sources[platform_id] = [platform] * len(x) # increment the counter result_number += 1 # assign the data self.assign_source(sources, self.source0, 0) self.assign_source(sources, self.source1, 1) self.assign_source(sources, self.source2, 2) self.assign_source(sources, self.source3, 3) self.assign_source(sources, self.source4, 4) self.assign_source(sources, self.source5, 5) self.assign_source(sources, self.source6, 6) self.assign_source(sources, self.source7, 7) self.assign_source(sources, self.source8, 8) self.assign_source(sources, self.source9, 9) def assign_source(self, src, dest, index): """Assigns the data from src to the dictionary in dest if the corresponding data exists in src.""" y_id, device_id, platform_id = self.make_field_ids(index) dest.data = dict() if y_id in src: dest.data['x'] = src['x'] dest.data['y'] = src[y_id] dest.data['device'] = src[device_id] dest.data['platform'] = src[platform_id] dest._dirty = True
air_thickness_input.disabled = True air_temperature_input.disabled = True if 2 in new: detector_material_input.disabled = False detector_thickness_input.disabled = False detector_density_input.disabled = False if 2 not in new: detector_material_input.disabled = True detector_thickness_input.disabled = True detector_density_input.disabled = True return new checkbox_group = CheckboxGroup(labels=["Material", "Air", "Detector"], active=[0, 1, 2]) checkbox_group.on_click(toggle_active) def update_button_action(): update_response("update_plot_button", 0, 0) update_data("update", 0, 0) update_plot_button = Button(label="Update Plot", button_type="success") update_plot_button.on_click(update_button_action) plot.x_range.on_change('start', update_data) plot.x_range.on_change('end', update_data) plot_checkbox_group = CheckboxGroup(labels=["ylog"], active=[])
from bokeh.document import Document from bokeh.plotting import curdoc, figure, show import asyncio from tornado.platform.asyncio import BaseAsyncIOLoop, AsyncIOMainLoop from tornado.ioloop import IOLoop doc = Document() def my_radio_handler(new): doc.title = str(new) print("Radio button " + str(new) + " option selected.") radio_button_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[]) radio_button_group.on_click(my_radio_handler) doc.add_root(radio_button_group) loop = asyncio.get_event_loop() io_loop = BaseAsyncIOLoop(asyncio_loop=loop) # io_loop = IOLoop._ioloop_for_asyncio[loop] # io_loop = IOLoop.current() # Open a session to keep our local document in sync with server session = push_session(doc, session_id="123", io_loop=io_loop) # Run forever (this is crucial to retrive callback's data) session._connection._loop.spawn_callback(session._connection._next) loop.run_forever() print("hw")
level='glyph', x_offset=5, source=sourceper, render_mode='canvas') labels_per.visible = False i.add_layout(labels_per) # checkbox_group button_group = CheckboxGroup( labels=[ "Average PPG Lines", "Average RPG Lines", "Average APG Lines", "Average PER Lines" ], active=[], ) button_group.on_click(update_avg_line) img = figure(plot_width=300, plot_height=200, x_range=(0, 370), y_range=(0, 834), x_axis_type=None, y_axis_type=None, tools=[]) imageglyph = img.image_url(url=['nba/static/images/kevin_durant.png'], x=0, y=0, w=369, h=834, anchor="bottom_left") img.grid.visible = False
# initialize data source for line plot source_curve = ColumnDataSource(data=dict(x=[], y=[])) # plotting for normal parametrization source_point_normal = ColumnDataSource(data=dict(x=[], y=[])) # plotting for arc length parametrization source_point_arc = ColumnDataSource(data=dict(x=[], y=[])) # initialize controls # choose between original and arc length parametrization parametrization_input = CheckboxGroup(labels=[ 'show original parametrization', 'show arc length parametrization' ], active=[0, 1]) parametrization_input.on_click(parametrization_change) # slider controlling the current parameter t t_value_input = Slider(title="parameter t", name='parameter t', value=arc_settings.t_value_init, start=arc_settings.t_value_min, end=arc_settings.t_value_max, step=arc_settings.t_value_step) t_value_input.on_change('value', t_value_change) # text input for the x component of the curve x_component_input = TextInput(value=arc_settings.x_component_input_msg, title="curve x") x_component_input.on_change('value', curve_change) # text input for the y component of the curve y_component_input = TextInput(value=arc_settings.y_component_input_msg, title="curve y")
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()
xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt] xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt] xtsel = [TapTool() for n in ts_cnt] xpan = [PanTool(dimensions=['width']) for n in ts_cnt] save = [SaveTool() for n in ts_cnt] reset = [ResetTool() for n in ts_cnt] tools = [ [ cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n], save[n], reset[n] ] for n in ts_cnt ] data_update_in_progress = False play_all_button = Button(label='Play', button_type='success', width=60) play_all_button.on_click(play_all) play_all_sox_button = Button(label='Play sox', button_type='success', width=60) play_all_sox_button.on_click(play_all_sox) audio_first_checkbox = CheckboxGroup(labels=['audio first'], active=[0]) audio_first_checkbox.on_click(audio_first_selected) fsel.on_change('value', file_selected) source.on_change('selected', selection_change) curdoc().add_root(row(fsel, play_all_button, play_all_sox_button, audio_first_checkbox, msgdiv)) (gp, ch0) = make_plot() x_range = ch0.x_range curdoc().add_root(row(gp))
def buildDevicesTab(): gfxVendorSelect = Select(title='Vendor', options=gfxVendors, value=gfxVendors[0]) gfxDeviceCheckbox = CheckboxGroup() source_release = ColumnDataSource(data=dict(x=[], y=[], height=[])) source_beta = ColumnDataSource(data=dict(x=[], y=[], height=[])) fig = Figure(title="GFX Devices", x_range=[], y_range=[0, 0], plot_width=1000, plot_height=650) hover = HoverTool(tooltips=[ ('Users', '@height %') ]) fig.add_tools(hover) fig.rect(x='x', y='y', height='height', source=source_release, width=0.4, color='orange', legend='Release') fig.rect(x='x', y='y', height='height', source=source_beta, width=0.4, color='blue', legend='Beta') fig.xaxis.major_label_orientation = np.pi / 3 def update_view(): vendor = gfxVendorSelect.value deviceNames = getDeviceNames('release', vendor, True) gfxDeviceCheckbox.labels = deviceNames devices = [deviceNames[i] for i in range(len(deviceNames)) if i in gfxDeviceCheckbox.active] releaseUsers = 100 * getUsersForDevices('release', vendor, devices) / gfxTotalReleaseUsers betaUsers = 100 * getUsersForDevices('beta', vendor, devices) / gfxTotalBetaUsers fig.x_range.factors = devices fig.y_range.end = max([releaseUsers.max(), betaUsers.max()]) source_release.data = dict( x=[c + ':0.3' for c in devices], y=releaseUsers / 2, height=releaseUsers, ) source_beta.data = dict( x=[c + ':0.7' for c in devices], y=betaUsers / 2, height=betaUsers, ) def update(attrname, old, new): gfxDeviceCheckbox.active = [i for i in range(5)] update_view() def click(selected): update_view() gfxVendorSelect.on_change('value', update) gfxDeviceCheckbox.on_click(click) update('value', '', gfxVendorSelect.value) deviceComparison = HBox(HBox(VBoxForm(*[gfxVendorSelect, gfxDeviceCheckbox]), width=300), fig, width=1100) return Panel(child=deviceComparison, title="GFX Device Comparison")
# Called with respect to change in attributes check-box def update_attributes(new): """ create a new active_attributes_list when any of the checkboxes are selected """ global selected_root active_attributes_list[:] = [] for i in new: active_attributes_list.append(list(Instance().attr_list)[i]) if selected_root != '' and selected_root not in active_attributes_list: apply_changes_button.disabled = True else: apply_changes_button.disabled = False attribute_checkbox.on_click(update_attributes) def modify_test_percentage(_attr, _old, new): Instance().update(Instance().data, Instance().attr_values, Instance().attr_list, Instance().attr_values_dict, Instance().attr_dict, Instance().cmap, new) dataset_slider.on_change('value', modify_test_percentage) def toggle_mode_set(new): """ toggles settings """
def expand_data_changed_callback(data, old, new): """ remove the selected indices when table is empty """ if old == empty_table: expand_table_source.selected.indices = [] # set callbacks expand_button.on_click(get_expand_results_callback) # save_button.on_click(save_data_callback) expand_table_source.selected.on_change('indices', row_selected_callback) expand_table_source.on_change('data', expand_data_changed_callback) checkbox_group.on_click(show_phrases_callback) search_input_box.on_change('value', search_callback) phrases_list.on_change('value', vocab_phrase_selected_callback) clear_seed_button.on_click(clear_seed_callback) export_button.callback = CustomJS(args=dict(source=expand_table_source), code=open( join(dirname(__file__), "download.js")).read()) # table_area.on_change('children', table_area_change_callback) # arrange components in page doc = curdoc() main_title = "Set Expansion Demo" doc.title = main_title doc.add_root(grid)
xzoom = [BoxZoomTool(dimensions=['width']) for n in ts_cnt] xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt] xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt] xtsel = [TapTool() for n in ts_cnt] xpan = [PanTool(dimensions=['width']) for n in ts_cnt] save = [SaveTool() for n in ts_cnt] reset = [ResetTool() for n in ts_cnt] tools = [[ cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n], save[n], reset[n] ] for n in ts_cnt] data_update_in_progress = False play_all_button = Button(label='Play', button_type='success', width=60) play_all_button.on_click(play_all) play_all_sox_button = Button(label='Play sox', button_type='success', width=60) play_all_sox_button.on_click(play_all_sox) audio_first_checkbox = CheckboxGroup(labels=['audio first'], active=[0]) audio_first_checkbox.on_click(audio_first_selected) fsel.on_change('value', file_selected) source.on_change('selected', selection_change) curdoc().add_root( row(fsel, play_all_button, play_all_sox_button, audio_first_checkbox, msgdiv)) (gp, ch0) = make_plot() x_range = ch0.x_range curdoc().add_root(row(gp))
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
] dataTable = DataTable(source=source, columns=columns, width=800, height=600) tab2 = Panel(child=dataTable, title="Table") tabs = Tabs(tabs=[tab1, tab2 ]) # tabs.css_classes = ["hide"] autoUpdateCheckbox = CheckboxGroup( labels=["Auto Update Data Source (every 15s)"], active=[]) autoUpdateCheckbox.disabled = True gatewayControl.on_change('value', lambda attr, old, new: update_device()) deviceControl.on_change('value', lambda attr, old, new: update_indicator()) submitButton.on_click(lambda: callback()) autoUpdateCheckbox.on_click(lambda attr: auto_update(attr)) sizing_mode = 'fixed' # 'scale_width' also looks nice with this example inputs = widgetbox(*controls, sizing_mode=sizing_mode, name="widgets") plotwidget = widgetbox([autoUpdateCheckbox, tabs], sizing_mode=sizing_mode, name="plotwidget") mainLayout = layout(children=[ [inputs, plotwidget] ], sizing_mode=sizing_mode, name="mainLayout") doc.add_root(mainLayout) doc.title = "ACME IoT Analytics" def epoch_to_datetime(epoch): """ :param epoch: str of epoch time
def table_tab(agg_all_nfolds): ## Define checkboxes to select data to display # Get possible values for each column nb_folds_list = list(np.unique(agg_all_nfolds['NbFolds'])) nb_folds_list.sort() score_type_list = list(np.unique(agg_all_nfolds['ScoreType'])) score_type_list.sort() region_list = list(np.unique(agg_all_nfolds['Region'])) region_list.sort() sources_set_list = list(np.unique(agg_all_nfolds['SourcesSet'])) sources_set_list.sort() is_best_list = list(np.unique(agg_all_nfolds['IsBest'])) is_best_list.sort() # Define boxes nb_folds_box = CheckboxGroup(labels=[np.str(x) for x in nb_folds_list], active=[0, 1]) score_type_box = CheckboxGroup(labels=score_type_list, active=[0, 1]) region_box = CheckboxGroup(labels=region_list, active=[0, 1]) sources_set_box = CheckboxGroup(labels=sources_set_list, active=[0, 1]) is_best_box = CheckboxGroup(labels=[np.str(x) for x in is_best_list], active=[0, 1]) # Divs to contain each checkbox's name nb_folds_div = Div(text='<b>Nb Folds</b>') score_type_div = Div(text='<b>Score Type</b>') region_div = Div(text='<b>Region</b>') sources_set_div = Div(text='<b>Sources Set</b>') is_best_div = Div(text='<b>Is Best</b>') # Buttons to select all/none regions or sources at once select_all_regions_button = Button(label="Select All") select_all_sources_button = Button(label="Select All") select_no_region_button = Button(label="Unselect All") select_no_source_button = Button(label="Unselect All") ########################################################################### # Update function def boxes_update(attr): #attr, old, new): # Get list of selected items for each button nb_folds_selected = [nb_folds_list[x] for x in nb_folds_box.active] score_type_selected = [ score_type_list[x] for x in score_type_box.active ] region_selected = [region_list[x] for x in region_box.active] sources_set_selected = [ sources_set_list[x] for x in sources_set_box.active ] is_best_selected = [is_best_list[x] for x in is_best_box.active] # Update source data conditions = { 'NbFolds': nb_folds_selected, 'ScoreType': score_type_selected, 'Region': region_selected, 'SourcesSet': sources_set_selected, 'IsBest': is_best_selected } new_data = data_to_show(agg_all_nfolds, conditions) # new_source = ColumnDataSource(data) source.data = new_data def update_all_regions(): region_box.active = list(range(len(region_list))) def update_all_sources(): sources_set_box.active = list(range(len(sources_set_list))) def update_no_region(): region_box.active = [] def update_all_source(): sources_set_box.active = [] ########################################################################### # Callback / Update function events nb_folds_box.on_click(boxes_update) score_type_box.on_click(boxes_update) region_box.on_click(boxes_update) sources_set_box.on_click(boxes_update) is_best_box.on_click(boxes_update) select_all_regions_button.on_click(update_all_regions) select_all_sources_button.on_click(update_all_sources) select_no_region_button.on_click(update_no_region) select_no_source_button.on_click(update_all_source) ## Create table and get data to display when opening the page starting_cond = { 'NbFolds': [nb_folds_list[x] for x in nb_folds_box.active], 'Region': [region_list[x] for x in region_box.active], 'SourcesSet': [sources_set_list[x] for x in sources_set_box.active] } data_start = data_to_show(agg_all_nfolds, conditions=starting_cond) source = ColumnDataSource(data_start) columns = [ TableColumn(field="NbFolds", title="Nb Folds"), TableColumn(field="ScoreType", title="Score Type"), TableColumn(field="Region", title="Region"), TableColumn(field="SourcesSet", title="Predictors Set"), TableColumn(field="IsBest", title="Is Best"), TableColumn(field="Value", title="Value", formatter=NumberFormatter(format='0,0.00')), ] # Create data table, fit_columns=False ensures we have a scrolling bar data_table = DataTable(source=source, columns=columns, width=700, height=900) # Put controls in a single element controls = row( column(nb_folds_div, nb_folds_box, width=60), column(score_type_div, score_type_box, width=90), column(region_div, select_all_regions_button, select_no_region_button, region_box, width=140), column(sources_set_div, select_all_sources_button, select_no_source_button, sources_set_box, width=200), column(is_best_div, is_best_box, width=90)) # Create a row layout layout = row(controls, data_table) # Make a tab with the layout tab = Panel(child=layout, title='Summary Results - Table') return tab
class BokehEvents(Environment): ''' Controls and events. The widgets and buttons are created here Also some other events and triggers such as update points selections ''' env = Environment def __init__(self, **kwargs): lg.info('-- INIT BOKEH EVENTS') self.env.bk_events = self self.env.source.selected.on_change('indices', self._update_selection) self.env.wmts_map_source.selected.on_change('indices', self._update_map_selection) self._init_cb_prof_invsbl_points() self._init_profile_nav() self._init_nearby_prof_cb() self._init_tabs() def _update_selection(self, attr, old, new_indices): ''' This is run when some elements are selected: @attr: 'selected' @old: >> does not work well yet with the new Selection class? @new: >> new_indices store the new selection indices list ''' lg.info('-- UPDATE SELECTION: {}'.format(new_indices)) self.env.dt_manual_update = False if self.env.selection != new_indices and new_indices != []: self.env.selection = new_indices self.env.sample_to_select = None # this is reselected later on `_upd_prof_srcs` self.env.stt_to_select = None self.env.cur_nearby_prof = None self.env.cur_partial_stt_selection = [] self._update_map_selection_prog(new_indices) self.env.bk_table.update_dt_source( ) # prof sources is updated inside self.env.reset_selection = False elif self.env.selection != [] and new_indices == []: # NOTE: Keeps the selection when the user click on a space without any sample if self.env.reset_selection: lg.info('>> RESET SELECTION') self.env.selection = [] self.env.sample_to_select = None # this is reselected later on `_upd_prof_srcs` self.env.stt_to_select = None self.env.cur_nearby_prof = None self.env.cur_partial_stt_selection = [] self.env.reset_selection = False else: lg.info('>> KEEP SELECTION') self.env.source.selected.indices = self.env.selection # keep selection self.env.dt_manual_update = True # reactivate the manual update of the datatable def _update_map_selection(self, attr, old, new_indices): lg.info('-- UPDATE MAP SELECTION') if self.env.map_selection != new_indices and new_indices != []: # this can be triggered by the user, and programmatically?? lg.info('>> NEW MAP SELECTION: {}'.format(new_indices)) self.env.map_selection = new_indices # triggers the _update_selection # lg.info('>> MAP SOURCE: {}'.format(self.env.wmts_map_source.data)) selected_stts = list( self.env.wmts_map_source.data[STNNBR][new_indices]) # self.env.cur_partial_stt_selection = selected_stts # TODO: how to get all the indices of the current selected stations?? by self.env.cds_df is updated?? sel_inds = list(self.env.cds_df[self.env.cds_df[STNNBR].isin( selected_stts)].index) self.env.source.selected.indices = sel_inds self._update_selection( attr='selected', old=None, new_indices=self.env.source.selected. indices # I need to trigger this manually as well ) elif self.env.map_selection != [] and new_indices == []: if self.env.reset_selection: lg.info('>> RESET MAP SELECTION') self.env.map_selection = [] self.env.wmts_map_source.selected.indices = [] else: lg.info('>> KEEP MAP SELECTION') self.env.wmts_map_source.selected.indices = self.env.map_selection def _update_map_selection_prog(self, new_indices): ''' Updates the map selection programmatically with the stations of the selected samples @new_indices: list of indices of the selected samples (cds_df) ''' lg.info('-- UPDATE MAP SELECTION PROGRAMMATICALLY') if self.env.map_selection != new_indices and new_indices != []: # this can be triggered by the user, and programmatically?? stt_to_select = list(self.env.cds_df.loc[new_indices, STNNBR]) indices_to_select = list(self.env.wmts_map_df[ self.env.wmts_map_df[STNNBR].isin(stt_to_select)].index) self.env.map_selection = indices_to_select self.env.wmts_map_source.selected.indices = indices_to_select elif self.env.map_selection != [] and new_indices == []: if self.env.reset_selection: lg.info('>> RESET MAP SELECTION') self.env.map_selection = [] self.env.wmts_map_source.selected.indices = [] def _init_cb_prof_invsbl_points(self): ''' Plot the profiles with the visible points or with the invisible as well ''' def on_click_cb_prof_invsbl_points(active_list): if active_list == [0]: self.env.plot_prof_invsbl_points = True else: self.env.plot_prof_invsbl_points = False self.env.bk_sources._upd_prof_srcs() self.cb_prof_invsbl_points = CheckboxGroup( width=200, height=10, labels=['Fixed profiles'], # Plot invisible points on profiles active=[], css_classes=['fixed_profiles_cb', 'bokeh_hidden']) self.cb_prof_invsbl_points.on_click(on_click_cb_prof_invsbl_points) def _init_profile_nav(self): def next_profile(): if self.nearby_prof_cb: lg.info('-- NEXT PROFILE') s = self.env.stations next_pos = s.index(self.env.cur_nearby_prof) + 1 if next_pos < len(self.env.stations): if s[next_pos] == self.env.stt_to_select: next_pos = next_pos + 1 if next_pos < len(self.env.stations): self.env.cur_nearby_prof = s[next_pos] self.env.bk_sources._upd_prof_srcs(force_selection=True) self.nearby_prof_div.text = str( int(self.env.cur_nearby_prof)) # adjust disabled buttons if next_pos + 1 == len(self.env.stations): self.next_prof_bt.disabled = True self.previous_prof_bt.disabled = False def previous_profile(): lg.info('-- PREVIOUS PROFILE') if self.nearby_prof_cb: s = self.env.stations previous_pos = s.index(self.env.cur_nearby_prof) - 1 if previous_pos >= 0: if s[previous_pos] == self.env.stt_to_select: previous_pos = previous_pos - 1 if previous_pos >= 0: self.env.cur_nearby_prof = s[previous_pos] self.env.bk_sources._upd_prof_srcs(force_selection=True) self.nearby_prof_div.text = str( int(self.env.cur_nearby_prof)) # adjust disabled buttons if previous_pos == 0: self.previous_prof_bt.disabled = True self.next_prof_bt.disabled = False self.next_prof_bt = Button( width=30, disabled=True, label=">", button_type="success", ) self.nearby_prof_div = Div( width=100, height=30, text='None', css_classes=['cur_stt'], ) self.previous_prof_bt = Button( width=30, disabled=True, label="<", button_type="success", ) self.next_prof_bt.on_click(next_profile) self.previous_prof_bt.on_click(previous_profile) def _init_nearby_prof_cb(self): def on_click_nearby_prof(active_list): lg.info('-- ONCLICK NEARBY PROF') lg.info('>> SELECTED STT: {}'.format(self.env.stt_to_select)) if 0 in active_list: self.env.plot_nearby_prof = True self.set_cur_nearby_prof() self.env.bk_sources._upd_prof_srcs(force_selection=True) else: self.env.plot_nearby_prof = False self.next_prof_bt.disabled = True self.previous_prof_bt.disabled = True self.env.cur_nearby_prof = None self.nearby_prof_div.text = 'None' self.env.bk_sources._upd_prof_srcs(force_selection=True) self.nearby_prof_cb = CheckboxGroup( width=200, height=20, labels=['Show nearby station'], active=[], css_classes=['show_nearby_station_cb', 'bokeh_hidden']) self.nearby_prof_cb.on_click(on_click_nearby_prof) def set_cur_nearby_prof(self): lg.info('-- SET CUR NEARBY PROF') self.next_prof_bt.disabled = False # TODO: if the database has only one station? self.previous_prof_bt.disabled = False # NOTE: get the default extra station: the next one if exists # if not, the previous one if self.env.stt_to_select is not None: next_pos = self.env.stations.index(self.env.stt_to_select) + 1 if next_pos < len(self.env.stations): self.env.cur_nearby_prof = self.env.stations[next_pos] self.nearby_prof_div.text = str(int(self.env.cur_nearby_prof)) else: previous_pos = self.env.stations.index( self.env.stt_to_select) - 1 if previous_pos >= 0: self.env.cur_nearby_prof = self.env.stations[previous_pos] self.nearby_prof_div.text = str( int(self.env.cur_nearby_prof)) def _init_tabs(self): lg.info('-- INIT TABS') panel_list = [] # lg.info('>> self.env.TABS_FLAGS_PLOTS: {}'.format(self.env.tabs_flags_plots)) SORT_TABS = False if SORT_TABS: ordered_tab_list = sorted(self.env.tabs_flags_plots) else: ordered_tab_list = list(self.env.tabs_flags_plots.keys()) self.env.cur_tab = ordered_tab_list[ 0] # self.env.cur_tab initialization self.env.cur_flag = self.env.cur_tab + FLAG_END # self.env.cur_tab initialization ly_settings = self.env.f_handler.get_layout_settings() for tab in ordered_tab_list: indices = self.env.tabs_flags_plots[tab]['plots'] children = [ x.plot for x in self.env.bk_plots if x.n_plot in indices ] # lg.info('>> CHILDREN: {}'.format(children)) gp = gridplot( children=children, ncols=ly_settings['ncols'], plot_width=ly_settings[ 'plot_width'], # if 350 then the points are blurred plot_height=ly_settings['plot_height'], toolbar_location= 'left', # TODO: separate the toolbars to set some tools active by default, # like this the hover icon can be shown as well ) name = 'panel_{}'.format(tab.lower()) panel_list.append( Panel( name='panel_{}'.format(tab.lower()), child=gp, title=tab, )) # TODO: closable=True lg.info('>> TABS WIDGET: {}'.format(self.env.tabs_widget)) if self.env.tabs_widget is None: self.env.tabs_widget = Tabs( name='tabs_widget', tabs=panel_list, width=1250, ) else: self.env.tabs_widget.tabs.clear() self.env.tabs_widget.tabs = panel_list def update_active_tab(attr, old, new): lg.info('-- UPDATE ACTIVE TAB | OLD: {} | NEW: {}'.format( old, new)) self.env.cur_tab = self.env.tabs_widget.tabs[new].title lg.info('>> CUR TAB: {}'.format(self.env.cur_tab)) flag = self.env.tabs_flags_plots[self.env.cur_tab]['flag'] if self.env.flagger_select.value != flag: self.env.tab_change = True self.env.flagger_select.value = flag # if they concide the update of the select is not triggered self.env.tabs_widget.on_change('active', update_active_tab)
class HyperloopClusteringServer: def __init__(self): self.MODULE = "{} v{}".format(__library__, __version__) self._logger("INIT " + self.MODULE) pd.options.display.float_format = '{:,.3f}'.format pd.set_option('expand_frame_repr', False) self.FULL_DEBUG = False self.s_prefix = dt.strftime(dt.now(), '%Y%m%d') self.s_prefix += "_" self.s_prefix += dt.strftime(dt.now(), '%H%M') self.s_prefix += "_" self.save_folder = "saved_data/" self.base_tree_file = "_tree.png" self.tree_file = "" self.current_X = 'N/A' self.current_Y = 'N/A' self.default_cluster_view = "F1/F2" self.nr_shown_records = 10 self.ClusterDescription = '' self.text_ClusterDesc = None self.cds_select = None self.dot_alpha = 0.5 self.dot_size = 4 self.nr_downsample = 1000 self.TableViewText = None self.nr_inits = 30 self.cds = None self._logger(self.s_prefix) self._logger("__name__: {}".format(__name__)) self._logger("__file__: {}".format(__file__)) self.current_cluster_glph_renderer = None self.initialize_data() self.initialize_layout() return def upper_config_str(self, mydict): newdict = dict() for k, v in mydict.items(): newdict[k.upper()] = v return newdict def _logger(self, logstr, show=True): if not hasattr(self, 'log'): self.log = list() nowtime = dt.now() strnowtime = nowtime.strftime( "[{}][%Y-%m-%d %H:%M:%S] ".format(__lib__)) logstr = strnowtime + logstr self.log.append(logstr) if show: print(logstr, flush=True) return def ClusterDownSampler(self, source_df, label_field, cluster_fields, nr_samples): if self.DownSample: t0 = tm.time() self._logger("DOWNSAMPLING ...") labels = list(source_df[label_field].unique()) if label_field in cluster_fields: cluster_fields.remove(label_field) all_fields = list(cluster_fields) all_fields.append(label_field) downsampled = pd.DataFrame() for label in labels: cluster_df = pd.DataFrame( source_df[source_df[label_field] == label]) if cluster_df.shape[0] > nr_samples: nr_cl = nr_samples else: nr_cl = cluster_df.shape[0] self._logger("Downsampling {} in {} points".format( label, nr_samples)) clf = KMeans(n_clusters=nr_cl, n_jobs=-1, n_init=5) clf.fit(np.array(cluster_df[cluster_fields])) cluster_df['DownCluster'] = clf.labels_ down_df = pd.DataFrame() i = 0 for fld in cluster_fields: down_df[fld] = clf.cluster_centers_[:, i] i += 1 down_df[label_field] = label self._logger("Downsampled data {}\n{}".format( down_df.shape, down_df.head(3))) downsampled = downsampled.append(down_df) t1 = tm.time() self._logger('Done in {:.1f}s downsampling {}\n{}'.format( t1 - t0, downsampled.shape, downsampled.head(3))) df_result = downsampled else: self._logger("NO DOWNSAMPLE !!!") df_result = source_df return df_result def UploadCluster(self, df, cluster_dict): clRep = ClusterRepository() clRep.UploadCluster(df, cluster_dict, self.sql) return def _upload_cluster(self, sClusterName, sClusterObs, sClusterGrade, nCentroidNo, nCustomerNo, sClusterAuthor, sClusterAlgorithm, sF1_Obs, sF2_Obs, sF3_Obs, sF4_Obs, sF5_Obs, df_cluster, df_desc): cConfig = self.cluster_config clRep = ClusterRepository() clRep.UploadClusterDetail(sClusterName, sClusterObs, sClusterGrade, nCentroidNo, nCustomerNo, sClusterAuthor, sClusterAlgorithm, sF1_Obs, sF2_Obs, sF3_Obs, sF4_Obs, sF5_Obs, df_cluster, df_desc, cConfig, self.sql) return def _loadconfig(self, config_file="cluster_config.txt"): self._logger("Loading config '{}'...".format(config_file)) cfg_file = open(config_file) self.config_data = json.load(cfg_file) if self.FULL_DEBUG: self._logger(self.config_data) self.cluster_config_list = list() for cluster_key in self.config_data.keys(): cluster_def = self.config_data[cluster_key] cluster_fields = cluster_def["Fields"] cluster_ID = cluster_def["ID"] cluster_name = cluster_def["Name"] if self.FULL_DEBUG: self._logger( "Loading definition for cluster: {}".format(cluster_key)) self._logger(" ID: {} / Name: {} / Fields: {}".format( cluster_ID, cluster_name, cluster_fields)) cluster_def["DATA"] = None self.cluster_config_list.append(cluster_def) return def _setup_fields(self, cluster_dict): self.cID = cluster_dict["ID"] #'PartnerId' #'CustID' self.cf = list() for i in range(5): if cluster_dict["Fields"][i] != '': self.cf.append(cluster_dict["Fields"][i]) #self.cf1 = cluster_dict["Fields"][0] #'RecencyScore' #R #self.cf2 = cluster_dict["Fields"][1] #'NrTransactions' #F #self.cf3 = cluster_dict["Fields"][2] # 'TotalAmount' #'TotalValue' #M self.nr_fields = len(self.cf) if self.nr_fields == 3: self.scale_cf = [1, 2] #[0,1,2] #log-scale fields by nr else: self.scale_cf = [0, 1] self.cfc = 'Segment' # cluster label column self.AssignmentID = "CentroidID" if "SEGMENTS" in cluster_dict.keys(): self.nr_clusters = int(cluster_dict["SEGMENTS"]) self._logger("Starting with {} clusters".format(self.nr_clusters)) else: self.nr_clusters = 4 self._logger("Defaulting to {} clusters".format(self.nr_clusters)) self.nr_tree_lvl = 3 self.hover_fields = dict() self.hover_fields['Tranzactii (avg)'] = "TranCount" self.hover_fields['Valoare totala (avg)'] = "TotalAmount" self.scaling_method = 'MinMax' self.refresh_tooltips(self.hover_fields) return def _load_db_cluster(self, strqry): df_temp = self.sql.Select(strqry) self.df_rfm = pd.DataFrame(df_temp[df_temp[self.cID] != -1]) self._logger("Loaded dataset {} rows with head(3) \n{}".format( self.df_rfm.shape[0], self.df_rfm.head(3))) self.origin_fields = list() self.cluster_fields = list() for i in range(len(self.cf)): if self.cf[i] != '': self.origin_fields.append(self.cf[i]) self.cluster_fields.append('F' + str(i + 1)) return def LoadDBClusterByID(self, sID): self._logger("Loading cluster by ID: {}".format(sID)) strqry = self.config_data[sID]["SQL"] self.cluster_config = self.config_data[sID] self.FastSave = False self.DownSample = True if "DOWNSAMPLE" in self.cluster_config.keys(): self.DownSample = int(self.cluster_config["DOWNSAMPLE"]) if not self.DownSample: self._logger("DOWNSAMPLING DISABLED !") if "FASTSAVE" in self.cluster_config.keys(): self.FastSave = int(self.cluster_config["FASTSAVE"]) if self.FastSave: self._logger("FASTSAVE ENABLED !") self._setup_fields(self.cluster_config) self._load_db_cluster(strqry) return def LoadDBClusterByName(self, sName): strqry = None cluster_dict = None for i in range(len(self.cluster_config_list)): if sName == self.cluster_config_list[i]["Name"]: strqry = self.cluster_config_list[i]["SQL"] cluster_dict = self.cluster_config_list[i] if strqry != None: self.cluster_config = cluster_dict self._logger("Loading cluster by Name: {}".format(sName)) self._setup_fields(self.cluster_config) self._load_db_cluster(strqry) else: self._logger("\nERROR LOADING CLUSTER CONFIGURATION FILE\n") return def refresh_tooltips(self, dict_tooltips): self.hover_fields = dict_tooltips self.tooltip1 = list(self.hover_fields.keys())[0] self.tooltip2 = list(self.hover_fields.keys())[1] self.tip1_fld = self.hover_fields[self.tooltip1] self.tip2_fld = self.hover_fields[self.tooltip2] return def refresh_cds(self, cluster=False, x_col=None, y_col=None): self._logger("Refreshing ColumnDataSource ...") df_downsamp = self.df_downrfm if x_col != None and y_col != None: if self.FULL_DEBUG: self._logger("Old X: {} Y: {} / New X: {} Y: {}".format( self.current_X, self.current_Y, x_col, y_col)) self.current_X = x_col self.current_Y = y_col if cluster and (x_col == None and y_col == None): if self.FULL_DEBUG: self._logger(" refreshing labels field '{}' only".format( self.cfc)) self.cds.data[self.cfc] = np.array(df_downsamp[self.cfc]) else: data_dict = dict(X=np.array(df_downsamp[self.current_X]), Y=np.array(df_downsamp[self.current_Y])) data_dict[self.cfc] = np.array(df_downsamp[self.cfc]) if False: data_dict[self.tip1_fld] = np.array(self.df_rfm[self.tip1_fld]) data_dict[self.tip2_fld] = np.array(self.df_rfm[self.tip2_fld]) data_dict[self.cID] = np.array(self.df_rfm[self.cID]) if self.FULL_DEBUG: self._logger(" refreshing full cds: {}".format( list(data_dict.keys()))) if self.cds == None: self.cds = ColumnDataSource(data_dict) else: self.cds.data = data_dict if self.FULL_DEBUG: self._logger("Done refreshing ColumnDataSource.") return def analyze_segments(self): self.segment_id_fld = "Cluster" self.segment_samples_fld = "Clienti" self.segment_value_fld = "Scor" self.segment_name_fld = self.cfc # default always self.df_clusters = pd.DataFrame() cluster_norm = np.zeros(self.nr_clusters) cluster_vals = np.zeros(self.nr_clusters) for i in range(self.nr_clusters): cluster_norm[i] = np.mean(self.cluster_centers[i, :]) if self.FULL_DEBUG: self._logger(" cluster {} vals {}".format( i, (self.df_rfm[self.cfc] == i).head(3))) cluster_vals[i] = (self.df_rfm[self.cfc] == i).sum() self.df_clusters[self.segment_id_fld] = np.arange( 0, self.nr_clusters, 1) self.df_clusters[self.segment_value_fld] = cluster_norm self.df_clusters[self.segment_samples_fld] = cluster_vals self.df_clusters.sort_values(by=self.segment_value_fld, ascending=False, inplace=True) self.df_clusters = self.df_clusters.reset_index() clfields = [ self.segment_id_fld, self.segment_value_fld, self.segment_samples_fld ] self.df_clusters = self.df_clusters[clfields] lev_2 = ["MOST VALUED CUSTOMERS", "LOWER RANGE CUSTOMERS"] lev_3 = [ "MOST VALUED CUSTOMERS", "AVERAGE CUSTOMERS", "LOWER RANGE CUSTOMERS" ] lev_4 = [ "MOST VALUED CUSTOMERS", "GOOD CUSTOMERS", "AVERAGE CUSTOMERS", "LOWER RANGE CUSTOMERS", "BOTTOM CUSTOMERS", "WORST CUSTOMERS" ] new_ids = list() for i in range(self.nr_clusters): new_ids.append(100 * (i + 1)) if self.nr_clusters == 2: self.levels = lev_2 elif self.nr_clusters == 3: self.levels = lev_3 else: self.levels = list() for i in range(self.nr_clusters): self.levels.append(lev_4[i]) self.df_clusters[self.cfc] = self.levels self.df_clusters['NewID'] = new_ids self._logger("Customer segmentation structure:\n {}".format( self.df_clusters)) self.clusters_dict = dict() for i in range(self.nr_clusters): self.clusters_dict[self.df_clusters.loc[ i, self.segment_id_fld]] = self.df_clusters.loc[i, self.cfc] if self.FULL_DEBUG: self._logger("Cluster dict: {}".format(self.clusters_dict)) self.class_names = list() for i in range(self.nr_clusters): self.class_names.append(self.clusters_dict[i]) if self.FULL_DEBUG: self._logger("Class names: {}".format(self.class_names)) # df_rfm[cfc] must be working #self.df_rfm["TEMP_SEGMENT"] = self.df_rfm[self.cfc].astype(str) #self.df_rfm["TEMP_SEGMENT"] = self.df_rfm["TEMP_SEGMENT"].map(self.map_func) self.df_rfm[self.AssignmentID] = self.df_rfm[self.cfc] self.df_rfm[self.cfc] = self.df_rfm[self.cfc].map(self.map_func) old_clusters_list = self.df_rfm[self.AssignmentID].unique() strDesc = '' for i in range(self.nr_clusters): old_cluster = old_clusters_list[i] pos = self.df_clusters[self.segment_id_fld] == old_cluster new_cluster = self.df_clusters[pos]["NewID"].values[0] sNrClients = str(self.df_clusters[pos]['Clienti'].values[0]) sLabel = self.df_clusters[pos]['Segment'].values[0] strDesc += " " + sNrClients + " clients in segment " + sLabel + "," self._logger('Replacing ClusterID {} with {}'.format( old_cluster, new_cluster)) self.df_rfm[self.AssignmentID].replace(old_cluster, new_cluster, inplace=True) self._logger('Found: {}'.format(strDesc)) self.ClusterDescription = self.cluster_config['Description'] + strDesc if self.text_ClusterDesc != None: self.text_ClusterDesc.value = self.ClusterDescription self._logger("Top and bottom 3:\nTop 3:\n{}\nBottom 3:\n{}\n".format( self.df_rfm.head(3), self.df_rfm.tail(3))) return def map_func(self, val): vvv = int(val) lvl = self.clusters_dict[vvv] return lvl def _deprecated_update_tree_figure(self, s_png): img = mat_Image.imread(s_png) img = (img * 255).astype(np.uint8) N, M, _ = img.shape img = img.view(dtype=np.uint32).reshape( (N, M)) #convert image NxM dtype=uint32 img = img[::-1] self._logger('IMG SHAPE {}'.format(img.shape)) y_rng = 10 xfact = float(M / N) x_rng = int(y_rng * xfact) self._logger("X:{} Y:{}".format(x_rng, y_rng)) # fig = self.tab2_layout.children[1] fig = figure(x_range=(0, x_rng), y_range=(0, y_rng)) # prepare tree display tab fig.plot_width = 900 fig.plot_height = int(fig.plot_width / xfact) # done tree display tab fig.image_rgba(image=[img], x=0, y=0, dw=x_rng, dh=y_rng) self.tab2_layout.children[1] = fig #self.tab2_empty_tree_fig.plot_width = 900 #self.tab2_empty_tree_fig.plot_height = int(900 / xfact) #self.tab2_empty_tree_fig.image_rgba(image=[img], # x=0, y=0, # dw=x_rng, dh=y_rng) self.update_cluster_image(self.current_cluster_view) return img def update_png(self): s_file = self.tree_file self.DivText3.text = self.DivText3.text + " {}".format( self.class_names) self._logger("Update tree view {} ...".format(s_file)) #img = self.update_tree_figure(s_png) image_url = "http://*****:*****@" + self.cfc), ("Client", "@" + self.cID), (tip1, "@" + self.hover_fields[tip1]), (tip2, "@" + self.hover_fields[tip2]), ]) if self.FULL_DEBUG: self._logger(" Tooltips: {}".format(self.hover.tooltips)) self.cluster_figure.add_tools(self.hover) self.update_cluster_image(self.current_cluster_view) self.empty_selection = self.current_cluster_glph_renderer.data_source.selected self.btn_reset = Button(label="Deselectare", width=20) self.btn_reset.on_click(self.on_reset_selection) self.btn_save = Button(label="Salvare", width=50) self.btn_save.on_click(self.on_save) self.btn_save_local = Button(label="Salvare doar local", width=50) self.btn_save_local.on_click(self.on_save_local) columns = list() for col in self.df_rfm.columns: if col == self.cfc: tblcol = TableColumn( field=col, title=col, width=200, formatter=StringFormatter(font_style="bold")) else: tblcol = TableColumn( field=col, title=col, width=50, formatter=NumberFormatter(format="0[.]00")) columns.append(tblcol) self.data_table = DataTable(source=self.cds_select, columns=columns, width=1200, height=500, fit_columns=False) self.cb_select_k = Select(title="Vizualizare segment:", value=self.current_segment, options=self.segments) self.cb_select_k.on_change("value", self.on_view_cluster) self.cb_scaling = Select(title="Metoda de scalare/normalizare:", value="MinMax", options=['MinMax', 'ZScore']) self.cb_scaling.on_change("value", self.on_cb_scaling) self.TableViewText = Div(text="N/A") self.ckbox_transf = CheckboxGroup( labels=["F1 LogTransform", "F2 LogTransform", "F3 LogTransform"], active=self.scale_cf) self.ckbox_transf.on_click(self.on_log_check) self.text_ClusterName = TextInput( value=self.cluster_config['Name'] + " ({} segments)".format(self.nr_clusters), title="Nume model:", width=400) self.cb_ClusterGrade = Select(title="Calitatea output:", value='PRODUCTION', width=300, options=['TESTS', 'PRODUCTION']) self.text_ClusterDesc = TextInput(value=self.ClusterDescription, title="Descriere:", width=700) self.text_Author = TextInput(value='Andrei Ionut Damian', title="Autor:") self.text_Algorithm = TextInput(value=self.sAlgorithm, title="Algoritm:", width=700) self.text_F1 = TextInput(value=self.cluster_config['Fields'][0], title="Descriere camp F1:") self.text_F2 = TextInput(value=self.cluster_config['Fields'][1], title="Descriere camp F2:") self.text_F3 = TextInput(value=self.cluster_config['Fields'][2], title="Descriere camp F3:") ## ## done with the controls ## ## ## now to layout preparation ## self.row_btns = row(self.btn_reset, self.btn_save) self.mytabs = list() # tab1: clusters self.tab1_col1_controls = column(widgetbox(self.slider), widgetbox(self.cb_select_rfm), widgetbox(self.slider_tree), widgetbox(self.cb_scaling), widgetbox(self.ckbox_transf), self.DivText1, self.DivText2, self.btn_reset, self.text_ClusterName, widgetbox(self.cb_ClusterGrade), self.text_Author) self.tab1_col2_controls = column(self.cluster_figure, self.text_ClusterDesc, self.text_Algorithm, self.text_F1, self.text_F2, self.text_F3, self.btn_save, self.btn_save_local) self.tab1_layout = row(self.tab1_col1_controls, self.tab1_col2_controls) self.tab1 = widgets.Panel(child=self.tab1_layout, title='Segmentare') self.mytabs.append(self.tab1) #tab 2 table view self.tab2_controls = row(widgetbox(self.slider_table), widgetbox(self.cb_select_k), self.TableViewText) self.tab2_layout = column(self.tab2_controls, self.data_table) self.tab2 = widgets.Panel(child=self.tab2_layout, title='Vizualizare date') self.mytabs.append(self.tab2) # tab 3 tree view #self.tab3_empty_tree_fig = figure(x_range=(0,40), y_range=(0,10)) self.DivTreeImage = Div(text="") dt3 = "Arborele de decizie al segmentarii clientilor." #dt3+= " 'Value' reprezinta numarul de elemente din clasele {}".format(self.class_names) self.DivText3 = Div(text=dt3, width=1000, height=50) self.tab3_layout = column(self.DivText3, self.DivTreeImage) self.tab3 = widgets.Panel(child=self.tab3_layout, title='Vizualizare arbore') self.mytabs.append(self.tab3) # finalizare layout self.update_png() self.update_texts(self.last_tree_accuracy, self.last_clustering_error) self.final_layout = widgets.Tabs(tabs=self.mytabs) self._logger("!!! DONE LAYOUT PREPARATION.\n") if self.FastSave: self.on_save() self._logger("SHUTTING DOWN ...") os.kill(os.getpid(), 9) return
button = Button(label="Push button", icon=Icon(name="check"), type="primary") button.on_click(button_handler) 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)
a_rad = 2.7 * ulens['mstar'] ulens_syms = p1.square(ulens['semi'] / a_rad, ulens['msini'] * mjup, fill_alpha=0.4, line_alpha=0.9, color='purple', size=8) p1.text([5.2 / 2.7], [317.8], ['J'], text_color="red", text_align="center") #xyouts, 5.2/2.7, 317.8, 'J', align=0.5 #xyouts, 9.6/2.7, 95.2, 'S', align=0.5 #xyouts, 19.2/2.7, 14.5, 'U', align=0.5 #xyouts, 30.1/2.7, 17.1, 'N', align=0.5 #xyouts, 1.0/2.7, 1.0, 'E', align=0.5 #xyouts, 0.72/2.7, 0.8, 'V', align=0.5 #xyouts, 1.5/2.7, 0.1, 'M', align=0.5 #xyouts, 0.39/2.7, 0.055, 'M', align=0.5 def update_image(active): print 'wHAT?' print active print active.__contains__(1) p = gridplot([[p1, checkbox_button_group]]) checkbox_button_group.on_click(update_image) curdoc().add_root(p)
player_table['war'].push(parseFloat(player[2])); player_table['team'].push(player[3]); player_table['country'].push(player[1]); } player_table['name'].pop(); player_table['war'].pop(); player_table['team'].pop(); player_table['country'].pop(); } table_source.data = player_table; """ controls = [min_year, max_year, search_player] for control in controls: control.on_change('value', lambda attr, old, new: update()) country_select.on_click(update_wrapped) clear_button.on_click(update_click_wrapped) controls += [country_select] controls.insert(3, clear_button) sizing_mode = 'fixed' # 'scale_width' also looks nice with this example # Add Circle tooltips on hover hover = HoverTool(tooltips=[("Team", "@team"), ("Total", "@war")], renderers=[circles]) click = TapTool(renderers=[circles]) click.callback = CustomJS(args={ 'source': source, 'circle': circles.data_source, 'table_source': table_source },
menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) dropdown.on_click(lambda value: print('dropdown: %s' % value)) 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=[
# toggle second axis button toggle_second_axis_button = Button(label="Toggle Second Axis", button_type="success") toggle_second_axis_button.on_click(toggle_second_axis) # averaging slider # This data source is just used to communicate / trigger the real callback averaging_slider_dummy_source = ColumnDataSource(data=dict(value=[])) averaging_slider_dummy_source.on_change('data', update_averaging) averaging_slider = Slider(title="Averaging window", start=1, end=101, step=10, callback_policy='mouseup') averaging_slider.callback = CustomJS(args=dict(source=averaging_slider_dummy_source), code=""" source.data = { value: [cb_obj.value] } """) # group properties checkbox group_cb = CheckboxGroup(labels=["Show statistics bands", "Ungroup signals"], active=[]) group_cb.on_click(toggle_group_property) # color selector color_selector_title = Div(text="""Select Color:""") crsource = ColumnDataSource(data=dict(x=crx, y=cry, crcolor=crcolor, RGBs=crRGBs)) color_selector = figure(x_range=(0, color_resolution), y_range=(0, 10), plot_width=300, plot_height=40, tools='tap') color_selector.axis.visible = False color_range = color_selector.rect(x='x', y='y', width=1, height=10, color='crcolor', source=crsource) crsource.on_change('selected', select_color) color_range.nonselection_glyph = color_range.glyph color_selector.toolbar.logo = None color_selector.toolbar_location = None
def h_t_tab(self): """Plots the humidity and temperature""" self.h_t_fig = figure(plot_width=int(self.page_width*0.9), plot_height=self.page_height, title="Temperature and humidity", toolbar_location="above", x_axis_type="datetime") self.h_t_fig.xaxis.axis_label = "Timestamp" self.h_t_fig.yaxis.axis_label = "Temperature (C)" # Ranges need to be defined here - causes update issues if this # doesn't happen here self.h_t_fig.y_range = Range1d(start=0, end=100) self.h_t_fig.extra_y_ranges = {'humidity': Range1d(start=0, end=100)} self.h_t_fig.add_layout(LinearAxis(y_range_name='humidity', axis_label="Relative humidity (%)"), 'right') # Add the lines self.h_t_line = 2*[None] # Plot the humidity/pressure self.h_t_line[0] = self.h_t_fig.line(x='Timestamp', y='Temperature (C)', source=self.source, color="blue", legend="Temperature", line_width=2) self.h_t_line[1] = self.h_t_fig.line(x="Timestamp", y="Relative humidity (%)", source=self.source, y_range_name="humidity", color="green", legend="Humidity", line_width=2) # Update the data and the plot ranges self.h_t_update() # Checkboxes to show lines resp_b = [0, 1] h_t_check_head = Div(text="Responses") h_t_check = CheckboxGroup(labels=["Temperature", "Humidity"], active=resp_b, name="Lines") h_t_check.on_click(self.h_t_lines_changed) # Lay out the page w = widgetbox(h_t_check_head, h_t_check, width=int(self.page_width*0.1)) l = row(w, self.h_t_fig) return Panel(child=l, title="Temperature and humidity")
# Create widgetbox of parameters widgets_select = widgetbox(text_dataset, slider_et, slider_ws, text_period) panel_select = Panel(child=widgets_select, title='Area/Time') text_events = Div(text='<h3>Select event types</h3>') checkbox_events = CheckboxGroup(labels=all_event_types, active=list(range(len(all_event_types)))) def checkbox_callback(variable): update_pivot_table(events_to_include=get_events_to_include()) update_time_window_datasources() checkbox_events.on_click(checkbox_callback) widgets_events = widgetbox(text_events, checkbox_events) panel_events = Panel(child=widgets_events, title='Types') # Create Panel of Prophet parameters prophet_widgets = widgetbox(text_prophet_parameters, checkbox_log_scale, slider_window_size, text_reg_changepoint, text_reg_season, slider_freq_days, text_periods) panel_prophet = Panel(child=prophet_widgets, title='Prophet') # Button: Run Prophet! button_run_prophet = Button(label="Run Prohpet!") def button_run_prophet_callback():
"Average edition bytes", "Monthly average edition bytes" ] cbg_pages = CheckboxGroup(labels=cbg_labels[0:4], active=[0], css_classes=['pages_checks']) cbg_editions = CheckboxGroup(labels=cbg_labels[4:10], active=[0], css_classes=['edition_checks']) cbg_users = CheckboxGroup(labels=cbg_labels[10:17], active=[], css_classes=['users_checks']) cbg_ratios = CheckboxGroup(labels=cbg_labels[17:20], active=[], css_classes=['other_checks']) cbg_pages.on_click(cb_callback) cbg_editions.on_click(cb_callback) cbg_users.on_click(cb_callback) cbg_ratios.on_click(cb_callback) #cbg.on_click(cb_callback) sizing_mode = "fixed" time_slider = Slider(start=1, end=len(dates), value=len(dates), step=1, title="Months from creation", width=1580) date_div = Div(text='<h1 style="text-align:center"> Stats until:' + time[-1] + '<h1>', width=1600)