def plot_bokeh(title): global topic_names, authors topic_names = grab_topics(t_model, feature_names, 5) x_ = [] y_ = [] t_ = [] o_=[] topic_ = [] global source source = ColumnDataSource( data =dict( x=x_, y=y_, t=t_, o=o_, desc=titles, topics=topic_, auth=authors, year=years )) #Draw plots update_plot() global year_from, year_to, custom_text, search_text, radio_search, search_items, Keyword_text, custom_text1 #Year filtering controls year_from = Slider(title="Include papers from", value=1981, start=1981, end=2017, step=1) year_to = Slider(title="Inlude papers to", value=2017, start=year_from.value-1, end=2017, step=1) year_from.on_change('value', update_years) year_to.on_change('value', update_years) now_change = Button(label="Update", button_type="success") now_change.on_click(update_plot) #Custom text placement controls #sizing_mode = 'scale_both' -- need to look for scaling the text box size #sizing_mode = 'stretch_both' custom_text = TextAreaInput(value=" ", title="Enter some text you are working on here:",width=600,height=400) text_button = Button(label="Process", button_type="success") # for i in custom_text.value: # if i == '.': # process_text() # callback1 = CustomJS( code=""" # // the event that triggered the callback is cb_obj: # // The event type determines the relevant attributes # console.log('Tap event occurred at x-position: ' + cb_obj.x) # """) # custom_text.on_change("value", my_text_input_handler) # custom_text.js_on_event('tap', callback1) # custom_text.on_event(MouseEnter, callback1) text_button.on_click(process_text) text_button.on_click(update_table) custom_text1 = TextAreaInput(value=" ", title="Enter text here if you want to search for individual words or lines:",width=600,height=200) text_button1 = Button(label="Process", button_type="success") text_button1.on_click(process_text1) text_button1.on_click(update_table) template200 = """ <div style="font-size: 15px;"> <%= value %> </div> """ keyword_data = ColumnDataSource(data ={}) columns =[TableColumn(field ="keywords_", title ="<b> Keyword </b>", width = 700, formatter=HTMLTemplateFormatter(template=template200))] # Keyword_text = TextAreaInput(value ="default",title="Keywords", width = 800, height = 100) Keyword_text = DataTable(source=keyword_data, columns=columns, width=800, row_height=50, editable=True, fit_columns = True) Keyword_text.source.selected.on_change("indices", some_func) #Search button controls search_text = TextInput(value="", title="Search box: (separate terms with ';' - not for DOIs)") search_button = Button(label="Search", button_type="success") search_button.on_click(process_search) radio_search = RadioButtonGroup(labels=["Title", "Full Text", "doi","Author"], active=1) print("helllllll") #increase size #txtIn_rng = widgetbox(children=[custom_text], width=wd) #curdoc().add_root(txtIn_rng) #Data Table for selected papers global table_data, chosen_papers,dict2,table_row, table_cell_column_1, value1, value2, table_cell_column_2, summary3, dict4 template = """<span href="#" data-toggle="tooltip" title="<%= value %>" style="font-size:15px"><%= value %></span>""" template_str = '<a href="http://dx.doi.org/<%=dois_%>" target="_blank"><%= value %></a>' # output_file("openurl.html") table_data = ColumnDataSource(data = {}) print("***********") columns = [TableColumn(field="years_", title="<b>Year</b>",width = 50, formatter=HTMLTemplateFormatter(template=template)), TableColumn(field="titles_", title="<b>Paper Title</b>", width = 200, formatter=HTMLTemplateFormatter(template=template)), TableColumn(field="authors_", title="<b>Authors</b>", width = 100, formatter=HTMLTemplateFormatter(template=template)), TableColumn(field="dois_", title="<b>Link</b>",width = 100, formatter=HTMLTemplateFormatter(template=template_str)),TableColumn(field="summary_", title="<b>Summary</b>", width =600,formatter=HTMLTemplateFormatter(template=template))] print("1*") chosen_papers = DataTable(source=table_data, columns=columns, width=600, row_height=100, editable=True, fit_columns = True) table_row = TextInput(value = '', title = "Row index:") value1 =[] value2 = int(0) value3 =[] dict4 =[] table_cell_column_1 = TextAreaInput(value = '', title = "Papers from table", height = 100) table_cell_column_2 = TextAreaInput(value = '', title = "Papers from graph", height = 100) summary3 = TextAreaInput(value = '', title = "Summary of the recently selected paper", height = 300) # table_cell_column_2 = TextInput(value= '', title = "Author", height = 100) chosen_papers.source.selected.on_change('indices', function_source) # Adding a title for data table pre = Div(text="""Please hover over each column to see the full text. </br> By clicking on each row, the desirable papers can be added to the 'Papers from table' list below.</br> By clicking on authors column, authors can be directly placed in search.""", width=600, height=50, style={'font-size': '100%', 'color': 'black', 'font-weight':'bold'}) # pre = PreText(text="""Please hover over each column to see the full text.\n # By clicking on each row, the desirable papers can be added to the 'Papers from table' list below.\n # By clicking on authors column, authors can be directly placed in search""", # width=500, height=100) # Adding title for keyword data table pre1 = Div(text=""" If you click on keywords, the keyword will be directly placed in the 'Search Box' """, width=500, height=20,style={'font-size': '100%', 'color': 'black', 'font-weight':'bold'}) # chosen_papers.append(HoverTool(tooltips=[("Summary", "@summary_")])) # para5 = Paragraph(text = 'summary' , height = 1) #chosen_papers.source.data.update(update_table()) # chosen_papers.source.on_change('data', update_table1) # global table_data1, chosen_papers1 # template = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>""" # table_data1 = ColumnDataSource(data = {}) # print("***********") # columns = [TableColumn(field="summary_", title="Summary", formatter=HTMLTemplateFormatter(template=template))] # print("1*") # chosen_papers1 = DataTable(source=table_data, columns=columns, width=800, row_height=100, editable=True,fit_columns = True, scroll_to_selection = True) # df = pd.DataFrame([ # ['this is a longer text that needs a tooltip, because otherwise we do not see the whole text', 'this is a short text'], # ['this is another loooooooooooooooong text that needs a tooltip', 'not much here'], # ], columns=['a', 'b']) # columns = [TableColumn(field=c, title=c, width=20, formatter=HTMLTemplateFormatter(template=template)) for c in ['a', 'b']] # table = DataTable(source=ColumnDataSource(df), columns=columns) # create a new plot with a title and axis labels global patch, value6, value7 p = figure(title="CHI scatter", tools="tap", x_axis_label='x', y_axis_label='y', width=800, plot_height=850) p.add_tools(BoxZoomTool()) p.add_tools(ZoomInTool()) p.add_tools(ZoomOutTool()) p.add_tools(ResetTool()) p.add_tools(HoverTool(tooltips=[("Title", "@desc"), ("Topic", "@topics"), ("Authors", "@auth"), ("Year", "@year")])) patch = p.circle(x='x', y='y', fill_color='t', nonselection_fill_color='t', radius=0.01, fill_alpha='o', nonselection_fill_alpha='o', line_color=None, source=source) url = "http://dx.doi.org/@dois" taptool = p.select(type=TapTool) taptool.callback = OpenURL(url=url) value6 = [] value7 = [] patch.data_source.on_change('selected', callback) p.on_event(Tap, callback1) l = gridplot([[ row([column(row([widgetbox(year_from, year_to, now_change), widgetbox(search_text, radio_search, search_button)]),widgetbox(custom_text, text_button), widgetbox(custom_text1, text_button1),widgetbox(pre,chosen_papers))]) ,column([p,widgetbox(pre1,Keyword_text)]) ],[table_cell_column_1], [table_cell_column_2], [summary3] ]) curdoc().add_root(l)
widget_binned_pixel_scale = RadioButtonGroup( name=dfs.string_binned_pixel_scale_header, labels=dfs.string_binned_pixel_scale_labels, active=0) # dropdown menus... there's one up there, above, too... could probably move it down here widget_types_types = Dropdown( label=dfs.string_object_types_types[0], menu=dfs.string_star_types, name=dfs.string_widget_names[6]) # TODO: dynamically set these widget_filters = Dropdown(label=dfs.string_widget_labels[0], menu=dfs.string_filters_menu, width=100, name=dfs.string_widget_names[7]) # text input widget_mag_input = TextInput(value=dfs.default_magnitude_two, title=dfs.string_suffixes[0].title(), width=100) widget_redshift = TextInput(value=str(dfs.default_redshift), title=dfs.string_title[3]) #widget_binned_pixel_scale = TextInput(value=dfs.default_binned_pixel_scale,title=dfs.string_binned_pixel_scale_manual) # TODO: hide on default # sliders widget_exposure_time = Slider(start=dfs.default_exposure_time_start, end=dfs.default_exposure_time_end, value=dfs.default_exposure_time, step=dfs.default_exposure_time_step, title=dfs.string_title[4], name=dfs.string_widget_names[8]) widget_seeing = Slider(start=dfs.default_seeing_start, end=dfs.default_seeing_end, value=dfs.default_seeing, step=dfs.default_seeing_step,
p.vline_stack(['R'], x='t', source=source, color='green', width=4, legend_label="Recovered or Death") p.legend.location = 'center_right' return p # Create first grapsh source = make_dataset() p = make_plot(source) # Set up widgets text = TextInput(title="title", value='My SIR model') gamma_ = Slider(title="Gamma", value=0.1, start=0.0, end=2.0, step=0.01) betta_ = Slider(title="Beta", value=0.35, start=0.0, end=2.0, step=0.01) # Update function takes three default parameters def update(attrname, old, new): """Notice this function does not retunr anything but modify the data for the graph""" # Get the current slider values t = np.linspace(0, 100, 10000) S0 = 0.9 I0 = 0.1 R0 = 0 betta = betta_.value gamma = gamma_.value
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)
# Set up plot plot = figure(plot_height=400, plot_width=400, title="my sine wave", tools="crosshair,pan,reset,save,wheel_zoom", indicators=[ ServerStatusIndicator( tooltip_prefix="Bokeh server connection status: ") ], x_range=[0, 4 * np.pi], y_range=[-2.5, 2.5]) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) # Set up widgets text = TextInput(title="title", value='my sine wave') offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1) amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0, step=0.1) phase = Slider(title="phase", value=0.0, start=0.0, end=2 * np.pi) freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1) # Set up callbacks def update_title(attrname, old, new): plot.title.text = text.value text.on_change('value', update_title) def update_data(attrname, old, new):
def _create_ui_components() -> (Figure, ColumnDataSource): # pylint: disable=too-many-statements global asp_table_source, asp_filter_src, op_table_source, op_filter_src global stats, aspects, tabs, lexicons_dropdown stats = pd.DataFrame(columns=['Quantity', 'Score']) aspects = pd.Series([]) def new_col_data_src(): return ColumnDataSource({'file_contents': [], 'file_name': []}) large_text = HTMLTemplateFormatter(template='''<div><%= value %></div>''') def data_column(title): return TableColumn(field=title, title='<span class="header">' + title + '</span>', formatter=large_text) asp_table_columns = [ data_column('Term'), data_column('Alias1'), data_column('Alias2'), data_column('Alias3') ] op_table_columns = [ data_column('Term'), data_column('Score'), data_column('Polarity') ] asp_table_source = empty_table('Term', 'Alias1', 'Alias2', 'Alias3') asp_filter_src = empty_table('Term', 'Alias1', 'Alias2', 'Alias3') asp_src = new_col_data_src() op_table_source = empty_table('Term', 'Score', 'Polarity', 'Polarity') op_filter_src = empty_table('Term', 'Score', 'Polarity', 'Polarity') op_src = new_col_data_src() asp_table = DataTable(source=asp_table_source, selectable='checkbox', columns=asp_table_columns, editable=True, width=600, height=500) op_table = DataTable(source=op_table_source, selectable='checkbox', columns=op_table_columns, editable=True, width=600, height=500) asp_examples_box = _create_examples_table() op_examples_box = _create_examples_table() asp_layout = layout([[asp_table, asp_examples_box]]) op_layout = layout([[op_table, op_examples_box]]) asp_tab = Panel(child=asp_layout, title="Aspect Lexicon") op_tab = Panel(child=op_layout, title="Opinion Lexicon") tabs = Tabs(tabs=[asp_tab, op_tab], width=700, css_classes=['mytab']) lexicons_menu = [("Open", "open"), ("Save", "save")] lexicons_dropdown = Dropdown(label="Edit Lexicons", button_type="success", menu=lexicons_menu, width=140, height=31, css_classes=['mybutton']) train_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")] train_dropdown = Dropdown(label="Extract Lexicons", button_type="success", menu=train_menu, width=162, height=31, css_classes=['mybutton']) inference_menu = [("Parsed Data", "parsed"), ("Raw Data", "raw")] inference_dropdown = Dropdown(label="Classify", button_type="success", menu=inference_menu, width=140, height=31, css_classes=['mybutton']) text_status = TextInput(value="Select training data", title="Train Run Status:", css_classes=['statusText']) text_status.visible = False train_src = new_col_data_src() infer_src = new_col_data_src() with open(join(dirname(__file__), "dropdown.js")) as f: args = dict(clicked=lexicons_dropdown, asp_filter=asp_filter_src, op_filter=op_filter_src, asp_src=asp_src, op_src=op_src, tabs=tabs, text_status=text_status, train_src=train_src, infer_src=infer_src, train_clicked=train_dropdown, infer_clicked=inference_dropdown, opinion_lex_generic="") code = f.read() args['train_clicked'] = train_dropdown train_dropdown.js_on_change('value', CustomJS(args=args, code=code)) args['train_clicked'] = inference_dropdown inference_dropdown.js_on_change('value', CustomJS(args=args, code=code)) args['clicked'] = lexicons_dropdown lexicons_dropdown.js_on_change('value', CustomJS(args=args, code=code)) def update_filter_source(table_source, filter_source): df = table_source.to_df() sel_inx = sorted(table_source.selected.indices) df = df.iloc[sel_inx, 1:] new_source = ColumnDataSource(df) filter_source.data = new_source.data def update_examples_box(data, examples_box, old, new): examples_box.source.data = {'Examples': []} unselected = list(set(old) - set(new)) selected = list(set(new) - set(old)) if len(selected) <= 1 and len(unselected) <= 1: examples_box.source.data.update({ 'Examples': [str(data.iloc[unselected[0], i]) for i in range(4, 24)] if len(unselected) != 0 else [str(data.iloc[selected[0], i]) for i in range(4, 24)] }) def asp_selected_change(_, old, new): global asp_filter_src, asp_table_source, aspects_data update_filter_source(asp_table_source, asp_filter_src) update_examples_box(aspects_data, asp_examples_box, old, new) def op_selected_change(_, old, new): global op_filter_src, op_table_source, opinions_data update_filter_source(op_table_source, op_filter_src) update_examples_box(opinions_data, op_examples_box, old, new) def read_csv(file_src, headers=False, index_cols=False, readCSV=True): if readCSV: raw_contents = file_src.data['file_contents'][0] if len(raw_contents.split(",")) == 1: b64_contents = raw_contents else: # remove the prefix that JS adds b64_contents = raw_contents.split(",", 1)[1] file_contents = base64.b64decode(b64_contents) return pd.read_csv(io.BytesIO(file_contents), encoding="ISO-8859-1", keep_default_na=False, na_values={None}, engine='python', index_col=index_cols, header=0 if headers else None) return file_src def read_parsed_files(file_content, file_name): try: # remove the prefix that JS adds b64_contents = file_content.split(",", 1)[1] file_content = base64.b64decode(b64_contents) with open(SENTIMENT_OUT / file_name, 'w') as json_file: data_dict = json.loads(file_content.decode("utf-8")) json.dump(data_dict, json_file) except Exception as e: print(str(e)) # pylint: disable=unused-argument def train_file_callback(attr, old, new): global train_data SENTIMENT_OUT.mkdir(parents=True, exist_ok=True) train = TrainSentiment(parse=True, rerank_model=None) if len(train_src.data['file_contents']) == 1: train_data = read_csv(train_src, index_cols=0) file_name = train_src.data['file_name'][0] raw_data_path = SENTIMENT_OUT / file_name train_data.to_csv(raw_data_path, header=False) print(f'Running_SentimentTraining on data...') train.run(data=raw_data_path) else: f_contents = train_src.data['file_contents'] f_names = train_src.data['file_name'] raw_data_path = SENTIMENT_OUT / train_src.data['file_name'][ 0].split('/')[0] if not os.path.exists(raw_data_path): os.makedirs(raw_data_path) for f_content, f_name in zip(f_contents, f_names): read_parsed_files(f_content, f_name) print(f'Running_SentimentTraining on data...') train.run(parsed_data=raw_data_path) text_status.value = "Lexicon extraction completed" with io.open(AcquireTerms.acquired_aspect_terms_path, "r") as fp: aspect_data_csv = fp.read() file_data = base64.b64encode(str.encode(aspect_data_csv)) file_data = file_data.decode("utf-8") asp_src.data = { 'file_contents': [file_data], 'file_name': ['nameFile.csv'] } out_path = LEXICONS_OUT / 'generated_opinion_lex_reranked.csv' with io.open(out_path, "r") as fp: opinion_data_csv = fp.read() file_data = base64.b64encode(str.encode(opinion_data_csv)) file_data = file_data.decode("utf-8") op_src.data = { 'file_contents': [file_data], 'file_name': ['nameFile.csv'] } def show_analysis() -> None: global stats, aspects, plot, source, tabs plot, source = _create_plot() events_table = _create_events_table() # pylint: disable=unused-argument def _events_handler(attr, old, new): _update_events(events_table, events_type.active) # Toggle display of in-domain / All aspect mentions events_type = RadioButtonGroup( labels=['All Events', 'In-Domain Events'], active=0) analysis_layout = layout([[plot], [events_table]]) # events_type display toggle disabled # analysis_layout = layout([[plot],[events_type],[events_table]]) analysis_tab = Panel(child=analysis_layout, title="Analysis") tabs.tabs.insert(2, analysis_tab) tabs.active = 2 events_type.on_change('active', _events_handler) source.selected.on_change('indices', _events_handler) # pylint: disable=no-member # pylint: disable=unused-argument def infer_file_callback(attr, old, new): # run inference on input data and current aspect/opinion lexicons in view global infer_data, stats, aspects SENTIMENT_OUT.mkdir(parents=True, exist_ok=True) df_aspect = pd.DataFrame.from_dict(asp_filter_src.data) aspect_col_list = ['Term', 'Alias1', 'Alias2', 'Alias3'] df_aspect = df_aspect[aspect_col_list] df_aspect.to_csv(SENTIMENT_OUT / 'aspects.csv', index=False, na_rep="NaN") df_opinion = pd.DataFrame.from_dict(op_filter_src.data) opinion_col_list = ['Term', 'Score', 'Polarity', 'isAcquired'] df_opinion = df_opinion[opinion_col_list] df_opinion.to_csv(SENTIMENT_OUT / 'opinions.csv', index=False, na_rep="NaN") solution = SentimentSolution() if len(infer_src.data['file_contents']) == 1: infer_data = read_csv(infer_src, index_cols=0) file_name = infer_src.data['file_name'][0] raw_data_path = SENTIMENT_OUT / file_name infer_data.to_csv(raw_data_path, header=False) print(f'Running_SentimentInference on data...') text_status.value = "Running classification on data..." stats = solution.run(data=raw_data_path, aspect_lex=SENTIMENT_OUT / 'aspects.csv', opinion_lex=SENTIMENT_OUT / 'opinions.csv') else: f_contents = infer_src.data['file_contents'] f_names = infer_src.data['file_name'] raw_data_path = SENTIMENT_OUT / infer_src.data['file_name'][ 0].split('/')[0] if not os.path.exists(raw_data_path): os.makedirs(raw_data_path) for f_content, f_name in zip(f_contents, f_names): read_parsed_files(f_content, f_name) print(f'Running_SentimentInference on data...') text_status.value = "Running classification on data..." stats = solution.run(parsed_data=raw_data_path, aspect_lex=SENTIMENT_OUT / 'aspects.csv', opinion_lex=SENTIMENT_OUT / 'opinions.csv') aspects = pd.read_csv(SENTIMENT_OUT / 'aspects.csv', encoding='utf-8')['Term'] text_status.value = "Classification completed" show_analysis() # pylint: disable=unused-argument def asp_file_callback(attr, old, new): global aspects_data, asp_table_source aspects_data = read_csv(asp_src, headers=True) # Replaces None values by empty string aspects_data = aspects_data.fillna('') new_source = ColumnDataSource(aspects_data) asp_table_source.data = new_source.data asp_table_source.selected.indices = list(range(len(aspects_data))) # pylint: disable=unused-argument def op_file_callback(attr, old, new): global opinions_data, op_table_source, lexicons_dropdown, df_opinion_generic df = read_csv(op_src, headers=True) # Replaces None values by empty string df = df.fillna('') # Placeholder for generic opinion lexicons from the given csv file df_opinion_generic = df[df['isAcquired'] == 'N'] # Update the argument value for the callback customJS lexicons_dropdown.js_property_callbacks.get( 'change:value')[0].args['opinion_lex_generic'] \ = df_opinion_generic.to_dict(orient='list') opinions_data = df[df['isAcquired'] == 'Y'] new_source = ColumnDataSource(opinions_data) op_table_source.data = new_source.data op_table_source.selected.indices = list(range(len(opinions_data))) # pylint: disable=unused-argument def txt_status_callback(attr, old, new): print("Previous label: " + old) print("Updated label: " + new) text_status.on_change("value", txt_status_callback) asp_src.on_change('data', asp_file_callback) # pylint: disable=no-member asp_table_source.selected.on_change('indices', asp_selected_change) op_src.on_change('data', op_file_callback) op_table_source.selected.on_change('indices', op_selected_change) # pylint: disable=no-member train_src.on_change('data', train_file_callback) infer_src.on_change('data', infer_file_callback) return layout( [[_create_header(train_dropdown, inference_dropdown, text_status)], [tabs]])
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) input_dbname = TextInput(value=config['dbname'], title="Database Name",
ra=[], dec=[], color=[], gMag=[] )) group_id = 0 divInfo = Div(text=""" <h1>Group {}</h1> """.format(group_id),) def callback(attr, old, new): global group_id group_id = int(new) plot_group(group_id) group_id_input = TextInput(value="0", placeholder='group id') group_id_input.on_change("value", callback) def go_next(): global group_id group_id += 1 group_id_input.value="{}".format(group_id) plot_group(group_id) def go_prev(): global group_id group_id -= 1 group_id_input.value="{}".format(group_id) plot_group(group_id) def plot_group(group_id): divInfo.text = "<h1>Group {}</h1>".format(group_id)
c.BEDROOMS, c.BED ] + list_amenities + [c.PRICE] listing_df[floats] = listing_df[floats].astype(float) converted = cm.to_matrix(listing_df, c.LISTING_COLUMNS) predicted_price = hp.predict_input(converted[0], c.DATASET_PROPERTIES[c.CITY]) PREDICT_VALUE.active = False HOST_PRICE.text = ('Your listing is valued at: $' + str(predicted_price[0]).split('.')[0] + ' per night') # INPUT WIDGETS API_KEY_INPUT = TextInput(value=GOOGLE_API_KEY, title='Google API Key') API_KEY_INPUT.on_change(c.VALUE, update_key) CITY_INPUT = TextInput(value=c.ADDRESS, title='Location:') CITY_INPUT.on_change(c.VALUE, update_map) MIN_NIGHT_INPUT = TextInput(value=c.EMPTY_STRING, title='Min. Nights:') MAX_NIGHT_INPUT = TextInput(value=c.EMPTY_STRING, title='Max. Nights:') # Slider Widget ACCOM = FILTER_PROPERTIES[c.ACCOMMODATES] ACCOMMODATES_SLIDER = Slider(start=ACCOM[0], end=ACCOM[1], value=ACCOM[0], step=1, title='Accommodates')
start_candles = 30 graph = pf_graph('5min', 50, '5 минут', start_candles) graphs.append(graph) graph = pf_graph('15min', 100, '15 минут', start_candles) graphs.append(graph) graph = pf_graph('hour', 150, '1 час', start_candles) graphs.append(graph) graph = pf_graph('daily', 300, '1 день', start_candles) graphs.append(graph) # Set up layouts and add to document #inputs = VBoxForm(children=[text, offset, amplitude, phase, freq]) ticker_input = TextInput(value='SPFB.RTS') div_input = TextInput(value='1.') length_input = TextInput(value=str(start_candles)) format_input = TextInput(value='0') button = Button(label='Change') button.on_click(change_source) curdoc().clear() curdoc().add_root( HBox(children=[ button, ticker_input, div_input, length_input, format_input ], width=900)) for graph in graphs:
def __init__(self, quote_period, box_size, graph_name, candles=30): # Set up data self.graph_counter = 0 self.data_length = candles self.data_slice = slice(-self.data_length, None) self.quote_period = quote_period self.ticker = 'SPFB.RTS' self.box_size_divider = 1. self.pf = point_and_figure.Point_and_Figure() #print(quote_period) if (quote_period == 'daily' or quote_period == 'hour'): self.from_date = (date.today() - timedelta( days=days_look_back_min_candles * 5)).strftime('%Y%m%d') else: self.from_date = ( date.today() - timedelta(days=days_look_back_min_candles)).strftime('%Y%m%d') self.get_quotes() self.last_quote_date = None self.pf.box_size = box_size self.pf.process_df(self.quote) self.pf.prepare_datasource() self.plot = Figure( plot_height=400, plot_width=600, title=graph_name, tools="crosshair,pan,reset,resize,wheel_zoom,save", ) self.yticker = bokeh.models.FixedTicker() #print pf.yticks self.yticker.ticks = list(self.pf.yticks) self.xticker = bokeh.models.FixedTicker() self.xticker.ticks = list(self.pf.xticks) # ticker.interval = 1 #p.xaxis.ticker = ticker self.plot.ygrid.ticker = self.yticker self.plot.xgrid.ticker = self.xticker self.plot.yaxis.formatter = bokeh.models.NumeralTickFormatter( format=self.pf.bokeh_ticks_format) self.plot.yaxis.ticker = self.yticker #self.plot.ygrid.band_fill_alpha = 0.05 #self.plot.ygrid.band_fill_color = "navy" #self.glyphs_size = 100. #self.glyphs_size = self.pf.box_size / 1. / len(self.pf.yticks) * self.pf.scale_factor self.scale = Slider(title="scale", value=300, start=300, end=3000, step=1) self.scale.on_change('value', self.scale_change) self.recalc_glyphs_size = True self.calc_glyphs() self.source_x = ColumnDataSource( data=dict(x=self.pf.x_x, y=self.pf.x_y, size=self.glyphs_size_x)) self.source_o = ColumnDataSource( data=dict(x=self.pf.o_x, y=self.pf.o_y, size=self.glyphs_size_o)) self.source_digits = ColumnDataSource( data=dict(x=self.pf.digits_x, y=self.pf.digits_y, text=self.pf.digits_text, size=self.font_size)) self.graph_o = self.plot.circle('x', 'y', source=self.source_o, alpha=0.5, size='size', color="navy") self.graph_x = self.plot.cross('x', 'y', source=self.source_x, alpha=0.5, size='size', color="navy", angle=np.pi / 4) self.graph_digits = self.plot.text( 'x', 'y', source=self.source_digits, alpha=0.5, text='text', color="navy", text_font_size='size') #text_font_size self.box = Slider(title="box", value=self.pf.box_size, start=10, end=500, step=1) self.box.on_change('value', self.box_change) self.text = TextInput() self.text_marker = 0
controls = widgetbox([x, y, color, size], width=200) lay = row(controls, create_figure()) curdoc().add_root(lay) print(result) print("Done loadCallback") df = None x = None y = None size = None color = None lay = None # LOAD Start part urlinput = TextInput(value="default", title="netCFD/OpenDAP Source URL:") btLoad = bokeh.models.Button(label="load") btLoad.on_click(loadCallback) l = layout([ [desc], [widgetbox(urlinput)], [widgetbox(btLoad)], ], sizing_mode=SIZING_MODE) curdoc().add_root(l) curdoc().title = "ncview2"
y_range=[0, 10]) plot.border_fill_color = 'black' plot.background_fill_color = 'black' plot.outline_line_color = None plot.grid.grid_line_color = None curdoc().add_periodic_callback(draw, 0.1) return plot plot = create_plot() # Set up widgets text = TextInput(title="title", value='Fractals') # Set up callbacks def update_title(attrname, old, new): plot.title.text = text.value text.on_change('value', update_title) # Set up layouts and add to document inputs = widgetbox(text) layout = row(inputs, plot) curdoc().add_root(layout) curdoc().title = "Fractals"
split_menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")] split = Dropdown(label="Split button", button_type="danger", menu=split_menu) checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) checkbox_button_group = CheckboxButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_button_group = RadioButtonGroup( labels=["Option 1", "Option 2", "Option 3"], active=0) text_input = TextInput(placeholder="Enter value ...") autocomplete_input = AutocompleteInput() select = Select(options=["Option 1", "Option 2", "Option 3"]) multi_select = MultiSelect(options=["Option %d" % (i + 1) for i in range(16)], size=6) slider = Slider(value=10, start=0, end=100) range_slider = RangeSlider() #date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31))) date_picker = DatePicker()
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)
def TextWidget(*args, **kw): """Forces a parameter value to be text""" kw['value'] = str(kw['value']) kw.pop('options', None) return TextInput(*args,**kw)
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 similarityGraph(si, sy, ey, db, abstractsim): #calculate similarity and return necessary info #ids = pmids of search, dates = dates of pmids, authors = authors of pmids, pmccites = number of cites, Y is x,y coordinate #from dimensionality reduction, topwords = labels of clusters from kmeans/tfidf, kcenters = x,y centers of clusters from kmeans #d is dictionary for all data storage d = SimilarityCalc(si, sy, ey, db, abstractsim) # for testing purposes # with open('data.pk','wb') as f: # pickle.dump(d,f) #convert authors list of lists to list of strings for display authors_str = [] for auths in d['authors']: authors_str.append(", ".join(auths)) #calcualte a scaled pt size based on citation quantity minw = 8 maxw = 30 # with open('citespkl.p','wb') as f: # pickle.dump(list(map(int,pmccites)),f) ptsizes = getScaledSizes(list(map(int, d['pmccites'])), minw, maxw) #create colors based on years published colors = getScaledColors(d['dates']) #colors = ['blue']*len(ids) alphas = [1] * len(d['ids']) source = ColumnDataSource(data=dict(x=d['Y'][:, 0], y=d['Y'][:, 1], PMID=d['ids'], titles=d['titles'], authors=authors_str, journals=d['journals'], dates=d['dates'], alphas=alphas, pmccites=d['pmccites'], ptsizes=ptsizes, colors=colors, colorsperm=colors)) ########publication view table from selected on tsne plot pubview_data = dict(titles=["Title"], dates=["Date"], journals=["Journal"], authors=["Author"], pmccites=["PMC Citations"], PMID=["pmids"]) pubview_source = ColumnDataSource(pubview_data) pubview_columns = [ TableColumn(field="titles", title="Article Title", width=400), TableColumn(field="authors", title="Authors", width=50), TableColumn(field="journals", title="Journal", width=50), TableColumn(field="dates", title="Date", width=80), TableColumn(field="pmccites", title="PMC Citations", width=80), TableColumn(field="PMID", title="PMIDS", width=0), ] pubview_table = DataTable(source=pubview_source, columns=pubview_columns, width=930, height=400) source.callback = CustomJS(args=dict(pubview_table=pubview_table), code=""" var selecteddata = cb_obj.selected["1d"].indices var count = 0 var s1 = cb_obj.get('data'); var d2 = pubview_table.get('source').get('data'); d2.index = [] d2.authors = [] d2.titles = [] d2.journals = [] d2.dates = [] d2.pmccites = [] d2.PMID = [] for(k = 0; k < selecteddata.length; k++){ tind = selecteddata[k] d2.index.push(count) d2.authors.push(s1.authors[tind]) d2.titles.push(s1.titles[tind]) d2.journals.push(s1.journals[tind]) d2.dates.push(s1.dates[tind]) d2.pmccites.push(parseInt(s1.pmccites[tind])) d2.PMID.push(s1.PMID[tind]) count += 1 } console.log(d2) pubview_table.trigger('change'); """) pubview_source.callback = CustomJS(code=""" var selecteddata = cb_obj.selected["1d"].indices var s1 = cb_obj.get('data'); var url = "https://www.ncbi.nlm.nih.gov/pubmed/"+s1.PMID[selecteddata[0]] window.open(url,'_blank'); """) #######END TABLE DISPLAY CODE##### #####max-width IS IMPORTANT FOR PROPER WRAPPING OF TEXT hover = HoverTool(tooltips=""" <div> <div style="max-width: 400px;"> <span style="font-size: 12px; font-weight: bold;">@titles</span> </div> <div style="max-width: 400px;"> <span style="font-size: 12px; color: #966;">@authors</span> <div> <div style="max-width: 400px;"> <span style="font-size: 12px; font-style: italic;">@journals, @dates</span> <div style="max-width: 400px;"> <span style="font-size: 10px;">PMID</span> <span style="font-size: 10px; color: #696;">@PMID</span> </div> <div style="max-width: 400px;"> <span style="font-size: 10px;">PMC Citations</span> <span style="font-size: 10px; color: #696;">@pmccites</span> </div> </div> """) resetCallback = CustomJS(args=dict(source=source), code=""" var data = source.get('data') var titles = data['titles'] for (i=0; i < titles.length; i++) { data.colors[i]=data.colorsperm[i] data.alphas[i]= 1 } source.trigger('change') """) #move function from reset callback to below so stuff updates automatically on textbox change textCallback = CustomJS(args=dict(source=source), code=""" var data = source.get('data') var value = cb_obj.get('value') var words = value.split(" ") for (i=0; i < data.titles.length; i++) { data.alphas[i]= 0.3 data.colors[i]=data.colorsperm[i] } for (i=0; i < data.titles.length; i++) { for(j=0; j < words.length; j++){ if (data.titles[i].toLowerCase().indexOf(words[j].toLowerCase()) !== -1) { if(j == words.length-1){ data.colors[i]='orange' data.alphas[i]= 1 } }else if(data.authors[i].toLowerCase().indexOf(words[j].toLowerCase()) !== -1){ if(j == words.length-1){ data.colors[i]='orange' data.alphas[i]= 1 } }else if(data.journals[i].toLowerCase().indexOf(words[j].toLowerCase()) !== -1){ if(j == words.length-1){ data.colors[i]='orange' data.alphas[i]= 1 } }else{ break } } } source.trigger('change') """) publistcallback = CustomJS(args=dict(pubview_table=pubview_table), code=""" var pmids = pubview_table.get('source').get('data').PMID; var pmidlist = pmids.join() var url = "https://www.ncbi.nlm.nih.gov/pubmed/"+pmidlist window.open(url,'_blank'); """) TOOLS = 'pan,lasso_select,wheel_zoom,tap,reset' p = figure(plot_width=900, plot_height=600, title="'" + si + "' tSNE similarity", tools=[TOOLS, hover], active_scroll='wheel_zoom', active_drag="lasso_select") p.circle('x', 'y', fill_color='colors', fill_alpha='alphas', size='ptsizes', line_color="#000000", line_alpha=0.2, source=source) #word labeles for plots wordsources = [] for idx in list(range(len(d['topwords']))): wordsources.append( ColumnDataSource( dict(x=d['kcenters'][idx][:, 0], y=d['kcenters'][idx][:, 1], text=d['topwords'][idx]))) wordglyph = Text(x="x", y="y", text="text", text_color="#000000", text_font_style="bold", text_font_size="14pt") #5 is used for initial slider set below initialclust = 5 wordholdsource = ColumnDataSource( dict(x=d['kcenters'][initialclust][:, 0], y=d['kcenters'][initialclust][:, 1], text=d['topwords'][initialclust])) p.add_glyph(wordholdsource, wordglyph) # source = ColumnDataSource(data=dict(x=x, y=y)) # # plot = Figure(plot_width=400, plot_height=400) # plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) args = {} args["wordholdsource"] = wordholdsource for idx in list(range(len(d['topwords']))): args["wordsource" + str(idx + d['minc'])] = wordsources[idx] #had to use eval hack because of limitations on the type of objects that can be passed into the callback, limited by bokeh backend slidercallback = CustomJS(args=args, code=""" var f = cb_obj.value var ndata = eval('wordsource' + f.toString()).data; wordholdsource.data.x = ndata.x wordholdsource.data.y = ndata.y wordholdsource.data.text = ndata.text wordholdsource.trigger('change'); """) wslider = Slider(start=d['minc'], end=d['maxc'], value=d['minc'] + initialclust, step=1, title="# of labels") # slider = Slider(start=0.1, end=4, value=1, step=.1, title="power", callback=callback) wslider.js_on_change('value', slidercallback) #formatting plot p.xaxis.axis_label = "Hover to view publication info, Click to open Pubmed link" p.xaxis.major_tick_line_color = None # turn off x-axis major ticks p.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks p.yaxis.major_tick_line_color = None # turn off y-axis major ticks p.yaxis.minor_tick_line_color = None p.xaxis.major_label_text_font_size = '0pt' # turn off x-axis tick labels p.yaxis.major_label_text_font_size = '0pt' left, right, bottom, top = np.amin(d['Y'][:, 0]) * 1.1, np.amax( d['Y'][:, 0]) * 1.1, np.amin(d['Y'][:, 1]) * 1.1, np.amax( d['Y'][:, 1]) * 1.1 p.x_range = Range1d(left, right) p.y_range = Range1d(bottom, top) #tap tool callback url = "https://www.ncbi.nlm.nih.gov/pubmed/@PMID" taptool = p.select(type=TapTool) taptool.callback = OpenURL(url=url) #work input callback word_input = TextInput(title="Search for term(s) in graph", placeholder="Enter term to highlight", callback=textCallback) reset = Button(label="Clear Highlighting", callback=resetCallback, width=150) spdiv = Div(text=" ", width=100, height=20) #add addition message saying data was cutoff in case of vague search terms if (len(d['rids']) == d['maxids']): cutoff_message = "<br>(Search was truncated to " + str( d['maxids']) + " newest articles due to memory constraints)" else: cutoff_message = "" tit1 = Div(text="<h1>" + si + " similarity plot</h1><br><h5>Displaying the " + str(d['sdfc_len']) + "/" + str(len(d['rids'])) + " articles that have data on pubmed" + cutoff_message + "</h5>", width=930) pubmed_list_button = Button(label="Export selected publications to pubmed", callback=publistcallback) lt = layout([[tit1], [word_input], [reset, spdiv, wslider], [p], [pubmed_list_button], [pubview_table]]) return lt
x = np.linspace(0, 4*np.pi, N) y = np.sin(x) source = ColumnDataSource(data=dict(x=x, y=y)) ser =serial.Serial('COM4',9600,timeout=0.2) # Set up plot plot = figure(plot_height=600, plot_width=800, title="my Graph", tools="crosshair,pan,reset,save,wheel_zoom", x_range=[-4*np.pi, 4*np.pi], y_range=[-2.5, 2.5]) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) # Set up widgets text = TextInput(title="Custom function", value='Enter f(x)') offset = Slider(title="Offset", value=0.0, start=-5.0, end=5.0, step=0.1) amplitude = Slider(title="Amplitude", value=1.0, start=-3.0, end=3.0, step=0.01) Speed= Slider(title="Speed", value=100, start=100, end=250) Delay = Slider(title="Delay", value=1, start=1, end=100) CurveList=[("Sin","C1"),("Poly","C2"),("Abs","C3"),("Custom","C4")] dropdown=Dropdown(label="Curve Lists",button_type="warning",menu=CurveList) button = Button(label="Run ", button_type="success") button1 = Button(label="Stop ", button_type="danger") # Set up callbacks def update_title(attrname, old, new):
def setup_bokeh_frame(self, doc): self.source = ColumnDataSource( data=dict(param_x=[], param_y=[], err_x=[], err_y=[])) self.source_static = ColumnDataSource( data=dict(param_x=[], param_y=[], err_x=[], err_y=[])) ''' --------------------------------------------------------------- Define Param Graph --------------------------------------------------------------- ''' self.param_graph = {} self.param_graph['obj_x_select'] = Select(value=self.param_names[0], options=self.nix( self.param_names[1], self.param_names)) self.param_graph['obj_y_select'] = Select(value=self.param_names[1], options=self.nix( self.param_names[0], self.param_names)) self.param_graph['x_min_entry'] = TextInput(placeholder='Min X Value', value='') self.param_graph['x_max_entry'] = TextInput(placeholder='Max X Value', value='') self.param_graph['y_min_entry'] = TextInput(placeholder='Min Y Value', value='') self.param_graph['y_max_entry'] = TextInput(placeholder='Max Y Value', value='') self.param_graph['plot_width'] = 610 self.param_graph['plot_height'] = 400 self.param_graph['tools'] = self.bokeh_tools self.param_graph['obj_figure'] = figure( plot_width=self.param_graph['plot_width'], plot_height=self.param_graph['plot_height'], tools=self.param_graph['tools'], title=self.param_graph['obj_x_select'].value + ' vs. ' + self.param_graph['obj_y_select'].value) self.param_graph['obj_figure'].xaxis.axis_label = self.param_graph[ 'obj_x_select'].value self.param_graph['obj_figure'].yaxis.axis_label = self.param_graph[ 'obj_y_select'].value self.param_graph['obj_glyph'] = Circle(x='param_x', y='param_y', size=1, fill_color='#5F77D5', line_color='#5F77D5') self.param_graph['obj_figure'].add_glyph(self.source, self.param_graph['obj_glyph']) ''' --------------------------------------------------------------- Define Err Graph --------------------------------------------------------------- ''' self.err_graph = {} self.err_graph['obj_x_select'] = Select(value=self.err_names[0], options=self.nix( self.err_names[1], self.err_names)) self.err_graph['obj_y_select'] = Select(value=self.err_names[1], options=self.nix( self.err_names[0], self.err_names)) self.err_graph['x_min_entry'] = TextInput(placeholder='Min X Value', value='') self.err_graph['x_max_entry'] = TextInput(placeholder='Max X Value', value='') self.err_graph['y_min_entry'] = TextInput(placeholder='Min Y Value', value='') self.err_graph['y_max_entry'] = TextInput(placeholder='Max Y Value', value='') self.err_graph['plot_width'] = 610 self.err_graph['plot_height'] = 400 self.err_graph['tools'] = self.bokeh_tools self.err_graph['obj_figure'] = figure( plot_width=self.err_graph['plot_width'], plot_height=self.err_graph['plot_height'], tools=self.err_graph['tools'], title=self.err_graph['obj_x_select'].value + ' vs. ' + self.err_graph['obj_y_select'].value) self.err_graph['obj_figure'].xaxis.axis_label = self.err_graph[ 'obj_x_select'].value self.err_graph['obj_figure'].yaxis.axis_label = self.err_graph[ 'obj_y_select'].value self.err_graph['obj_glyph'] = Circle(x='err_x', y='err_y', size=1, fill_color='#5F77D5', line_color='#5F77D5') self.err_graph['obj_figure'].add_glyph(self.source, self.err_graph['obj_glyph']) def update(): param_name_x = self.param_graph['obj_x_select'].value param_name_y = self.param_graph['obj_y_select'].value err_name_x = self.err_graph['obj_x_select'].value err_name_y = self.err_graph['obj_y_select'].value self.update_data(param_name_x, param_name_y, err_name_x, err_name_y) param_widgets = bokeh.layouts.row(self.param_graph['obj_x_select'], self.param_graph['obj_y_select']) param_x_entry = bokeh.layouts.row(self.param_graph['x_min_entry'], self.param_graph['x_max_entry']) param_y_entry = bokeh.layouts.row(self.param_graph['y_min_entry'], self.param_graph['y_max_entry']) param_pane = bokeh.layouts.column(param_widgets, self.param_graph['obj_figure'], param_x_entry, param_y_entry) err_widgets = bokeh.layouts.row(self.err_graph['obj_x_select'], self.err_graph['obj_y_select']) err_x_entry = bokeh.layouts.row(self.err_graph['x_min_entry'], self.err_graph['x_max_entry']) err_y_entry = bokeh.layouts.row(self.err_graph['y_min_entry'], self.err_graph['y_max_entry']) err_pane = bokeh.layouts.column(err_widgets, self.err_graph['obj_figure'], err_x_entry, err_y_entry) layout = bokeh.layouts.row(param_pane, err_pane) doc.add_root(layout) update() # callback functions def param_x_select_change(attrname, old, new): self.source.data['param_x'] = self.total_df[new] self.param_graph[ 'obj_figure'].title.text = new + ' vs. ' + self.param_graph[ 'obj_y_select'].value self.param_graph['obj_figure'].xaxis.axis_label = new def param_y_select_change(attrname, old, new): self.source.data['param_y'] = self.total_df[new] self.param_graph['obj_figure'].title.text = self.param_graph[ 'obj_x_select'].value + ' vs. ' + new self.param_graph['obj_figure'].yaxis.axis_label = new self.param_graph['obj_x_select'].on_change('value', param_x_select_change) self.param_graph['obj_y_select'].on_change('value', param_y_select_change) def err_x_select_change(attrname, old, new): self.source.data['err_x'] = self.total_df[new] self.err_graph[ 'obj_figure'].title.text = new + ' vs. ' + self.err_graph[ 'obj_y_select'].value self.err_graph['obj_figure'].xaxis.axis_label = new def err_y_select_change(attrname, old, new): self.source.data['err_y'] = self.total_df[new] self.err_graph['obj_figure'].title.text = self.err_graph[ 'obj_x_select'].value + ' vs. ' + new self.err_graph['obj_figure'].yaxis.axis_label = new self.err_graph['obj_x_select'].on_change('value', err_x_select_change) self.err_graph['obj_y_select'].on_change('value', err_y_select_change) def source_callback(attrname, old, new): selected_index_list = list(new['1d']['indices']) selected_rows = [] for i in selected_index_list: data_row = self.total_df.ix[i] selected_rows.append(data_row) formatted_rows = [] for rows in selected_rows: rows = rows[: -4] # remove the 4 copied columns used in source callback formatted_rows.append(list(rows.get_values())) ''' for rows in selected_rows: param_x_row = self.param_graph['obj_x_select'].value+': '+str(rows[self.param_graph['obj_x_select'].value]) param_y_row = self.param_graph['obj_y_select'].value+': '+str(rows[self.param_graph['obj_y_select'].value]) err_x_row = self.err_graph['obj_x_select'].value+': '+str(rows[self.err_graph['obj_x_select'].value]) err_y_row = self.err_graph['obj_y_select'].value+': '+str(rows[self.err_graph['obj_y_select'].value]) formatted_rows.append(str(param_x_row)+' '+str(param_y_row)+' '+str(err_x_row)+' '+str(err_y_row)) ''' with open('selected_points.txt', 'w') as f: f.write(' '.join(self.param_names) + ' ' + ' '.join(self.err_names) + '\n') for fr in formatted_rows: # apparently python cannot write a list to a file so the extra formatting is necessary fr = str(fr) fr.replace('[', '') fr.replace(']', '') f.write(fr + '\n') self.source.on_change('selected', source_callback) def param_x_min_callback(attrname, old, new): self.param_graph['obj_figure'].x_range.start = float(new) def param_x_max_callback(attrname, old, new): self.param_graph['obj_figure'].x_range.end = float(new) def param_y_min_callback(attrname, old, new): self.param_graph['obj_figure'].y_range.start = float(new) def param_y_max_callback(attrname, old, new): self.param_graph['obj_figure'].y_range.end = float(new) self.param_graph['x_min_entry'].on_change('value', param_x_min_callback) self.param_graph['x_max_entry'].on_change('value', param_x_max_callback) self.param_graph['y_min_entry'].on_change('value', param_y_min_callback) self.param_graph['y_max_entry'].on_change('value', param_y_max_callback) def err_x_min_callback(attrname, old, new): self.err_graph['obj_figure'].x_range.start = float(new) def err_x_max_callback(attrname, old, new): self.err_graph['obj_figure'].x_range.end = float(new) def err_y_min_callback(attrname, old, new): self.err_graph['obj_figure'].y_range.start = float(new) def err_y_max_callback(attrname, old, new): self.err_graph['obj_figure'].y_range.end = float(new) self.err_graph['x_min_entry'].on_change('value', err_x_min_callback) self.err_graph['x_max_entry'].on_change('value', err_x_max_callback) self.err_graph['y_min_entry'].on_change('value', err_y_min_callback) self.err_graph['y_max_entry'].on_change('value', err_y_max_callback)
# %% rsq = Paragraph(text=r_sqr_str, width=100, height=10) # Importance Table imp_outputDF = df_importance.sort_values(by='score', ascending=False) imp_resultDF = ColumnDataSource(imp_outputDF) imp_columns = [TableColumn(field=col, title=col)\ for col in imp_outputDF.columns] imp_data_table = DataTable(source=imp_resultDF, columns=imp_columns, width=300, height=400) # Setup Widgets text = TextInput(title='title', value='Enter the name of Y') SliderList_x = [ Slider(title=col, value=x_values.loc['mean', col], start=x_values.loc['min', col], end=x_values.loc['max', col], step=(x_values.loc['max', col] - x_values.loc['min', col]) / 100, orientation='vertical', width=100, height=400) for col in x_values.columns ] # Get the current slider values presentDF = pd.DataFrame.from_dict({val.title: val.value\ for val in SliderList_x}, orient='index').T pred = model.predict(presentDF)
#output_file('gist.html') plot = figure(title="Gist Algorithmus", toolbar_location=None) source = ColumnDataSource(data=dict(x=tt, y=np.transpose(gv)[:, 0])) #plot.scatter(t, np.transpose(gv)[:,0]) plot.line('x', 'y', source=source) auswahl_dim = { 'klein': [200, 400], 'mittel': [2000, 6000], 'groß': [10000, 20000] } a_list = [] for k in auswahl_dim: a_list.append("{} {}".format(k, auswahl_dim[k])) dimension = Select(title="Dimension", value='klein', options=a_list) text = TextInput(title="Offset", value='Zeitverzug') offset = Slider(title="phase", value=0.0, start=-10.0, end=10.0, step=0.1) calculate = Button(label="recalculate") density = Slider(title="densitiy", value=0.01, start=0.01, end=1.0, step=0.01) def update_title(attrname, old, new): plot.title.text = text.value text.on_change('value', update_title) o = 0 sigma = 0.01
def pointsApp(doc): radii = [str(x) for x in df.Radius.unique()] # Create Input controls number = Slider(title="Value Cutoff", value=0, start=0, end=4, step=0.1, width=150) residue = TextInput(title="Residue name (3 letter code):", width=200) gpcr = Select(title="Proteins", value=list(df.Protein.unique())[0], options=list(df.Protein.unique()), width=100) lipid = Select(title="Lipids", value=list(df.Lipids.unique())[0], options=list(df.Lipids.unique()), width=100) radius = Select(title="Radius", value=radii[-1], options=radii, width=100) options = list(df.columns)[:-5] + ['ResID'] x_axis = Select(title="X Axis", options=options, value="ResID", width=150) y_axis = Select(title="Y Axis", options=options, value=options[0], width=150) cc_colors = [ x for x in cc.all_original_names() if x.startswith('linear') or x.startswith('rainbow') ] cmap = Select(title="Colormap", options=cc_colors, value='linear_kryw_0_100_c71', width=150) # Create Column Data Source that will be used by the plot source = ColumnDataSource( data=dict(x=[], y=[], ResName=[], ResID=[], Protein=[])) TOOLTIPS = [("ResName", "@ResName"), ("ResID", "@ResID"), ("Value", "@y")] mapper = linear_cmap( field_name='y', palette=cc.CET_L19, low=df[df.Protein == gpcr.value][y_axis.value].min(), high=df[df.Protein == gpcr.value][y_axis.value].max()) # p = figure(plot_height=400, plot_width=800, title="", toolbar_location="right", tooltips=TOOLTIPS) p = figure(tooltips=TOOLTIPS, ) global c c = p.circle(x="x", y="y", source=source, line_color='black', fill_color=mapper, **kwargs) p.toolbar.autohide = True p.axis.axis_label_text_font_size = "12pt" p.axis.axis_label_text_font_style = "bold" p.title.align = 'center' def update(df): y_value = y_axis.value x_value = x_axis.value df = df[(df[y_value] >= number.value) & (df['Protein'] == gpcr.value) & (df['Lipids'] == lipid.value) & (df['Radius'] == float(radius.value))] if (residue.value != ""): df = df[df.ResName.str.contains(residue.value.upper()) == True] # x_value = x_value # y_value = y_value mapper = linear_cmap( field_name='y', palette=cc.palette[cmap.value], low=df[df.Protein == gpcr.value][y_value].min(), high=df[df.Protein == gpcr.value][y_value].max()) c.glyph.fill_color = mapper p.xaxis.axis_label = x_value p.yaxis.axis_label = y_value p.title.text = "Showing %d Data Points " % len(df) source.data = dict( x=df[x_value], y=df[y_value], ResName=df["ResName"], ResID=df["ResID"], Protein=df["Protein"], ) controls = [number, gpcr, lipid, radius, y_axis, x_axis, residue, cmap] for control in controls: control.on_change('value', lambda attr, old, new: update(df)) sizing_mode = 'scale_width' inputs = row(*controls, sizing_mode=sizing_mode) inputs2 = row([gpcr, lipid, radius, residue], sizing_mode=sizing_mode) inputs3 = row([number, x_axis, y_axis, cmap], sizing_mode=sizing_mode) layout1 = layout([[inputs2]], sizing_mode=sizing_mode) layout2 = layout([p], sizing_mode=sizing_mode) layout3 = layout([inputs3], sizing_mode="scale_width") update(df) doc.add_root(layout1) doc.add_root(layout2) doc.add_root(layout3) doc.title = "Scatter Application" doc.theme = Theme(json=yaml.load(""" attrs: Figure: toolbar_location: above height: 500 width: 800 Grid: grid_line_dash: [6, 4] grid_line_color: black """, Loader=yaml.FullLoader))
Gain = Select(title="Gain", options=['100', '3k', '30k', '300k', '3M', '30M'], value='30k', max_width=105) Connect = Button(label='Connect', width=320) Random_test = Button(label='Random', button_type='warning', width=320) Start = Button(label='Start', button_type='success', width=320) Voltage_Window = RangeSlider(start=-1.5, end=1.5, value=(0.1,0.3), step=0.01, title="Voltage Window", bar_color='#f44336') 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.
from bokeh.io import curdoc from bokeh.models.widgets import TextInput, Button, Paragraph from bokeh.layouts import layout text_input = TextInput(value="") button = Button(label="generate text") output = Paragraph() def update(): output.text = "Hello, " + text_input.value button.on_click(update) lay_out = layout([[button, text_input], [output]]) curdoc().add_root(lay_out)
def init_view_name_input(self): value = self._model.get_active_view_alias() text_input = TextInput(title="New view:", value=value) return text_input
# Set up widgets # ============================================================================= # using the fake data source method for CustumJS callback # look at https://stackoverflow.com/questions/38375961/throttling-in-bokeh-application/38379136 dend_threshold_slider = Slider(title="Dendrogram Threshold over distance", value=2.0, start=0.0, end=10, step=0.05, callback_policy='mouseup', callback=CustomJS( args=dict(source=source_for_slider), code=""" source.data = { value: [cb_obj.value] } """)) issues_list_input = TextInput(title="Enter issues IDs") clipboard_text = TextInput(title="Selected issues IDs") columns = [ TableColumn(field="leaves_names", title="Issue ID"), TableColumn(field="clusters", title="Cluster"), ] data_table = DataTable(source=leaves_source, columns=columns, width=280) submit_button = Button(label="Submit", button_type="success") universe_checkbox = CheckboxGroup( labels=["Universe issues dendrogram (please allow 30s to complete)"]) # ============================================================================= # Set up callbacks # ============================================================================= def update_issue_list():
def __init__(self): self.grepolis = Grepolis() imgRessource = [] for v in ["Bois", "Pierre", "Argent"]: r = "static/" + v + ".png" d = dict(url=[r]) imgRessource.append(Image(d)) colRess = column(*[img.figure for img in imgRessource]) self.inputRess = [ TextInput(value="", title=el + " :", width=150) for el in ["Bois", "Pierre", "Argent"] ] colinputRess = column(*self.inputRess) imgDieu = [] for v in ["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"]: r = "static/" + v + ".png" d = dict(url=[r]) imgDieu.append(Image(d, multiplier=3)) rowDieu = [HFill(5)] for img in imgDieu: rowDieu.append(HFill(5)) rowDieu.append(img.figure) rowDieu = row(*rowDieu) imgAtt = [] for v in ["Att_hack", "Att_sharp", "Att_distance"]: r = "static/" + v + ".png" d = dict(url=[r]) imgAtt.append(Image(d)) colAtt = column(*[img.figure for img in imgAtt]) self.inputAtt = [ TextInput(value="", title=el + " :", width=150) for el in ["Contondantes", "Blanches", "De Jet"] ] colinputAtt = column(*self.inputAtt) imgDef = [] for v in ["Def_hack", "Def_sharp", "Def_distance"]: r = "static/" + v + ".png" d = dict(url=[r]) imgDef.append(Image(d)) colDef = column(*[img.figure for img in imgDef]) self.inputDef = [ TextInput(value="", title=el + " :", width=150) for el in ["Contondantes", "Blanches", "De Jet"] ] rowinputDef = column(*self.inputDef) imgOther = [] for v in ["Vitesse", "Butin", "Faveur"]: r = "static/" + v + ".png" d = dict(url=[r]) imgOther.append(Image(d)) colOther = column(*[img.figure for img in imgOther]) self.inputFavBut = [ TextInput(value="", title=el + " :", width=150) for el in ["Vitesse", "Butin", "Faveur"] ] self.inputOther = column(*self.inputFavBut) self.imgUnit = [] for v in [ "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char", "Envoye", "Centaure", "Pegase" ]: r = "static/" + v + ".jpg" d = dict(url=[r]) self.imgUnit.append(Image(d, multiplier=2)) rowUnit = row(HFill(10), *[img.figure for img in self.imgUnit]) imgDefAtt = [] for v in ["Pop", "Attaque", "Defense"]: r = "static/" + v + ".png" d = dict(url=[r]) imgDefAtt.append(Image(d)) rowInputUnit = [HFill(10)] self.unitInput = [ TextInput(value="", title=el + " :", width=80) for el in [ "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char", "Envoye", "Centaure", "Pegase" ] ] for inp in self.unitInput: rowInputUnit.append(inp) rowInputUnit.append(HFill(30)) rowInputUnit = row(HFill(10), *rowInputUnit) self.selectUnit = CheckboxButtonGroup(labels=[ "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char", "Envoye", "Centaure", "Pegase" ], active=[i for i in range(9)]) self.selectUnit.on_change("active", self.updateSelectUnit) self.Dieu = RadioButtonGroup( labels=["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"], active=0, width=1110) self.Dieu.on_change('active', self.updateUnit) self.attdef = RadioButtonGroup(labels=["Attaque", "Defense"], active=0, width=200) self.attdef.on_change('active', self.switchAttDef) self.typeAtt = RadioGroup( labels=["Armes Contondantes", "Armes Blanches", "Armes de Jet"], active=0, width=150) self.typeAtt.on_change('active', self.process2) self.imgFaveur = Image(dict(url=["static/" + "Faveur" + ".png"])) self.launch = Button(label="Lancer") self.launch.on_click(self.process) self.inputPop = TextInput(value="1500", title="Population : ", width=120) self.inputPop.on_change("value", self.process2) self.inputFav = TextInput(value="1500", title="Faveur Max : ", width=120) self.inputFav.on_change("value", self.process2) rowPop = row(HFill(10), self.typeAtt, imgDefAtt[1].figure, self.attdef, HFill(30), imgDefAtt[2].figure, HFill(50), imgDefAtt[0].figure, self.inputPop, HFill(50), self.imgFaveur.figure, self.inputFav, HFill(50)) self.doc = column( rowDieu, self.Dieu, VFill(20), rowPop, VFill(20), self.selectUnit, rowUnit, rowInputUnit, VFill(20), row(HFill(50), colRess, colinputRess, HFill(40), colAtt, colinputAtt, HFill(40), colDef, rowinputDef, HFill(40), colOther, self.inputOther)) #curdoc().add_root(column(rowDieu,self.Dieu,VFill(20),rowPop,VFill(20),self.selectUnit,rowUnit,rowInputUnit,VFill(20),row(HFill(50),colRess,colinputRess,HFill(40),colAtt,colinputAtt,HFill(40),colDef,rowinputDef,HFill(40),colOther,self.inputOther))) self.process(None)
from bokeh.models.widgets import TextInput from bokeh.plotting import curdoc def my_text_input_handler(attr, old, new): print("Previous label: " + old) print("Updated label: " + new) text_input = TextInput(value="default", title="Label:") text_input.on_change("value", my_text_input_handler) curdoc().add_root(text_input) #bokeh serve --show test4.py
source=source, radius_dimension='max') squa = p.quad(top='top', bottom='bottom', left='left', right='right', color="navy", alpha=0.8, source=source) p.xaxis.ticker = [x for x in range(-20, 20)] p.yaxis.ticker = [x for x in range(-20, 20)] circ.visible = False squa.visible = False text_input = TextInput(value="", title="INPUT (only numbers):") circlebutton = Button(label="Circle", button_type="primary") circlebutton.on_event(ButtonClick, circlecallback) squarebutton = Button(label="Square", button_type="primary") squarebutton.on_event(ButtonClick, squarecallback) clearbutton = Button(label="Clear", button_type="warning") clearbutton.on_event(ButtonClick, clearcallback) div2 = Div(text='', width=300, height=100) aa = row([text_input, circlebutton, squarebutton, clearbutton]) bb = column([p, aa, div2]) doc.add_root(bb)