def create_disp(): ##### 各画面要素作成 # テーブル作成 df_columns = target_data.columns.tolist() datatable_source = ColumnDataSource(data=target_data) table_columns = create_datatable_columns(df_columns) data_table = DataTable(source=datatable_source, selectable=True, columns=table_columns, sortable=True) # カラムが変わった時に呼び出す関数リスト column_change_functions = [] # 表示を切り替えるplotリスト visible_plots = [] cm_operation_area, cm_plot_area = create_cm(column_change_functions, visible_plots, datatable_source) # upload button がクリックされた時の処理 def upload_button_callback(event): global target_data global user csv_str = base64.b64decode(csv_input.value) target_data = pd.read_csv(io.BytesIO(csv_str)) df_columns = target_data.columns.tolist() call_column_change(column_change_functions, df_columns) table_columns = create_datatable_columns(df_columns) data_table.columns = table_columns datatable_source.data = target_data data_table.update() try: user.csv_data = target_data.to_json() db.session.commit() except Exception as e: warn = str(e) # csvアップロード実行ボタン upload_button = Button(label="Upload", button_type="success") upload_button.on_event(ButtonClick, upload_button_callback) # ファイル選択ボックス csv_input = FileInput() scatter_operation_area, scatter_plot_area = create_scatter( column_change_functions, visible_plots, datatable_source) # サブオペレーションエリア sub_operation_area = Row(cm_operation_area, scatter_operation_area) operation_area = Column(csv_input, upload_button, sub_operation_area, data_table) graph_area = Column(cm_plot_area, scatter_plot_area) layout_disp = Row(graph_area, operation_area) return layout_disp
def _make_doc_layout(self): """ Constructs the document layout object. Returns: -------- doc_layout : bokeh.layouts.layout object Grid layout of bokeh models used in figure. """ cb_figure = Column(self._create_colour_bar()) widgets = Column(self.widgets['select_color'], self.widgets['change_color']) draughtsman_plot = gridplot(self.figures.tolist()) doc_layout = layout([[draughtsman_plot, cb_figure, widgets]]) return doc_layout
def _setup_tabs(sec_to_elements): """Create tabs for each section in sec_to_elements with titles. Args: sec_to_elements (dict): A nested dictionary. The first level keys will be the sections ("running", "succeeded", "failed", "scheduled"). The second level keys are the database names and the second level values a list consisting of the link to the dashboard and a button to activate tha dashboard. Returns: tabs (bokeh.models.Tabs): a tab for every section in sec_to_elements. """ tab_list = [] for section, name_to_row in sec_to_elements.items(): text = f"{len(name_to_row.column_names)} optimizations {section}" table_rows = [ Row(Div(text=text, width=400), name=f"{section}_how_many") ] for name, row in name_to_row.data.items(): table_rows.append(Row(*row, name=name)) panel = Panel( child=Column(*table_rows, name=f"{section}_col"), title=section.capitalize(), name=f"{section}_panel", ) tab_list.append(panel) tabs = Tabs(tabs=tab_list, name="tabs") return tabs
def generate_graph(gat_log_df: pd.DataFrame, graph_output_path: str, right_y_axis_filter: str, percentile: int) -> object: # Get the List of Scenarios in Test Run scenario_list = get_list_of_scenarios(gat_log_df) # Set Graph Output File output_file(graph_output_path) # Empty List to contain individual scenario graphs scenario_plots = [] # Looping over Scenarios in Test for scnIndex in range(len(scenario_list)): # Get the scenario Name scenario_name = scenario_list[scnIndex] # Get scenario_metrics_df and overall_percentile_df get_scenario_metrics(scenario_name, gat_log_df, right_y_axis_filter, percentile) # Plot Graphs of the Transactions in Scenario complete_scenario_graph = plot_graph_by_scenarios_vs_right_y_axis(scenario_name, right_y_axis_filter, percentile) # Add the Scenario Graphs to the Final Combined Graph scenario_plots.append(complete_scenario_graph) print("{} Completed.".format(scenario_name)) # put all the plots in a Column layout = Column(children=scenario_plots) # Return the layout return layout
def generate_graph(gat_log_df, graph_output_path, show_graph=False): # Get the List of Scenarios in Test Run scenario_list = get_list_of_scenarios(gat_log_df) # Set Graph Output File output_file(graph_output_path) # Empty List to contain individual scenario graphs scenario_plots = [] # Looping over Scenarios in Test for scnIndex in range(len(scenario_list)): # Get the scenario Name scenario_name = scenario_list[scnIndex] # Get scenario_metrics_df and overall_ninety_fifth_df (scenario_metrics_df, overall_ninety_fifth_df) = get_scenario_metrics( scenario_name, gat_log_df) # Plot Graphs of the Transactions in Scenario complete_scenario_graph = plot_graph_by_transaction( scenario_metrics_df, overall_ninety_fifth_df, scenario_name) # Add the Scenario Graphs to the Final Combined Graph scenario_plots.append(complete_scenario_graph) print("{} Completed.".format(scenario_name)) logger.info("{} Completed.".format(scenario_name)) # put all the plots in a Column layout = Column(children=scenario_plots, sizing_mode='stretch_both') # Display Graph once done if show_graph: show(layout)
def plot_table(df, header_style="color: #757575; font-family: Courier; font-weight:800", table_style="color: #757575; font-family: Courier; font-weight:normal", height=250): source = ColumnDataSource(df) header = Div(text="<style>.slick-header.ui-state-default{" + header_style + "}</style>") template = """ <div style="{}"> <%= value %> </div> """.format(table_style) columns = [ TableColumn(field=col, title=col, formatter=HTMLTemplateFormatter(template=template) ) for col in df.columns ] data_table = DataTable(source=source, columns=columns, fit_columns=True, header_row=True, index_position=None, height=height ) return Column(header, widgetbox(data_table))
def covid_app(doc, plot_data, description): """Create the page with the master dashboard. Args: doc (bokeh.Document): document where the overview over the optimizations will be displayed by their current stage. plot_data (dict) description (pd.DataFrame) """ tab_names = ["Overview", "Timeline"] tab_list = [] for i, sec_title in enumerate(tab_names): subtopic = description["subtopic"].unique()[i] title = Div(text=subtopic.capitalize(), style={"font-size": "200%"}) p = create_standard_figure(title="") source = ColumnDataSource(plot_data) p.line(source=source, x="x", y="y") col = Column(*[title, p]) panel = Panel( child=col, title=sec_title, name=f"{sec_title}_panel", ) tab_list.append(panel) tabs = Tabs(tabs=tab_list, name="tabs") doc.add_root(tabs)
def make_filter_widget(church_info, filter_value, filter_choice_value): selected = None if filter_value == "None": filter_value = None category_select_cb = CustomJS(code="reloadWithParams(['filter_by', 'filter_choice'], [cb_obj.value, null])") filter_by_selector = Select( title="Filter by:", options=FILTER_OPTIONS, callback=category_select_cb, value=filter_value, ) filter_choice_selector = None if filter_value: if filter_value == 'City': filter_choice_options = _get_city_strings(church_info) if filter_value == 'Church': filter_choice_options = list(church_info['name']) if filter_value == 'District': filter_choice_options = list(DISTRICT_NAMES.keys()) filter_choice_options.sort() selected = filter_choice_value or filter_choice_options[0] filter_choice_cb = CustomJS(code="reloadWithParams('filter_choice', cb_obj.value)") filter_choice_selector = Select( options=filter_choice_options, callback=filter_choice_cb, value=filter_choice_value, ) if filter_choice_selector: return Column(filter_by_selector, filter_choice_selector), selected else: return filter_by_selector, selected
def make_time_series_plot(church_data, prop): churches = church_data.groupby('church_id') plot_bounds = get_extents('year', prop, church_data) prop_string = get_category_string(prop) time_series_data = ColumnDataSource(data=dict( x=[x[1] for x in churches['year']], y=[y[1] for y in churches[prop]], church_name=[church[1]['name'].iloc[-1] for church in churches], delta=[ "{0:.1f}%".format(y[1].iloc[-1] / y[1].iloc[0] * 100 - 100 if y[1].iloc[0] != 0 else float('nan')) for y in churches[prop] ], church_id=[church[1]['church_id'].iloc[-1] for church in churches], )) plot = make_plot_object( title=prop_string + " over time", x_axis_label='Year', y_axis_label=prop_string, plot_bounds=plot_bounds, tools=_make_time_series_tools(time_series_data, prop_string), ) lines = plot.multi_line( xs='x', ys='y', source=time_series_data, ) apply_theme(plot, lines) prop_slider = make_range_slider( plot_bounds['y_range'], title=prop_string, callback=CustomJS(args={'plot': plot}, code="plot.y_range.end = cb_obj.value;"), step=1 / 100, ) year_slider = make_range_slider( plot_bounds['x_range'], title='Years', callback=CustomJS(args={'plot': plot}, code="plot.x_range.end = cb_obj.value;"), ) return Column( make_category_select(prop), plot, prop_slider, year_slider, )
def __init__(self, doc): ''' Attributes ---------- view : 階層化メニューシステム menus : Column 階層化メニューを表すウィジェット path : list of str 階層化メニューから選択された項目のリスト ''' def set_callback(choice, level): ''' level番目のメニューchoiceの要素が選択されたとき(active)の挙動(on_change)を設定 Parameters ---------- choice : メニュー level : メニュー階層のレベル (0-index) Notes ----- set_callback に choice, level を与えることで、これらを含む関数閉包を構成していることに注意 ''' def on_change(attr, old, new): if new is None: return # 無効化されたメニューについては無視する self.path = self.path[:level] + [choice.labels[new]] self._update() choice.on_change('active', on_change) def button_group(level): choice = RadioButtonGroup(labels=['None'], visible=False, active=None) set_callback(choice, level) return choice self.menus = Column( name='region_menus', children=[button_group(level) for level in range(4)], css_classes=['spix', 'spix-region-view'], sizing_mode='scale_width') self.path = [] self._update() doc.add_root(self.menus)
def make_tools(self): #ボタンやスライダーを作成 end = self.make_button(self.exit_hander, "終了") self.searchbox = self.make_search_input_textbox() self.searchbox.on_change("value", self.celestial_bodies_search_handler) self.celestial_text = Div(text="", width=300, height=220) self.celestial_text.background = (10, 10, 10, 0.05) self.plotting_mode_text = Div(text="投影図法:メルカトル", width=140, height=20) self.plotting_mode_text.background = (10, 10, 10, 0.05) self.plotting_linkage_button = self.make_button( self.switch_plotting_linkage_handler, "視等級とズームの連動", default_size=100) self.plotting_linkage_button.button_type = "primary" self.angle_simu_enlarge_slider = self.make_slider( self.update_angle_square_enlarge, "焦点距離", 35, 10, 200, 1) self.angle_simu_rotate_slider = self.make_slider( self.update_angle_square_rotate, "回転角度", 0, -360, 360, 1) self.angle_simu_button = self.make_button( self.switch_angle_simulator_handler, "撮影シミュレーション") angle_simu = Column(self.angle_simu_button, self.angle_simu_enlarge_slider, self.angle_simu_rotate_slider) angle_simu.background = (0, 100, 60, 0.2) self.star_label_button = self.make_button(self.switch_starlabel_hander, "恒星の名前:on/off", button_type="primary") self.galaxy_button = self.make_button(self.switch_galaxy_handler, "銀河:off/点のみ/メシエ番号") self.star_line_button = self.make_button(self.switch_star_line_handler, "星座線:on/off") self.constellation_button = self.make_button( self.switch_constellation_handler, "星座の名前:on/off") switches = Column(self.star_label_button, self.galaxy_button, self.star_line_button, self.constellation_button) switches.background = (0, 40, 100, 0.2) tools = Column( end, self.searchbox, self.celestial_text, Row(self.plotting_mode_text, self.plotting_linkage_button), angle_simu, switches) return tools
def generate_app(doc): df = pd.read_csv('data/headcount.csv', sep = '\t') df = df.pivot_table(values = 'Headcount', index = ['FT or PT'],columns='Month').reset_index() source = ColumnDataSource(data=df) """def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = dict(ColumnDataSource(data=data).data) """ slider = Slider(start=0, end=30, value=0, step=2, title="Smoothing by N Days") #slider.on_change('value', callback) columns = [] for column in df.columns: columns.append(TableColumn(field=column, title=column)) data_table = DataTable(source=source, columns=columns, width=1200, height=800) doc.add_root(Column(slider, data_table))
def _make_doc_layout(self): """ Constructs the document layout object. Note: Row and Column are experimental features. The positions of the widgets could be hardcoded. Returns: -------- doc_layout : bokeh.layouts.layout object Grid layout of bokeh models. """ top_row = Row(self.widgets['add'], Spacer(width=25), self.widgets['clear']) right_column = Column(self.widgets['method'], self.widgets['num_train_inst'], self.widgets['color'], self.widgets['change_color'], self.widgets['start']) doc_layout = layout([top_row, [self.fig, right_column]]) return doc_layout
def plots( self, x_label='timestamp_local', subjects=('speed', 'cadence', 'heart_rate', 'altitude'), include_map=True, interval: tuple = None, ): interval = _parse_interval(interval) y_labels = {'speed': 'speed_km'} datasource = self.datasource(interval=interval) x_axis_types = { 'timestamp': 'datetime', 'timestamp_local': 'datetime', } x_range = None plots = [self.route_map(interval=interval)] if include_map else [] for subject in subjects: p = figure( x_axis_type=x_axis_types.get(x_label, 'linear'), x_range=x_range, title=subject, title_location="left", plot_width=800, plot_height=300, ) p.add_tools(self.hovertool()) x_range = p.x_range if x_range is None else x_range p.scatter( x_label, y_labels.get(subject, subject), source=datasource, hover_color="firebrick", size=1, ) plots.append(p) return Column(*plots)
def dead_dropdown_callback(self, attr, old, new): color_choice = dead_color_dropdown.value dead_data_source.data['color'] = [color_choice] * len(dead_data_source.data['color']) def speed_slider_callback(self, attr, old, new): self.speed = speed_slider.value def start_button_callback(self): for generation_num in range(self.starting_gen_num, generations + 1): plot.title.text = 'Generation ' + str(generation_num) self.adjust_data(alive_data_source, dead_data_source, output_dict, generation_num) sleep(1/(2*self.speed)) def adjust_data(self, alive_data_source, dead_data_source, output_dict, gen_num): output_dict[gen_num][0].data['color'] = [alive_data_source.data['color'][0]] * len(output_dict[gen_num][0].data['x']) output_dict[gen_num][1].data['color'] = [dead_data_source.data['color'][0]] * len(output_dict[gen_num][1].data['x']) alive_data_source.data = output_dict[gen_num][0].data dead_data_source.data = output_dict[gen_num][1].data callbacks = Callbacks() generations_slider.on_change('value', callbacks.generations_slider_callback) speed_slider.on_change('value', callbacks.speed_slider_callback) alive_color_dropdown.on_change('value', callbacks.alive_dropdown_callback) dead_color_dropdown.on_change('value', callbacks.dead_dropdown_callback) start_button.on_click(callbacks.start_button_callback) layout = Row(Column(generations_slider, alive_color_dropdown, dead_color_dropdown, speed_slider, start_button), plot) curdoc().add_root(layout)
def temperature_plots(conn, start, end): '''Combines plots to a tab Parameters ---------- conn : DBobject Connection object that represents database start : time Startlimit for x-axis and query (typ. datetime.now()- 4Months) end : time Endlimit for x-axis and query (typ. datetime.now()) Return ------ p : tab object used by dashboard.py to set up dashboard ''' descr = Div(text=""" <style> table, th, td { border: 1px solid black; background-color: #efefef; border-collapse: collapse; padding: 5px } table { border-spacing: 15px; } </style> <body> <table style="width:100%"> <tr> <th><h6>Plotname</h6></th> <th><h6>Mnemonic</h6></th> <th><h6>Description</h6></th> </tr> <tr> <td>IRSU monitored Temperatures</td> <td>SI_GZCTS75A<br> SI_GZCTS68A<br> SI_GZCTS81A<br> SI_GZCTS80A<br> SI_GZCTS76A<br> SI_GZCTS79A<br> SI_GZCTS77A<br> SI_GZCTS78A<br> SI_GZCTS69A</td> <td>CAA IRSU Temperature<br> CAM IRSU Temperature<br> COM1 Nominal IRSU Temperature<br> COM1 Redundant IRSU Temperature<br> FWA IRSU Temperature<br> GWA IRSU Temperature<br> Thermal Strap Nominal IRSU Temperature<br> Thermal Strap Redundant IRSU Temperature<br> MSA Nominal IRSU Temperature<br> MSA Redundant IRSU Temperature</td> </tr> <tr> <td>FPE Temperatures/td> <td>IGDP_NRSI_C_CAM_TEMP<br> IGDP_NRSI_C_COL_TEMP<br> IGDP_NRSI_C_COM1_TEMP<br> IGDP_NRSI_C_FOR_TEMP<br> IGDP_NRSI_C_IFU_TEMP<br> IGDP_NRSI_C_BP1_TEMP<br> IGDP_NRSI_C_BP2_TEMP<br> IGDP_NRSI_C_BP3_TEMP<br> IGDP_NRSI_C_BP4_TEMP<br> IGDP_NRSI_C_RMA_TEMP</td> <td>OA CAM Temperature<br> OA COL Temperature<br> OA COM1 Temperature<br> OA FOR Temperature<br> OA IFU Temperature<br> OA BP1 Temperature<br> OA BP2 Temperature<br> OA BP3 Temperature<br> OA BP4 Temperature<br> OA RMA Temperature</td> </tr> <tr> <td>Box Temperatures</td> <td>IGDP_NRSD_ALG_TEMP<br> INRSH_HK_TEMP1<br> INRSH_HK_TEMP2</td> <td>ICE Internal Temperature 1<br> ICE Internal Temperature 2</td> </tr> <tr> <td>MCE internal Temperatures</td> <td>INRSM_MCE_PCA_TMP1<br> INRSM_MCE_PCA_TMP2<br> INRSM_MCE_AIC_TMP_FPGA<br> INRSM_MCE_AIC_TMP_ADC<br> INRSM_MCE_AIC_TMP_VREG<br> INRSM_MCE_MDAC_TMP_FPGA<br> INRSM_MCE_MDAC_TMP_OSC<br> INRSM_MCE_MDAC_TMP_BRD<br> INRSM_MCE_MDAC_TMP_PHA<br> INRSM_MCE_MDAC_TMP_PHB</td> <td>MCE PCA Board Temperature 1<br> MCE PCA Board Temperature 2<br> MCE AIC Board FPGA Temperature<br> MCE AIC Board Analog/Digital Converter Temperature<br> MCE AIC Board Voltage Regulator Temperature<br> MCE MDAC Board FPGA Temperature<br> MCE MDAC Board Oscillator Temperature<br> MCE MDAC Board Temperature<br> MCE MDAC Board Phase A PA10 Temperature<br> MCE MDAC Board Phase B PA10 Temperature</td> </tr> <tr> <td>MSA Temperatures</td> <td>INRSM_Q1_TMP_A<br> INRSM_Q2_TMP_A<br> INRSM_Q3_TMP_A<br> INRSM_Q4_TMP_A<br> INRSM_MECH_MTR_TMP_A<br> INRSM_LL_MTR_TMP_A<br> INRSM_MSA_TMP_A</td> <td>MSA Quad 1 Temperature<br> MSA Quad 2 Temperature<br> MSA Quad 3 Temperature<br> MSA Quad 4 Temperature<br> MSA Magnetic Arm Motor Temperature<br> MSA Launch Lock Motor Temperature<br> MSA Frame Temperature</td> </tr> <tr> <td>FPA Temperatures</td> <td>IGDP_NRSD_ALG_FPA_TEMP<br> IGDP_NRSD_ALG_A1_TEMP<br> IGDP_NRSD_ALG_A2_TEMP</td> <td>FPE Temperature<br> FPA Temperature<br> ASIC 1 Temperature<br> ASIC 2 Temperature</td> </tr> <tr> <td>Heat Strap Temperatures (Trim Heaters)</td> <td>SI_GZCTS74A<br> SI_GZCTS67A</td> <td>FPA TH-Strap A Temperature from IRSU A<br> FPA TH-Strap B Temperature from IRSU A</td> </tr> <tr> <td>CAA Lamps / FWA,GWA</td> <td>IGDP_NRSI_C_CAAL1_TEMP<br> IGDP_NRSI_C_CAAL2_TEMP<br> IGDP_NRSI_C_CAAL3_TEMP<br> IGDP_NRSI_C_CAAL4_TEMP<br> IGDP_NRSI_C_FWA_TEMP<br> IGDP_NRSI_C_GWA_TEMP</td> <td>CAA Temperature LINE1<br> CAA Temperature LINE2<br> CAA Temperature LINE3<br> CAA Temperature LINE4<br> FWA Temperature Sensor Value<br> GWA Temperature Sensor Value</td> </tr> </table> </body> """, width=1100) plot1 = irsu_temp(conn, start, end) plot2 = fpe_temp(conn, start, end) plot3 = box_temp(conn, start, end) plot4 = mce_internal_temp(conn, start, end) plot5 = msa_temp(conn, start, end) plot6 = fpa_temp(conn, start, end) plot7 = heat_strap_temp(conn, start, end) plot8 = caal_temp(conn, start, end) layout = Column(descr, plot1, plot2, plot3, plot4, plot5, plot6, plot7, plot8) tab = Panel(child=layout, title="TEMPERATURE") return tab
animate_start = animate_start + 2000 p_trade_feed.x_range.start = animate_start p_trade_feed.x_range.end = animate_start + 600000 callback_id = None def animate(): global callback_id, start, end if button.label == '► Play': button.label = '❚❚ Pause' callback_id = curdoc().add_periodic_callback(animate_update, 1) else: button.label = '► Play' start = datetime(2019, 3, 3, 14, 0, 0, tzinfo=timezone.utc).timestamp() * 1000 end = datetime(2019, 3, 3, 15, 0, 0, tzinfo=timezone.utc).timestamp() * 1000 curdoc().remove_periodic_callback(callback_id) button = Button(label='► Play', width=60) button.on_click(animate) left = Column(p_trade_feed, p_candlestick, p_trade_feed_hist, WidgetBox(button)) right = Column(p_order_book, p_trade_feed_distribution, p_buy_sell_pie) curdoc().add_root(Row(left, right))
import pandas as pd from bokeh.io import curdoc from scatter_plot import create_scatter_plot from population_per_region import create_bar_chart from child_mortality_plot import create_mortality_bar_plot from bokeh.layouts import Row, Column main_df = pd.read_csv('gapminder_tidy.csv', index_col='Year') scatter_plot = create_scatter_plot(main_df) pop_per_region_bar = create_bar_chart(main_df) child_mortality_bar = create_mortality_bar_plot(main_df) column = Column(pop_per_region_bar, child_mortality_bar) first_row = Row(scatter_plot) second_row = Row(child_mortality_bar, pop_per_region_bar) curdoc().add_root(first_row) curdoc().add_root(second_row)
def bias_plots(conn, start, end): '''Combines plots to a tab Parameters ---------- conn : DBobject Connection object that represents database start : time Startlimit for x-axis and query (typ. datetime.now()- 4Months) end : time Endlimit for x-axis and query (typ. datetime.now()) Return ------ p : tab object used by dashboard.py to set up dashboard ''' descr = Div(text=""" <style> table, th, td { border: 1px solid black; background-color: #efefef; border-collapse: collapse; padding: 5px } table { border-spacing: 15px; } </style> <body> <table style="width:100%"> <tr> <th><h6>Plotname</h6></th> <th><h6>Mnemonic</h6></th> <th><h6>Description</h6></th> </tr> <tr> <td>VSSOUT</td> <td>IGDP_MIR_IC_V_VSSOUT<br> IGDP_MIR_SW_V_VSSOUT<br> IGDP_MIR_LW_V_VSSOUT<br> </td> <td>Detector Bias VSSOUT (IC,SW, & LW)</td> </tr> <tr> <td>VDETCOM</td> <td>IGDP_MIR_IC_V_VDETCOM<br> IGDP_MIR_SW_V_VDETCOM<br> IGDP_MIR_LW_V_VDETCOM<br> </td> <td>Detector Bias VDETCOM (IC,SW, & LW)</td> </tr> <tr> <td>VRSTOFF</td> <td>IGDP_MIR_IC_V_VRSTOFF<br> IGDP_MIR_SW_V_VRSTOFF<br> IGDP_MIR_LW_V_VRSTOFF<br> </td> <td>Detector Bias VRSTOFF (IC,SW, & LW)</td> </tr> <tr> <td>VP</td> <td>IGDP_MIR_IC_V_VP<br> IGDP_MIR_SW_V_VP<br> IGDP_MIR_LW_V_VP<br> </td> <td>Detector Bias VP (IC,SW, & LW)</td> </tr> <tr> <td>VDDUC</td> <td>IGDP_MIR_IC_V_VDDUC<br> IGDP_MIR_SW_V_VDDUC<br> IGDP_MIR_LW_V_VDDUC<br> </td> <td>Detector Bias VDDUC (IC,SW, & LW)</td> </tr> </table> </body> """, width=1100) plot1 = vdetcom(conn, start, end) plot2 = vssout(conn, start, end) plot3 = vrstoff(conn, start, end) plot4 = vp(conn, start, end) plot5 = vdduc(conn, start, end) l = gridplot([ [plot2, plot1], \ [plot3, plot4], \ [plot5, None]], merge_tools=False) layout = Column(descr, l) tab = Panel(child=layout, title="BIAS") return tab
p.js_on_event(events.PanEnd, CustomJS.from_py_func(pan_end)) #def mouse_move(ld = tweet_data_controller.lod_dummy): # print("Mouse Move:") #p.js_on_event(events.MouseMove, CustomJS.from_py_func(mouse_move)) #def mouse_wheel(ld = tweet_data_controller.lod_dummy): # print("Mouse Wheel:") #p.js_on_event(events.MouseWheel, CustomJS.from_py_func(mouse_wheel)) lhs = Column(map_widgets.radio_button_data_type, Row(map_widgets.toggle_data, map_widgets.button_clear), map_widgets.text_selection_details, map_widgets.toggle_sde_ellipse, map_widgets.toggle_sibling_ellipses, map_widgets.toggle_dissolve, map_widgets.toggle_blend, map_widgets.slider_blend, map_widgets.text_input, map_widgets.button_find, map_widgets.toggle_legend) filter_sliders \ = Column( Row( Column(map_widgets.button_count_start_minus, map_widgets.button_count_start_plus, width=50), map_widgets.range_slider_count, Column(map_widgets.button_count_end_minus, map_widgets.button_count_end_plus)), Row( Column(map_widgets.button_area_start_minus, map_widgets.button_area_start_plus, width=50), map_widgets.range_slider_area, Column(map_widgets.button_area_end_minus, map_widgets.button_area_end_plus)), Row( Column(map_widgets.button_distance_start_minus, map_widgets.button_distance_start_plus, width=50), map_widgets.range_slider_distance, Column(map_widgets.button_distance_end_minus, map_widgets.button_distance_end_plus)), Row( Column(map_widgets.button_ratio_start_minus, map_widgets.button_ratio_start_plus, width=50),
y_axis_label="City MPG") # Adding the square glyph to the scatterplot scatChart.square(x='xVal', y='yVal',source=cdsAuto) # Getting dataset ready for viewing mean MPG values by Body_style. # reset_index() converts the groupby object back to the dataframe. meanCity = dfAuto.groupby(['Body_Style'])['City_MPG'].mean().reset_index() # Preparing CDS object ready to populate the bar chart cdsMean = ColumnDataSource(data=dict(xVal = meanCity['Body_Style'], yVal = meanCity['City_MPG'])) # Bar chart and its vbar glyph # Again remember that for bar charts, you need to specify x_range when you create # the figure. List passed here should be unique values of type 'string'. barChart = figure(height=400, width=700, title="Summarizing City_MPG mean values", x_range=meanCity['Body_Style']) barChart.vbar(x='xVal', top='yVal', source=cdsMean, width=.3) # Capturing the event of change of value xSelect.on_change('value', updateScatter) barSelect.on_change('value', updateBar) weightSlider.on_change('value', updateScatter) # Equivalent of show()... Curdoc() allows your charts to be rendered with server. curdoc().add_root(Row(Column(xSelect, weightSlider, scatChart), Column(barSelect, barChart)))
def index(): """ Very simple embedding of a lightcurve chart """ # FLASK # Grab the inputs arguments from the URL # This is automated by the button args = flask.request.args _from = str(args.get('_from', str(DEFAULT_TR.start))) _to = str(args.get('_to', str(DEFAULT_TR.end))) tr = TimeRange(parse_time(_from), parse_time(_to)) if 'next' in args: tr = tr.next() if 'prev' in args: tr = tr.previous() if 'next_hour' in args: tr = TimeRange(tr.start + ONE_HOUR, tr.end + ONE_HOUR) if 'next_day' in args: tr = TimeRange(tr.start + ONE_DAY, tr.end + ONE_DAY) if 'prev_hour' in args: tr = TimeRange(tr.start - ONE_HOUR, tr.end - ONE_HOUR) if 'prev_day' in args: tr = TimeRange(tr.start - ONE_DAY, tr.end - ONE_DAY) _from = str(tr.start) _to = str(tr.end) # get the data goes = lc.GOESLightCurve.create(tr) # resample to reduce the number of points for debugging goes.data = goes.data.resample("1T").mean() # add time string for display of hover tool goes.data['time_str'] = goes.data.index.strftime('%F %H:%M:%S') source = ColumnDataSource(data=goes.data) source_static = ColumnDataSource(data=goes.data) # now create the bokeh plots # XRS-B Plot fig1 = figure(title="GOES", tools=TOOLS, plot_height=PLOT_HEIGHT, width=PLOT_WIDTH, x_axis_type='datetime', y_axis_type="log", y_range=(10**-9, 10**-2), toolbar_location="right") fig1.xaxis.formatter = formatter fig1.line('index', 'xrsb', source=source_static, color='red', line_width=2, legend="xrsa 1-8 Angstrom") fig2 = figure(title="GOES", tools=TOOLS, plot_height=PLOT_HEIGHT, width=PLOT_WIDTH, x_axis_type='datetime', y_axis_type="log", y_range=(10**-9, 10**-2)) fig2.xaxis.formatter = formatter fig2.line('index', 'xrsa', source=source_static, color='blue', line_width=2, legend="xrsa 0.5-4.0 Angstrom") # link the x-range for common panning fig2.x_range = fig1.x_range fig = Column(fig1, fig2) source_static.callback = CustomJS(code=""" var inds = cb_obj.selected['1d'].indices; var d1 = cb_obj.data; var m = 0; if (inds.length == 0) { return; } for (i = 0; i < inds.length; i++) { d1['color'][inds[i]] = "red" if (d1['y'][inds[i]] > m) { m = d1['y'][inds[i]] } } console.log(m); cb_obj.trigger('change'); """) hover = HoverTool() hover.tooltips = [("time", "@time_str"), ("xrsb", "@xrsb"), ("xrsa", "@xrsa")] fig1.add_tools(hover) hover2 = HoverTool() hover2.tooltips = [("time", "@time_str"), ("xrsb", "@xrsb"), ("xrsa", "@xrsa")] fig2.add_tools(hover2) # Configure resources to include BokehJS inline in the document. # For more details see: # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#bokeh-embed js_resources = INLINE.render_js() css_resources = INLINE.render_css() # For more details see: # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components script, div = components(fig, INLINE) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, js_resources=js_resources, css_resources=css_resources, _from=_from, _to=_to, ) return encode_utf8(html)
plot_1.title.text = "Circular Layout (NodesAndLinkedEdges inspection policy)" plot_1.add_tools(HoverTool(tooltips=None)) plot_2 = create_graph(nx.spring_layout, selection_policy=NodesAndLinkedEdges(), scale=2, center=(0, 0)) plot_2.title.text = "Spring Layout (NodesAndLinkedEdges selection policy)" plot_2.add_tools(TapTool(), BoxSelectTool()) plot_3 = create_graph(nx.random_layout, inspection_policy=EdgesAndLinkedNodes(), center=(0, 0)) plot_3.title.text = "Random Layout (EdgesAndLinkedNodes inspection policy)" plot_3.add_tools(HoverTool(tooltips=None)) plot_4 = create_graph(nx.fruchterman_reingold_layout, selection_policy=EdgesAndLinkedNodes(), scale=2, center=(0, 0), dim=2) plot_4.title.text = "FR Layout (EdgesAndLinkedNodes selection policy)" plot_4.add_tools(TapTool()) layout = Column(Row(plot_1, plot_2), Row(plot_3, plot_4)) doc = curdoc() doc.add_root(layout) show(layout)
def monitoring_app(doc, database_name, session_data): """Create plots showing the development of the criterion and parameters. Options are loaded from the database. Supported options are: - rollover (int): How many iterations to keep before discarding. Args: doc (bokeh.Document): Argument required by bokeh. database_name (str): Short and unique name of the database. session_data (dict): Infos to be passed between and within apps. Keys of this app's entry are: - last_retrieved (int): last iteration currently in the ColumnDataSource. - database_path (str or pathlib.Path) - callbacks (dict): dictionary to be populated with callbacks. """ database = load_database(session_data["database_path"]) start_params = read_scalar_field(database, "start_params") dash_options = read_scalar_field(database, "dash_options") rollover = dash_options["rollover"] tables = ["criterion_history", "params_history"] criterion_history, params_history = _create_bokeh_data_sources( database=database, tables=tables ) session_data["last_retrieved"] = 1 # create initial bokeh elements without callbacks initial_convergence_plots = _create_initial_convergence_plots( criterion_history=criterion_history, params_history=params_history, start_params=start_params, ) activation_button = Toggle( active=False, label="Start Updating from Database", button_type="danger", width=50, height=30, name="activation_button", ) # add elements to bokeh Document bokeh_convergence_elements = [Row(activation_button)] + initial_convergence_plots convergence_tab = Panel( child=Column(*bokeh_convergence_elements), title="Convergence Tab" ) tabs = Tabs(tabs=[convergence_tab]) doc.add_root(tabs) # add callbacks activation_callback = partial( _activation_callback, button=activation_button, doc=doc, database=database, session_data=session_data, rollover=rollover, tables=tables, ) activation_button.on_change("active", activation_callback)
def volt_plots(conn, start, end): '''Combines plots to a tab Parameters ---------- conn : DBobject Connection object that represents database start : time Startlimit for x-axis and query (typ. datetime.now()- 4Months) end : time Endlimit for x-axis and query (typ. datetime.now()) Return ------ p : tab object used by dashboard.py to set up dashboard ''' descr = Div(text=""" <style> table, th, td { border: 1px solid black; background-color: #efefef; border-collapse: collapse; padding: 5px } table { border-spacing: 15px; } </style> <body> <table style="width:100%"> <tr> <th><h6>Plotname</h6></th> <th><h6>Mnemonic</h6></th> <th><h6>Description</h6></th> </tr> <tr> <td>ICE_SEC_VOLT1/3</td> <td>IMIR_HK_ICE_SEC_VOLT1 <br> IMIR_HK_ICE_SEC_VOLT3 <br> </td> <td>ICE Secondary Voltage (HV) V1 and V3</td> </tr> <tr> <td>ICE_SEC_VOLT2</td> <td>IMIR_HK_SEC_VOLT2</td> <td>ICE secondary voltage (HV) V2</td> </tr> <tr> <td>ICE_SEC_VOLT4</td> <td>IMIR_HK_SEC_VOLT2</td> <td>ICE secondary voltage (HV) V4 - HV on and IDLE</td> </tr> <tr> <td>Wheel Sensor Supply</td> <td>IMIR_HK_FW_POS_VOLT<br> IMIR_HK_GW14_POS_VOLT<br> IMIR_HK_GW23_POS_VOLT<br> IMIR_HK_CCC_POS_VOLT</td> <td>Wheel Sensor supply voltages </td> </tr> </table> </body> """, width=1100) plot1 = volt1_3(conn, start, end) plot2 = volt2(conn, start, end) plot3 = volt4(conn, start, end) plot4 = pos_volt(conn, start, end) l = gridplot([[plot1, plot2], [plot3, plot4]], merge_tools=False) layout = Column(descr, l) tab = Panel(child=layout, title="ICE/WHEEL VOLTAGE") return tab
# mass_finder_range_text = Div(text= " Range mz:", width= 150, height=30 ) mass_finder_range_slider = RangeSlider(start=1.0, end=500.0, value=(1.0,50.0), title='Charge range:',name='mass_finder_range_slider', step=1, width= 250, height=30) # mass_finder_mass_text = Div(text= " Mass of Complex (kDa):", width= 150, height=30 ) mass_finder_mass = Slider(value=100, start=0.0, end=1000.0, step=10.0, title='Mass of Complex (kDa)',name='gau_sigma', width=250, height=30) mass_finder_exact_mass_text = Div(text= "Enter exact Mass (Da)", width= 150, height=30 ) mass_finder_exact_mass_sele = TextInput(value=str(mass_finder_mass.value*1000), disabled=False, width=100, height=30) mass_finder_line_text = Div(text= "Show mz prediction", width= 150, height=30 ) mass_finder_line_sele = Toggle(label='off', active=False, width=100, height=30, callback=toggle_cb) mass_finder_cb =CustomJS(args=dict(mass_finder_line_sele=mass_finder_line_sele, raw_mz=raw_mz, mass_finder_data=mass_finder_data, mass_finder_exact_mass_sele=mass_finder_exact_mass_sele, mass_finder_mass=mass_finder_mass, mass_finder_range_slider=mass_finder_range_slider, mfl=mfl), code=open(os.path.join(os.getcwd(), 'JS_Functions', "mass_finder_cb.js")).read()) mass_finder_exact_cb =CustomJS(args=dict(mass_finder_line_sele=mass_finder_line_sele, mass_finder_exact_mass_sele=mass_finder_exact_mass_sele, mass_finder_mass=mass_finder_mass), code=open(os.path.join(os.getcwd(), 'JS_Functions', "mass_finder_exact_cb.js")).read()) mass_finder_exact_mass_sele.js_on_change('value', mass_finder_exact_cb) mass_finder_column=Column(mass_finder_header,mass_finder_mass, mass_finder_range_slider, Row(mass_finder_exact_mass_text,mass_finder_exact_mass_sele), Row(mass_finder_line_text, mass_finder_line_sele), visible=False) mass_finder.js_link('active', mass_finder_column, 'visible') mass_finder_line_sele.js_link('active', mfl, 'visible') mass_finder_mass.js_on_change('value', mass_finder_cb) mass_finder_line_sele.js_on_change('active', mass_finder_cb) mass_finder_range_slider.js_on_change('value',mass_finder_cb) ### DATA PROCESSING ### cropping = Div(text= " Range mz:", width= 150, height=30 ) # crop_max = Div(text= " ", width= 150, height=30 ) gau_name = Div(text= " Gaussian Smoothing:", width= 150, height=30 ) n_smooth_name = Div(text= " Repeats of Smoothing:", width= 150, height=30 ) # bin_name = Div(text= " Bin Every:", width= 150, height=30 ) int_name = Div(text= " Intensity Threshold (%)", width= 150, height=30 ) sub_name = Select(options=['Substract Minimum', 'Substract Line', 'Substract Curved'], name='sub_mode', value='Substract Minimum', width= 150, height=30 ) # add_name = Div(text= " Adduct Mass (Da)", width= 150, height=30 )
title='Which buildings use what fuel?', tools=['pan', 'reset', 'tap']) bar.xaxis.axis_label = 'Types of Buildings in NYC' bar.yaxis.axis_label = 'Total number of Buildings' bar.xaxis.major_label_orientation = pi / 3 barColor = factor_cmap('btype', palette=Category20c[20], factors=sorted(df['BuildingType'].unique())) bar.vbar(x='btype', top='count', width=.3, color=barColor, source=cdsbar) fuelSelect = Select(title='Select the fuel type', options=list(df['PrimaryFuel'].unique()), value='4 (Clean Oil)') fuelSelect.on_change('value', updateBar) barHover = HoverTool( tooltips=[('Type of building', '@btype'), ('Fuel used', '@fuel'), ('Total # of buildings', '@count')]) bar.add_tools(barHover) curdoc().add_root( Column(Column(xSelect, line), Row(scatHigh, scatLow), Column(fuelSelect, bar)))
c = next(colors) fig5.circle('total_deaths', 'new_deaths', source=plotdata, color=c, legend_label=state) # fig5.line('total_deaths', 'new_deaths', source=plotdata, color=c, # legend_label=state) d_mean = cases_state[cases_state.State == state].new_deaths.rolling( 5).mean().fillna(0) fig5.line(x=cases_state[cases_state.State == state].total_deaths, y=d_mean, color=c, legend_label=state) fig0.legend.location = "top_left" fig0.legend.click_policy = "hide" fig1.legend.location = "top_left" fig1.legend.click_policy = "hide" fig2.legend.location = "top_left" fig2.legend.click_policy = "hide" fig3.legend.location = "top_left" fig3.legend.click_policy = "hide" fig4.legend.location = "top_left" fig4.legend.click_policy = "hide" fig5.legend.location = "top_left" fig5.legend.click_policy = "hide" bkp.output_file('covid19_us.html') bkp.show(Column(fig0, fig1, fig2, fig3, fig4, fig5))
def tab_testing(): data_list = glob.glob('./np/Regression/*.npy') data_list = sorted(data_list) select_data = Select(title="Data:", value="", options=data_list) model_list = os.listdir('./model/Regression/') model_list = sorted(model_list) select_model = Select(title="Trained Model:", value="", options=model_list) notifier = Paragraph(text=""" Notification """, width=200, height=100) def refresh_handler(): data_list_new = glob.glob('./np/Regression/*.npy') data_list_new = sorted(data_list_new) select_data.options = data_list_new model_list_new = os.listdir('./model/Regression/') model_list_new = sorted(model_list_new) select_model.options = model_list_new button_refresh = Button(label="Refresh list") button_refresh.on_click(refresh_handler) button_test = Button(label="Test model") select_result = MultiSelect(title="Key(result):") src = ColumnDataSource() df = pd.DataFrame(columns=['key', 'y', 'y_hat']) table_src = ColumnDataSource(pd.DataFrame(columns=['Key', 'MSE', 'R^2'])) table_columns = [ TableColumn(field=col, title=col) for col in ['Key', 'MSE', 'R^2'] ] table_acc = DataTable(source=table_src, columns=table_columns, width=350, height=400, fit_columns=True, name="Accuracy per Key") def test_handler(): df.drop(df.index, inplace=True) print("Start test") tf.reset_default_graph() K.clear_session() notifier.text = """ Start testing """ if (select_data.value == ""): data = np.load(select_data.options[0]) else: data = np.load(select_data.value) data = data.item() notifier.text = """ Import data """ data_x = data.get('x') if (data_x.shape[-1] == 1 and not 'cnn' in select_model.value): data_x = np.squeeze(data_x, -1) data_y = data.get('y') data_key = data.get('key1') print(data_x.shape) print(data_y.shape) df['key'] = data_key df['y'] = data_y[:, 0] op_list = [] for i in df['key'].unique(): op_list.append(str(i)) select_result.options = op_list print(data_x.shape) print(data_y.shape) print(data.get('key1')) if (select_model.value == ""): model_name = select_model.options[0] else: model_name = select_model.value model_save_dir = './model/Regression/' + model_name + '/' model_dl = glob.glob(model_save_dir + '*.h5') model_ml = glob.glob(model_save_dir + '*.sav') print(model_save_dir + '*.h5') print(model_dl) print(model_ml) if (len(model_dl) > len(model_ml)): model = keras.models.load_model(model_save_dir + model_name + '.h5') target_hat = model.predict(data_x) DL = True elif (len(model_dl) < len(model_ml)): model = pickle.load( open(model_save_dir + model_name + '.sav', 'rb')) data_x = data_x.reshape([data_x.shape[0], -1]) target_hat = model.predict(data_x) target_hat = np.expand_dims(target_hat, -1) DL = False notifier.text = """ Model restored """ print("Model restored.") xs = [] ys = [] keys = [] color = ['blue', 'red'] xs.append([i for i in range(data_y.shape[0])]) xs.append([i for i in range(data_y.shape[0])]) ys.append(data_y) keys.append(data_key) print(target_hat.shape) K.clear_session() ys.append(target_hat) keys.append(data_key) print(target_hat[:, 0]) df['y_hat'] = target_hat[:, 0] src.data = ColumnDataSource( data=dict(xs=xs, ys=ys, color=color, keys=keys)).data figure_trend.multi_line('xs', 'ys', source=src, color='color') line_mse = [] line_r_2 = [] for unit in df['key'].unique(): target = df[df['key'] == unit] y = target['y'].values y_hat = target['y_hat'].values unit_mse = np.sum((y - y_hat)**2) / target.shape[0] unit_r_2 = np.max([r2_score(y, y_hat), 0]) line_mse.append(unit_mse) line_r_2.append(unit_r_2) acc = pd.DataFrame(columns=['Key', 'MSE', 'R^2']) acc['Key'] = df['key'].unique() mse_mean = np.mean(line_mse) r_2_mean = np.mean(line_r_2) line_mse = list(map(lambda x: format(x, '.2f'), line_mse)) acc['MSE'] = line_mse line_r_2 = list(map(lambda x: format(x, '.2f'), line_r_2)) acc['R^2'] = line_r_2 acc_append = pd.DataFrame(columns=acc.columns) acc_append['Key'] = ['MSE average', 'R^2 average'] acc_append['MSE'] = [mse_mean, r_2_mean] acc = pd.concat([acc, acc_append]) table_src.data = ColumnDataSource(acc).data notifier.text = """ Drawing complete """ history.text = history.text + "\n\t" + model_name + "'s R^2 score: " + format( np.mean(r_2_mean), '.2f') def update(attr, old, new): key_to_plot = select_result.value xs = [] ys = [] keys = [] y = [] y_hat = [] key = [] key_type = type(df['key'].values[0]) for k in key_to_plot: y += list(df[df['key'] == key_type(k)]['y'].values) y_hat += list(df[df['key'] == key_type(k)]['y_hat'].values) key += [k for _ in range(df[df['key'] == key_type(k)].shape[0])] ys.append(y) ys.append(y_hat) xs.append([i for i in range(len(y))]) xs.append([i for i in range(len(y))]) keys.append(key) keys.append(key) color = ['blue', 'red'] src.data = ColumnDataSource( data=dict(xs=xs, ys=ys, color=color, keys=keys)).data select_result.on_change("value", update) button_test.on_click(test_handler) button_export = Button(label="Export result") def handler_export(): df.to_csv('./Export/result.csv', index=False) button_export.on_click(handler_export) figure_trend = figure(title="Prediction result", width=800, height=460) history = PreText(text="", width=300, height=460) layout = Column( Row(button_refresh), Row(select_data, select_model, button_test, select_result, notifier), Row(table_acc, figure_trend, history, button_export)) tab = Panel(child=layout, title='Regression Test') return tab
data_table = plot_table( df_melt[['GroupName', 'IntervationName', 'Profit', 'TruePositiveRate']].sort_values(by=['IntervationName']) ) text_mandatory = Div( text=""" <h2 style='margin-block-end:0'> Graph 1: Using mandatory parameters only </h2> """ ) text_optional= Div( text=""" <h2 style='margin-block-end:0'> Graph 2: Using additional and optional function parameters </h2> """ ) text_table = Div( text=""" <h2 style='margin-block-end:0'> Data used in graph</h2> <span style='color: #616161'><i>Scrollable table</i></span> """ ) show( layout( Column(text_mandatory, p_mandatory, text_optional, p_optional, text_table, data_table) ) )