def _init_recorder(self): self.rec_button = Toggle(label=u"\u25CF Record", button_type="default", active=False, width=210) self.file_name_widget = TextInput(value="test_file", title="File name:", width=210) self.file_type_widget = RadioGroup(labels=["EDF (BDF+)", "CSV"], active=0, width=210) columns = [ widgets.TableColumn( field='timer', title="Record time", formatter=widgets.StringFormatter(text_align='center')) ] self.timer = widgets.DataTable(source=self._timer_source, index_position=None, sortable=False, reorderable=False, header_row=False, columns=columns, width=210, height=50, css_classes=["timer_widget"]) self.rec_button.on_click(self._toggle_rec) return column(Spacer(width=210, height=5), self.file_name_widget, self.file_type_widget, self.rec_button, self.timer)
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 ranking_general(df_all): try: Rank_cds = bmodels.ColumnDataSource(df_all) fixed2 = bmw.NumberFormatter(format='0.00') cols = [ bmw.TableColumn(field='team', title='Team'), bmw.TableColumn(field='avgCargo', title='Average Cargo', formatter=fixed2), bmw.TableColumn(field='avgHatch', title='Average Hatches', formatter=fixed2), bmw.TableColumn(field='avgHatchPoints', title='Hatch Points', formatter=fixed2), bmw.TableColumn(field='avgCargoPoints', title='Cargo Points', formatter=fixed2), bmw.TableColumn(field='avgPoints', title='Average Points', formatter=fixed2), bmw.TableColumn(field='climb1', title='Total Lvl1 Climbs', formatter=fixed2), bmw.TableColumn(field='climb2', title='Total Lvl2 Climbs', formatter=fixed2), bmw.TableColumn(field='climb3', title='Total Lvl3 Climbs', formatter=fixed2), bmw.TableColumn(field='Defense', title='Avg Defense', formatter=fixed2), ] data_table = bmw.DataTable(source=Rank_cds, columns=cols, width=900, height=380) except: return bmw.Div(text="Error with general ranking table") return data_table
def ranking_auto(df_all): try: Rank_cds = bmodels.ColumnDataSource(df_all) fixed2 = bmw.NumberFormatter(format='0.00') cols = [ bmw.TableColumn(field='team', title='Team'), bmw.TableColumn(field='level2hab', title='Move lvl2', formatter=fixed2), bmw.TableColumn(field='level1hab', title='Move lvl1', formatter=fixed2), bmw.TableColumn(field='dontMove', title='Don\'t Move', formatter=fixed2), bmw.TableColumn(field='rocketHatch', title='Rocket Hatch', formatter=fixed2), bmw.TableColumn(field='frontBay', title='CS Front Hatch', formatter=fixed2), bmw.TableColumn(field='closeHatch', title='CS Close Hatch', formatter=fixed2), bmw.TableColumn(field='centerHatch', title='CS Center Hatch', formatter=fixed2), bmw.TableColumn(field='farHatch', title='CS Far Hatch', formatter=fixed2), ] data_table = bmw.DataTable(source=Rank_cds, columns=cols, width=900, height=380) except: return bmw.Div(text="Error with auto ranking table") return data_table
def main() -> None: df = pd.read_csv("../_data/iris.csv") # データソースの初期設定 source = bkhmodels.ColumnDataSource(df) # データ表示データテーブル data_table = bkhwidgets.DataTable( source=source, columns=[ bkhwidgets.TableColumn(field=column, title=column) for column in df.columns ], fit_columns=True, ) # レイアウト layout = bkhlayouts.column(data_table, sizing_mode="stretch_both") bkhio.curdoc().add_root(layout)
title, dept = title_input.value, dept_input.value titleCondition = "title like '{}'".format( [title + '%', '%' + title + '%', '%' + title][btnGroupTitle.active]) deptCondition = "dept_name like '{}'".format( [dept + '%', '%' + dept + '%', '%' + dept][btnGroupTitle.active]) rows = fetchRows("select * from lgu.course where {} {} {}".format( titleCondition, conj, deptCondition)) updateCourseData(rows) refresh.on_click(refreshByFilter) # course info table columns = [ wd.TableColumn(field='id', title='Course ID'), wd.TableColumn(field='title', title='Title'), wd.TableColumn(field='dept', title='Department'), wd.TableColumn(field='credits', title='Credit'), wd.TableColumn(field='instructor', title='Instructor'), ] table = wd.DataTable(source=ColumnDataSource(), columns=columns, width=800) # course info layout courseInfo = layout([ [wb(btnGroupLetters, width=1000)], [wb(btnGroupTitle), wb(btnGroupDept)], [ wb(title_input), wb(paragraph, optionGroup, width=100), wb(dept_input),
def tool_handler_2d(self, doc): from bokeh import events from bokeh.layouts import row, column, widgetbox, Spacer from bokeh.models import ColumnDataSource, widgets from bokeh.models.mappers import LinearColorMapper from bokeh.models.widgets.markups import Div from bokeh.plotting import figure arr = self.arr # Set up the data x_coords, y_coords = arr.coords[arr.dims[0]], arr.coords[arr.dims[1]] # Styling default_palette = self.default_palette if arr.S.is_subtracted: default_palette = cc.coolwarm error_alpha = 0.3 error_fill = '#3288bd' # Application Organization self.app_context.update({ 'data': arr, 'data_range': { 'x': (np.min(x_coords.values), np.max(x_coords.values)), 'y': (np.min(y_coords.values), np.max(y_coords.values)), }, 'show_stat_variation': False, 'color_mode': 'linear', }) def stats_patch_from_data(data, subsampling_rate=None): if subsampling_rate is None: subsampling_rate = int(min(data.values.shape[0] / 50, 5)) if subsampling_rate == 0: subsampling_rate = 1 x_values = data.coords[data.dims[0]].values[::subsampling_rate] values = data.values[::subsampling_rate] sq = np.sqrt(values) lower, upper = values - sq, values + sq return { 'x': np.append(x_values, x_values[::-1]), 'y': np.append(lower, upper[::-1]), } def update_stat_variation(plot_name, data): patch_data = stats_patch_from_data(data) if plot_name != 'right': # the right plot is on transposed axes plots[plot_name + '_marginal_err'].data_source.data = patch_data else: plots[plot_name + '_marginal_err'].data_source.data = { 'x': patch_data['y'], 'y': patch_data['x'], } figures, plots, app_widgets = self.app_context[ 'figures'], self.app_context['plots'], self.app_context['widgets'] if self.cursor_default is not None and len(self.cursor_default) == 2: self.cursor = self.cursor_default else: self.cursor = [ np.mean(self.app_context['data_range']['x']), np.mean(self.app_context['data_range']['y']) ] # try a sensible default # create the main inset plot main_image = arr prepped_main_image = self.prep_image(main_image) self.app_context['color_maps']['main'] = LinearColorMapper( default_palette, low=np.min(prepped_main_image), high=np.max(prepped_main_image), nan_color='black') main_tools = ["wheel_zoom", "tap", "reset", "save"] main_title = 'Bokeh Tool: WARNING Unidentified' try: main_title = "Bokeh Tool: %s" % arr.S.label[:60] except: pass figures['main'] = figure(tools=main_tools, plot_width=self.app_main_size, plot_height=self.app_main_size, min_border=10, min_border_left=50, toolbar_location='left', x_axis_location='below', y_axis_location='right', title=main_title, x_range=self.app_context['data_range']['x'], y_range=self.app_context['data_range']['y']) figures['main'].xaxis.axis_label = arr.dims[0] figures['main'].yaxis.axis_label = arr.dims[1] figures['main'].toolbar.logo = None figures['main'].background_fill_color = "#fafafa" plots['main'] = figures['main'].image( [prepped_main_image.T], x=self.app_context['data_range']['x'][0], y=self.app_context['data_range']['y'][0], dw=self.app_context['data_range']['x'][1] - self.app_context['data_range']['x'][0], dh=self.app_context['data_range']['y'][1] - self.app_context['data_range']['y'][0], color_mapper=self.app_context['color_maps']['main']) app_widgets['info_div'] = Div(text='', width=self.app_marginal_size, height=100) # Create the bottom marginal plot bottom_marginal = arr.sel(**dict([[arr.dims[1], self.cursor[1]]]), method='nearest') figures['bottom_marginal'] = figure( plot_width=self.app_main_size, plot_height=200, title=None, x_range=figures['main'].x_range, y_range=(np.min(bottom_marginal.values), np.max(bottom_marginal.values)), x_axis_location='above', toolbar_location=None, tools=[]) plots['bottom_marginal'] = figures['bottom_marginal'].line( x=bottom_marginal.coords[arr.dims[0]].values, y=bottom_marginal.values) plots['bottom_marginal_err'] = figures['bottom_marginal'].patch( x=[], y=[], color=error_fill, fill_alpha=error_alpha, line_color=None) # Create the right marginal plot right_marginal = arr.sel(**dict([[arr.dims[0], self.cursor[0]]]), method='nearest') figures['right_marginal'] = figure( plot_width=200, plot_height=self.app_main_size, title=None, y_range=figures['main'].y_range, x_range=(np.min(right_marginal.values), np.max(right_marginal.values)), y_axis_location='left', toolbar_location=None, tools=[]) plots['right_marginal'] = figures['right_marginal'].line( y=right_marginal.coords[arr.dims[1]].values, x=right_marginal.values) plots['right_marginal_err'] = figures['right_marginal'].patch( x=[], y=[], color=error_fill, fill_alpha=error_alpha, line_color=None) cursor_lines = self.add_cursor_lines(figures['main']) # Attach tools and callbacks toggle = widgets.Toggle(label="Show Stat. Variation", button_type="success", active=False) def set_show_stat_variation(should_show): self.app_context['show_stat_variation'] = should_show if should_show: main_image_data = arr update_stat_variation( 'bottom', main_image_data.sel(**dict([[arr.dims[1], self.cursor[1]]]), method='nearest')) update_stat_variation( 'right', main_image_data.sel(**dict([[arr.dims[0], self.cursor[0]]]), method='nearest')) plots['bottom_marginal_err'].visible = True plots['right_marginal_err'].visible = True else: plots['bottom_marginal_err'].visible = False plots['right_marginal_err'].visible = False toggle.on_click(set_show_stat_variation) scan_keys = [ 'x', 'y', 'z', 'pass_energy', 'hv', 'location', 'id', 'probe_pol', 'pump_pol' ] scan_info_source = ColumnDataSource({ 'keys': [k for k in scan_keys if k in arr.attrs], 'values': [ str(v) if isinstance(v, float) and np.isnan(v) else v for v in [arr.attrs[k] for k in scan_keys if k in arr.attrs] ], }) scan_info_columns = [ widgets.TableColumn(field='keys', title='Attr.'), widgets.TableColumn(field='values', title='Value'), ] POINTER_MODES = [ ( 'Cursor', 'cursor', ), ( 'Path', 'path', ), ] COLOR_MODES = [ ( 'Adaptive Hist. Eq. (Slow)', 'adaptive_equalization', ), # ('Histogram Eq.', 'equalization',), # not implemented ( 'Linear', 'linear', ), # ('Log', 'log',), # not implemented ] def on_change_color_mode(attr, old, new_color_mode): self.app_context['color_mode'] = new_color_mode if old is None or old != new_color_mode: right_image_data = arr.sel(**dict( [[arr.dims[0], self.cursor[0]]]), method='nearest') bottom_image_data = arr.sel(**dict( [[arr.dims[1], self.cursor[1]]]), method='nearest') main_image_data = arr prepped_right_image = self.prep_image(right_image_data) prepped_bottom_image = self.prep_image(bottom_image_data) prepped_main_image = self.prep_image(main_image_data) plots['right'].data_source.data = { 'image': [prepped_right_image] } plots['bottom'].data_source.data = { 'image': [prepped_bottom_image.T] } plots['main'].data_source.data = { 'image': [prepped_main_image.T] } update_main_colormap(None, None, main_color_range_slider.value) color_mode_dropdown = widgets.Dropdown(label='Color Mode', button_type='primary', menu=COLOR_MODES) color_mode_dropdown.on_change('value', on_change_color_mode) symmetry_point_name_input = widgets.TextInput( title='Symmetry Point Name', value="G") snap_checkbox = widgets.CheckboxButtonGroup(labels=['Snap Axes'], active=[]) place_symmetry_point_at_cursor_button = widgets.Button( label="Place Point", button_type="primary") def update_symmetry_points_for_display(): pass def place_symmetry_point(): cursor_dict = dict(zip(arr.dims, self.cursor)) skip_dimensions = {'eV', 'delay', 'cycle'} if 'symmetry_points' not in arr.attrs: arr.attrs['symmetry_points'] = {} snap_distance = { 'phi': 2, 'beta': 2, 'kx': 0.01, 'ky': 0.01, 'kz': 0.01, 'kp': 0.01, 'hv': 4, } cursor_dict = { k: v for k, v in cursor_dict.items() if k not in skip_dimensions } snapped = copy.copy(cursor_dict) if 'Snap Axes' in [ snap_checkbox.labels[i] for i in snap_checkbox.active ]: for axis, value in cursor_dict.items(): options = [ point[axis] for point in arr.attrs['symmetry_points'].values() if axis in point ] options = sorted(options, key=lambda x: np.abs(x - value)) if options and np.abs(options[0] - value) < snap_distance[axis]: snapped[axis] = options[0] arr.attrs['symmetry_points'][ symmetry_point_name_input.value] = snapped place_symmetry_point_at_cursor_button.on_click(place_symmetry_point) main_color_range_slider = widgets.RangeSlider( start=0, end=100, value=( 0, 100, ), title='Color Range (Main)') layout = row( column(figures['main'], figures['bottom_marginal']), column(figures['right_marginal'], Spacer(width=200, height=200)), column( widgetbox( widgets.Dropdown(label='Pointer Mode', button_type='primary', menu=POINTER_MODES)), widgets.Tabs(tabs=[ widgets.Panel(child=widgetbox( Div(text='<h2>Colorscale:</h2>'), color_mode_dropdown, main_color_range_slider, Div(text= '<h2 style="padding-top: 30px;">General Settings:</h2>' ), toggle, self._cursor_info, sizing_mode='scale_width'), title='Settings'), widgets.Panel(child=widgetbox( app_widgets['info_div'], Div(text= '<h2 style="padding-top: 30px; padding-bottom: 10px;">Scan Info</h2>' ), widgets.DataTable(source=scan_info_source, columns=scan_info_columns, width=400, height=400), sizing_mode='scale_width', width=400), title='Info'), widgets.Panel(child=widgetbox( Div(text='<h2>Preparation</h2>'), symmetry_point_name_input, snap_checkbox, place_symmetry_point_at_cursor_button, sizing_mode='scale_width'), title='Preparation'), ], width=400))) update_main_colormap = self.update_colormap_for('main') def on_click_save(event): save_dataset(arr) print(event) def click_main_image(event): self.cursor = [event.x, event.y] right_marginal_data = arr.sel(**dict( [[arr.dims[0], self.cursor[0]]]), method='nearest') bottom_marginal_data = arr.sel(**dict( [[arr.dims[1], self.cursor[1]]]), method='nearest') plots['bottom_marginal'].data_source.data = { 'x': bottom_marginal_data.coords[arr.dims[0]].values, 'y': bottom_marginal_data.values, } plots['right_marginal'].data_source.data = { 'y': right_marginal_data.coords[arr.dims[1]].values, 'x': right_marginal_data.values, } if self.app_context['show_stat_variation']: update_stat_variation('right', right_marginal_data) update_stat_variation('bottom', bottom_marginal_data) figures['bottom_marginal'].y_range.start = np.min( bottom_marginal_data.values) figures['bottom_marginal'].y_range.end = np.max( bottom_marginal_data.values) figures['right_marginal'].x_range.start = np.min( right_marginal_data.values) figures['right_marginal'].x_range.end = np.max( right_marginal_data.values) self.save_app() figures['main'].on_event(events.Tap, click_main_image) main_color_range_slider.on_change('value', update_main_colormap) doc.add_root(layout) doc.title = "Bokeh Tool" self.load_app() self.save_app()
def create_table_column(field): if field == "Tool": return widgets.TableColumn(title=field, field=field, width=600) else: return widgets.TableColumn(title=DESCRIPTION_COMPLETENESS_COL[field][COL_TITLE], field=field)
def show_shar(): df = pd.read_csv('indeed.csv') df = df[~pd.isnull(df["Salaire_annuel_moyen"])] ############################################################################################## df_ville = df.groupby('Ville')['Salaire_annuel_moyen'].median() source1 = ColumnDataSource(pd.DataFrame(df_ville)) ville = source1.data['Ville'].tolist() salaire = source1.data['Salaire_annuel_moyen'].tolist() ############################################################################################## df_job= df[['DATA SCIENTIST','DATA ANALYST', 'BUSINESS INTELLIGENCE', 'DEVELOPPEUR']].sum() df_job = pd.DataFrame({'Job':df_job.index, 'count_job':df_job.values}) job = df_job['Job'] count_job = (df_job['count_job']/df_job['count_job'].sum())*100 ############################################################################################## df_langage= df[["C", "R","PYTHON", "langage C++", "langage C#", "VBA", "MATLAB", "SPARK","GITHUB","AIRFLOW","POSTGRES","EC2","EMR","RDS", "REDSHIFT","AZURE","AWS","JAVA","HTML","CSS","JS","PHP","SQL", "RUBY","SAS","TCL","PERL","ORACLE","MYSQL","MONGODB","REDIS", "NEO4J","TWITTER","LDAP","FILE","HADOOP","DB2","SYBASE","AS400", "ACCESS","FLASK","BOOTSTRAP"]].sum() ############################################################################################## div1 = Div(text="""<h1>Projet Indeed</h1> <h2>Ce projet a été développé en trois phases:</h2> <ul> <li>Collection des données en scrapant le site indeed.</li> <li>Traitement de ces données (préprocessing).</li> <li>Application des models RandomForest et SVM pour predire les salaires.</li> </ul> <h2>Etude Statistique:</h2> """, width=800, height=180) div2 = Div(text=""" <h2>Etude Model Random Forest:</h2> """, width=300, height=30) div3 = Div(text=""" <h3>Confusion matrix:</h3> """, width=300, height=20) div4 = Div(text=""" <h2>Etude Model SVM:</h2> """, width=300, height=30) div5 = Div(text=""" <h3>Confusion matrix:</h3> """, width=300, height=20) div6 = Div(text=""" <h3>Classification report rfc:</h3> """, width=300, height=20) div7 = Div(text=""" <h3>Classification report svm:</h3> """, width=300, height=20) ###################################################################################### df_job = pd.DataFrame({'langage':df_langage.index, 'count_langage':df_langage.values}) langage = df_job['langage'] count_langage = (df_job['count_langage']/df_job['count_langage'].sum())*100 ############################################################################################## df_accurancy = pd.read_csv('accuracy.csv') accuracy_rfc = round(float(df_accurancy['accuracy_rfc'][0]), 2) accuracy_svm = round(float(df_accurancy['accuracy_svm'][0]), 2) ############################################################################################## p1 = figure(x_range=ville, plot_height=300, plot_width=400, title="Le salaire moyen annuel par ville", toolbar_location=None, tools="", x_axis_label = "Ville", y_axis_label = "Salaire") p1.vbar(x=ville, top=salaire, width=0.2, color='deepskyblue') p1.xgrid.grid_line_color = None p1.y_range.start = 0 p1.title.text_font_size = "25px" ############################################################################################## p2 = figure(x_range=job, plot_height=300, plot_width=650, title="Le pourcentage des métiers demandés", toolbar_location=None, tools="", x_axis_label = "Métier", y_axis_label = "pourcentage") p2.vbar(x=job, top=count_job, width=0.2) p2.xgrid.grid_line_color = None p2.y_range.start = 0 p2.title.text_font_size = "25px" ################################################################################################ p3 = figure(y_range=langage, plot_width=600, plot_height=900, title = 'Le pourcentag des langages demandés', x_axis_label='Pourcentage', y_axis_label='Langage', tools="" ) p3.hbar(y=langage, right=count_langage, height=0.3, color='mediumblue') p3.title.text_font_size = "25px" ################################################################################################ ###Random Forest chart_colors = ['#44e5e2', '#e29e44', '#e244db', '#d8e244', '#eeeeee', '#56e244', '#007bff', 'black'] x_rfc = { 'True values': round(accuracy_rfc) , 'False values': round(100 - accuracy_rfc)} data = pd.Series(x_rfc).reset_index(name='value').rename(columns={'index':'accuracy_rfc'}) data['angle'] = data['value']/sum(x_rfc.values())*2*pi data['color'] = chart_colors[:len(x_rfc)] p4 = figure(plot_height=350, title="Accuracy", toolbar_location=None, tools="hover", tooltips="@accuracy_rfc: @value") p4.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend='accuracy_rfc', source=data) p4.title.text_font_size = "25px" data["value"] = data['value'].astype(str) data["value"] = data["value"].str.pad(35, side = "left") source = ColumnDataSource(data) labels = LabelSet(x=0, y=1, text='value', level='glyph', angle=cumsum('angle', include_zero=True), source=source, render_mode='canvas') p4.add_layout(labels) ################################################################################################ ###confusion_matrix Random Forest df_confusion_matrix = pd.read_csv('confusion_matrix.csv') source = ColumnDataSource(df_confusion_matrix) columns = [ widgets.TableColumn(field=c, title=c) for c in df_confusion_matrix.columns ] data_matrix_rfc = DataTable(source=source, columns=columns,width=400, height=100) ################################################################################################ ###classification_report Random Forest df_classification_report_rfc = pd.read_csv('classification_rfc_report.csv') source = ColumnDataSource(df_classification_report_rfc) columns = [ widgets.TableColumn(field=c, title=c) for c in df_classification_report_rfc.columns ] data_repport_rfc = DataTable(source=source, columns=columns,width=800, height=200) ################################################################################################# ###SVM x_svm = { 'True values': round(accuracy_svm) , 'False values': round(100 - accuracy_svm)} data = pd.Series(x_svm).reset_index(name='value').rename(columns={'index':'accuracy_svm'}) data['angle'] = data['value']/sum(x_svm.values())*2*pi data['color'] = chart_colors[:len(x_svm)] p5 = figure(plot_height=350, title="Model SVM", toolbar_location=None, tools="hover", tooltips="@accuracy_svm: @value") p5.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend='accuracy_svm', source=data) p5.title.text_font_size = "25px" data["value"] = data['value'].astype(str) data["value"] = data["value"].str.pad(35, side = "left") source = ColumnDataSource(data) labels = LabelSet(x=0, y=1, text='value', level='glyph', angle=cumsum('angle', include_zero=True), source=source, render_mode='canvas') p5.add_layout(labels) ################################################################################################ ###confusion_matrix SVM df_confusion_matrix_svm = pd.read_csv('confusion_matrix_svm.csv') source = ColumnDataSource(df_confusion_matrix_svm) columns = [ widgets.TableColumn(field=c, title=c) for c in df_confusion_matrix_svm.columns ] data_matrix_svm = DataTable(source=source, columns=columns,width=400, height=100) ################################################################################################ ###classification_report SVM df_classification_report_svm = pd.read_csv('classification_svm_report.csv') source = ColumnDataSource(df_classification_report_svm) columns = [ widgets.TableColumn(field=c, title=c) for c in df_classification_report_svm.columns ] data_repport_svm = DataTable(source=source, columns=columns,width=800, height=200) ################################################################################################ grid = gridplot([div1, p1, p2, p3, div2, p4, div3, widgetbox(data_matrix_rfc), div6, widgetbox(data_repport_rfc), div4, p5, div5, widgetbox(data_matrix_svm), div7, widgetbox(data_repport_svm)], ncols=1) show(grid) save(grid)
def main() -> None: """dependencty walker のツリー情報を解析する。 """ FILEPATH = "hoge.txt" df = to_df(FILEPATH) df = df[df["legend2"] != "Missing Module"] np.random.seed(0) graph = nx.from_pandas_edgelist(df, "name", "parent", edge_attr=None, create_using=nx.DiGraph()) nx.set_node_attributes( graph, df.drop_duplicates(subset="name").set_index("name").to_dict("index")) # グラフデータを bokeh 用に変換 render = bkgraphs.from_networkx(graph, nx.spring_layout, scale=1, center=(0, 0)) render.node_renderer.glyph = bkmodels.Circle( size=8, fill_color=bkpalettes.Spectral4[0]) # グラフ初期設定 p = bkplotting.figure( tools=("pan,box_zoom,lasso_select,box_select,poly_select" ",tap,wheel_zoom,reset,save,zoom_in"), title="dependency link", x_range=(-1.1, 1.1), y_range=(-1.1, 1.1), ) tooltips = [ ("name", "@index"), ("legend1", "@legend1"), ("legend2", "@legend2"), ("legend3", "@legend3"), ] p.add_tools(bkmodels.HoverTool(tooltips=tooltips)) p.renderers.append(render) # データ表示データテーブル data_table = bkwidgets.DataTable( source=render.node_renderer.data_source, columns=[ bkwidgets.TableColumn(field=column, title=column) for column in ["index", "legend1", "legend2", "legend3"] ], fit_columns=True, ) dependency_source = bkmodels.ColumnDataSource(df) dependency_table = bkwidgets.DataTable( source=dependency_source, columns=[ bkwidgets.TableColumn(field=column, title=column) for column in ["name", "parent", "legend1", "legend2", "legend3"] ], fit_columns=True, ) # 依存関係の始点と終点を設定するテキストボックス target_text = bkwidgets.TextInput(value="None", title="Target Module") source_text = bkwidgets.TextInput(value="Input Module Name", title="Source Module") cutoff_text = bkwidgets.TextInput(value="3", title="Number of Cutoff") # 実行ボタン def execute_callback(event) -> None: nonlocal render nonlocal dependency_source np.random.seed(0) all_pathes = nx.all_simple_paths( graph, source=f"{source_text.value}", target=f"{target_text.value}", cutoff=int(f"{cutoff_text.value}"), ) pathes: Set = set() for path in all_pathes: pathes |= set(path) subgraph = graph.subgraph(pathes) render = bkgraphs.from_networkx(subgraph, nx.spring_layout, scale=1, center=(0, 0)) render.node_renderer.glyph = bkmodels.Circle( size=8, fill_color=bkpalettes.Spectral4[0]) p.renderers.clear() p.renderers.append(render) data_table.source = render.node_renderer.data_source x, y = zip(*render.layout_provider.graph_layout.values()) render.node_renderer.data_source.data["x"] = x render.node_renderer.data_source.data["y"] = y labels = bkmodels.LabelSet(x="x", y="y", text="index", source=render.node_renderer.data_source) p.renderers.append(labels) dependency_df = df[df["name"].isin(pathes) & df["parent"].isin(pathes)].drop_duplicates( subset=["name", "parent"]) dependency_source = bkmodels.ColumnDataSource(dependency_df) dependency_table.source = dependency_source execute_button = bkwidgets.Button(label="execute", button_type="success") execute_button.on_click(execute_callback) # 検索結果をクリアするボタン def clear_callback(event) -> None: np.random.seed(0) render = bkgraphs.from_networkx(graph, nx.spring_layout, scale=1, center=(0, 0)) render.node_renderer.glyph = bkmodels.Circle( size=8, fill_color=bkpalettes.Spectral4[0]) p.renderers.clear() p.renderers.append(render) # p.renderers.pop(0) data_table.source = render.node_renderer.data_source clear_button = bkwidgets.Button(label="clear", button_type="success") clear_button.on_click(clear_callback) # レイアウト execute_button_area = bklayouts.layout([[execute_button, clear_button]], sizing_mode="stretch_width") execute_area = bklayouts.layout( [ target_text, source_text, cutoff_text, execute_button_area, dependency_table ], sizing_mode="stretch_width", ) operation_area = bklayouts.layout([data_table, execute_area], sizing_mode="stretch_both") layout = bklayouts.layout([[p, operation_area]], sizing_mode="stretch_both") bkio.curdoc().add_root(layout)
title_input = wd.TextInput(value="", title="Title", placeholder="Serach title") options = wd.RadioGroup(labels=['and', 'or'], active=0, width=100, inline=True) button_refresh = wd.Button(label="Refresh") Group_choices = wd.RadioButtonGroup( name="Title", labels=['Begins with ...', '... contains ...', '... ends with'], active=1) Department_choices = wd.RadioButtonGroup( name="Department", labels=['Begins with ...', '... contains ...', '... ends with'], active=1) Text_Instruction = wd.Paragraph(text="Option") # Data used in Tab1 columns = [ wd.TableColumn(field="id", title="Course ID"), wd.TableColumn(field="title", title="Title"), wd.TableColumn(field="dept", title="Department"), wd.TableColumn(field="credit", title="Credits"), wd.TableColumn(field="instructor", title="Instructor"), ] 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()
pAVO = plotAVO(TOOLS, intfMod) pRPRS = plotRPRS(TOOLS, intfMod) pAIVPVS = plotAIVPVS(TOOLS, lithAr) pLMR = plotLMR(TOOLS, lithAr) p = bkl.gridplot([[pAVO, pRPRS], [pLMR, pAIVPVS]]) #toggle boxes #intfnames=[i.name for i in intfMod]; actNames=[i for i in range(len(intfnames))] #toggleIntf = CheckboxGroup( labels=intfnames,active=actNames) #titleIntf = PreText(text='Interfaces') #q = VBox(titleIntf,toggle) columns = [ bkw.TableColumn(field="name", title="Unit"), bkw.TableColumn(field="colour", title="Colour"), bkw.TableColumn(field="vp", title="Velp"), bkw.TableColumn(field="vs", title="Vels"), bkw.TableColumn(field="rho", title="Rho"), bkw.TableColumn(field="vp_std", title="Velp_Std"), bkw.TableColumn(field="vs_std", title="Vels_Std"), bkw.TableColumn(field="rho_std", title="Rho_Std"), ] data_table = bkw.DataTable(source=source, columns=columns, width=1500, height=500, editable=True) #tab1 = Panel(HBox(q,p))
def total_rt(self): Rank_cds = bmodels.ColumnDataSource(self.df) fixed2 = bmw.NumberFormatter(format='0.00') cols = [ bmw.TableColumn(field='team', title='Team'), bmw.TableColumn(field='avg_points', title='Average Points', formatter=fixed2), bmw.TableColumn(field='avg_autoLower', title='Average Shoot Lower Auto', formatter=fixed2), bmw.TableColumn(field='avg_autoOuter', title='Average Shoot Outer Auto', formatter=fixed2), bmw.TableColumn(field='avg_autoInner', title='Average Shoot Inner Auto', formatter=fixed2), bmw.TableColumn(field='avg_teleLower', title='Average Shoot Lower Teleop', formatter=fixed2), bmw.TableColumn(field='avg_teleOuter', title='Average Shoot Outer Teleop', formatter=fixed2), bmw.TableColumn(field='avg_teleInner', title='Average Shoot Inner Teleop', formatter=fixed2), bmw.TableColumn(field='avg_launchLower', title='Average Shoot Lower', formatter=fixed2), bmw.TableColumn(field='avg_launchOuter', title='Average Shoot Upper', formatter=fixed2), bmw.TableColumn(field='positionControl', title='Total position control', formatter=fixed2), bmw.TableColumn(field='rotationControl', title='Total Rotation Control', formatter=fixed2), bmw.TableColumn(field='movedAuto', title='Total moved auto', formatter=fixed2), bmw.TableColumn(field='climb', title='Total Climbs', formatter=fixed2) ] self.datatable = bmw.DataTable(source=Rank_cds, columns=cols, width=1600, height=380) return self.datatable