def acc_loss_visual(history, result_path, script_name, model_name, time_global): """ Plot accuracy and loss """ separate_result_file = os.path.join(result_path, time_global) if not os.path.isdir(separate_result_file): os.mkdir(separate_result_file) acc_arr = np.array(history['acc'], dtype=float) loss_arr = np.array(history['loss'], dtype=float) val_acc_arr = np.array(history['val_acc'], dtype=float) val_loss_arr = np.array(history['val_loss'], dtype=float) output_file(os.path.join(separate_result_file,"legends_"+script_name+"_"+model_name+".html")) p1 = figure() p1.title.text = "Training and Cross validation accuracy" p1.xaxis.axis_label = 'Iterations' p1.yaxis.axis_label = 'Accuracy' p1.circle(range(0,len(acc_arr)), acc_arr,color="green", legend="Train_Acc") p1.line(range(0,len(acc_arr)), acc_arr,line_color="green", legend="Train_Acc") p1.circle(range(0,len(val_acc_arr)), val_acc_arr,color="orange", legend="Val_Acc") p1.line(range(0,len(val_acc_arr)), val_acc_arr, line_color="orange",legend="Val_Acc") p2 = figure() p2.title.text = "Training and Cross validation loss_error" p2.xaxis.axis_label = 'Iterations' p2.yaxis.axis_label = 'Loss_error' p2.circle(range(0,len(loss_arr)), loss_arr,color="green", legend="Train_loss") p2.line(range(0,len(loss_arr)), loss_arr,line_color="green", legend="Train_loss") p2.circle(range(0,len(val_loss_arr)), val_loss_arr,color="orange", legend="Val_loss") p2.line(range(0,len(val_loss_arr)), val_loss_arr, line_color="orange", legend="Val_loss") p = Column(p1, p2) show(p)
def execute(args, parser): config = Config(args.config, verbose=False) with config.trialscontext() as session: q = (session.query(Trial) .filter(Trial.status == 'SUCCEEDED') .order_by(Trial.started)) data = [curr.to_dict() for curr in q.all()] bk.output_file(args.filename, title='osprey') plots = [] ss = config.search_space() warp = {key:('warp' in value and value['warp'] == 'log') for key,value in config.__dict__['config']['search_space'].items()} for plot in PLOTS: plt = plot(data, ss, warp) if plt is not None: plt = plt if isinstance(plt, list) else [plt] plots.extend(plt) p = Column(*plots) if args.browser: bk.show(p) else: bk.save(p)
def make_layout(): import pandas as pd plot, source = make_plot() template = """<span href="#" data-toggle="tooltip" title="<%= value %>"><%= value %></span>""" columns = [ TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads", editor=IntEditor()), ] 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']] source = ColumnDataSource(data=df) data_table = DataTable(source=source, columns = columns) l = layout([[data_table]]) return l data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True) button = Button(label="Randomize data", button_type="success") button.on_click(click_handler) buttons = WidgetBox(children=[button], width=400) column = Column(children=[buttons, plot, data_table]) return column
def create_layout(): year_select = Select(title="Year:", value="2010", options=years) location_select = Select(title="Location:", value="World", options=locations) year_select.on_change('value', on_year_change) location_select.on_change('value', on_location_change) controls = WidgetBox(children=[year_select, location_select], height=150, width=600) layout = Column(children=[controls, pyramid(), population()]) return layout
def make_layout(): plot, source = make_plot() columns = [ TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True) button = Button(label="Randomize data", button_type="success") button.on_click(click_handler) buttons = WidgetBox(children=[button], width=400) column = Column(children=[buttons, plot, data_table]) return column
def main(): state_xs, state_ys = get_us_state_outline() left, right = minmax(state_xs) bottom, top = minmax(state_ys) plot = Figure(title=TITLE, plot_width=1000, plot_height=700, tools="pan, wheel_zoom, box_zoom, reset", x_range=Range1d(left, right), y_range=Range1d(bottom, top), x_axis_label='Longitude', y_axis_label='Latitude') plot_state_outline(plot, state_xs, state_ys) density_overlay = DensityOverlay(plot, left, right, bottom, top) density_overlay.draw() grid_slider = Slider(title="Details", value=density_overlay.gridcount, start=10, end=100, step=10) grid_slider.on_change("value", density_overlay.grid_change_listener) radiance_slider = Slider(title="Min. Radiance", value=density_overlay.radiance, start=np.min(density_overlay.rad), end=np.max(density_overlay.rad), step=10) radiance_slider.on_change("value", density_overlay.radiance_change_listener) listener = ViewListener(plot, density_overlay, name="viewport") plot.x_range.on_change("start", listener) plot.x_range.on_change("end", listener) plot.y_range.on_change("start", listener) plot.y_range.on_change("end", listener) backends = ["CPU", "ROC"] default_value = backends[kde.USE_ROC] backend_select = Select(name="backend", value=default_value, options=backends) backend_select.on_change('value', density_overlay.backend_change_listener) doc = curdoc() doc.add_root( Column(children=[plot, grid_slider, radiance_slider, backend_select])) doc.add_periodic_callback(density_overlay.periodic_callback, 0.5)
def large_plot(n): from bokeh.models import ( Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, SaveTool, ResetTool ) from bokeh.models.layouts import Column from bokeh.models.glyphs import Line col = Column() objects = set([col]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis() plot.add_layout(xaxis, "below") yaxis = LinearAxis() plot.add_layout(yaxis, "left") xgrid = Grid(dimension=0) plot.add_layout(xgrid, "center") ygrid = Grid(dimension=1) plot.add_layout(ygrid, "center") tickers = [xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool() zoom_in = ZoomInTool() zoom_out = ZoomOutTool() wheel_zoom = WheelZoomTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() save = SaveTool() reset = ResetTool() tools = [pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset] plot.add_tools(*tools) col.children.append(plot) objects |= set([ xdr, ydr, xaxis, yaxis, xgrid, ygrid, renderer, renderer.view, glyph, source, source.selected, source.selection_policy, plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title, box_zoom.overlay, box_select.overlay, ] + tickers + tools) return col, objects
def check_children_prop(layout_callable): ## component subclasses are layouts, widgets and plots components = [Row(), Column(), Figure()] # Test layout accepts splatted components layout1 = layout_callable(*components) assert layout1.children == components # Test layout accepts children argument layout2 = layout_callable(children=components) assert layout2.children == components # Test value error raised when non-layout is provided as children with pytest.raises(ValueError): layout_callable(children=[ColumnDataSource()])
def _make_grid_plot(lang_data): upos_plt_info, txt_plt_info = _make_data_sources(lang_data) upos_plot = make_plot(*upos_plt_info[:2]) text_plot = make_plot(*txt_plt_info[:2]) upos_stats_table, upos_interval_table = _make_stats_tables( upos_plt_info[2]) text_stats_table, text_interval_table = _make_stats_tables(txt_plt_info[2]) upos_stats = Column(upos_stats_table, sizing_mode="fixed", height=350, width=150) upos_interval = Column(upos_interval_table, sizing_mode="fixed", height=350, width=150, margin=(0, 0, 0, 10)) text_stats = Column(text_stats_table, sizing_mode="fixed", height=350, width=150) text_interval = Column(text_interval_table, sizing_mode="fixed", height=350, width=150, margin=(0, 0, 0, 10)) gp = gridplot([ upos_stats, upos_interval, upos_plot, text_stats, text_interval, text_plot ], ncols=3, sizing_mode="stretch_width", plot_height=350) return gp
def start_view(): curdoc().add_root( Column( bpViewer, bpButtonGroup, hrViewer, spo2Viewer, ppgViewer, ppgButtonGroup, ppgViewer2, qosButtonGroup, ekgViewer, ekgButtonGroup, Row(pageIndicator, bckButton, fwdButton), Row(alarmIndicator, bckAlarmButton, fwdAlarmButton), # Row(pageIndicator, bckButton, fwdButton,alarmIndicator, bckAlarmButton, fwdAlarmButton) ))
def interactive_CMD(specs,cid1='g_SDSS',cid2='i_SDSS'): ''' Simplistic tool to create an interactive bokeh plot where outliers can be marked and saved in '/home/ekaterina/Documents/appaloosa/stars_shortlist/share/temp' ''' # Create some random data and put it into a ColumnDataSource s = specs.set_index('EPIC') s = s[[cid1, cid2, 'e_'+cid1,'e_'+cid2]].dropna(how='any') x = list(s[cid1]-s[cid2]) y = list(s[cid2]) size = list(np.sqrt(s['e_'+cid1]**2+s['e_'+cid2]**2)*100.) z = list(s.index.values) source_data = ColumnDataSource(data=dict(x=x, y=y,desc=z)) # Create a button that saves the coordinates of selected data points to a file savebutton = Button(label="Save", button_type="success") savebutton.callback = CustomJS(args=dict(source_data=source_data), code=""" var inds = source_data.selected['1d'].indices; var data = source_data.data; var out = ""; for (i = 0; i < inds.length; i++) { out += data['desc'][inds[i]] + " "; } var file = new Blob([out], {type: 'text/plain'}); var elem = window.document.createElement('a'); elem.href = window.URL.createObjectURL(file); elem.download = 'selected-data.txt'; document.body.appendChild(elem); elem.click(); document.body.removeChild(elem); """) # Plot the data and save the html file p = figure(plot_width=800, plot_height=400, #y_range=(20,7), tools="lasso_select, reset, hover",) p.circle(x='x', y='y', source=source_data, fill_alpha=0.8)#add size='desc' to visualize uncertainties on mag p.xaxis.axis_label = '{}-{}'.format(cid1,cid2) p.yaxis.axis_label = cid1 plot = Column(p, savebutton) output_file("test.html") show(plot) return
start=-30, end=0, value=exponents[par_name], step=1, title='{0}: Exponent'.format(par_name)) elif par_name == 'Shunt Resistance' or par_name == 'Series Resistance': sliders['{0} exponent'.format(par_name)] = Slider( start=-2, end=20, value=exponents[par_name], step=1, title='{0}: Exponent'.format(par_name)) #Loop through callbacks and look for activity for w in [sliders[key] for key in sliders]: w.on_change('value', update_plot) #Define layout of resulting web side plots = Column(children=[plot_fit_by_eye]) plots_log = Column(children=[plot_fit_by_eye_log]) inputs_sliders_prefactors = Column(children=[ sliders['{0} prefactor'.format(par_name)] for par_name in parameter_names ]) inputs_sliders_exponents = Column(children=[ sliders['{0} exponent'.format(par_name)] for par_name in parameter_names if par_name != 'Ideality Factor' ]) inputs_sliders = Row( children=[inputs_sliders_prefactors, inputs_sliders_exponents]) inputs = Column(children=[inputs_sliders]) curdoc().add_root(Row(children=[plots, plots_log, inputs]))
hwy = plot.add_glyph(source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) layout = Column(plot, data_table) doc = Document() doc.add_root(layout) if __name__ == "__main__": doc.validate() filename = "data_tables.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Data Tables")) print("Wrote %s" % filename) view(filename)
label_data = ColumnDataSource( data=dict(x=[1, 2, 3], y=[0, 0, 0], t=['Original', 'Normal', 'Uniform'])) label_set = LabelSet(x='x', y='y', text='t', y_offset=-4, source=label_data, render_mode='css', text_baseline="top", text_align='center') p.add_layout(label_set) callback = CustomJS(args=dict(source=source, normal=normal, uniform=uniform), code=""" const data = source.data; for (var i = 0; i < data.y.length; i++) { data.xn[i] = normal.compute(data.x[i] + 1); } for (var i = 0; i < data.y.length; i++) { data.xu[i] = uniform.compute(data.x[i] + 2); } source.change.emit(); """) button = Button(label='Press to apply Jitter!', width=300) button.js_on_click(callback) output_file("transform_jitter.html", title="Example Jitter Transform") show(Column(button, p))
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) plot.add_tools(HoverTool()) tab = Panel(child=plot, title=title) return tab def make_tabs(objs): return Tabs(tabs=[make_tab(title, obj) for title, obj in objs], width=600) layout = Column(children=[ Paragraph(text="Only Image and ImageRGBA glyphs are not demonstrated."), make_tabs(glyphs), make_tabs(markers) ]) doc = Document() doc.add_root(layout) if __name__ == "__main__": doc.validate() filename = "glyphs.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Glyphs")) print("Wrote %s" % filename) view(filename)
var avg = arrSum(avgList) / avgList.length for (var i = 0; i < alpha.length; i++){ line_y[i] = avg } source.change.emit(); line_source.change.emit(); """) p.add_tools(bar_hover) p.add_tools(line_hover) p.sizing_mode = 'scale_width' p.background_fill_color = "#fdf6e3" p.border_fill_color = "#fdf6e3" p.yaxis[0].formatter = NumeralTickFormatter(format="$0,0") p.outline_line_color = None range_slider = RangeSlider(start=0, end=max(id_range), value=(0, max(id_range)), step=1, title="Showing IDs") range_slider.js_on_change('value', callback) # range_slider.js_on_change("value", CustomJS(code=""" # console.log('range_slider: value=' + this.value[0], this.toString()) # """)) range_slider.background = "#fdf6e3" layout = Column(p, range_slider) layout.sizing_mode = "scale_width" # show the results show(layout)
except Exception as exception: errbox.text = str(exception) else: errbox.text = "" update_data() slider = Slider(start=1, end=20, value=order, step=1, title="Order", callback_policy='mouseup') slider.on_change('value', on_slider_value_change) text = TextInput(value=str(expr), title="Expression:") text.on_change('value', on_text_value_change) errbox = PreText() inputs = WidgetBox(children=[slider, text, errbox], width=600) layout = Column(children=[inputs, plot]) update_data() document.add_root(layout) session.show(layout) if __name__ == "__main__": document.validate() print("\npress ctrl-C to exit") session.loop_until_closed()
:return: """ global windowInSecs, totalPages windowInSecs = new totalPages = int(ppgDataFrame['time'].size / (windowInSecs * fs)) - 1 jumpSlider.end = totalPages fwdButton.on_click(jump_forward) bckButton.on_click(jump_backward) jumpSlider.on_change('value', slide_to_page) yScaleSlider.on_change('value', resize_y_scale) timeSlider.on_change('value', change_time_window) annotationTextInput.on_change('value', annotate_selection) ppgDataSource.on_change('selected', selection_change) ppgLineMarkersDataSource.on_change('selected', selection_change) #### Initialize #### jump_forward() #### Add plot and widgets to the document. #### curdoc().add_root(Column( mainViewer, HBox(pageIndicator, annotationTextInput, bckButton, fwdButton), HBox(yScaleSlider, timeSlider, jumpSlider), ) )
def create_download_simple(): from bokeh.io import output_file, show from bokeh.resources import CDN from bokeh.embed import file_html from bokeh.embed import autoload_static from bokeh.resources import INLINE from bokeh.resources import Resources # from jinja2 import Template import jinja2 global cv, indx, controls, selectsrc, xval, yval, plt_name, xcol, ycol, ccol, rcol, server_prefix, Periodic_color, frac, alphas, pss title = 'Sketchmap for ' + appname + ': Colored with ' + ccol.value + ' Point Size Variation: ' + rcol.value Periodic_color = False style = 'smapstyle' if len(grid.active) > 0: style = None if len(periodic_checkbox.active) > 0: Periodic_color = True p1, p2, table = cv.bkplot(xcol.value, ycol.value, ccol.value, radii=rcol.value, palette=plt_name.value, ps=pss.value, minps=pss.value / 2., alpha=alphas.value, pw=700, ph=600, Hover=True, toolbar_location="above", table=True, table_width=550, table_height=300, title='', Periodic_color=Periodic_color, frac_load=frac.value, style=style, marker=[marker.value]) spacer1 = Spacer(width=200, height=10) spacer2 = Spacer(width=200, height=20) plotpanel_static = Row( p1, Column(spacer1, Row(Spacer(width=200), p2), spacer2, table)) js, tag = autoload_static(plotpanel_static, Resources(mode='inline'), "") if (sys.version_info[0] < 3): js = js.decode("utf-8") #need this for python 2.7 but not python 3.3 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = appname + "/templates/offline-template-minimal.html" #print TEMPLATE_FILE template = templateEnv.get_template(TEMPLATE_FILE) html = template.render(js_resources=js, div=tag, appname=appname, title=title, server_prefix=server_prefix) # html = file_html(plotpanel_static, CDN, "my plot") fbase = appname + '-sketchmap_' + xcol.value + '-' + ycol.value + '-' + ccol.value + '-' + rcol.value + '-' + plt_name.value + '-f' + str( frac.value) + '-ps' + str(pss.value) + 'a' + str(alphas.value) if Periodic_color: fbase = fbase + '_Periodic' fname = os.path.join(server_prefix, 'static', fbase + '-minimal.html') # if (os.path.isfile(fname)): os.remove(fname) if (sys.version_info[0] < 3): f = open(fname, 'w') #python 2.7 else: f = open(fname, 'wb') #python 3.3 f.write(html.encode("utf-8")) f.close() return fname, fbase
def test_Column(): check_props_with_sizing_mode(Column()) check_children_prop(Column)
def create_plot(): global cv, selectsrc, columns, button, slider, n, xcol, ycol, ccol, rcol, plt_name, indx, controls, ps, jmolsettings, Periodic_color, pss, frac # Set up main plot Periodic_color = False if len(periodic_checkbox.active) > 0: Periodic_color = True style = 'smapstyle' if len(grid.active) > 0: style = None p1, p2, table, plotdatasrc = cv.bkplot(xcol.value, ycol.value, ccol.value, radii=rcol.value, palette=plt_name.value, ps=pss.value, minps=pss.value / 2.0, alpha=alphas.value, pw=700, ph=600, Hover=True, toolbar_location="above", table=True, table_height=170, Periodic_color=Periodic_color, return_datasrc=True, frac_load=frac.value, style=style, marker=[marker.value]) # Set up mouse selection callbacks # The following code is very tricky to understand properly. # the %s are the function or variable to pass from python depending on the slider callback or mouse callback. # One could write 3 seperate callbacks to connect slider,jmol and mouse selection but this way it is more compact ! code = """ var refdata = ref.data; var data = source.data; var plotdata=plotsrc.data; var ind = %s ; Array.prototype.min = function() { return Math.min.apply(null, this); }; var inds =ind%s; var idx = %s; //plotdata['id'][inds]; console.log(inds); var xs = refdata['x'][inds]; var ys = refdata['y'][inds]; data['xs'] = [xs]; data['ys'] = [ys]; data=refdata[inds]; source.change.emit(); %s; var str = "" + idx; var pad = "000000"; var indx = pad.substring(0, pad.length - str.length) + str; var settings= "%s" ; var file= "javascript:Jmol.script(jmolApplet0," + "'set frank off; load %s/static/%s-structures/set."+ indx+ ".xyz ;" + settings + "')" ; location.href=file; localStorage.setItem("indexref",indx); document.getElementById("p1").innerHTML = " Selected frame:"+ indx ; //document.getElementById("info").innerHTML = "Complete Selection: " + plotdata['id'][ind] ; """ # Set up Slider # print (jmolsettings) iold = 0 selectsrc = ColumnDataSource({ 'xs': [cv.pd[xcol.value][iold]], 'ys': [cv.pd[ycol.value][iold]] }) refsrc = ColumnDataSource({'x': cv.pd[xcol.value], 'y': cv.pd[ycol.value]}) slider = Slider(start=0, end=n - 1, value=0, step=1, title="Structure id", width=400) slider_callback = CustomJS( args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("cb_obj.value", ".toFixed(0)", "inds", "", jmolsettings, server_prefix, appname)) slider.js_on_change('value', slider_callback) slider.on_change('value', slider_update) #set up mouse callback = CustomJS( args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("plotsrc.selected['1d'].indices", ".min()", "plotdata['id'][inds]", "slider.value=idx", jmolsettings, server_prefix, appname)) taptool = p1.select(type=TapTool) taptool.callback = callback # p1.add_tools(HoverTool(tooltips=None, callback=callback)) #test p1.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=15, name="selectcircle") # Draw Selection on Overview Plot p2.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=8, name="mycircle") # layout stuffs spacer1 = Spacer(width=200, height=0) spacer2 = Spacer(width=200, height=190) indx = 0 xval = cv.pd[xcol.value][indx] yval = cv.pd[ycol.value][indx] #slider slider_widget = widgetbox(slider, width=400, height=50, sizing_mode='fixed') spacer = Spacer(width=300, height=50) # create buttons play_widget, download_widget = create_buttons() playpanel = Row(Spacer(width=30), play_widget, Spacer(width=30), slider_widget) plotpanel = Row( Column(p1, Spacer(height=40), Row(Spacer(width=10, height=40), download_widget)), Column(spacer1, p2, spacer2, playpanel, Spacer(height=10), table)) return plotpanel
bottom_layout = Row(children=[ date_range_slider, play_button, ]) svg_layout = Row(svg_div, width=450, height=380) arroba_layout = Row(children=[ ghost_fig, svg_layout, user_barplot, mention_barplot, ]) heatmap_layout = Column(children=[ keycluster_select, neigh_heatmap, ]) main_layout = Row(children=[ Column(children=[ grid, bottom_layout, arroba_layout, heatmap_layout, save_button, ]), ]) init_plot() # initial load of the data curdoc().add_root(main_layout)
p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_text_font_size = "10pt" p.axis.major_label_standoff = 0 p.xaxis.major_label_orientation = np.pi / 3 hover = p.select(dict(type=HoverTool)) hover.tooltips = [ ('tgt/src', '@yname, @xname'), ('attn', '@count'), ] return p if __name__ == '__main__': src = ["le", "est", "un"] tgt = ["the", "one", "is", "about"] alignment = np.array( [[0, 1, 2, 5], [2, 4, 6, 7], [9, 1, 3, 3]] ) / 10.0 print(alignment) p1 = make_alignment_figure(src, tgt, alignment) p2 = make_alignment_figure(src, tgt, alignment) p_all = Column(p1, p2) show(p)
ys=[[y0, y0, Y[i + 1], Y[i]] for i in range(len(Y[:-1]))], color=data.colors[:-1])) patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color") plot.add_glyph(patches_source, patches) line_source = ColumnDataSource(dict(x=data.dist, y=data.alt)) line = Line(x='x', y='y', line_color="black", line_width=1) plot.add_glyph(line_source, line) return plot data = prep_data(obiszow_mtb_xcm) trail = trail_map(data) altitude = altitude_profile(data) layout = Column(children=[altitude, trail]) doc = Document() doc.add_root(layout) if __name__ == "__main__": doc.validate() filename = "trail.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Trail map and altitude profile")) print("Wrote %s" % filename) view(filename)
def getHeatMap(results, parameters, bgcolor, contextdict): Yname = parameters[2] Xname = parameters[3] Xdict = BokehHeatmap.getDataParts(Xname, results) Ydict = BokehHeatmap.getDataParts(Yname, results) #colours row wise factorsx = sorted(list(Xdict)) factorsy = sorted(list(Ydict), reverse=True) rowlen = len(factorsx) collen = len(factorsy) countmatrix, maxval, observations = BokehHeatmap.getCountMatrix( Xname, Yname, factorsx, factorsy, results, bokutils.FIRST_YEAR, bokutils.LAST_YEAR) rate = [] LOWVALUE = 1 HIGHVALUE = int(float(maxval) + float(0.5)) - 1 COLOURBAR = True hcolors = bokutils.generateColorGradientHex( bokutils.hex_to_rgb(bgcolor), (255, 204, 204), 4) hcolors = ["#0C7D03", "#489D42", "#85BE81", "#C2DEC0"] textcolors = hcolors[::-1] for i, items in enumerate(factorsx): factorsx[i] = bokutils.makeLegendKey(items) for i, items in enumerate(factorsy): factorsy[i] = bokutils.makeLegendKey(items) x = [] y = [] totcount = 0 # Initialise with last year as base for col in range(collen): for row in range(rowlen): x.append(factorsx[row]) y.append(factorsy[col]) count = int(countmatrix[-1][col][row] + float(0.5)) rate.append(count) totcount = totcount + count if (totcount == 0): COLOURBAR = False HIGHVALUE = float(2) LOWVALUE = float(0.8) elif (HIGHVALUE == -1): COLOURBAR = False HIGHVALUE = 1 elif (HIGHVALUE == 0): COLOURBAR = False HIGHVALUE = float(0.9) LOWVALUE = float(0.8) elif (HIGHVALUE == 1): HIGHVALUE = float(1.9) LOWVALUE = float(0.8) textcolors = ["#C2DEC0"] hcolors = ["#0C7D03"] elif (HIGHVALUE <= LOWVALUE): HIGHVALUE = float(HIGHVALUE) - 0.1 LOWVALUE = float(HIGHVALUE - 0.1) COLOURBAR = False mapper = LinearColorMapper(palette=textcolors, high=float(HIGHVALUE), low=float(LOWVALUE), low_color="white", high_color="#45334C") source = ColumnDataSource(data=dict(x=x, y=y, rate=rate)) allsource = ColumnDataSource(data=dict(ratebyyear=countmatrix)) textmapper = LinearColorMapper(palette=hcolors[:], high=maxval) TOOLS = "hover,save" if (str(type(Xname)) == "<type 'str'>"): DXname = Xname else: DXname = Xname[0] if (str(type(Yname)) == "<type 'str'>"): DYname = Yname else: DYname = Yname[0] if (DXname == bokutils.PLOT_GLOCATION_KEY or DXname == bokutils.PLOT_GLOCATION_KEY): location = parameters[5] title = "Visualisations/Plot/X = " + location[ 1:] + " Y = " + "/".join(Yname).replace("_", " ") else: location = ", location=" + str( contextdict[bokutils.PLOT_LOCATION_KEY][0].replace("'", "")) title = "Visualisations/Plot/X = " + "/".join(Xname).replace( "_", " ") + " Y = " + "/".join(Yname).replace("_", " ") #Visualisations/Plot/X = Governance/Independent Y = Classification 2018 p = figure(title=title, x_range=factorsx, y_range=factorsy, x_axis_location="above", plot_width=900, plot_height=900, tools=TOOLS, toolbar_location='below') # border_fill_color=hcolors[0]) p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_text_font_size = "10pt" p.axis.major_label_standoff = 0 p.xaxis.major_label_orientation = pi / 3 labels = LabelSet(x='x', y='y', text='rate', level='glyph', text_color={ 'field': 'rate', 'transform': textmapper }, x_offset=-10, y_offset=-10, source=source, render_mode='canvas') p.rect(x="x", y="y", width=1, height=1, source=source, fill_color={ 'field': 'rate', 'transform': mapper }, line_color="white") if (COLOURBAR): color_bar = ColorBar( color_mapper=mapper, major_label_text_font_size="10pt", ticker=BasicTicker(desired_num_ticks=len(hcolors)), formatter=PrintfTickFormatter(format="%d"), label_standoff=6, border_line_color=hcolors[0], location=(0, 0)) p.add_layout(color_bar, 'right') p.add_layout(Title(text="X", align="center"), "below") p.add_layout(Title(text="Y", align="center"), "left") p.add_layout(Title(text="Colour to count legend", align="center"), "right") p.add_layout(labels) p.select_one(HoverTool).tooltips = [ ('Point', '@y # @x'), ('Count', '@rate '), ] slider = Slider(start=bokutils.FIRST_YEAR, end=bokutils.LAST_YEAR, value=bokutils.LAST_YEAR, step=1, title='Year', bar_color=hcolors[0]) paramsource = ColumnDataSource(data=dict(params=[rowlen, collen])) callback = CustomJS(args=dict(source=source, slider=slider, plot=p, window=None, source2=allsource, source3=paramsource), code=""" var cb; cb = function (source, slider, plot, window, source2, source3) { var al, arr, data, end, i; source = (source === undefined) ? source: source; //console.log("slider "+slider); slider = (slider === undefined) ? slider: slider; plot = (plot === undefined) ? p: plot; window = (window === undefined) ? null: window; data = source.data; var arr = source.data["rate"]; //console.log("rate"+arr); var allcounts=source2.data["ratebyyear"]; //console.log(allcounts); var params=source3.data["params"]; var rowlen=params[0]; var collen=params[1]; //console.log("arrlen"+arr.length); //console.log("rowlen"+rowlen); //console.log("collen"+collen); var startidx=slider.value - 1960; //console.log("START"+startidx); var i=0; var j=0; var tot=0; while (j < collen) { while (i < rowlen) { arr[tot] = Math.round(allcounts[startidx][j][i]); i = i + 1; tot=tot+1; } j = j + 1; i=0; } //console.log("TOT="+tot); //console.log("rate"+arr); source.change.emit(); return null; }; cb(source, slider, plot,window,source2,source3); """) slider.js_on_change('value', callback) wb = widgetbox(children=[slider], sizing_mode='scale_width') thisrow = Column(children=[p, wb], sizing_mode='scale_both') return thisrow
value='Log', options=['Log', 'Linear']) fit_methods_select = Select(title='Fitting method:', value='by eye', options=[ 'By Eye', 'Gradient Descent', 'Brute Force - I_0', 'Brute Force - R_S' ]) #Loop through callbacks and look for activity for w in [sliders[key] for key in sliders]: w.on_change('value', update_plot) Fit_button.on_click(fit_data) Save_button.on_click(save_data) #Define layout of resulting web side plots = Column(children=[plot_fit_by_eye, plot_final_fit]) plots_log = Column(children=[plot_fit_by_eye_log, plot_final_fit_log]) inputs_sliders_prefactors = Column(children=[ sliders['{0} prefactor'.format(par_name)] for par_name in parameter_names ]) inputs_sliders_exponents = Column(children=[ sliders['{0} exponent'.format(par_name)] for par_name in parameter_names if par_name != 'Ideality Factor' ]) inputs_buttons = Column( children=[Fit_button, Save_button, methods_select, fit_methods_select]) inputs_sliders = Row( children=[inputs_sliders_prefactors, inputs_sliders_exponents]) inputs = Column(children=[inputs_sliders, inputs_buttons]) curdoc().add_root(Row(children=[plots, plots_log, inputs]))
def download_extended(): from bokeh.io import output_file, show from bokeh.resources import CDN, INLINE from bokeh.embed import file_html from bokeh.embed import autoload_static from bokeh.resources import INLINE from jinja2 import Template import jinja2 import os, zipfile from shutil import copyfile global cv, indx, controls, selectsrc, xval, yval, plt_name, xcol, ycol, ccol, rcol, jmolsettings, appname, server_prefix, Periodic_color title = 'Sketchmap for ' + appname + ': Colored with ' + ccol.value + ' Point Size Variation: ' + rcol.value Periodic_color = False style = 'smapstyle' if len(grid.active) > 0: style = None if len(periodic_checkbox.active) > 0: Periodic_color = True p1, p2, table, plotdatasrc = cv.bkplot(xcol.value, ycol.value, ccol.value, radii=rcol.value, palette=plt_name.value, ps=pss.value, minps=pss.value / 2., alpha=alphas.value, pw=700, ph=600, Hover=True, toolbar_location="above", table=True, table_width=550, table_height=400, title='', Periodic_color=Periodic_color, return_datasrc=True, frac_load=frac.value, style=style, marker=[marker.value]) # Set up mouse selection callbacks # The following code is very tricky to understand properly. # the %s are the function or variable to pass from python depending on the slider callback or mouse callback. # One could write 3 seperate callbacks to connect slider,jmol and mouse selection but this way it is more compact ! code = """ var refdata = ref.data; var data = source.data; var plotdata=plotsrc.data; var ind = %s ; Array.prototype.min = function() { return Math.min.apply(null, this); }; var inds =ind%s; var idx=plotdata['id'][inds]; var xs = refdata['x'][inds]; var ys = refdata['y'][inds]; data['xs'] = [xs]; data['ys'] = [ys]; data=refdata[inds]; source.change.emit(); %s; var str = "" + idx; var pad = "000000"; var indx = pad.substring(0, pad.length - str.length) + str; var settings= "%s" ; var file= "javascript:Jmol.script(jmolApplet0," + "'set frank off; load %s/static/%s-structures/set."+ indx+ ".xyz ;" + settings + "')" ; location.href=file; localStorage.setItem("indexref",indx); document.getElementById("p1").innerHTML = " Selected frame:"+ indx ; """ # Set up Slider #print (jmolsettings) iold = 0 selectsrc = ColumnDataSource({ 'xs': [cv.pd[xcol.value][iold]], 'ys': [cv.pd[ycol.value][iold]] }) refsrc = ColumnDataSource({'x': cv.pd[xcol.value], 'y': cv.pd[ycol.value]}) slider = Slider(start=0, end=n - 1, value=0, step=1, title="Primary Selection", width=400) slider_callback = CustomJS( args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("cb_obj.value", ".toFixed(0)", "", jmolsettings, '.', appname)) slider.js_on_change('value', slider_callback) slider.on_change('value', slider_update) #set up mouse callback = CustomJS(args=dict(source=selectsrc, ref=refsrc, slider=slider, plotsrc=plotdatasrc), code=code % ("plotsrc.selected['1d'].indices", ".min()", "slider.value=idx", jmolsettings, '.', appname)) taptool = p1.select(type=TapTool) taptool.callback = callback p1.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=15, name="selectcircle") # Draw Selection on Overview Plot p2.circle('xs', 'ys', source=selectsrc, fill_alpha=0.9, fill_color="blue", line_color='black', line_width=1, size=8, name="mycircle") # spacer1 = Spacer(width=200, height=20) # spacer2 = Spacer(width=200, height=170) # plotpanel=Row(p1,Column(spacer1,p2,spacer2,table)) # layout stuffs spacer1 = Spacer(width=200, height=30) spacer2 = Spacer(width=200, height=170) indx = 0 xval = cv.pd[xcol.value][indx] yval = cv.pd[ycol.value][indx] #slider slider_widget = widgetbox(slider, width=400, height=50, sizing_mode='fixed') spacer = Spacer(width=300, height=50) # create buttons # play_widget,download_widget=create_buttons() playpanel = Row(Spacer(width=80), slider_widget) plotpanel = Row( Column(p1, Spacer(height=40)), Column(spacer1, p2, spacer2, playpanel, Spacer(height=50), table)) # Get JavaScript/HTML resources js, tag = autoload_static(plotpanel, INLINE, "") if (sys.version_info[0] < 3): js = js.decode("utf-8") #need this for python 2.7 but not python 3.3 # print "jS",js # print "TAG",tag # return css = [] for f in ["w3"]: css.append("./static/css/" + f + '.css') templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = appname + "/templates/offline-template.html" #print TEMPLATE_FILE template = templateEnv.get_template(TEMPLATE_FILE) html = template.render(js_resources=js, div=tag, jmolsettings=jmolsettings, appname=appname, server_prefix='.', css_files=css, title=title) fbase = appname + '-sketchmap_' + xcol.value + '-' + ycol.value + '-' + ccol.value + '-' + rcol.value + '-' + plt_name.value + '-f' + str( frac.value) + '-ps' + str(pss.value) + 'a' + str(alphas.value) if Periodic_color: fbase = fbase + '_Periodic' fname = os.path.join(server_prefix, 'static', fbase + '.html') zname = os.path.join(server_prefix, 'static', fbase + '.zip') # fname=fbase+'.html' if (sys.version_info[0] < 3): f = open(fname, 'w') #python 2.7 else: f = open(fname, 'wb') #python 3.3 f.write(html.encode("utf-8")) f.close() # prepare zip file from template if (os.path.isfile(zname)): os.remove(zname) copyfile( os.path.join(server_prefix, 'static', appname + '-static-offline.zip'), zname) zip = zipfile.ZipFile(zname, 'a') zip.write(fname, fbase + '.html') # zip.write(os.path.join(server_prefix,'static','README'),'README') zip.close() return CustomJS(code=""" alert('Extended offline html file might fail to load on your browser. Refer to README file in download for solution. '); window.open("%s",title="%s"); """ % (zname, fbase))
label_data = ColumnDataSource( data=dict(x=[1, 2, 3], y=[0, 0, 0], t=['Original', 'Normal', 'Uniform'])) label_set = LabelSet(x='x', y='y', text='t', y_offset=-4, source=label_data, render_mode='css', text_baseline="top", text_align='center') p.add_layout(label_set) callback = CustomJS(args=dict(source=source, normal=normal, uniform=uniform), code=""" data=source.get('data') for (i=0; i < data['y'].length; i++) { data['xn'][i] = normal.compute(data['x'][i]+1) } for (i=0; i < data['y'].length; i++) { data['xu'][i] = uniform.compute(data['x'][i]+2) } source.trigger('change') """) button = Button(label='Press to apply Jitter!', callback=callback) output_file("transform_jitter.html", title="Example Jitter Transform") show(Column(WidgetBox(button, width=300), p))
div.background = `rgb(${r}, ${g}, ${b})` """) red.js_on_change('value', cb) green.js_on_change('value', cb) blue.js_on_change('value', cb) return Row(children=[red, green, blue, div]) sliders = Row(children=[ Column(children=[ slider, disabled_slider, range_slider, date_slider, date_range_slider, only_value_slider, no_title_slider, ]), color_picker(), ]) doc = Document() doc.add_root(sliders) if __name__ == "__main__": doc.validate() filename = "sliders.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "sliders"))
def bkapp(dfile, pcol, app_name, server_static_root, title='Sketch-map', pointsize=10, jmol_settings=""): global cv, controls, selectsrc, columns, button, slider, n, xcol, ycol, ccol, rcol, plt_name, indx, ps, jmolsettings, appname, lay, server_prefix, periodic_checkbox, pss, frac, alphas, grid, marker appname = app_name server_prefix = server_static_root ps = pointsize jmolsettings = jmol_settings #initialise data datafile = join(appname, 'data', dfile) cv = smap(name=title) cv.read(datafile) n = len(cv.data) columns = [i for i in cv.columns] # set up selection options tcol = pcol[0] - 1 xcol = Select(title='X-Axis', value=columns[tcol], options=columns, width=50) xcol.on_change('value', update) tcol = pcol[1] - 1 ycol = Select(title='Y-Axis', value=columns[tcol], options=columns, width=50) ycol.on_change('value', update) roptions = ['None'] for option in columns: roptions.append(option) rcol = Select(title='Size', value='None', options=roptions, width=50) rcol.on_change('value', update) if (len(pcol) > 2): tcol = pcol[2] - 1 ccol = Select(title='Color', value=columns[tcol], options=roptions, width=50) else: ccol = Select(title='Color', value='None', options=roptions, width=50) ccol.on_change('value', update) marker_options = [ 'circle', 'diamond', 'triangle', 'square', 'asterisk', 'cross', 'inverted_triangle', 'variable' ] marker = Select(title='Marker', value='circle', options=marker_options, width=50) marker.on_change('value', update) periodic_checkbox = CheckboxGroup(labels=["Periodic Palette"], active=[]) periodic_checkbox.on_change('active', update) grid = CheckboxGroup(labels=["Show Axis"], active=[0]) grid.on_change('active', update) plt_name = Select(title='Palette', width=50, value='Inferno256', options=[ "Magma256", "Plasma256", "Spectral6", "Inferno256", "Viridis256", "Greys256", "cosmo" ]) plt_name.on_change('value', update) pss = Slider(start=0, end=50, value=ps, step=1, callback_policy='mouseup', title="Point Size", width=150) pss.on_change('value', update) frac = Slider(start=0, end=1, value=min(1.0, round(3000. / n, 1)), step=0.1, callback_policy='mouseup', title="Fraction Of Data Loaded", width=200) frac.on_change('value', update) alphas = Slider(start=0, end=1, value=0.75, step=0.1, callback_policy='mouseup', title="Point Alpha", width=150) alphas.on_change('value', update) xm = widgetbox(xcol, width=170, sizing_mode='fixed') ym = widgetbox(ycol, width=170, sizing_mode='fixed') cm = widgetbox(ccol, width=170, sizing_mode='fixed') mm = widgetbox(marker, width=170, sizing_mode='fixed') cp = widgetbox(periodic_checkbox, width=100, sizing_mode='fixed') gc = widgetbox(grid, width=100, sizing_mode='fixed') rm = widgetbox(rcol, width=170, sizing_mode='fixed') pm = widgetbox(plt_name, width=170, sizing_mode='fixed') psw = widgetbox(pss, width=210, height=50, sizing_mode='fixed') asl = widgetbox(alphas, width=210, height=50, sizing_mode='fixed') fw = widgetbox(frac, width=270, height=50, sizing_mode='fixed') controls = Column( Row(xm, ym, cm, rm, pm, mm, width=1050, sizing_mode='scale_width'), Row(gc, fw, psw, asl, cp, width=1050, sizing_mode='fixed')) # create plot and slider plotpanel = create_plot() # full layout lay = layout([ [controls], [plotpanel], ], sizing_mode='fixed') return lay