def make_doc(self): title = Div(text="<h2>Retrieved quantities</h2>") c = column(title, self.checks, self.plots) return c
def make_retrieval_panel(simulation): z = np.copy(simulation.workspace.z_field.value.ravel()) p = np.copy(simulation.workspace.p_grid.value.ravel()) retrieval_result_plot = RetrievalResultPlot(z, p, simulation.retrieval) r = retrieval_result_plot.make_doc() if type(simulation.retrieval.results) is list: results = simulation.retrieval.results else: results = [simulation.retrieval.results] if all([not r.avk is None for r in simulation.retrieval.results]): avks = AVKPlot(simulation) r.children += avks.make_doc().children return Panel(child=r, title="Retrieval", width=600) observation_plots = {} for s in simulation.sensors: observation_plots[s] = ObservationPlot(s) if type(simulation.retrieval.results) is list: plots = [] for r in simulation.retrieval.results: for s in r.sensors: i, j = r.sensor_indices[s.name] observation_plots[s].add_observation(r.y[i:j]) print(r.y[i:j]) observation_plots[s].add_observation(r.yf[i:j]) print(r.yf[i:j]) plot = ProfilePlot(z, p) for q in r.retrieval_quantities: x = r.get_result(q) plot.add_quantity(x, r.name, dict(line_dash="solid", line_width=3)) xa = r.get_result(q, "xa") plot.add_quantity(xa, r.name, dict(line_dash="dashed")) x0 = r.get_result(q, "x0") if not all(xa == x0): plot.add_quantity(x0, r.name, dict(line_dash="dotted")) plots += [plot] else: plot = ProfilePlot(z, p) for q in r.retrieval_quantities: x = r.get_result(q) plot.add(x, r.name, "blue") plots = [plot] title = Div(text="<h2>Retrieved quantities</h2>") doms = [title] + [p.make_doc() for p in plots] title = Div(text="<h2>Fitted measurements</h2>") doms += [title ] + [observation_plots[s].make_doc() for s in simulation.sensors] c = column(*doms) return Panel(child=c, title="Retrieval", width=600)
def get_heading_and_info(ulog, px4_ulog, plot_width, db_data, vehicle_data, vtol_states): """ get a bokeh widgetbox object with the html heading text and some tables with additional text info, such as logging duration, max speed etc. """ # Heading sys_name = '' if 'sys_name' in ulog.msg_info_dict: sys_name = cgi.escape(ulog.msg_info_dict['sys_name']) + ' ' div = Div(text="<h1>" + sys_name + px4_ulog.get_mav_type() + "</h1>", width=int(plot_width * 0.9)) header_divs = [div] if db_data.description != '': div_descr = Div(text="<h4>" + db_data.description + "</h4>", width=int(plot_width * 0.9)) header_divs.append(div_descr) ### Setup the text for the left table with various information ### table_text_left = [] # airframe airframe_name_tuple = get_airframe_name(ulog, True) if airframe_name_tuple is not None: airframe_name, airframe_id = airframe_name_tuple if len(airframe_name) == 0: table_text_left.append(('Airframe', airframe_id)) else: table_text_left.append( ('Airframe', airframe_name + ' <small>(' + airframe_id + ')</small>')) # HW & SW sys_hardware = '' if 'ver_hw' in ulog.msg_info_dict: sys_hardware = cgi.escape(ulog.msg_info_dict['ver_hw']) table_text_left.append(('Hardware', sys_hardware)) release_str = ulog.get_version_info_str() if release_str is None: release_str = '' release_str_suffix = '' else: release_str += ' <small>(' release_str_suffix = ')</small>' branch_info = '' if 'ver_sw_branch' in ulog.msg_info_dict: branch_info = '<br> branch: ' + ulog.msg_info_dict['ver_sw_branch'] if 'ver_sw' in ulog.msg_info_dict: ver_sw = cgi.escape(ulog.msg_info_dict['ver_sw']) ver_sw_link = 'https://github.com/PX4/Firmware/commit/' + ver_sw table_text_left.append( ('Software Version', release_str + '<a href="' + ver_sw_link + '" target="_blank">' + ver_sw[:8] + '</a>' + release_str_suffix + branch_info)) if 'sys_os_name' in ulog.msg_info_dict and 'sys_os_ver_release' in ulog.msg_info_dict: os_name = cgi.escape(ulog.msg_info_dict['sys_os_name']) os_ver = ulog.get_version_info_str('sys_os_ver_release') if os_ver is not None: table_text_left.append(('OS Version', os_name + ', ' + os_ver)) table_text_left.append(('Estimator', px4_ulog.get_estimator())) table_text_left.append(('', '')) # spacing # logging start time & date try: # get the first non-zero timestamp gps_data = ulog.get_dataset('vehicle_gps_position') indices = np.nonzero(gps_data.data['time_utc_usec']) if len(indices[0]) > 0: # we use the timestamp from the log and then convert it with JS to # display with local timezone logging_start_time = int( gps_data.data['time_utc_usec'][indices[0][0]] / 1000000) js_code = """ <script type="text/javascript"> var logging_span = $('#logging-start-element'); var d = new Date(0); d.setUTCSeconds(logging_span.text()); var date_str = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2); logging_span.text(date_str); logging_span.show(); </script> """ table_text_left.append( ('Logging Start', '<span style="display:none" id="logging-start-element">' + str(logging_start_time) + '</span>' + js_code)) except: # Ignore. Eg. if topic not found pass # logging duration m, s = divmod(int((ulog.last_timestamp - ulog.start_timestamp) / 1e6), 60) h, m = divmod(m, 60) table_text_left.append( ('Logging Duration', '{:d}:{:02d}:{:02d}'.format(h, m, s))) # dropouts dropout_durations = [dropout.duration for dropout in ulog.dropouts] if len(dropout_durations) > 0: total_duration = sum(dropout_durations) / 1000 if total_duration > 5: total_duration_str = '{:.0f}'.format(total_duration) else: total_duration_str = '{:.2f}'.format(total_duration) table_text_left.append( ('Dropouts', '{:} ({:} s)'.format(len(dropout_durations), total_duration_str))) # total vehicle flight time flight_time_s = get_total_flight_time(ulog) if flight_time_s is not None: m, s = divmod(int(flight_time_s), 60) h, m = divmod(m, 60) days, h = divmod(h, 24) flight_time_str = '' if days > 0: flight_time_str += '{:d} days '.format(days) if h > 0: flight_time_str += '{:d} hours '.format(h) if m > 0: flight_time_str += '{:d} minutes '.format(m) flight_time_str += '{:d} seconds '.format(s) table_text_left.append(('Vehicle Flight Time', flight_time_str)) table_text_left.append(('', '')) # spacing # vehicle UUID (and name if provided). SITL does not have a UUID if 'sys_uuid' in ulog.msg_info_dict and sys_hardware != 'SITL': sys_uuid = cgi.escape(ulog.msg_info_dict['sys_uuid']) if vehicle_data is not None and vehicle_data.name != '': sys_uuid = sys_uuid + ' (' + vehicle_data.name + ')' if len(sys_uuid) > 0: table_text_left.append(('Vehicle UUID', sys_uuid)) table_text_left.append(('', '')) # spacing # Wind speed, rating, feedback if db_data.wind_speed >= 0: table_text_left.append(('Wind Speed', db_data.wind_speed_str())) if len(db_data.rating) > 0: table_text_left.append(('Flight Rating', db_data.rating_str())) if len(db_data.feedback) > 0: table_text_left.append( ('Feedback', db_data.feedback.replace('\n', '<br/>'))) if len(db_data.video_url) > 0: table_text_left.append( ('Video', '<a href="' + db_data.video_url + '" target="_blank">' + db_data.video_url + '</a>')) ### Setup the text for the right table: estimated numbers (e.g. max speed) ### table_text_right = [] try: local_pos = ulog.get_dataset('vehicle_local_position') pos_x = local_pos.data['x'] pos_y = local_pos.data['y'] pos_z = local_pos.data['z'] pos_xyz_valid = np.multiply(local_pos.data['xy_valid'], local_pos.data['z_valid']) local_vel_valid_indices = np.argwhere( np.multiply(local_pos.data['v_xy_valid'], local_pos.data['v_z_valid']) > 0) vel_x = local_pos.data['vx'][local_vel_valid_indices] vel_y = local_pos.data['vy'][local_vel_valid_indices] vel_z = local_pos.data['vz'][local_vel_valid_indices] # total distance (take only valid indexes) total_dist_m = 0 last_index = -2 for valid_index in np.argwhere(pos_xyz_valid > 0): index = valid_index[0] if index == last_index + 1: dx = pos_x[index] - pos_x[last_index] dy = pos_y[index] - pos_y[last_index] dz = pos_z[index] - pos_z[last_index] total_dist_m += sqrt(dx * dx + dy * dy + dz * dz) last_index = index if total_dist_m < 1: pass # ignore elif total_dist_m > 1000: table_text_right.append( ('Distance', "{:.2f} km".format(total_dist_m / 1000))) else: table_text_right.append( ('Distance', "{:.1f} m".format(total_dist_m))) if len(pos_z) > 0: max_alt_diff = np.amax(pos_z) - np.amin(pos_z) table_text_right.append( ('Max Altitude Difference', "{:.0f} m".format(max_alt_diff))) table_text_right.append(('', '')) # spacing # Speed if len(vel_x) > 0: max_h_speed = np.amax(np.sqrt(np.square(vel_x) + np.square(vel_y))) speed_vector = np.sqrt( np.square(vel_x) + np.square(vel_y) + np.square(vel_z)) max_speed = np.amax(speed_vector) if vtol_states is None: mean_speed = np.mean(speed_vector) table_text_right.append( ('Average Speed', "{:.1f} km/h".format(mean_speed * 3.6))) else: local_pos_timestamp = local_pos.data['timestamp'][ local_vel_valid_indices] speed_vector = speed_vector.reshape((len(speed_vector), )) mean_speed_mc, mean_speed_fw = _get_vtol_means_per_mode( vtol_states, local_pos_timestamp, speed_vector) if mean_speed_mc is not None: table_text_right.append( ('Average Speed MC', "{:.1f} km/h".format(mean_speed_mc * 3.6))) if mean_speed_fw is not None: table_text_right.append( ('Average Speed FW', "{:.1f} km/h".format(mean_speed_fw * 3.6))) table_text_right.append( ('Max Speed', "{:.1f} km/h".format(max_speed * 3.6))) table_text_right.append(('Max Speed Horizontal', "{:.1f} km/h".format(max_h_speed * 3.6))) table_text_right.append( ('Max Speed Up', "{:.1f} km/h".format(np.amax(-vel_z) * 3.6))) table_text_right.append( ('Max Speed Down', "{:.1f} km/h".format(-np.amin(-vel_z) * 3.6))) table_text_right.append(('', '')) # spacing vehicle_attitude = ulog.get_dataset('vehicle_attitude') roll = vehicle_attitude.data['roll'] pitch = vehicle_attitude.data['pitch'] if len(roll) > 0: # tilt = angle between [0,0,1] and [0,0,1] rotated by roll and pitch tilt_angle = np.arccos(np.multiply(np.cos(pitch), np.cos(roll))) * 180 / np.pi table_text_right.append( ('Max Tilt Angle', "{:.1f} deg".format(np.amax(tilt_angle)))) rollspeed = vehicle_attitude.data['rollspeed'] pitchspeed = vehicle_attitude.data['pitchspeed'] yawspeed = vehicle_attitude.data['yawspeed'] if len(rollspeed) > 0: max_rot_speed = np.amax( np.sqrt( np.square(rollspeed) + np.square(pitchspeed) + np.square(yawspeed))) table_text_right.append( ('Max Rotation Speed', "{:.1f} deg/s".format(max_rot_speed * 180 / np.pi))) table_text_right.append(('', '')) # spacing battery_status = ulog.get_dataset('battery_status') battery_current = battery_status.data['current_a'] if len(battery_current) > 0: max_current = np.amax(battery_current) if max_current > 0.1: if vtol_states is None: mean_current = np.mean(battery_current) table_text_right.append( ('Average Current', "{:.1f} A".format(mean_current))) else: mean_current_mc, mean_current_fw = _get_vtol_means_per_mode( vtol_states, battery_status.data['timestamp'], battery_current) if mean_current_mc is not None: table_text_right.append( ('Average Current MC', "{:.1f} A".format(mean_current_mc))) if mean_current_fw is not None: table_text_right.append( ('Average Current FW', "{:.1f} A".format(mean_current_fw))) table_text_right.append( ('Max Current', "{:.1f} A".format(max_current))) except: pass # ignore (e.g. if topic not found) # generate the tables def generate_html_table(rows_list, tooltip=None, max_width=None): """ return the html table (str) from a row list of tuples """ if tooltip is None: tooltip = '' else: tooltip = 'data-toggle="tooltip" delay="{show: 500, hide: 100}" title="' + tooltip + '" ' table = '<table ' + tooltip if max_width is not None: table += ' style="max-width: ' + max_width + ';"' table += '>' padding_text = '' for label, value in rows_list: if label == '': # empty label means: add some row spacing padding_text = ' style="padding-top: 0.5em;" ' else: table += ('<tr><td ' + padding_text + 'class="left">' + label + ':</td><td' + padding_text + '>' + value + '</td></tr>') padding_text = '' return table + '</table>' left_table = generate_html_table(table_text_left, max_width='65%') right_table = generate_html_table( table_text_right, 'Note: most of these values are based on estimations from the vehicle,' ' and thus requiring an accurate estimator') html_tables = ( '<div style="display: flex; justify-content: space-between;">' + left_table + right_table + '</div>') header_divs.append(Div(text=html_tables)) return widgetbox(header_divs, width=int(plot_width * 0.99))
value=10, title="Sample Size for Simulations") msmt_error_input = RangeSlider( start=0, end=100., value=(10, 35), step=2, title="Measurement Uncertainty [%]", ) toggle_button = Toggle(label="Simulate Measurement Error", button_type="success") ffa_info = Div(width=550, text="Mean of {} simulations for a sample size of {}.".format( 'x', 'y')) error_info = Div(text="", style={'color': 'red'}) # Set up data table for summary statistics datatable_columns = [ TableColumn(field="parameter", title="Parameter"), TableColumn(field="value_all", title="All Data"), TableColumn(field="value_selection", title="Selected Data"), ] data_table = DataTable(source=datatable_source, columns=datatable_columns, width=450, height=125,
def plot_sv_alleles(annotations, aligned_regions_file): alignments = list(load_alignments(aligned_regions_file)) query_ids = sorted(list(set(a.query.id for a in alignments))) plots = [] for query_id in query_ids: alns = [a for a in alignments if a.query.id == query_id] x0 = [a.hit.start for a in alns] x1 = [a.hit.end for a in alns] y0 = [a.query.start for a in alns] y1 = [a.query.end for a in alns] min_x = min(x0 + x1) max_x = max(x0 + x1) x_range = (min_x, max_x) width = x_range[1] - x_range[0] pad = 0.1 * width x_range = (int(min_x - pad), int(max_x + pad)) colors = ["red" if a.hit.strand == '-' else "blue" for a in alns] fig = figure(width=800, height=300, x_range=x_range) fig.segment(x0, y0, x1, y1, line_color=colors, line_width=5, line_alpha=0.75, line_cap="butt") fig.title.text = query_id fig.yaxis.axis_label = "Amplicon" fig.xaxis.visible = False fig.yaxis.ticker = zooming_ticker() fig.xaxis.formatter = NumeralTickFormatter(format="0,0") fig.add_tools(hover) plots.append(fig) transcripts = transcripts_from_gffutils(annotations, next(a.hit.id for a in alns), x_range[0], x_range[1]) fig2 = gene_viz.GenePlot( dict(row_height=15, exon_color="Black", pack=True, label_horiz_position="center", label_vert_position="above", label_justify="center", label_offset=(0, -4), label_font_size="6pt", intron_width_percent=0.001)) fig2.link_x_range(fig) fig2.figure.xaxis.axis_label = next(a.hit.id for a in alns) fig2.figure.yaxis.visible = False fig2.figure.background_fill_color = "black" fig2.figure.background_fill_alpha = 0.15 fig2.transcripts = transcripts box = BoxAnnotation(left=min_x, right=max_x, fill_color='white', fill_alpha=1, level="underlay") fig2.figure.add_layout(box) for a in alns: box = BoxAnnotation( left=min([a.hit.start, a.hit.end]), right=max([a.hit.start, a.hit.end]), fill_color="red" if a.hit.strand == '-' else "blue", fill_alpha=0.25, level="underlay") fig2.figure.add_layout(box) fig2.update() plots.append(fig2.figure) if len(plots) > 0: save( gridplot(plots, ncols=1, toolbar_location="right", toolbar_options=dict(logo=None))) else: save(Div(text="No Data"))
end=dfs.default_slit_width_end, value=dfs.default_slit_width, step=dfs.default_slit_width_step, title=dfs.string_title[6], name=dfs.string_widget_names[10]) # range sliders widget_wavelengths = RangeSlider(start=dfs.default_limits_wavelength[0], end=dfs.default_limits_wavelength[1], value=(dfs.default_limits_wavelength), step=dfs.default_wavelength_step, title=dfs.string_title[8], name=dfs.string_widget_names[11]) # other widgets widget_header = Div(text='<h1>' + dfs.string_header_one + '</h1><h3>' + dfs.string_header_two + '</h3>', width=500, height=70) widget_plot_types = CheckboxButtonGroup( labels=dfs.string_plot_types, active=dfs.default_plot_types, name=dfs.string_widget_names[12]) # TODO: make double-off == double-on widget_message_box = Paragraph(text='hello') widget_plot_step = Slider(start=dfs.default_plot_step[1], end=dfs.default_plot_step[2], value=dfs.default_plot_step[0], step=dfs.default_plot_step_step, title=dfs.string_plot_step) widget_moon_days_header = Paragraph(text=dfs.string_title[7]) ''' plot it - figures are the... yeah if you're reading this, then you know what that means
# # Generate the new ranges # source.data['time'] = data_model['time'][ai:bi] # source.data['y'] = data_model['y'][ai:bi] # #source.data = dict(x=x, y=y) # for w in [start, end ]: # w.on_change('value', update_range) # title = PreText("cam: b0") # layout = column( # row( column(widgetbox(select_y)), column( row(plot, pv), # row(ph, Spacer(width= pv.width, height=ph.height)) ))) frame_title = """<div><p align="center" style="font-size: 40px;">Selected arm: b</p></div>""" layout = column( widgetbox(Div(text=frame_title), width=1000, height=100), row(column(widgetbox(select_y), widgetbox(range_select)), plot)) # column( # row( column(widgetbox(select_y)), column( row(plot, pv), # row(ph, Spacer(width= pv.width, height=ph.height)) ))) curdoc().add_root(layout) # def get_data(N): # return dict(x=random(size=N), y=random(size=N), r=random(size=N) * 0.03) # source = ColumnDataSource(data=get_data(200)) # p = Figure(tools="", toolbar_location=None) # r = p.circle(x='x', y='y', radius='r', source=source, # color="navy", alpha=0.6, line_color="white")
def histogram_bokeh(ks_distributions, labels): """ Run an interactive bokeh application. This requires a running bokeh server! Use ``bokeh serve &`` to start a bokeh server in the background. :param ks_distributions: a list of Ks distributions (pandas data frames) :param labels: a list of labels for the corresponding distributions :return: bokeh app """ from bokeh.io import curdoc from bokeh.layouts import widgetbox, layout from bokeh.models.widgets import Select, TextInput, Slider, Div from bokeh.models.widgets import CheckboxGroup, Toggle from bokeh.plotting import figure, output_file, show from bokeh.client import push_session from pylab import cm from .utils import gaussian_kde from .modeling import reflect # helper functions def get_colors(cmap_choice='binary'): too_light = [ 'binary', 'hot', 'copper', 'pink', 'summer', 'bone', 'Pastel1', 'Pastel2', 'gist_ncar', 'nipy_spectral', 'Greens' ] cmap = cm.get_cmap(cmap_choice, len(ks_distributions)) if cmap_choice in too_light: cmap = cm.get_cmap(cmap_choice, len(ks_distributions) * 4) c = [] for i in range(cmap.N): rgb = cmap(i)[:3] # will return rgba, but we need only rgb c.append(matplotlib.colors.rgb2hex(rgb)) if cmap_choice in too_light: if len(ks_distributions) > 1: c = c[2:-2] else: c = [c[-1]] return c def get_data(df, var, scale, r1, r2, outliers_included): df = filter_group_data(df, min_ks=r1, max_ks=r2, weights_outliers_included=outliers_included) data = df[var].dropna() if scale == 'log10': data = np.log10(data) return data, df # get the distributions dists = [pd.read_csv(x, sep='\t') for x in ks_distributions] if labels: labels = labels.split(',') else: labels = ks_distributions # basics c = get_colors() variables = ['Ks', 'Ka', 'Omega'] scales = ['Normal', 'log10'] # set up widgets div = Div(text=BOKEH_APP_DIV, width=800) var = Select(title='Variable', value='Ks', options=variables) scale = Select(title='Scale', value='Normal', options=scales) r1 = TextInput(title="Minimum", value='0.1') r2 = TextInput(title="Maximum", value='5') bins = TextInput(title="Bins", value='50') bandwidth = TextInput(title="Bandwidth", value='0.1') line = Slider(title="Lines", start=0, end=1, value=0.3, step=0.1) density = CheckboxGroup(labels=["Histogram", "KDE"], active=[0]) density_alpha = Slider(title="Density alpha value", start=0, end=1, value=0.6, step=0.1) hist_alpha = Slider(title="Histogram alpha value", start=0, end=1, value=0.6, step=0.1) color_choice = Select(options=[ 'binary', 'hsv', 'hot', 'magma', 'viridis', 'Greens', 'spring', 'autumn', 'copper', 'cool', 'winter', 'pink', 'summer', 'bone', 'RdBu', 'RdYlGn', 'coolwarm', 'inferno', 'Pastel1', 'Pastel2', 'tab10', 'gnuplot', 'brg', 'gist_ncar', 'jet', 'rainbow', 'nipy_spectral', 'ocean', 'cubehelix' ], value='binary', title='Color map') no_reweight = Toggle(label="Don't adapt weights when filtering", active=False) # set up figure p1 = figure( plot_width=1000, plot_height=700, # output_backend="svg", tools='pan,wheel_zoom,xwheel_zoom,ywheel_zoom,save') p1.xgrid.grid_line_color = None p1.ygrid.grid_line_color = None p1.border_fill_color = 'white' p1.outline_line_color = None p1.yaxis.axis_label = 'Duplications' p1.xaxis.axis_label = 'Ks' # draw initial plot hist_dict = {} density_dict = {} all_data = [] # set up callbacks def update(selected=None): redraw_plots() def redraw_plots(): print(density.active) c = get_colors(color_choice.value) p1.legend.items = [] all_data = [] for i in range(len(dists)): df = dists[i] data, df = get_data(df, var.value, scale.value, float(r1.value), float(r2.value), no_reweight.active) all_data.append(data) edges = np.histogram(np.hstack(tuple(all_data)), bins=int(bins.value))[1] for i in range(len(dists)): if density.active == [0]: hist = np.histogram(all_data[i], bins=int(bins.value))[0] p1.yaxis.axis_label = 'Duplications' else: hist = np.histogram(all_data[i], bins=int(bins.value), density=True)[0] p1.yaxis.axis_label = 'density' # First histograms if i in hist_dict: remove_plot(hist_dict, i) if 0 in density.active: hist_dict[i] = p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color=c[i], line_color="black", fill_alpha=hist_alpha.value, line_alpha=line.value, legend=labels[i]) # Then KDEs if i in density_dict: density_dict[i].data_source.data['x'] = [] density_dict[i].data_source.data['y'] = [] if 1 in density.active: X = reflect(all_data[i]) kde = gaussian_kde(X, bw_method=float(bandwidth.value)) x = np.linspace( float(r1.value) + 0.000001, float(r2.value), 1000) if scale.value == 'log10': x = np.log10(x) pdf = np.array(kde(x)) * 2 # add boundaries such that it is a nice curve! pdf = np.hstack([0, pdf, 0]) if scale.value == 'log10': x = np.hstack([ np.log10(float(r1.value) + 0.00000099), x, np.log10(float(r2.value) + 0.000001) ]) else: x = np.hstack( [float(r1.value), x, float(r2.value) + 0.000001]) density_dict[i] = p1.patch(x=x, y=pdf, fill_color=c[i], line_width=2, line_color="black", line_alpha=line.value, alpha=density_alpha.value, legend=labels[i]) p1.legend.label_text_font_style = "italic" p1.legend.click_policy = "hide" p1.legend.inactive_fill_alpha = 0.6 v = var.value if v == "Omega": v = "Ka/Ks" if scale.value == 'log10': v = 'log10(' + v + ')' p1.xaxis.axis_label = v def remove_plot(hist_dict, i): hist_dict[i].data_source.data["top"] = [] hist_dict[i].data_source.data["left"] = [] hist_dict[i].data_source.data["right"] = [] def change_update(attrname, old, new): update() def feat_change(attrname, old, new): c = get_colors(color_choice.value) for i, d in density_dict.items(): d.glyph.fill_color = c[i] d.glyph.line_color = "black" d.glyph.fill_alpha = density_alpha.value d.glyph.line_alpha = line.value for i, d in hist_dict.items(): d.glyph.fill_color = c[i] d.glyph.line_color = "black" d.glyph.fill_alpha = hist_alpha.value d.glyph.line_alpha = line.value def bins_update(attrname, old, new): update() var.on_change('value', bins_update) bandwidth.on_change('value', bins_update) scale.on_change('value', bins_update) r1.on_change('value', bins_update) r2.on_change('value', bins_update) line.on_change('value', feat_change) bins.on_change('value', bins_update) color_choice.on_change('value', feat_change) density.on_change('active', bins_update) density_alpha.on_change('value', feat_change) hist_alpha.on_change('value', feat_change) no_reweight.on_change("active", bins_update) # set up layout widgets1 = widgetbox(var, scale, color_choice, density, line, hist_alpha, density_alpha, r1, r2, bins, bandwidth, no_reweight, sizing_mode='fixed') l = layout([ [div], [widgets1, p1], ], sizing_mode='fixed') # initialize update() session = push_session(curdoc()) curdoc().add_root(l) session.show(l) # open the document in a browser session.loop_until_closed() # run forever return # show(p1)
source=source) # 통합 디자인 부분임 for f in [p1, p2, p3, p4]: f.add_tools( HoverTool( line_policy='next', tooltips=[('Region', '@region')], )) f.legend.orientation = "horizontal" f.legend.background_fill_alpha = 0.2 crops = df.crop.unique().tolist() # 작물 연도별 순위 데이터 보여주는 데이터 칼럼 보기 titlediv = Div(text="""<h1>연도별 재배면적 상위 10개 작물</h1>""", width=1000) db, cum, rank = ranktrim(df) columns = [TableColumn(field=c, title=c) for c in db.column_names] data_table = DataTable(source=db, columns=columns, height=300, width=1000) cums_table = DataTable(source=cum, columns=columns, height=70, width=1000) para = Paragraph(text="""상위 10개 종목의 평창군 전체 재배면적 대비 누적 면적(%)""", height=25, width=1000) # rank chart 그리는 부분임 ranksource = ColumnDataSource( data={ 'crop': list(rank.keys()), 'rank': list(rank.values()), 'year': [db.column_names] * len(rank), 'color': Category20[14]
datetime.datetime.now()) string1 += "Number of symbols: " + str(symbols) + "<br>" string1 += "Test period: {:%b %d %Y} ".format(start) string1 += "to {:%b %d %Y} ".format(end) string1 += "with " + format(lookback, "1.0f") + " months lookback<br>" string1 += "Total of " + format(model.shape[0], "1.0f") + " months<br>" string1 += "<br>" #Result variables below string1 += "Average correlation among symbols: %.1f <br>" % corr_grid[ 'Mean'].mean() string1 += "R-Square of rank as predictor: %1.3f <br>" % (r_value * r_value) string1 += "Model gain (loss): %1.3f <br>" % model_gain string1 += "Max drawdown: %1.3f <br>" % model['DD'].min() string1 += "Market gain (loss): %1.3f <br>" % spy_gain string1 += "Model CAGR: %1.3f <br>" % CAGR string1 += "Sharpe Ratio: %1.3f <br>" % Sharpe para1 = Div(text=string1, width=450) title = "Rank for past " + format(lookback, "1.0f") + " months, R-Square = " + format( r_value * r_value, "1.3f") s1 = figure(plot_width=450, plot_height=420, title=title) s1.vbar(returns['Rank'], width=0.5, top=returns['Return']) s1.line(returns['Rank'], returns['Pred'], line_color='red') s1.xaxis.axis_label = 'Symbol Rank' s1.yaxis.axis_label = 'Following Month Return' s2 = figure(x_range=distro['Symbol'], plot_width=450, plot_height=420, title="Average Allocation by Symbol") s2.vbar(distro['Symbol'], width=0.5, top=distro['Alloc'])
def _get_title_div(text): div = Div(text="""{}""".format(text), height=1) return div
def show_searching_message(): ctl_recommended_games.children = [ Div(text='<h1>Searching for recommendations...</h1>') ]
def recommender_tab_simple(recommender): # create a list of divs def make_div_list(textlist, max_lines, fmt_str="""%s""", **attribs): """create a list of divs containing text to display""" divs = [] for i in range(max_lines): if len(textlist) > i: divs.append(Div(text=fmt_str % (textlist[i]), **attribs)) else: divs.append(Div(text=fmt_str % (' '), **attribs)) return divs def make_rec_list(titles, max_lines): """create a recommendation list of games, with a thumbnail, game title, info and Amazon buy links""" global games_by_title fmt_str1 = """ <div class="rec-post-container"> <div class="rec-post-thumb"><img src="%s" /></div> <div class="rec-post-content"> <h3 class="rec-post-title">%s<br> <a href="%s" target="_blank">Info</a><span> </span> <a href="%s" target="_blank">Buy on Amazon</a> </h3> </div> </div>""" fmt_str2 = """""" divs = [] for i in range(max_lines): # there is a title available for this list slot if len(titles) > i: divs.append( Div(text=fmt_str1 % (games_by_title['pic_url'].loc[titles[i]], titles[i], 'https://boardgamegeek.com/boardgame/' + str(games_by_title['id'].loc[titles[i]]), 'https://www.amazon.com/s?k=' + titles[i].replace(' ', '+') + '&i=toys-and-games'))) # there no title available for this list slot else: divs.append(Div(text=fmt_str2)) return divs # update the 'liked games' list UI elements def update_liked_list(titlelist): global max_liked ctl_liked_games.children = make_div_list(titlelist, max_liked, fmt_str=liked_list_fmt, render_as_text=False) # update the 'recommended games' list UI elements def update_recommended_list(titlelist): global n_recommendations ctl_recommended_games.children = make_rec_list(titlelist, n_recommendations) def show_searching_message(): ctl_recommended_games.children = [ Div(text='<h1>Searching for recommendations...</h1>') ] # called when a control widget is changed def update_preflist(attr, old, new): global liked_games liked_games.append(ctl_game_entry.value) liked_games = list(filter(None, set(liked_games))) # get control values update_liked_list(liked_games) ctl_game_entry.value = '' # clear out the list of preferred games def reset_preferred_games(): global liked_games liked_games = [] update_liked_list(liked_games) # user wants some recommendations (clicked the rec button) def recommend_games(): global liked_games, recommended_games global games_all, n_recommendations, title_list global title_list_lower # display a "Searching for recommendations..." message # Note: Bokeh doesn't do redraw while inside handlers show_searching_message() # get some default filter parameters: weight = [] minrating = 6.5 categories = ['Any category'] mechanics = ['Any mechanism'] for title in liked_games: idx = (np.array(title_list_lower) == title.lower()).nonzero()[0][0] info = games_all.iloc[idx, :] weight.append(info['weight']) categories += info['categories'].split(',') mechanics += info['mechanics'].split(',') # select a range of weights around the liked game weights weightrange = [ max(1, np.min(weight) - 0.25), min(5, np.max(weight) + 0.25) ] # get game IDs for titles liked_ids = recommender.get_item_title_id(liked_games) # select games to search from based on filters: recommended_games = recommender.recommend_items_by_pref_list( liked_ids, num2rec=n_recommendations, weightrange=weightrange, minrating=minrating, categories_include=categories, categories_exclude=['Expansion for Base-game'], mechanics_include=mechanics, mechanics_exclude=[]) update_recommended_list(recommended_games) # NOTE: I'm using globals because I'm running into variable scope # problems with the bokeh handlers. Easiest to declare globals global liked_games, recommended_games, games_all global n_recommendations, max_liked, title_list, title_list_lower global games_by_title # layout params n_recommendations = 10 max_liked = 8 # Format to use for liked list. # This needs to be changed to work like rec list liked_list_fmt = """<div style="font-size : 14pt; line-height:14pt;">%s</div>""" # variables used by the tab liked_games = [] recommended_games = [] weight_range = [1, 5] games_all = recommender.item_data # use all games for search games_by_title = recommender.item_data.set_index('name') # list of all game titles title_list = games_all['name'] title_list_lower = [s.lower() for s in title_list] # preferred game entry text control ctl_game_entry = AutocompleteInput(completions=list(title_list) + list(title_list_lower), min_characters=1, title='Enter some game names you like:') ctl_game_entry.on_change('value', update_preflist) # reset liked game list button ctl_reset_prefs = Button(label='Reset game list', width_policy='min', align='end') ctl_reset_prefs.on_click(reset_preferred_games) # liked list title ctl_liked_list_title = Div( text= """<div style="font-size : 18pt; line-height:16pt;">Games you like:</div>""" ) # liked game entries ctl_liked_games = WidgetBox( children=make_div_list(liked_games, max_liked, fmt_str=liked_list_fmt)) # recommended list title ctl_recommended_list_title = Div( text= """<div style="font-size : 18pt; line-height:16pt;">Games we recommend:</div>""" ) # recommended games list widget ctl_recommended_games = WidgetBox( children=make_rec_list(recommended_games, n_recommendations)) # Recommend games button ctl_recommend = Button(label='Recommend some games!', width_policy='min') ctl_recommend.on_click(recommend_games) # controls to select preferred games pref_controls = WidgetBox(ctl_liked_list_title, ctl_liked_games, Spacer(min_height=20), ctl_game_entry, ctl_reset_prefs, Spacer(min_height=40), ctl_recommend) # recommendation results results_controls = WidgetBox(ctl_recommended_list_title, ctl_recommended_games) # Create a row layout layout = row(pref_controls, results_controls) # Make a tab with the layout tab = Panel(child=layout, title='Simple Game Recommender') return tab
Voltage_Start = Slider(start=-1.5, end=1.5, value=0.2, step=0.01, title='Voltage Start') Voltage_WE2 = Slider(start=-1.5, end=1.5, value=0.2, step=0.01, title='Voltage Working Electrode 2', visible=False) Sweep_direction = RadioButtonGroup(name='Sweep Direction', labels=['Cathodic', 'Anodic'], active=0) Voltammetry_Mode = RadioButtonGroup(name='CV Mode', labels=['Single Mode', 'Dual Mode'], active=0) Scan_rate = TextInput(title='Scan rate (mV/s):', value='100', max_width=105) Segments = TextInput(title='Sweep Segments:', value='3', max_width=105) Comm_Status_Message = Paragraph(text="Status: Not connected", width=160) Port_input = TextInput(title='Port:', value='COM15', width=160) Save = Button(label='Save', button_type='warning', width=320) Message_Output = Div(width=320, height = 160, text="Cyclic Voltammetry GUI", background='#eceff1', css_classes=["Style.css"], style={'color': '#263238', 'font-family': 'Arial', 'padding': '20px', 'font-weight':'300','word-break':'break-word', 'border': 'border: 4px solid #263238', 'border-radius': '6px', 'word-break': 'break-word'}) #----------------------------# # Figure Configuration # #----------------------------# """Dataframe structure""" #NOTE AS of now, I will only receive raw data. transferData = {'time':[], 'raw_data':[], #'current':[] } acquiredData = {'timestamp':[], 'raw_data':[]} source = ColumnDataSource(data=transferData)
def load_qa(self): cam = self.selected_arm + str(self.selected_spectrograph) mergedqa = QLFModels().get_output(self.selected_process_id, cam) gen_info = mergedqa['GENERAL_INFO'] check_spectra = mergedqa['TASKS']['CHECK_SPECTRA'] std_fiberid = mergedqa['GENERAL_INFO']['STAR_FIBERID'] nrg = check_spectra['PARAMS']['DELTAMAG_TGT_NORMAL_RANGE'] wrg = check_spectra['PARAMS']['DELTAMAG_TGT_WARN_RANGE'] fiber_mag = np.array(mergedqa['GENERAL_INFO']['FIBER_MAGS']) if 'b' in cam: arm_id = 0 elif 'r' in cam: arm_id = 1 else: arm_id = 2 fiber_mag = fiber_mag[arm_id] #.flatten() tooltip = """ <div> <div> <span style="font-size: 1vw; font-weight: bold; color: #303030;">INTEG: </span> <span style="font-size: 1vw; color: #515151;">@integ</span> </div> <div> <span style="font-size: 1vw; font-weight: bold; color: #303030;">FIBER ID: </span> <span style="font-size: 1vw; color: #515151;">@x</span> </div> </div> """ source = ColumnDataSource( data={ 'integ': [i if i > -999 else np.nan for i in fiber_mag], 'x': np.arange(len(fiber_mag)), }) print(len(fiber_mag)) yrange = [0, 1.1 * max(fiber_mag)] fiber_hist = Plot2d( yrange, x_label="Fibers", y_label="Integral (counts)", tooltip=tooltip, title="", width=600, height=400, yscale="auto", hover_mode="vline", ).vbar( source, y="integ", ) info_col = Title().write_description('integ') # Reading obj_type objlist = mergedqa["TASKS"]["CHECK_SPECTRA"]["METRICS"]["OBJLIST"] if 'SKY' in objlist: objlist.remove('SKY') # Prepare tables current_exposures = check_spectra['METRICS']['DELTAMAG_TGT'] program = gen_info['PROGRAM'].upper() reference_exposures = check_spectra['PARAMS']['DELTAMAG_TGT_' + program + '_REF'] keynames = ["DELTAMAG_TGT" + " ({})".format(i) for i in objlist] table = Table().single_table(keynames, current_exposures, reference_exposures, nrg, wrg) layout = column(info_col, Div(), table, Div(), column(fiber_hist, sizing_mode='scale_both', css_classes=["main-one"]), css_classes=["display-grid"]) return file_html(layout, CDN, "INTEG")
GET_arguments = curdoc().session_context.request.arguments if GET_arguments is not None and 'stats' in GET_arguments: # show the statistics page plots = [] start_time = timer() statistics = StatisticsPlots(plot_config, debug_verbose_output()) print_timing("Data Loading Stats", start_time) start_time = timer() # title div = Div(text="<h3>Statistics</h3>") plots.append(column(div)) div = Div(text="<h4>All Logs</h4>") plots.append(column(div)) p = statistics.plot_log_upload_statistics( [colors8[0], colors8[1], colors8[3], colors8[4], colors8[5]]) plots.append(p) div_info = Div(text="Number of Continous Integration (Simulation Tests) Logs: %i<br />" \ "Total Number of Logs on the Server: %i" % (statistics.num_logs_ci(), statistics.num_logs_total())) plots.append(column(div_info)) div = Div(text="<br/><h4>Flight Report Logs " "<small class='text-muted'>(Public Logs only)</small></h4>")
def __init__(self, sources, time_series, correlation, regression, custom_title, data_tables): self.sources = sources self.time_series = time_series self.correlation = correlation self.regression = regression self.dvh_review_rois = [] self.query = None self.temp_dvh_info = Temp_DICOM_FileSet() self.dvh_review_mrns = self.temp_dvh_info.mrn if self.dvh_review_mrns[0] != '': self.dvh_review_rois = self.temp_dvh_info.get_roi_names( self.dvh_review_mrns[0]).values() self.dvh_review_mrns.append('') else: self.dvh_review_rois = [''] # Add Current row to source self.add_endpoint_row_button = Button(label="Add Endpoint", button_type="primary", width=200) self.add_endpoint_row_button.on_click(self.add_endpoint) self.ep_row = Select(value='', options=[''], width=50, title="Row") self.ep_options = [ "Dose (Gy)", "Dose (%)", "Volume (cc)", "Volume (%)" ] self.select_ep_type = Select(value=self.ep_options[0], options=self.ep_options, width=180, title="Output") self.select_ep_type.on_change('value', self.select_ep_type_ticker) self.ep_text_input = TextInput(value='', title="Input Volume (cc):", width=180) self.ep_text_input.on_change('value', self.ep_text_input_ticker) self.ep_units_in = RadioButtonGroup(labels=["cc", "%"], active=0, width=100) self.ep_units_in.on_change('active', self.ep_units_in_ticker) self.delete_ep_row_button = Button(label="Delete", button_type="warning", width=100) self.delete_ep_row_button.on_click(self.delete_ep_row) tools = "pan,wheel_zoom,box_zoom,reset,crosshair,save" self.plot = figure(plot_width=1050, plot_height=500, tools=tools, logo=None, active_drag="box_zoom") self.plot.min_border_left = options.MIN_BORDER self.plot.min_border_bottom = options.MIN_BORDER self.plot.add_tools( HoverTool(show_arrow=False, line_policy='next', tooltips=[('Label', '@mrn @roi_name'), ('Dose', '$x'), ('Volume', '$y')])) self.plot.xaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE self.plot.yaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE self.plot.xaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE self.plot.yaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE self.plot.yaxis.axis_label_text_baseline = "bottom" self.plot.lod_factor = options.LOD_FACTOR # level of detail during interactive plot events # Add statistical plots to figure stats_median_1 = self.plot.line( 'x', 'median', source=sources.stats_1, line_width=options.STATS_1_MEDIAN_LINE_WIDTH, color=options.GROUP_1_COLOR, line_dash=options.STATS_1_MEDIAN_LINE_DASH, alpha=options.STATS_1_MEDIAN_ALPHA) stats_mean_1 = self.plot.line( 'x', 'mean', source=sources.stats_1, line_width=options.STATS_1_MEAN_LINE_WIDTH, color=options.GROUP_1_COLOR, line_dash=options.STATS_1_MEAN_LINE_DASH, alpha=options.STATS_1_MEAN_ALPHA) stats_median_2 = self.plot.line( 'x', 'median', source=sources.stats_2, line_width=options.STATS_2_MEDIAN_LINE_WIDTH, color=options.GROUP_2_COLOR, line_dash=options.STATS_2_MEDIAN_LINE_DASH, alpha=options.STATS_2_MEDIAN_ALPHA) stats_mean_2 = self.plot.line( 'x', 'mean', source=sources.stats_2, line_width=options.STATS_2_MEAN_LINE_WIDTH, color=options.GROUP_2_COLOR, line_dash=options.STATS_2_MEAN_LINE_DASH, alpha=options.STATS_2_MEAN_ALPHA) # Add all DVHs, but hide them until selected self.plot.multi_line('x', 'y', source=sources.dvhs, selection_color='color', line_width=options.DVH_LINE_WIDTH, alpha=0, line_dash=options.DVH_LINE_DASH, nonselection_alpha=0, selection_alpha=1) # Shaded region between Q1 and Q3 iqr_1 = self.plot.patch('x_patch', 'y_patch', source=sources.patch_1, alpha=options.IQR_1_ALPHA, color=options.GROUP_1_COLOR) iqr_2 = self.plot.patch('x_patch', 'y_patch', source=sources.patch_2, alpha=options.IQR_2_ALPHA, color=options.GROUP_2_COLOR) # Set x and y axis labels self.plot.xaxis.axis_label = "Dose (Gy)" self.plot.yaxis.axis_label = "Normalized Volume" # Set the legend (for stat dvhs only) legend_stats = Legend(items=[("Median", [stats_median_1]), ("Mean", [stats_mean_1]), ("IQR", [iqr_1]), ("Median", [stats_median_2]), ("Mean", [stats_mean_2]), ("IQR", [iqr_2])], location=(25, 0)) # Add the layout outside the plot, clicking legend item hides the line self.plot.add_layout(legend_stats, 'right') self.plot.legend.click_policy = "hide" self.download_endpoints_button = Button(label="Download Endpoints", button_type="default", width=150) self.download_endpoints_button.callback = CustomJS( args=dict(source=sources.endpoint_calcs), code=open(join(dirname(__file__), "download_endpoints.js")).read()) # Setup axis normalization radio buttons self.radio_group_dose = RadioGroup( labels=["Absolute Dose", "Relative Dose (Rx)"], active=0, width=200) self.radio_group_dose.on_change('active', self.radio_group_ticker) self.radio_group_volume = RadioGroup( labels=["Absolute Volume", "Relative Volume"], active=1, width=200) self.radio_group_volume.on_change('active', self.radio_group_ticker) # Setup selectors for dvh review self.select_reviewed_mrn = Select(title='MRN to review', value='', options=self.dvh_review_mrns, width=300) self.select_reviewed_mrn.on_change('value', self.update_dvh_review_rois) self.select_reviewed_dvh = Select(title='ROI to review', value='', options=[''], width=360) self.select_reviewed_dvh.on_change('value', self.select_reviewed_dvh_ticker) self.review_rx = TextInput(value='', title="Rx Dose (Gy):", width=170) self.review_rx.on_change('value', self.review_rx_ticker) if options.LITE_VIEW: self.layout = column( Div(text="<b>DVH Analytics v%s</b>" % options.VERSION), row(self.radio_group_dose, self.radio_group_volume), self.add_endpoint_row_button, row(self.ep_row, Spacer(width=10), self.select_ep_type, self.ep_text_input, Spacer(width=20), self.ep_units_in, self.delete_ep_row_button, Spacer(width=50), self.download_endpoints_button), data_tables.ep) else: self.layout = column( Div(text="<b>DVH Analytics v%s</b>" % options.VERSION), row(custom_title['1']['dvhs'], Spacer(width=50), custom_title['2']['dvhs']), row(self.radio_group_dose, self.radio_group_volume), row(self.select_reviewed_mrn, self.select_reviewed_dvh, self.review_rx), self.plot, Div(text="<b>DVHs</b>", width=1200), data_tables.dvhs, Div(text="<hr>", width=1050), Div(text="<b>Define Endpoints</b>", width=1000), self.add_endpoint_row_button, row(self.ep_row, Spacer(width=10), self.select_ep_type, self.ep_text_input, Spacer(width=20), self.ep_units_in, self.delete_ep_row_button, Spacer(width=50), self.download_endpoints_button), data_tables.ep, Div(text="<b>DVH Endpoints</b>", width=1200), data_tables.endpoints)
legend='Material', line_width=3) # plot.circle('Time (s)', 'Temperature (°C)', source = source, legend = 'Material', size = 10, color = dict(field = 'Material', transform=color_mapper) ) # CREATE LOADS AND CIs CHECKBOXES mats_menu = CheckboxGroup(labels=mat_list, active=[0]) loads_menu = CheckboxGroup(labels=load_list, active=[0]) cis_menu = CheckboxGroup(labels=ci_list, active=[0]) # ADD UPDATE EVENT LISTENING mats_menu.on_click(update) loads_menu.on_click(update) cis_menu.on_click(update) # ADD A TITLE FOR BOTH CHECKBOXES mat_title = Div(text="""<h3>Material:</h3>""", width=200) loads_title = Div(text="""<h3>Load (g):</h3>""", width=200) cis_title = Div(text="""<h3>Coil Index:</h3>""", width=200) # ADD PLOT TITLE plot.title.text = 'Temperature & Contraction over Time' # ADJUST LEGEND POSITION plot.legend.location = 'top_left' # CREATE THE LAYOUT layout = row( widgetbox(mat_title, mats_menu, loads_title, loads_menu, cis_title, cis_menu), plot) # ADD THE LAYOUT TO THE DOCUMENT ROOT
def create_widget(self, dim, holomap=None, editable=False): """" Given a Dimension creates bokeh widgets to select along that dimension. For numeric data a slider widget is created which may be either discrete, if a holomap is supplied or the Dimension.values are set, or a continuous widget for DynamicMaps. If the slider is discrete the returned mapping defines a mapping between values and labels making it possible sync the two slider and label widgets. For non-numeric data a simple dropdown selection widget is generated. """ label, mapping = None, None if holomap is None: if dim.values: if dim.default is None: default = dim.values[0] elif dim.default not in dim.values: raise ValueError( "%s dimension default %r is not in dimension values: %s" % (dim, dim.default, dim.values)) else: default = dim.default value = dim.values.index(default) if all(isnumeric(v) for v in dim.values): values = sorted(dim.values) labels = [unicode(dim.pprint_value(v)) for v in values] if editable: label = AutocompleteInput(value=labels[value], completions=labels, title=dim.pprint_label) else: label = Div(text='<b>%s</b>' % dim.pprint_value_string(labels[value])) widget = Slider(value=value, start=0, end=len(dim.values) - 1, title=None, step=1) mapping = list(enumerate(zip(values, labels))) else: values = [(v, dim.pprint_value(v)) for v in dim.values] widget = Select(title=dim.pprint_label, value=values[value][0], options=values) else: start = dim.soft_range[0] if dim.soft_range[0] else dim.range[0] end = dim.soft_range[1] if dim.soft_range[1] else dim.range[1] dim_range = end - start int_type = isinstance(dim.type, type) and issubclass( dim.type, int) if dim.step is not None: step = dim.step elif isinstance(dim_range, int) or int_type: step = 1 else: step = 10**((round(math.log10(dim_range)) - 3)) if dim.default is None: default = start elif (dim.default < start or dim.default > end): raise ValueError( "%s dimension default %r is not in the provided range: %s" % (dim, dim.default, (start, end))) else: default = dim.default if editable: label = TextInput(value=str(default), title=dim.pprint_label) else: label = Div(text='<b>%s</b>' % dim.pprint_value_string(default)) widget = Slider(value=default, start=start, end=end, step=step, title=None) else: values = (dim.values if dim.values else list( unique_array(holomap.dimension_values(dim.name)))) if dim.default is None: default = values[0] elif dim.default not in values: raise ValueError( "%s dimension default %r is not in dimension values: %s" % (dim, dim.default, values)) else: default = dim.default if isinstance(values[0], np.datetime64) or isnumeric(values[0]): values = sorted(values) labels = [dim.pprint_value(v) for v in values] value = values.index(default) if editable: label = AutocompleteInput(value=labels[value], completions=labels, title=dim.pprint_label) else: label = Div(text='<b>%s</b>' % (dim.pprint_value_string(labels[value]))) widget = Slider(value=value, start=0, end=len(values) - 1, title=None, step=1) else: labels = [dim.pprint_value(v) for v in values] widget = Select(title=dim.pprint_label, value=default, options=list(zip(values, labels))) mapping = list(enumerate(zip(values, labels))) return widget, label, mapping
def make_div(text): div = Div(text=text) return div
def __init__(self): self.config = load_sql_settings() self.backup_select = Select(value='', options=[''], title="Available SQL Backups", width=450) self.delete_backup_button = Button(label='Delete', button_type='warning', width=100) self.restore_db_button = Button(label='Restore', button_type='primary', width=100) self.backup_db_button = Button(label='Backup', button_type='success', width=100) self.backup_pref_select = Select(value='', options=[''], title="Available Preferences Backups", width=450) self.delete_backup_button_pref = Button(label='Delete', button_type='warning', width=100) self.restore_pref_button = Button(label='Restore', button_type='primary', width=100) self.backup_pref_button = Button(label='Backup', button_type='success', width=100) warning_div = Div( text= "<b>WARNING for Non-Docker Users:</b> Restore requires your OS user name to be both a" " PostgreSQL super user and have ALL PRIVILEGES WITH GRANT OPTIONS. Do NOT attempt otherwise." " It's possible you have multiple PostgreSQL servers installed, so be sure your backup" " file isn't empty. Validate by typing 'psql' in a terminal/command prompt, then" " <i>SELECT * FROM pg_settings WHERE name = 'port';</i> " " The resulting port should match the port below" " (i.e., make sure you're backing up the correct database).", width=650) host_div = Div(text="<b>Host</b>: %s" % self.config['host']) port_div = Div(text="<b>Port</b>: %s" % self.config['port']) db_div = Div(text="<b>Database</b>: %s" % self.config['dbname']) self.delete_backup_button.on_click(self.delete_backup) self.backup_db_button.on_click(self.backup_db) self.restore_db_button.on_click(self.restore_db) self.delete_backup_button_pref.on_click(self.delete_backup_pref) self.backup_pref_button.on_click(self.backup_pref) self.restore_pref_button.on_click(self.restore_preferences) self.update_backup_select() self.layout = column( row(self.backup_select, self.delete_backup_button, self.restore_db_button, self.backup_db_button), row(self.backup_pref_select, self.delete_backup_button_pref, self.restore_pref_button, self.backup_pref_button), warning_div, host_div, port_div, db_div)
def get_changed_parameters(initial_parameters, plot_width): """ get a bokeh widgetbox object with a table of the changed parameters :param initial_parameters: ulog.initial_parameters """ param_names = [] param_values = [] param_defaults = [] param_mins = [] param_maxs = [] param_descriptions = [] default_params = get_default_parameters() for param_name in sorted(initial_parameters): param_value = initial_parameters[param_name] if param_name.startswith('RC') or param_name.startswith('CAL_'): continue try: if param_name in default_params: default_param = default_params[param_name] if default_param['type'] == 'FLOAT': is_default = abs( float(default_param['default']) - float(param_value)) < 0.00001 if 'decimal' in default_param: param_value = round(param_value, int(default_param['decimal'])) else: is_default = int( default_param['default']) == int(param_value) if not is_default: param_names.append(param_name) param_values.append(param_value) param_defaults.append(default_param['default']) param_mins.append(default_param.get('min', '')) param_maxs.append(default_param.get('max', '')) param_descriptions.append( default_param.get('short_desc', '')) else: # not found: add it as if it were changed param_names.append(param_name) param_values.append(param_value) param_defaults.append('') param_mins.append('') param_maxs.append('') param_descriptions.append('(unknown)') except Exception as error: print(type(error), error) param_data = dict(names=param_names, values=param_values, defaults=param_defaults, mins=param_mins, maxs=param_maxs, descriptions=param_descriptions) source = ColumnDataSource(param_data) columns = [ TableColumn(field="names", title="Name", width=int(plot_width * 0.2), sortable=False), TableColumn(field="values", title="Value", width=int(plot_width * 0.15), sortable=False), TableColumn(field="defaults", title="Default", width=int(plot_width * 0.1), sortable=False), TableColumn(field="mins", title="Min", width=int(plot_width * 0.075), sortable=False), TableColumn(field="maxs", title="Max", width=int(plot_width * 0.075), sortable=False), TableColumn(field="descriptions", title="Description", width=int(plot_width * 0.40), sortable=False), ] data_table = DataTable(source=source, columns=columns, width=plot_width, height=300, sortable=False, selectable=False) div = Div( text= """<b>Non-default Parameters</b> (except RC and sensor calibration)""", width=int(plot_width / 2)) return widgetbox(div, data_table, width=plot_width)
def __init__(self, sources, categories, custom_title): self.sources = sources self.correlation_names = categories.correlation_names self.range_categories = categories.range self.regression = None self.data = {n: [] for n in GROUP_LABELS} self.bad_uid = {n: [] for n in GROUP_LABELS} self.fig = figure(plot_width=900, plot_height=700, x_axis_location="above", tools="pan, box_zoom, wheel_zoom, reset, save", x_range=[''], y_range=['']) self.fig.xaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE self.fig.yaxis.axis_label_text_font_size = options.PLOT_AXIS_LABEL_FONT_SIZE self.fig.xaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE self.fig.yaxis.major_label_text_font_size = options.PLOT_AXIS_MAJOR_LABEL_FONT_SIZE self.fig.min_border_left = 175 self.fig.min_border_top = 130 self.fig.xaxis.major_label_orientation = pi / 4 self.fig.toolbar.active_scroll = "auto" self.fig.title.align = 'center' self.fig.title.text_font_style = "italic" self.fig.xaxis.axis_line_color = None self.fig.xaxis.major_tick_line_color = None self.fig.xaxis.minor_tick_line_color = None self.fig.xgrid.grid_line_color = None self.fig.ygrid.grid_line_color = None self.fig.yaxis.axis_line_color = None self.fig.yaxis.major_tick_line_color = None self.fig.yaxis.minor_tick_line_color = None self.fig.outline_line_color = None corr_1_pos = self.fig.circle(x='x', y='y', color='color', alpha='alpha', size='size', source=sources.correlation_1_pos) corr_1_neg = self.fig.circle(x='x', y='y', color='color', alpha='alpha', size='size', source=sources.correlation_1_neg) corr_2_pos = self.fig.circle(x='x', y='y', color='color', alpha='alpha', size='size', source=sources.correlation_2_pos) corr_2_neg = self.fig.circle(x='x', y='y', color='color', alpha='alpha', size='size', source=sources.correlation_2_neg) self.fig.add_tools( HoverTool( show_arrow=True, line_policy='next', tooltips=[('Group', '@group'), ('x', '@x_name'), ('y', '@y_name'), ('r', '@r'), ('p', '@p'), ('Norm p-value x', '@x_normality{0.4f}'), ('Norm p-value y', '@y_normality{0.4f}')], )) self.fig.line(x='x', y='y', source=sources.corr_matrix_line, line_width=3, line_dash='dotted', color='black', alpha=0.8) # Set the legend legend_corr = Legend(items=[("+r Group 1", [corr_1_pos]), ("-r Group 1", [corr_1_neg]), ("+r Group 2", [corr_2_pos]), ("-r Group 2", [corr_2_neg])], location=(0, -575)) # Add the layout outside the plot, clicking legend item hides the line self.fig.add_layout(legend_corr, 'right') self.fig.legend.click_policy = "hide" self.fig_text_1 = Div(text="Group 1:", width=110) self.fig_text_2 = Div(text="Group 2:", width=110) self.fig_include = CheckboxGroup( labels=self.correlation_names, active=options.CORRELATION_MATRIX_DEFAULTS_1) self.fig_include_2 = CheckboxGroup( labels=['DVH Endpoints', 'EUD', 'NTCP / TCP'], active=options.CORRELATION_MATRIX_DEFAULTS_2) self.fig_include.on_change('active', self.fig_include_ticker) self.fig_include_2.on_change('active', self.fig_include_ticker) self.download_corr_fig = Button( label="Download Correlation Figure Data", button_type="default", width=150) self.download_corr_fig.callback = CustomJS( args=dict(source=self.sources.correlation_csv), code=open(join(dirname(dirname(__file__)), "download_new.js")).read()) self.layout = column( Div(text="<b>DVH Analytics v%s</b>" % options.VERSION), row(custom_title['1']['correlation'], Spacer(width=50), custom_title['2']['correlation']), self.download_corr_fig, row(Div(text="<b>Sample Sizes</b>", width=100), self.fig_text_1, self.fig_text_2), row(self.fig, self.fig_include, self.fig_include_2))
# Plot object which is updated plot = figure(title="Meetup Network Analysis", x_range=(-1.4,2.6), y_range=(-2.0,2.0), tools = "pan,wheel_zoom,box_select,reset,box_zoom,crosshair", plot_width=800, plot_height=700) # Assign layout for nodes, render graph, and add hover tool graph.node_renderer.data_source.selected.on_change("indices", selected_points) graph.layout_provider = StaticLayoutProvider(graph_layout=positions) graph.node_renderer.glyph = Circle(size='node_size', fill_color='node_color') graph.selection_policy = NodesOnly() plot.renderers.append(graph) plot.tools.append(HoverTool(tooltips=[('Name', '@index')])) # Create Summary Data Table num_format = NumberFormatter(format="0.00") summary_table_title = Div(text="""<b>Summary Statistics</b>""", width=525, height=10) summary_table_cols = [TableColumn(field='summary_stats', title="SummaryStats"), TableColumn(field='mean_member_count', title="Member Count",formatter=num_format), TableColumn(field='mean_degree_centrality', title="Degree Centrality",formatter=num_format), TableColumn(field='mean_rel_closeness_centrality', title="Rel. Closeness Centrality",formatter=num_format)] summary_data_table = DataTable(source=summary_data_table_source, columns=summary_table_cols, width=525, height=80) # Create Data Table data_table_cols = [TableColumn(field="group_name", title="Node Name"), TableColumn(field="member_count", title="Member Count",formatter=num_format), TableColumn(field="degree_centrality", title="Degree Centrality",formatter=num_format), TableColumn(field="rel_closeness_centrality", title="Rel. Closeness Centrality",formatter=num_format)] data_table = DataTable(source=data_table_source, columns=data_table_cols, width=525, height=550) data_table_title = Div(text="""<b>Selected Data List</b>""", width=525, height=10)
print("i") # Setup Plots ## TOF Live p = figure(x_range=[0, N_datapts], y_range=[-400, 30], plot_width=1200, plot_height=400) l = p.line(x='x', y='y', source=d_src_tof) ## Train ID Display def trainId_to_html(trainID): return '<span style="font-size:30pt">' + str(trainID) + '</span>' div_trainId = Div(text='tid', width=200, height=100) #div_trainId = Div(text='tid', source=d_src_text,width=200, height=100) print("i") # Define current document doc = curdoc() print("i") # Update Plots Routine @gen.coroutine def update(x, y, tid): patches_tof = {'x': [(slice(N_datapts), x)], 'y': [(slice(N_datapts), y)]} patches_text = {'tid': [(0, tid)]} d_src_tof.patch(patches_tof) #d_src_text.patch(patches_text)
button_type="primary", width=100, callback=callback_play) time_slider.on_change('value', callback_time_slider) slider_active_toggle.on_click(callback_toggle_slider_activity) pattern_select.on_change('active', callback_pattern_selection) aggregate_select.on_change('active', callback_aggregation_selection) groupby_select.on_change('active', callback_groupby_selection) type_filter.on_change('value', callback_type_filter) geo_source.on_change('selected', callback_map_selection) select_all_types_button.on_click(callback_select_all_types) ## end callbacks # headers map_head = Div(text="<h2>Spatial distribution of incidents</h2>", css_classes=["plot-head"], width=LEFT_COLUMN_WIDTH) ts_head = Div(text="<h2>Time distribution of incidents</h2>", css_classes=["plot-head"], width=RIGHT_COLUMN_WIDTH) status_available_style = {"font-size": "8pt", "color": "green"} status_unavailable_style = {"font-size": "8pt", "color": "red"} status = Div(text="""<i>Status: at your service</i>""", style={ "font-size": "8pt", "color": "green" }) pattern_head = Div(text="Pattern:", css_classes=["filter-head"]) agg_head = Div(text="Aggregate by:", css_classes=["filter-head"]) groupby_head = Div(text="Group by:", css_classes=["filter-head"])
elif clear_tables_button.button_type == 'primary': clear_tables_button.button_type = 'danger' clear_tables_button.label = 'Are you sure?' create_tables_button.button_type = 'success' create_tables_button.label = 'Cancel' def save_needed_sql(attr, old, new): save_sql_settings_button.label = 'Save Needed' save_sql_settings_button.button_type = 'warning' ###################################################### # Layout objects ###################################################### div_import = Div(text="<b>DICOM Directories</b>") div_horizontal_bar_settings = Div(text="<hr>", width=900) input_inbox = TextInput(value=directories['inbox'], title="Inbox", width=300) input_inbox.on_change('value', update_inbox_status) input_imported = TextInput(value=directories['imported'], title="Imported", width=300) input_imported.on_change('value', update_imported_status) input_review = TextInput(value=directories['review'], title="Review", width=300) input_review.on_change('value', update_review_status) div_sql = Div(text="<b>SQL Settings</b>") input_host = TextInput(value=config['host'], title="Host", width=300) input_port = TextInput(value=config['port'], title="Port", width=300)
def make_doc(self): title = Div(text="<h2>Averaging kernels</h2>") t = Tabs(tabs=self.panels) return column(title, t)
def body_figs(data, height=500, width=1000): #Data setup data['date_str'] = data['date'].map(str) ma_cds_working = ColumnDataSource(dict(date=data['date'], date_str=data['date_str'], bpm=data['bpm'], hrv=data['hrv'], scaled_hrv=data['scaled_hrv'], sleep_overall_q=data['sleep_overall_q'], sleep_onset=data['sleep_onset'], sleep_duration=data['sleep_duration'], sleep_how_much_more=data['sleep_how_much_more'], sleep_how_deep=data['sleep_how_deep'], sleep_interruptions=data['sleep_interruptions'], glucose=data['glucose'], ketones=data['ketones'], weight=data['weight'], bodyfat=data['bodyfat'])) ma_cds_static = ColumnDataSource(dict(date=data['date'], date_str=data['date_str'], bpm=data['bpm'], hrv=data['hrv'], scaled_hrv=data['scaled_hrv'], sleep_overall_q=data['sleep_overall_q'], sleep_onset=data['sleep_onset'], sleep_duration=data['sleep_duration'], sleep_how_much_more=data['sleep_how_much_more'], sleep_how_deep=data['sleep_how_deep'], sleep_interruptions=data['sleep_interruptions'], glucose=data['glucose'], ketones=data['ketones'], weight=data['weight'], bodyfat=data['bodyfat'])) #Plot tools configuration wz = WheelZoomTool(dimensions='width') plt_biomarkers_tools = [HoverTool(tooltips=[("Date", "@date_str"), ("RHR", "@bpm{0,0} bpm"), ("Sleep Q", "@sleep_overall_q"), ("Glucose", "@glucose{0,0} mg/dl"), ("Ketones", "@ketones{1.11} mmol/L")],names=["bpm", "glucose"],mode='vline'), PanTool(dimensions='width'), wz, ResetTool(), SaveTool()] wz2 = WheelZoomTool(dimensions='width') plt_bcomp_tools = [HoverTool(tooltips=[("Date", "@date_str"), ("Weight", "@weight{1.1} lbs"), ("BF", "@bodyfat{1.1}%")],mode='vline'), PanTool(dimensions='width'), wz2, ResetTool(), SaveTool()] wz3 = WheelZoomTool(dimensions='width') plt_sleep_tools = [HoverTool(tooltips=[("Date", "@date_str"),("Sleep Quality", "@sleep_overall_q"),("Duration", "@sleep_duration"),("Satisfaction", "@sleep_how_much_more"),("Depth", "@sleep_how_deep"),("Interruptions", "@sleep_interruptions")],names=["sleep_overall_q"],mode='vline'), PanTool(dimensions='width'), wz3, ResetTool(), SaveTool()] #Plot Blood (glucose and ketones) plot_blood = figure(x_axis_type="datetime", title="Biomarkers (Various)", h_symmetry=False, v_symmetry=False, min_border=0, plot_height=height, y_range=[40, 140], plot_width=int(width/2 - 50), toolbar_location="above", outline_line_color="#666666", tools=plt_biomarkers_tools, active_scroll=wz) plot_blood.extra_y_ranges = {"ketones_range": Range1d(start=0, end=7)} plot_blood.add_layout(LinearAxis(y_range_name="ketones_range"), 'right') plot_blood.line('date', 'glucose', name="glucose", source=ma_cds_working, line_color="#FF7700", line_width=3, line_alpha=0.6, legend="Blood Glucose") plot_blood.cross('date', 'ketones', source=ma_cds_working, line_color="#C74D56", line_alpha=0.6, legend="Blood Ketones", y_range_name="ketones_range") plot_blood.ray(x=data['date'][1195],y=.5, length=0, angle=0, line_color="#C74D56", line_width=1, y_range_name="ketones_range") plot_blood.ray(x=data['date'][1195],y=1, length=0, angle=0, line_color="#C74D56", line_width=1, y_range_name="ketones_range") plot_blood.legend.location = "top_left" plot_blood.legend.click_policy="hide" #Plot Heartrate plot_rhr = figure(x_axis_type="datetime", title="Morning Resting HR", h_symmetry=False, v_symmetry=False, min_border=0, plot_height=int(height/2), plot_width=int(width/2), x_range=plot_blood.x_range, outline_line_color="#666666") plot_rhr.line('date', 'bpm', name="bpm", source=ma_cds_working, line_color="#8B0A50", line_width=3, line_alpha=0.6, legend="BPM") plot_rhr.line('date', 'hrv', name="hrv", source=ma_cds_working, line_color="#0a8b45", line_width=3, line_alpha=0.6, legend="HRV") plot_rhr.line('date', 'scaled_hrv', name="scaled_hrv", source=ma_cds_working, line_color="#333366", line_width=3, line_alpha=0.6, y_range_name="scaled_hrv_range", legend="HRV (Scaled)") #***TODO*** Add SNS/PNS indicator plot_rhr.extra_y_ranges = {"scaled_hrv_range": Range1d(start=1, end=10)} plot_rhr.add_layout(LinearAxis(y_range_name="scaled_hrv_range"), 'right') plot_rhr.legend.location = "bottom_left" plot_rhr.legend.click_policy="hide" plot_rhr.toolbar_location = None #Plot sleep quality (single indicator) plot_osq = figure(x_axis_type="datetime", title="Overall Sleep Quality", h_symmetry=False, v_symmetry=False, min_border=0, plot_height=int(height/2), plot_width=int(width/2), y_range=[1, 9], x_range=plot_blood.x_range, outline_line_color="#666666") plot_osq.line('date', 'sleep_overall_q', source=ma_cds_working, line_color="#333366", line_width=3, line_alpha=0.6) plot_osq.toolbar_location = None #Plot body compostion (weight and bodyfat) plot_composition = figure(x_axis_type="datetime", title="Body Composition", h_symmetry=False, v_symmetry=False, min_border=0, plot_height=height, plot_width=width, y_range=[120,180], toolbar_location="above", outline_line_color="#666666", tools=plt_bcomp_tools, active_scroll=wz2) plot_composition.extra_y_ranges = {"bodyfat_range": Range1d(start=5, end=15)} plot_composition.add_layout(LinearAxis(y_range_name="bodyfat_range"), 'right') plot_composition.line('date', 'weight', name="weight", source=ma_cds_working, line_color="#FF7700", line_width=3, line_alpha=0.6, legend="Weight") plot_composition.line('date', 'bodyfat', source=ma_cds_working, line_color="#333366", line_width=3, line_alpha=0.6, legend="Bodyfat", y_range_name="bodyfat_range") plot_composition.legend.location = "top_left" plot_composition.legend.click_policy="hide" #Plot sleep (all indicators) plot_sleep = figure(x_axis_type="datetime", title="Sleep", h_symmetry=False, v_symmetry=False, min_border=0, plot_height=height, plot_width=width, y_range=[1,9], x_range=plot_blood.x_range, toolbar_location="above", outline_line_color="#666666", tools=plt_sleep_tools, active_scroll=wz3) plot_sleep.extra_y_ranges = {"sleep_range": Range1d(start=0, end=12)} plot_sleep.add_layout(LinearAxis(y_range_name="sleep_range"), 'right') plot_sleep.line('date', 'sleep_overall_q', name='sleep_overall_q', source=ma_cds_working, line_color="#8B0A50", line_width=2, line_alpha=0.6, legend="Sleep Quality") plot_sleep.line('date', 'sleep_how_much_more', source=ma_cds_working, line_color="#FF7700", line_width=2, line_alpha=0.6, legend="Satisfaction") plot_sleep.line('date', 'sleep_how_deep', source=ma_cds_working, line_color="#C74D56", line_width=2, line_alpha=0.6, legend="Depth") plot_sleep.line('date', 'sleep_interruptions', source=ma_cds_working, line_color="#0a8b45", line_width=2, line_alpha=0.6, legend="Interruptions") plot_sleep.line('date', 'sleep_duration', source=ma_cds_working, line_color="#333366", line_width=5, line_alpha=0.6, legend="Duration (hrs)", y_range_name="sleep_range") plot_sleep.legend.location = "top_left" plot_sleep.legend.click_policy="hide" #Statistics divs for the control panel div_days = Div() div_avg_bg = Div() div_avg_rhr = Div() div_avg_slp_dur = Div() div_avg_slp_q = Div() div_days_bc = Div() div_avg_wt = Div() div_avg_bf = Div() #Callbacks ma_cb = CustomJS(args=dict(w=ma_cds_working, s=ma_cds_static), code=MA_SLIDER_CODE) plot_blood.x_range.callback = CustomJS(args=dict(d_d=div_days, d_a_bg=div_avg_bg, d_a_r=div_avg_rhr, d_a_s_d=div_avg_slp_dur, d_a_s_q=div_avg_slp_q, s=ma_cds_static), code=BODY_STATS_CODE) plot_composition.x_range.callback = CustomJS(args=dict(d_d_bc=div_days_bc, d_a_wt=div_avg_wt, d_a_bf=div_avg_bf, s=ma_cds_static), code=BODY_COMP_STATS_CODE) ma_slider = Slider(start=1, end=30, value=7, step=1, title="Moving Average", callback=ma_cb) return components((div_days, div_avg_bg, div_avg_rhr, div_avg_slp_dur, div_avg_slp_q, div_days_bc, div_avg_wt, div_avg_bf, plot_blood, plot_rhr, plot_osq, plot_composition, plot_sleep, ma_slider))
#p_temp.xaxis.minor_tick_line_color = None p_tvoc.add_tools(hover) p_co2.add_tools(hover) p_temp.add_tools(hover) p_rh.add_tools(hover) #DIVS logo_path = '/DT481_bokeh_serveur/static/seb_logo.png' logo_str = '<img src= "{}" alt="{}" height="50px">'.format( logo_path, logo_path) div_str = """ <h1 style="text-align: left"> {}   DT481 - MOx Data Processing Dashboard</h1>""".format( logo_str) #div_str = """ <h1 style="text-align: left"> DT481 - MOx Data Processing Dashboard</h1> """ div = Div(text=div_str, width=plot_width, height=50) def auto_update(): print("auto-update") get_df() date_select.options = get_dates(curr_sensor) update() def update_sensor(): global curr_sensor global curr_date print("sensor update") curr_sensor = sensor_select.value sensor_select.options = get_box_ls()
# p_logo.border_fill_color = "black" # p_logo.grid.grid_line_color = "black" # p_logo.outline_line_color = "black" # radio button group for uploading file radio_group = RadioButtonGroup(labels=["NO-SPLIT", "SPLIT", "START"], button_type="success") radio_group.width = 500 radio_group.on_click(_fit_util) # text for console output text_input = TextInput(value="", title="CONSOLE") text_input.width = 500 cluster_stats = Div( render_as_text=False, text=generate_display_string("", name="Cluster Statistics", height=100) ) cluster_stats.width = 500 cluster_stats.height = 100 cluster_commonality = Div( render_as_text=False, text=generate_display_string("") ) cluster_commonality.width = 500 cluster_commonality.height = 300 split_button = Button(label="Split", button_type="success", width=150) no_split_button = Button(label="Keep", button_type="success", width=150) start_button = Button(label="Start", button_type="success", width=150)