def _generate_dataframecontainer(self, container): self.data_column = widgets.Select( title='Data Column', options=container.dataframe.columns.to_list()) self.labels_column = widgets.Select( title='Labels Column', options=container.dataframe.columns.to_list()) self.controls = [self.data_column, self.labels_column] for c in self.controls: show(c)
def setup_layout(self): #layout setup self.flights = bkwidgets.MultiSelect() tile_provider = get_provider(Vendors.CARTODBPOSITRON) p = bkplot.figure(x_axis_type='mercator', y_axis_type='mercator') p.add_tile(tile_provider) self.p2 = bkplot.figure() self.lines = self.p2.line(x='time', y='param', source=self.source2) self.hist = self.p2.quad(source=self.source3, top='top', bottom='bottom', left='left', right='right') self.params = bkwidgets.Select( options=['altitude', 'tas', 'fpf', 'performance_hist'], value='altitude') p2control = bklayouts.WidgetBox(self.params) layout = bklayouts.layout(self.controls, p) self.tables = bkwidgets.Select(options=self.tableList, value=self.tableList[0]) self.time = bkwidgets.RangeSlider() self.populated = False #plot setup self.points = p.triangle(x='longitude', y='latitude', angle='heading', angle_units='deg', alpha=0.5, source=self.source) hover = bk.models.HoverTool() hover.tooltips = [("Callsign", "@callsign"), ("Time", "@time"), ("Phase", "@status"), ("Heading", "@heading"), ("Altitude", "@altitude"), ("Speed", "@tas")] hover2 = bk.models.HoverTool() hover2.tooltips = [("Callsign", "@callsign")] self.p2.add_tools(hover2) p.add_tools(hover) #callback setup self.params.on_change('value', self.plot_param) self.tables.on_change('value', self.set_data_source) self.cmdline.on_change('value', self.runCmd) self.controls = bklayouts.row( bklayouts.WidgetBox(self.tables, self.cmdline), bk.models.Div(width=20), p2control) self.layout = bklayouts.column(self.controls, bklayouts.row(p, self.p2))
def __init__(self): #Set connection to postgres database based on the credentials mentioned self.db_access = Access() cursor = self.db_access.cursor self.cmdline = bkwidgets.TextInput() self.tableList = getTableList(cursor) self.tables = bkwidgets.Select(options=self.tableList, value=self.tableList[0]) self.controls = bklayouts.widgetbox() #data source setup self.results = pd.DataFrame(columns=[ 'id', 'time', 'callsign', 'latitude', 'longitude', 'heading', 'altitude', 'tas', 'param' ]) self.source = ColumnDataSource(self.results) self.source2 = ColumnDataSource(self.results) self.source3 = ColumnDataSource({ 'top': [], 'bottom': [], 'left': [], 'right': [] }) self.perf_results = None self.setup_layout()
def create_layout(self, match): plot_6t = self.total_6t(match) match_sel = bk_widgets.Select(title='Match', options=self.list_matches()) match_sel.on_change('value', self.callback_6t) self.layout = bk_layouts.row(match_sel, plot_6t) return self.layout
def _init_controls(self): """Initialize all controls in the dashboard""" # EEG/ECG Radio button self.mode_control = widgets.Select(title="Signal", value='EEG', options=MODE_LIST, width=170, height=50) self.mode_control.on_change('value', self._change_mode) self.t_range = widgets.Select(title="Time window", value="10 s", options=list(TIME_RANGE_MENU.keys()), width=170, height=50) self.t_range.on_change('value', self._change_t_range) self.y_scale = widgets.Select(title="Y-axis Scale", value="1 mV", options=list(SCALE_MENU.keys()), width=170, height=50) self.y_scale.on_change('value', self._change_scale) # Create device info tables columns = [widgets.TableColumn(field='heart_rate', title="Heart Rate (bpm)")] self.heart_rate = widgets.DataTable(source=self._heart_rate_source, index_position=None, sortable=False, reorderable=False, columns=columns, width=170, height=50) columns = [widgets.TableColumn(field='firmware_version', title="Firmware Version")] self.firmware = widgets.DataTable(source=self._firmware_source, index_position=None, sortable=False, reorderable=False, columns=columns, width=170, height=50) columns = [widgets.TableColumn(field='battery', title="Battery (%)")] self.battery = widgets.DataTable(source=self._battery_source, index_position=None, sortable=False, reorderable=False, columns=columns, width=170, height=50) columns = [widgets.TableColumn(field='temperature', title="Device temperature (C)")] self.temperature = widgets.DataTable(source=self.temperature_source, index_position=None, sortable=False, reorderable=False, columns=columns, width=170, height=50) columns = [widgets.TableColumn(field='light', title="Light (Lux)")] self.light = widgets.DataTable(source=self.light_source, index_position=None, sortable=False, reorderable=False, columns=columns, width=170, height=50) if self.mode == 'signal': widget_list = [Spacer(width=170, height=30), self.mode_control, self.y_scale, self.t_range, self.heart_rate, self.battery, self.temperature, self.firmware] elif self.mode == 'impedance': widget_list = [Spacer(width=170, height=40), self.battery, self.temperature, self.firmware] widget_box = widgetbox(widget_list, width=175, height=450, sizing_mode='fixed') return widget_box
def layout_1t(self, team, tasks): self.total_1t(team, tasks) self.team_sel = bk_widgets.Select(title='Match', options=self.list_teams(), value=team) self.team_sel.on_change('value', self.team_callback) self.task_sel = bk_widgets.MultiSelect(title='Tasks', options=self.data.enum_tasks, size=40, value=tasks) btn = bk_widgets.Button(label='Update') btn.on_click(self.button_callback) col_layout = bk_layouts.column(self.team_sel, self.task_sel, btn) self.layout = bk_layouts.row(col_layout, self.pcplot) return self.layout
def Select(ps, a, opts, backend="python"): """Create a selector with callback for plots "ps" with glyph attribute "a" Args: ps: a list of plots a: glyph attribute opts: a dictionary where the keys are data source columns and values are selector labels. backend: choose callback backend; the only supported backend is "python" Returns: An instance of Bokeh Select Examples: >>> import interview as iv >>> ... >>> plt = fig.circle(...) >>> sel = iv.widget.Select(plt, 'x', opts) """ import bokeh.models.widgets as bw if not isinstance(ps, list): ps = [ps] s = bw.Select(title =a.upper()+" Axis", options=list(opts.values()), value =opts[getattr(ps[0].glyph, a)]) if backend == "python": def callback(attr, old, new): for p in ps: setattr(p.glyph, a, list(opts.keys())[list(opts.values()).index(new)]) s.on_change("value", callback) else: raise ValueError('the only supported backend is "python"') return s
int((legend_index + 1) * max_value / map_legend_steps)) + '</span></div>' map_legend_string += '</div>' return map_legend_string widgets = col.OrderedDict(( ('legends_heading', bmw.Div(text='Legends', id='legends_heading')), ('techs_legend', bmw.Div(text=tech_legend_string, id='techs_legend')), ('scenarios_legend', bmw.Div(text=scenario_legend_string, id='scenarios_legend')), ('maps_legend', bmw.Div(text=build_map_legend(), id='maps_legend')), ('show_heading', bmw.Div(text='Show', id='show_heading')), ('scenarios_compare', bmw.Select(value='Show All', options=['Show All', 'Show Difference with Base'], id='scenarios_compare')), ('result', bmw.Select(value=gdx_structure.keys()[0], options=gdx_structure.keys(), id='result')), ('format', bmw.Select(value='Chart', options=['Figure', 'Table', 'Map'], id='format')), ('charttype', bmw.Select(value='Stacked Area', options=['Stacked Area'], id='charttype')), ('set_axis_ranges_heading', bmw.Div(text='Set axis ranges', id='set_axis_ranges_heading')), ('set_x_min', bmw.TextInput(title='x min', value='', id='set_x_min')), ('set_x_max', bmw.TextInput(title='x max', value='', id='set_x_max')),
from bokeh.models import widgets from bokeh.io import show, curdoc from bokeh.layouts import widgetbox button = widgets.Button(label='Refresh') username = widgets.TextInput(title='Name', placeholder='enter your name...') school = widgets.Select(title='School', options=['SSE', 'SME', 'HSS']) def onClick(): print('hahaha') def onUserNameChange(attr, old, new): print(attr, old, new) def onSchoolChange(attr, old, new): print('school', old, new) button.on_click(onClick) username.on_change('value', onUserNameChange) school.on_change('value', onSchoolChange) # show(widgetbox(button, username, school)) curdoc().add_root(widgetbox(button, username, school))
] data_table = wd.DataTable(columns=columns, source=ColumnDataSource(), width=800) # Select the department esql = "SELECT dept_name FROM lgu.department" sqlConn_1 = connectSQLServer() with sqlConn_1.cursor(as_dict=True) as cursor_1: cursor_1.execute(esql) departments = cursor_1.fetchall() departmentlist = ['All'] for dept in departments: departmentlist.append(dept['dept_name']) dept_select = wd.Select(title="Department:", value="All", options=departmentlist) # Tab2 gpa = ['A+', 'A', 'B+', 'B', 'C+', 'C', 'D+', 'D', 'F'] # All possible grades years = ['2015', '2016', '2017'] # All possible years colors = ['#c9d9d3', '#718dbf', '#e84d60'] # Set the colors for the bar # Build up the figure data = {} data['gpa'] = [] for yr in years: data[yr] = [] source = ColumnDataSource(data=data) chart = figure(x_range=gpa,
try: return pymssql.connect(**attr) except Exception as e: print(e) quit() tsql = "SELECT dept_name FROM lgu.department" sqlConn = connectSQLServer() with sqlConn.cursor(as_dict=True) as cursor: cursor.execute(tsql) departments = cursor.fetchall() deptlist = ['All'] for dept in departments: deptlist.append(dept['dept_name']) deptSelect = wd.Select(title='Department', value='All', options=deptlist) global idx_a, idx_b, idx_c, event_a, event_b event_a = event_b = "" idx_a = idx_b = 1 idx_c = 0 def titleChoice(idx=-1): global idx_a idx_a = idx def deptChoice(idx=-1): global idx_b idx_b = idx
def build_widgets(df_source, cols, defaults, init_load=False, init_config={}): ''' Use a dataframe and its columns to set widget options. Widget values may be set by URL parameters via init_config. Args: df_source (pandas dataframe): Dataframe of the csv source. cols (dict): Keys are categories of columns of df_source, and values are a list of columns of that category. defaults (dict): Keys correspond to widgets, and values (str) are the default values of those widgets. init_load (boolean, optional): If this is the initial page load, then this will be True, else False. init_config (dict): Initial widget configuration passed via URL. Returns: wdg (ordered dict): Dictionary of bokeh.model.widgets. ''' #Add widgets wdg = collections.OrderedDict() wdg['data'] = bmw.TextInput(title='Data Source (required)', value=defaults['data_source'], css_classes=['wdgkey-data']) wdg['x_dropdown'] = bmw.Div(text='X-Axis (required)', css_classes=['x-dropdown']) wdg['x'] = bmw.Select(title='X-Axis (required)', value=defaults['x'], options=['None'] + cols['all'], css_classes=['wdgkey-x', 'x-drop']) wdg['x_group'] = bmw.Select(title='Group X-Axis By', value=defaults['x_group'], options=['None'] + cols['seriesable'], css_classes=['wdgkey-x_group', 'x-drop']) wdg['y_dropdown'] = bmw.Div(text='Y-Axis (required)', css_classes=['y-dropdown']) wdg['y'] = bmw.Select(title='Y-Axis (required)', value=defaults['y'], options=['None'] + cols['all'], css_classes=['wdgkey-y', 'y-drop']) wdg['y_agg'] = bmw.Select(title='Y-Axis Aggregation', value='Sum', options=AGGREGATIONS, css_classes=['wdgkey-y_agg', 'y-drop']) wdg['series_dropdown'] = bmw.Div(text='Series', css_classes=['series-dropdown']) wdg['series'] = bmw.Select(title='Separate Series By', value=defaults['series'], options=['None'] + cols['seriesable'], css_classes=['wdgkey-series', 'series-drop']) wdg['series_legend'] = bmw.Div(text='', css_classes=['series-drop']) wdg['explode_dropdown'] = bmw.Div(text='Explode', css_classes=['explode-dropdown']) wdg['explode'] = bmw.Select(title='Explode By', value=defaults['explode'], options=['None'] + cols['seriesable'], css_classes=['wdgkey-explode', 'explode-drop']) wdg['explode_group'] = bmw.Select(title='Group Exploded Charts By', value=defaults['explode_group'], options=['None'] + cols['seriesable'], css_classes=['wdgkey-explode_group', 'explode-drop']) wdg['filters'] = bmw.Div(text='Filters', css_classes=['filters-dropdown']) for j, col in enumerate(cols['filterable']): val_list = [str(i) for i in sorted(df_source[col].unique().tolist())] wdg['heading_filter_'+str(j)] = bmw.Div(text=col, css_classes=['filter-head']) wdg['filter_'+str(j)] = bmw.CheckboxGroup(labels=val_list, active=list(range(len(val_list))), css_classes=['wdgkey-filter_'+str(j), 'filter']) wdg['update'] = bmw.Button(label='Update Filters', button_type='success', css_classes=['filters-update']) wdg['adjustments'] = bmw.Div(text='Plot Adjustments', css_classes=['adjust-dropdown']) wdg['chart_type'] = bmw.Select(title='Chart Type', value=defaults['chart_type'], options=CHARTTYPES, css_classes=['wdgkey-chart_type', 'adjust-drop']) wdg['plot_width'] = bmw.TextInput(title='Plot Width (px)', value=str(PLOT_WIDTH), css_classes=['wdgkey-plot_width', 'adjust-drop']) wdg['plot_height'] = bmw.TextInput(title='Plot Height (px)', value=str(PLOT_HEIGHT), css_classes=['wdgkey-plot_height', 'adjust-drop']) wdg['plot_title'] = bmw.TextInput(title='Plot Title', value='', css_classes=['wdgkey-plot_title', 'adjust-drop']) wdg['plot_title_size'] = bmw.TextInput(title='Plot Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-plot_title_size', 'adjust-drop']) wdg['opacity'] = bmw.TextInput(title='Opacity (0-1)', value=str(OPACITY), css_classes=['wdgkey-opacity', 'adjust-drop']) wdg['x_scale'] = bmw.TextInput(title='X Scale', value=str(X_SCALE), css_classes=['wdgkey-x_scale', 'adjust-drop']) wdg['x_min'] = bmw.TextInput(title='X Min', value='', css_classes=['wdgkey-x_min', 'adjust-drop']) wdg['x_max'] = bmw.TextInput(title='X Max', value='', css_classes=['wdgkey-x_max', 'adjust-drop']) wdg['x_title'] = bmw.TextInput(title='X Title', value='', css_classes=['wdgkey-x_title', 'adjust-drop']) wdg['x_title_size'] = bmw.TextInput(title='X Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-x_title_size', 'adjust-drop']) wdg['x_major_label_size'] = bmw.TextInput(title='X Labels Font Size', value=str(PLOT_AXIS_LABEL_SIZE), css_classes=['wdgkey-x_major_label_size', 'adjust-drop']) wdg['x_major_label_orientation'] = bmw.TextInput(title='X Labels Degrees', value=str(PLOT_LABEL_ORIENTATION), css_classes=['wdgkey-x_major_label_orientation', 'adjust-drop']) wdg['y_scale'] = bmw.TextInput(title='Y Scale', value=str(Y_SCALE), css_classes=['wdgkey-y_scale', 'adjust-drop']) wdg['y_min'] = bmw.TextInput(title='Y Min', value='', css_classes=['wdgkey-y_min', 'adjust-drop']) wdg['y_max'] = bmw.TextInput(title='Y Max', value='', css_classes=['wdgkey-y_max', 'adjust-drop']) wdg['y_title'] = bmw.TextInput(title='Y Title', value='', css_classes=['wdgkey-y_title', 'adjust-drop']) wdg['y_title_size'] = bmw.TextInput(title='Y Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-y_title_size', 'adjust-drop']) wdg['y_major_label_size'] = bmw.TextInput(title='Y Labels Font Size', value=str(PLOT_AXIS_LABEL_SIZE), css_classes=['wdgkey-y_major_label_size', 'adjust-drop']) wdg['circle_size'] = bmw.TextInput(title='Circle Size (Dot Only)', value=str(CIRCLE_SIZE), css_classes=['wdgkey-circle_size', 'adjust-drop']) wdg['bar_width'] = bmw.TextInput(title='Bar Width (Bar Only)', value=str(BAR_WIDTH), css_classes=['wdgkey-bar_width', 'adjust-drop']) wdg['line_width'] = bmw.TextInput(title='Line Width (Line Only)', value=str(LINE_WIDTH), css_classes=['wdgkey-line_width', 'adjust-drop']) wdg['download'] = bmw.Button(label='Download csv', button_type='success') wdg['export_config'] = bmw.Div(text='Export Config to URL', css_classes=['export-config', 'bk-bs-btn', 'bk-bs-btn-success']) #use init_config (from 'widgets' parameter in URL query string) to configure widgets. if init_load: for key in init_config: if key in wdg: if hasattr(wdg[key], 'value'): wdg[key].value = str(init_config[key]) elif hasattr(wdg[key], 'active'): wdg[key].active = init_config[key] #Add update functions for widgets wdg['data'].on_change('value', update_data) wdg['update'].on_click(update_plots) wdg['download'].on_click(download) for name in wdg_col: wdg[name].on_change('value', update_wdg_col) for name in wdg_non_col: wdg[name].on_change('value', update_wdg) return wdg
def tool_handler(self, doc): from bokeh.layouts import row, column, widgetbox from bokeh.models import widgets, Spacer from bokeh.models.mappers import LinearColorMapper from bokeh.plotting import figure default_palette = self.default_palette x_coords, y_coords = self.arr.coords[ self.arr.dims[1]], self.arr.coords[self.arr.dims[0]] self.app_context.update({ 'data': self.arr, 'cached_data': {}, 'gamma_cached_data': {}, 'plots': {}, 'data_range': self.arr.T.range(), 'figures': {}, 'widgets': {}, 'color_maps': {} }) self.app_context['color_maps']['d2'] = LinearColorMapper( default_palette, low=np.min(self.arr.values), high=np.max(self.arr.values), nan_color='black') self.app_context['color_maps']['curvature'] = LinearColorMapper( default_palette, low=np.min(self.arr.values), high=np.max(self.arr.values), nan_color='black') self.app_context['color_maps']['raw'] = LinearColorMapper( default_palette, low=np.min(self.arr.values), high=np.max(self.arr.values), nan_color='black') plots, figures, data_range, cached_data, gamma_cached_data = ( self.app_context['plots'], self.app_context['figures'], self.app_context['data_range'], self.app_context['cached_data'], self.app_context['gamma_cached_data'], ) cached_data['raw'] = self.arr.values gamma_cached_data['raw'] = self.arr.values figure_kwargs = { 'tools': ['reset', 'wheel_zoom'], 'plot_width': self.app_main_size, 'plot_height': self.app_main_size, 'min_border': 10, 'toolbar_location': 'left', 'x_range': data_range['x'], 'y_range': data_range['y'], 'x_axis_location': 'below', 'y_axis_location': 'right', } figures['d2'] = figure(title='d2 Spectrum', **figure_kwargs) figure_kwargs.update({ 'y_range': self.app_context['figures']['d2'].y_range, 'x_range': self.app_context['figures']['d2'].x_range, 'toolbar_location': None, 'y_axis_location': 'left', }) figures['curvature'] = figure(title='Curvature', **figure_kwargs) figures['raw'] = figure(title='Raw Image', **figure_kwargs) figures['curvature'].yaxis.major_label_text_font_size = '0pt' # TODO add support for color mapper plots['d2'] = figures['d2'].image( [self.arr.values], x=data_range['x'][0], y=data_range['y'][0], dw=data_range['x'][1] - data_range['x'][0], dh=data_range['y'][1] - data_range['y'][0], color_mapper=self.app_context['color_maps']['d2']) plots['curvature'] = figures['curvature'].image( [self.arr.values], x=data_range['x'][0], y=data_range['y'][0], dw=data_range['x'][1] - data_range['x'][0], dh=data_range['y'][1] - data_range['y'][0], color_mapper=self.app_context['color_maps']['curvature']) plots['raw'] = figures['raw'].image( [self.arr.values], x=data_range['x'][0], y=data_range['y'][0], dw=data_range['x'][1] - data_range['x'][0], dh=data_range['y'][1] - data_range['y'][0], color_mapper=self.app_context['color_maps']['raw']) smoothing_sliders_by_name = {} smoothing_sliders = [] # need one for each axis axis_resolution = self.arr.T.stride(generic_dim_names=False) for dim in self.arr.dims: coords = self.arr.coords[dim] resolution = float(axis_resolution[dim]) high_resolution = len(coords) / 3 * resolution low_resolution = resolution # could make this axis dependent for more reasonable defaults default = 15 * resolution if default > high_resolution: default = (high_resolution + low_resolution) / 2 new_slider = widgets.Slider(title='{} Window'.format(dim), start=low_resolution, end=high_resolution, step=resolution, value=default) smoothing_sliders.append(new_slider) smoothing_sliders_by_name[dim] = new_slider n_smoothing_steps_slider = widgets.Slider(title="Smoothing Steps", start=0, end=5, step=1, value=2) beta_slider = widgets.Slider(title="β", start=-8, end=8, step=1, value=0) direction_select = widgets.Select( options=list(self.arr.dims), value='eV' if 'eV' in self.arr.dims else self.arr.dims[0], # preference to energy, title='Derivative Direction') interleave_smoothing_toggle = widgets.Toggle( label='Interleave smoothing with d/dx', active=True, button_type='primary') clamp_spectrum_toggle = widgets.Toggle( label='Clamp positive values to 0', active=True, button_type='primary') filter_select = widgets.Select(options=['Gaussian', 'Boxcar'], value='Boxcar', title='Type of Filter') color_slider = widgets.RangeSlider(start=0, end=100, value=( 0, 100, ), title='Color Clip') gamma_slider = widgets.Slider(start=0.1, end=4, value=1, step=0.1, title='Gamma') # don't need any cacheing here for now, might if this ends up being too slow def smoothing_fn(n_passes): if n_passes == 0: return lambda x: x filter_factory = { 'Gaussian': gaussian_filter, 'Boxcar': boxcar_filter, }.get(filter_select.value, boxcar_filter) filter_size = { d: smoothing_sliders_by_name[d].value for d in self.arr.dims } return filter_factory(filter_size, n_passes) @Debounce(0.25) def force_update(): n_smoothing_steps = n_smoothing_steps_slider.value d2_data = self.arr if interleave_smoothing_toggle.active: f = smoothing_fn(n_smoothing_steps // 2) d2_data = d1_along_axis(f(d2_data), direction_select.value) f = smoothing_fn(n_smoothing_steps - (n_smoothing_steps // 2)) d2_data = d1_along_axis(f(d2_data), direction_select.value) else: f = smoothing_fn(n_smoothing_steps) d2_data = d2_along_axis(f(self.arr), direction_select.value) d2_data.values[ d2_data.values != d2_data. values] = 0 # remove NaN values until Bokeh fixes NaNs over the wire if clamp_spectrum_toggle.active: d2_data.values = -d2_data.values d2_data.values[d2_data.values < 0] = 0 cached_data['d2'] = d2_data.values gamma_cached_data['d2'] = d2_data.values**gamma_slider.value plots['d2'].data_source.data = {'image': [gamma_cached_data['d2']]} curv_smoothing_fn = smoothing_fn(n_smoothing_steps) smoothed_curvature_data = curv_smoothing_fn(self.arr) curvature_data = curvature(smoothed_curvature_data, self.arr.dims, beta=beta_slider.value) curvature_data.values[ curvature_data.values != curvature_data.values] = 0 if clamp_spectrum_toggle.active: curvature_data.values = -curvature_data.values curvature_data.values[curvature_data.values < 0] = 0 cached_data['curvature'] = curvature_data.values gamma_cached_data[ 'curvature'] = curvature_data.values**gamma_slider.value plots['curvature'].data_source.data = { 'image': [gamma_cached_data['curvature']] } update_color_slider(color_slider.value) # TODO better integrate these, they can share code with the above if we are more careful. def take_d2(d2_data): n_smoothing_steps = n_smoothing_steps_slider.value if interleave_smoothing_toggle.active: f = smoothing_fn(n_smoothing_steps // 2) d2_data = d1_along_axis(f(d2_data), direction_select.value) f = smoothing_fn(n_smoothing_steps - (n_smoothing_steps // 2)) d2_data = d1_along_axis(f(d2_data), direction_select.value) else: f = smoothing_fn(n_smoothing_steps) d2_data = d2_along_axis(f(self.arr), direction_select.value) d2_data.values[ d2_data.values != d2_data. values] = 0 # remove NaN values until Bokeh fixes NaNs over the wire if clamp_spectrum_toggle.active: d2_data.values = -d2_data.values d2_data.values[d2_data.values < 0] = 0 return d2_data def take_curvature(curvature_data, curve_dims): curv_smoothing_fn = smoothing_fn(n_smoothing_steps_slider.value) smoothed_curvature_data = curv_smoothing_fn(curvature_data) curvature_data = curvature(smoothed_curvature_data, curve_dims, beta=beta_slider.value) curvature_data.values[ curvature_data.values != curvature_data.values] = 0 if clamp_spectrum_toggle.active: curvature_data.values = -curvature_data.values curvature_data.values[curvature_data.values < 0] = 0 return curvature_data # These functions will always be linked to the current context of the curvature tool. self.app_context['d2_fn'] = take_d2 self.app_context['curvature_fn'] = take_curvature def force_update_change_wrapper(attr, old, new): if old != new: force_update() def force_update_click_wrapper(event): force_update() @Debounce(0.1) def update_color_slider(new): def update_plot(name, data): low, high = np.min(data), np.max(data) dynamic_range = high - low self.app_context['color_maps'][name].update( low=low + new[0] / 100 * dynamic_range, high=low + new[1] / 100 * dynamic_range) update_plot('d2', gamma_cached_data['d2']) update_plot('curvature', gamma_cached_data['curvature']) update_plot('raw', gamma_cached_data['raw']) @Debounce(0.1) def update_gamma_slider(new): gamma_cached_data['d2'] = cached_data['d2']**new gamma_cached_data['curvature'] = cached_data['curvature']**new gamma_cached_data['raw'] = cached_data['raw']**new update_color_slider(color_slider.value) def update_color_handler(attr, old, new): update_color_slider(new) def update_gamma_handler(attr, old, new): update_gamma_slider(new) layout = column( row( column(self.app_context['figures']['d2'], interleave_smoothing_toggle, direction_select), column(self.app_context['figures']['curvature'], beta_slider, clamp_spectrum_toggle), column(self.app_context['figures']['raw'], color_slider, gamma_slider)), widgetbox( filter_select, *smoothing_sliders, n_smoothing_steps_slider, ), Spacer(height=100), ) # Attach event handlers for w in (n_smoothing_steps_slider, beta_slider, direction_select, *smoothing_sliders, filter_select): w.on_change('value', force_update_change_wrapper) interleave_smoothing_toggle.on_click(force_update_click_wrapper) clamp_spectrum_toggle.on_click(force_update_click_wrapper) color_slider.on_change('value', update_color_handler) gamma_slider.on_change('value', update_gamma_handler) force_update() doc.add_root(layout) doc.title = 'Curvature Tool'
active=1) btnGroupDept = wd.RadioButtonGroup( name='dept', labels=['begins with...', '...contains...', '...ends with'], active=1) page_info = layout( [[wb(btnGroupLetters, width=1000)], [wb(btnGroupTitle), wb(btnGroupDept)], [wb(title_input), wb(paragraph, optionGroup, width=100), wb(dept_input)], [wb(refresh, width=100)], [wb(table)]]) # +----------+ Statistics +----------+ selectDept = wd.Select(title='Department:', value='', options=dept_list()) colors = ['#c9d9d3', '#718dbf', '#e84d60'] gpa = ['A+', 'A', 'B+', 'B', 'C+', 'C', 'D+', 'D', 'F'] years = ['2015', '2016', '2017'] data = {} data['gpa'] = gpa data['2015'] = [0] * 9 data['2016'] = [0] * 9 data['2017'] = [0] * 9 source = ColumnDataSource(data=data) p = figure(x_range=gpa, plot_height=500,
def histo_highlighter(attr, old, new): inds = np.array(new['1d']['indices']) data_dict = data_reloader(select_img_data, vcount_dir) histo_dict, hedges = load_histo(data_dict) if len(inds) == 0 or len(inds) == len(data_dict['pc']): histo_dict['highlights'] = np.zeros(len(histo_dict['hhist'])) else: histo_dict['highlights'], __ = np.histogram(data_dict['pc'][inds], bins=hedges) source2.data = histo_dict select_img_data = widgets.Select(title="Select Image Data:", value=data_name, options=image_set) select_img_data.on_change('value', img_change) select_img_data.on_change('value', update_particles) select_img_data.on_change('value', update_histo) all_circles.data_source.on_change('selected', histo_highlighter) def particle_select(attr, old, new): inds = np.array(new['1d']['indices']) data_dict = data_reloader(select_img_data, vcount_dir) histo_dict, hedges = load_histo(data_dict) print(len(inds)) if (len(inds) == len(data_dict['pc'])) or len(inds) == 0: data_dict['select'] = data_dict['pc'] * 4