new_data['sizes'] = size_interpolated new_data['ridership'] = list( df_all[df_all['temp'] == temps[idx]]['avg_trip_count']) new_data['x'] = ds.data['x'] new_data['y'] = ds.data['y'] new_data['stationname'] = ds.data['stationname'] ds.data = new_data #save every iteration to .png file #export_png(p, filename = '{0}/gif/plot_{1}.png'.format(path, i)) i += 1 button = Button(label="Start") button.on_click(start_graph) temp_button = Button(label=str(int(temps[0]))) loc = (-9756040, 5148472) mytext = Label(x=loc[0], y=loc[1], text='Temp: 30\N{DEGREE SIGN}F', text_font_size='25pt') p.add_layout(mytext) beaches = [ 'Lake Shore Dr & North Blvd', 'Streeter Dr & Grand Ave', 'Lake Shore Dr & Monroe St', 'Theater on the Lake', 'Michigan Ave & Oak St' ]
def __init__(self, button_kwargs): super().__init__() self.button = Button(**button_kwargs) self.layout = self.button
def __init__(self, label, callback): self.ref = "button-" + make_id() self.obj = Button(label=label, css_classes=[self.ref]) self.obj.js_on_event('button_click', callback)
#Selections and Sliders day__select = Select(title = "Day", value = "Friday", width=200, options = days) time_select = Select(title = "Time", value = dayTimesPassedToCreatePark[0], width = 200, options = dayTimesPassedToCreatePark) scan_next_second_button = Button(label="Scan Next Second", button_type="success") scan_prev_hour_button = Button(label="Scan Prev Second", button_type="success") #Functionality og Selectors, Sliders, and Buttons def updateDay(): pass def updateTime(): pass def goToNextSecond(): currentSecondIndex = getCurrentSecondIndex() if currentSecondIndex < len(dayTimesPassedToCreatePark)-1:
def create(palm): connected = False current_message = None stream_t = 0 doc = curdoc() # Streaked and reference waveforms plot waveform_plot = Plot( title=Title(text="eTOF waveforms"), x_range=DataRange1d(), y_range=DataRange1d(), plot_height=PLOT_CANVAS_HEIGHT, plot_width=PLOT_CANVAS_WIDTH, toolbar_location="right", ) # ---- tools waveform_plot.toolbar.logo = None waveform_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()) # ---- axes waveform_plot.add_layout(LinearAxis(axis_label="Photon energy, eV"), place="below") waveform_plot.add_layout(LinearAxis(axis_label="Intensity", major_label_orientation="vertical"), place="left") # ---- grid lines waveform_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) waveform_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- line glyphs waveform_source = ColumnDataSource( dict(x_str=[], y_str=[], x_ref=[], y_ref=[])) waveform_ref_line = waveform_plot.add_glyph( waveform_source, Line(x="x_ref", y="y_ref", line_color="blue")) waveform_str_line = waveform_plot.add_glyph( waveform_source, Line(x="x_str", y="y_str", line_color="red")) # ---- legend waveform_plot.add_layout( Legend(items=[("reference", [waveform_ref_line]), ("streaked", [waveform_str_line])])) waveform_plot.legend.click_policy = "hide" # Cross-correlation plot xcorr_plot = Plot( title=Title(text="Waveforms cross-correlation"), x_range=DataRange1d(), y_range=DataRange1d(), plot_height=PLOT_CANVAS_HEIGHT, plot_width=PLOT_CANVAS_WIDTH, toolbar_location="right", ) # ---- tools xcorr_plot.toolbar.logo = None xcorr_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()) # ---- axes xcorr_plot.add_layout(LinearAxis(axis_label="Energy shift, eV"), place="below") xcorr_plot.add_layout(LinearAxis(axis_label="Cross-correlation", major_label_orientation="vertical"), place="left") # ---- grid lines xcorr_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) xcorr_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- line glyphs xcorr_source = ColumnDataSource(dict(lags=[], xcorr=[])) xcorr_plot.add_glyph(xcorr_source, Line(x="lags", y="xcorr", line_color="purple")) # ---- vertical span xcorr_center_span = Span(location=0, dimension="height") xcorr_plot.add_layout(xcorr_center_span) # Delays plot pulse_delay_plot = Plot( title=Title(text="Pulse delays"), x_range=DataRange1d(), y_range=DataRange1d(), plot_height=PLOT_CANVAS_HEIGHT, plot_width=PLOT_CANVAS_WIDTH, toolbar_location="right", ) # ---- tools pulse_delay_plot.toolbar.logo = None pulse_delay_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()) # ---- axes pulse_delay_plot.add_layout(LinearAxis(axis_label="Pulse number"), place="below") pulse_delay_plot.add_layout( LinearAxis(axis_label="Pulse delay (uncalib), eV", major_label_orientation="vertical"), place="left", ) # ---- grid lines pulse_delay_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) pulse_delay_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- line glyphs pulse_delay_source = ColumnDataSource(dict(x=[], y=[])) pulse_delay_plot.add_glyph(pulse_delay_source, Line(x="x", y="y", line_color="steelblue")) # Pulse lengths plot pulse_length_plot = Plot( title=Title(text="Pulse lengths"), x_range=DataRange1d(), y_range=DataRange1d(), plot_height=PLOT_CANVAS_HEIGHT, plot_width=PLOT_CANVAS_WIDTH, toolbar_location="right", ) # ---- tools pulse_length_plot.toolbar.logo = None pulse_length_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()) # ---- axes pulse_length_plot.add_layout(LinearAxis(axis_label="Pulse number"), place="below") pulse_length_plot.add_layout( LinearAxis(axis_label="Pulse length (uncalib), eV", major_label_orientation="vertical"), place="left", ) # ---- grid lines pulse_length_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) pulse_length_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- line glyphs pulse_length_source = ColumnDataSource(dict(x=[], y=[])) pulse_length_plot.add_glyph(pulse_length_source, Line(x="x", y="y", line_color="steelblue")) # Image buffer slider def buffer_slider_callback(_attr, _old, new): message = receiver.data_buffer[new] doc.add_next_tick_callback(partial(update, message=message)) buffer_slider = Slider( start=0, end=59, value=0, step=1, title="Buffered Image", callback_policy="throttle", callback_throttle=500, ) buffer_slider.on_change("value", buffer_slider_callback) # Connect toggle button def connect_toggle_callback(state): nonlocal connected if state: connected = True connect_toggle.label = "Connecting" connect_toggle.button_type = "default" else: connected = False connect_toggle.label = "Connect" connect_toggle.button_type = "default" connect_toggle = Toggle(label="Connect", button_type="default", width=250) connect_toggle.on_click(connect_toggle_callback) # Intensity stream reset button def reset_button_callback(): nonlocal stream_t stream_t = 1 # keep the latest point in order to prevent full axis reset reset_button = Button(label="Reset", button_type="default", width=250) reset_button.on_click(reset_button_callback) # Stream update coroutine async def update(message): nonlocal stream_t if connected and receiver.state == "receiving": y_ref = message[receiver.reference].value[np.newaxis, :] y_str = message[receiver.streaked].value[np.newaxis, :] delay, length, debug_data = palm.process({ "0": y_ref, "1": y_str }, debug=True) prep_data, lags, corr_res_uncut, _ = debug_data waveform_source.data.update( x_str=palm.energy_range, y_str=prep_data["1"][0, :], x_ref=palm.energy_range, y_ref=prep_data["0"][0, :], ) xcorr_source.data.update(lags=lags, xcorr=corr_res_uncut[0, :]) xcorr_center_span.location = delay[0] pulse_delay_source.stream({ "x": [stream_t], "y": [delay] }, rollover=120) pulse_length_source.stream({ "x": [stream_t], "y": [length] }, rollover=120) stream_t += 1 # Periodic callback to fetch data from receiver async def internal_periodic_callback(): nonlocal current_message if waveform_plot.inner_width is None: # wait for the initialization to finish, thus skip this periodic callback return if connected: if receiver.state == "polling": connect_toggle.label = "Polling" connect_toggle.button_type = "warning" elif receiver.state == "stopped": connect_toggle.label = "Not available" connect_toggle.button_type = "danger" elif receiver.state == "receiving": connect_toggle.label = "Receiving" connect_toggle.button_type = "success" # Set slider to the right-most position if len(receiver.data_buffer) > 1: buffer_slider.end = len(receiver.data_buffer) - 1 buffer_slider.value = len(receiver.data_buffer) - 1 if receiver.data_buffer: current_message = receiver.data_buffer[-1] doc.add_next_tick_callback(partial(update, message=current_message)) doc.add_periodic_callback(internal_periodic_callback, 1000) # assemble tab_layout = column( row( column(waveform_plot, xcorr_plot), Spacer(width=30), column(buffer_slider, row(connect_toggle, reset_button)), ), row(pulse_delay_plot, Spacer(width=10), pulse_length_plot), ) return Panel(child=tab_layout, title="Stream")
x_range,y_range=([-9350837,-8794239], [2875744,3632749]) #bounding box for Florida plot=figure(x_range=x_range,y_range=y_range,x_axis_type='mercator',y_axis_type='mercator',plot_width=500,tools='pan,wheel_zoom,reset',sizing_mode='fixed',active_scroll='wheel_zoom') plot.add_tile(tile_provider) # seed with color PlotStation=plot.circle('Xmerc','Ymerc',source=cdsInitStations,fill_color='color',size=5,fill_alpha=0.8,line_width=0.5) plot.add_tools(HoverTool(renderers=[PlotStation],tooltips=[('Station','@StationAddress'),('Supplier','@TName'),('cpg','@cpg')])) PlotTerminal=plot.diamond('Xmerc','Ymerc',source=cdsTerminals,fill_color='color',size=15,fill_alpha=0.8,line_width=0.5) plot.add_tools(HoverTool(renderers=[PlotTerminal],tooltips=[('Terminal','@terminalname'),('Trucks','@Trucks'),('Demand (kgal/mo)','@Demand'),('Stations Supplied','@Stations'),('Trips','@Trips')])) #create page title divheader=Div(text='<H2 style="white-space: nowrap">Florida Gasoline Optimizer - adjust inputs and click Optimize</H2>') #create placeholder for objfn value objtext='objective not calculated' divright = Div(text=objtext, style={'font-size': '150%', 'color': 'red'}) #create Optimize button OptButton = Button(label='Optimize',sizing_mode='fixed') #create copyright script (add link to license file) divcopy=Div(text='Copyright (c) 2020 Francis X. Kelly under License') #set up output table columns = [TableColumn(field="terminalname", title="Terminal"),TableColumn(field="Trucks", title="Trucks",formatter=NumberFormatter(format='0.00')), TableColumn(field="Stations", title="Stations supplied",formatter=NumberFormatter(format='0')),TableColumn(field="Trips", title="# of trips",formatter=NumberFormatter(format='0')),TableColumn(field="Demand", title="Demand kgal/mo",formatter=NumberFormatter(format='0'))] OutputTable=DataTable(source=cdsTerminals, columns=columns, width=600, height=600,index_position=None,sizing_mode='fixed') CapacitySliderHeader='<b>Terminal min/max capacity, gal/mo</b>' divCSH = Div(text=CapacitySliderHeader, style={'font-size': '100%', 'color': 'black'},sizing_mode='fixed') sliders=[] for rowi in dftd.itertuples(): CapacitySlider = RangeSlider(start=0, end=10000000, value=(rowi.Tmin,rowi.capacity), step=100000, title=rowi.terminalname, bar_color=rowi.color,format='0,0',sizing_mode='fixed') sliders.append(CapacitySlider) CostSliderHeader='<b>Supply premium(+)/discount(-), cpg</b>' divCostSH = Div(text=CostSliderHeader, style={'font-size': '100%', 'color': 'black'},sizing_mode='fixed')
doc = curdoc() x = range(3) fig1 = figure(plot_width=250, plot_height=250) fig1.renderers = [] fig2 = figure(plot_width=250, plot_height=250) fig2.renderers = [] dum_fig = figure(plot_width=250, plot_height=500, outline_line_alpha=0) legend = Legend(click_policy='hide', border_line_alpha=0, location='top_left') dum_fig.renderers = [legend] # set a range of values that will not include any data dum_fig.x_range.end = 1005 dum_fig.x_range.start = 1000 button = Button(label="add a line", width=100) def add_line(): colo = choice(Category20_20) randname = str(random()) line1 = fig1.line(x, [random() for i in x], color=colo, line_width=3, legend=randname) line2 = fig2.line(x, [random() for i in x], color=colo, line_width=3) line1.on_change('visible', partial(share_visible, line1=line1, line2=line2)) update_legend(line1)
def __init__(self, server, doc=None, **kwargs): if doc is not None: self.doc = weakref.ref(doc) self.server = server self.log = self.server.io_loop.profile self.start = None self.stop = None self.ts = {'count': [], 'time': []} self.state = profile.get_profile(self.log) data = profile.plot_data(self.state, profile_interval) self.states = data.pop('states') self.profile_plot, self.source = profile.plot_figure(data, **kwargs) changing = [False] # avoid repeated changes from within callback @without_property_validation def cb(attr, old, new): if changing[0]: return with log_errors(): if isinstance(new, list): # bokeh >= 1.0 selected = new else: selected = new['1d']['indices'] try: ind = selected[0] except IndexError: return data = profile.plot_data(self.states[ind], profile_interval) del self.states[:] self.states.extend(data.pop('states')) changing[0] = True # don't recursively trigger callback self.source.data.update(data) if isinstance(new, list): # bokeh >= 1.0 self.source.selected.indices = old else: self.source.selected = old changing[0] = False if BOKEH_VERSION >= '1.0.0': self.source.selected.on_change('indices', cb) else: self.source.on_change('selected', cb) self.ts_source = ColumnDataSource({'time': [], 'count': []}) self.ts_plot = figure(title='Activity over time', height=100, x_axis_type='datetime', active_drag='xbox_select', y_range=[0, 1 / profile_interval], tools='xpan,xwheel_zoom,xbox_select,reset', **kwargs) self.ts_plot.line('time', 'count', source=self.ts_source) self.ts_plot.circle('time', 'count', source=self.ts_source, color=None, selection_color='orange') self.ts_plot.yaxis.visible = False self.ts_plot.grid.visible = False def ts_change(attr, old, new): with log_errors(): try: selected = self.ts_source.selected.indices except AttributeError: selected = self.ts_source.selected['1d']['indices'] if selected: start = self.ts_source.data['time'][min(selected)] / 1000 stop = self.ts_source.data['time'][max(selected)] / 1000 self.start, self.stop = min(start, stop), max(start, stop) else: self.start = self.stop = None self.trigger_update() if BOKEH_VERSION >= '1.0.0': self.ts_source.selected.on_change('indices', ts_change) else: self.ts_source.on_change('selected', ts_change) self.reset_button = Button(label="Reset", button_type="success") self.reset_button.on_click(lambda: self.update(self.state)) self.update_button = Button(label="Update", button_type="success") self.update_button.on_click(self.trigger_update) self.root = column( row(self.reset_button, self.update_button, sizing_mode='scale_width'), self.profile_plot, self.ts_plot, **kwargs)
p = figure( tools= "pan,wheel_zoom,zoom_in,zoom_out,reset,tap,lasso_select,box_select,box_zoom,undo,redo" ) p.scatter(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None) # Add a div to display events and a button to trigger button click events div = Div(width=1000) button = Button(label="Button", button_type="success", width=300) layout = column(button, row(p, div)) ## Register event callbacks # Button event button.js_on_event(events.ButtonClick, display_event(div)) # LOD events p.js_on_event(events.LODStart, display_event(div)) p.js_on_event(events.LODEnd, display_event(div)) # Point events point_attributes = ['x', 'y', 'sx', 'sy'] p.js_on_event(events.Tap, display_event(div, attributes=point_attributes)) p.js_on_event(events.DoubleTap, display_event(div,
plot_width=400, plot_height=400, x_axis_type=None, y_axis_label='y_i value') plot2.line(x='xs', y='ys', source=source4) plot2.scatter('xs', 'ys', color='colors', source=source4, line_width=3, line_alpha=0.6) ticker = SingleIntervalTicker(interval=1, num_minor_ticks=0) xaxis = LinearAxis(ticker=ticker, axis_label='y index') plot2.add_layout(xaxis, 'below') resample_Button = Button(label="Resample") covariance_slider = Slider(start=0.0, end=.99, value=0, step=.01, title="Covariance") x1_slider = Slider(start=-2.5, end=2.5, value=0, step=.1, title="y1") resample_Button.on_click(lambda: resample_wrapper()) covariance_slider.on_change('value', lambda attr, old, new: update_all()) x1_slider.on_change('value', lambda attr, old, new: update_xs()) controls = [covariance_slider, x1_slider, resample_Button] inputs = widgetbox(*controls, sizing_mode='fixed') l = gridplot([[inputs], [plot, plot2]])
plot = figure(plot_height=400, plot_width=400, title="my sine wave", tools="crosshair,pan,reset,save,wheel_zoom", 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) logout = Button(label="logout") logout.js_on_click( CustomJS(code="window.location.href='%s'" % curdoc().session_context.logout_url)) # 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 __init__(self, server, doc=None, **kwargs): if doc is not None: self.doc = weakref.ref(doc) self.server = server self.log = self.server.io_loop.profile self.start = None self.stop = None self.ts = {"count": [], "time": []} self.state = profile.get_profile(self.log) data = profile.plot_data(self.state, profile_interval) self.states = data.pop("states") self.profile_plot, self.source = profile.plot_figure(data, **kwargs) changing = [False] # avoid repeated changes from within callback @without_property_validation def cb(attr, old, new): if changing[0] or len(new) == 0: return with log_errors(): data = profile.plot_data(self.states[new[0]], profile_interval) del self.states[:] self.states.extend(data.pop("states")) changing[0] = True # don't recursively trigger callback update(self.source, data) self.source.selected.indices = old changing[0] = False self.source.selected.on_change("indices", cb) self.ts_source = ColumnDataSource({"time": [], "count": []}) self.ts_plot = figure( title="Activity over time", height=150, x_axis_type="datetime", active_drag="xbox_select", tools="xpan,xwheel_zoom,xbox_select,reset", sizing_mode="stretch_width", toolbar_location="above", ) self.ts_plot.line("time", "count", source=self.ts_source) self.ts_plot.circle("time", "count", source=self.ts_source, color=None, selection_color="orange") self.ts_plot.yaxis.visible = False self.ts_plot.grid.visible = False def ts_change(attr, old, new): with log_errors(): selected = self.ts_source.selected.indices if selected: start = self.ts_source.data["time"][min(selected)] / 1000 stop = self.ts_source.data["time"][max(selected)] / 1000 self.start, self.stop = min(start, stop), max(start, stop) else: self.start = self.stop = None self.trigger_update() self.ts_source.selected.on_change("indices", ts_change) self.reset_button = Button(label="Reset", button_type="success") self.reset_button.on_click(lambda: self.update(self.state)) self.update_button = Button(label="Update", button_type="success") self.update_button.on_click(self.trigger_update) self.root = column( row(self.reset_button, self.update_button, sizing_mode="scale_width"), self.profile_plot, self.ts_plot, **kwargs, )
def __init__(self, server, doc=None, **kwargs): if doc is not None: self.doc = weakref.ref(doc) try: self.key = doc.session_context.request.arguments.get( "key", None) except AttributeError: self.key = None if isinstance(self.key, list): self.key = self.key[0] if isinstance(self.key, bytes): self.key = self.key.decode() self.task_names = ["All", self.key] if self.key else ["All"] else: self.key = None self.task_names = ["All"] self.server = server self.start = None self.stop = None self.ts = {"count": [], "time": []} self.state = profile.create() data = profile.plot_data(self.state, profile_interval) self.states = data.pop("states") self.profile_plot, self.source = profile.plot_figure(data, **kwargs) changing = [False] # avoid repeated changes from within callback @without_property_validation def cb(attr, old, new): if changing[0] or len(new) == 0: return with log_errors(): data = profile.plot_data(self.states[new[0]], profile_interval) del self.states[:] self.states.extend(data.pop("states")) changing[0] = True # don't recursively trigger callback update(self.source, data) self.source.selected.indices = old changing[0] = False self.source.selected.on_change("indices", cb) self.ts_source = ColumnDataSource({"time": [], "count": []}) self.ts_plot = figure( title="Activity over time", height=150, x_axis_type="datetime", active_drag="xbox_select", tools="xpan,xwheel_zoom,xbox_select,reset", sizing_mode="stretch_width", toolbar_location="above", ) self.ts_plot.line("time", "count", source=self.ts_source) self.ts_plot.circle("time", "count", source=self.ts_source, color=None, selection_color="orange") self.ts_plot.yaxis.visible = False self.ts_plot.grid.visible = False def ts_change(attr, old, new): with log_errors(): selected = self.ts_source.selected.indices if selected: start = self.ts_source.data["time"][min(selected)] / 1000 stop = self.ts_source.data["time"][max(selected)] / 1000 self.start, self.stop = min(start, stop), max(start, stop) else: self.start = self.stop = None self.trigger_update(update_metadata=False) self.ts_source.selected.on_change("indices", ts_change) self.reset_button = Button(label="Reset", button_type="success") self.reset_button.on_click(lambda: self.update(self.state)) self.update_button = Button(label="Update", button_type="success") self.update_button.on_click(self.trigger_update) self.select = Select(value=self.task_names[-1], options=self.task_names) def select_cb(attr, old, new): if new == "All": new = None self.key = new self.trigger_update(update_metadata=False) self.select.on_change("value", select_cb) self.root = column( row( self.select, self.reset_button, self.update_button, sizing_mode="scale_width", height=250, ), self.profile_plot, self.ts_plot, **kwargs, )
from bokeh.models import Button, ColumnDataSource from bokeh.plotting import figure x = [3, 4, 6, 12, 10, 1] y = [7, 1, 3, 4, 1, 6] source = ColumnDataSource(data=dict(x=x, y=y)) plot_figure = figure(height=450, width=600, tools="save,reset", x_range=[0, 14], y_range=[0, 12], toolbar_location="below") plot_figure.scatter('x', 'y', source=source, size=10) button = Button(label="Click to set plot title", button_type="success") def button_click(): plot_figure.title.text = 'Button Clicked' button.on_click(button_click) layout = row(button, plot_figure) curdoc().add_root(layout) curdoc().title = "Button Bokeh Server"
max_cutoff_slider = Slider(title="MaxCutoff", value=np.max(haar_coef), start=0.0, end=np.max(haar_coef), step=0.01) start_reconstruct = Slider(title='Reconstruct Start', value=0, start=0, end=2**j, step=1) stop_reconstruct = Slider(title='Reconstruct Stop', value=2**j, start=0, end=2**j, step=1) recompute_button = Button(label="Recompute") signal_select = Select(title="Source", value="Lenna-64.png", options=list(images)) def update_data(): global current_source global y global j global haar_coef global comp_y global comp_haar_coef min_cutoff = min_cutoff_slider.value max_cutoff = max_cutoff_slider.value rec_start = start_reconstruct.value
'qty': '100' } socketIO.emit('submitOrder', newOrder) print(newOrder) ## ORDERING def button_buy(): newOrder = { 'type': 'NewOrder', 'clientOrderId': str(uuid.uuid4()), 'symbol': 'AAPL', 'buySell': 'BUY', 'qty': '100' } socketIO.emit('submitOrder', newOrder) print(newOrder) # add a button widget and configure with the call back sell_button = Button(label="Sell") sell_button.on_click(button_sell) buy_button = Button(label="Buy") buy_button.on_click(button_buy) # put the button and plot in a layout and add to the document doc.add_root(column(data_table, sell_button, buy_button)) ## # model = joblib.load()
_elements = ['Al','Au','Sc', 'Ti','V','Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Rb', 'Sr','Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag','Cd', 'Cs','Ba','Hf','Ta','W','Re','Os','Ir','Pt','Hg'] element = Select(title='Metals 1', value='Pt', options=_elements) element.on_change('value', lambda attr, old, new: CF1.update_element()) properties = ['B','dB','V0','E0'] prop = Select(title='Properties 1', value='E0', options=properties) prop.on_change('value', lambda attr, old, new: CF1.update_prop()) #range_slider_lowK1 = RangeSlider(start=-5, end=5, value=(-5,5), step=1, title="Low K-point") #range_slider_medK1 = RangeSlider(start=-5, end=5, value=(-5,5), step=1, title="Medium K-point") #range_slider_highK1 = RangeSlider(start=-5, end=5, value=(-5,5), step=1, title="High K-point") apply_crossfilter = Button(label='Values vs. Kpoints') apply_crossfilter.on_click(CF1.plot_prec_value1) apply_precision = Button(label='Inter-Property Precision') apply_precision.on_click(CF1.multi_precisions_correlate1) clean_crossfilter = Button(label='Clear') clean_crossfilter.on_click(CF1.clear_crossfilter1) CF1.query_dict={'code':'VASP','exchange':'PBE',\ 'structure':'fcc','element':'Pt','properties':'E0'} #### PLOT 2 codes2 = ['DMol3','VASP']
param_source.data['update_delay'][0]) # Set up param_source param_source = _init_param_source() # Set up data source data_source = _init_data_source() # Set up figure fig = figure() fig.line(source=data_source, x='x', y='y') fig.line(source=data_source, x='x', y='avg', line_color="red") # Set up pause button btn = Button(label='Pause') btn.on_click(pause) # Set up slider to change update speed def _change_update_delay(attr, old, new): logger.debug('Slider has been moved, new {}: {}'.format(attr, new)) param_source.data['update_delay'][0] = new curdoc().remove_periodic_callback(update) curdoc().add_periodic_callback(update, param_source.data['update_delay'][0]) delay_slider = Slider(start=10, end=100, value=50,
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.from_coffeescript(args=dict(source=source, normal=normal, uniform=uniform), code=""" data = source.get 'data' for i in [0...data['y'].length] data['xn'][i] = normal.compute(data['x'][i] + 1) for i in [0...data['y'].length] data['xu'][i] = uniform.compute(data['x'][i] + 2) source.change.emit() """) button = Button(label='Press to apply Jitter!', callback=callback) output_file("transform_jitter_coffee.html", title="Example Jitter Transform (CoffeeScript callback)") show(Column(WidgetBox(button, width=300), p))
def __init__( self, datasets: Sequence[DatasetSection], lang_freqs_by_dataset: Mapping[str, Counter[str]], query_freqs_by_dataset: Mapping[str, Counter[str]], url_netloc_freqs_by_dataset: Mapping[str, Counter[str]], ): self._datasets = datasets self._lang_freqs = lang_freqs_by_dataset self._query_freqs = query_freqs_by_dataset self._url_netloc_freqs = url_netloc_freqs_by_dataset self.dataset = self._datasets[0] self._hide_button = Button(label="+", button_type="primary", sizing_mode="fixed", width=30, height=30) self._hide_button.on_click(lambda _event: self._on_click_hide_button()) # General: self._dataset_name = Select( title="Dataset:", options=[dataset.name for dataset in self._datasets], value=self._datasets[0].name, ) self._dataset_name.on_change( "value", lambda _attr, _old, _new: self._on_change_name()) self._lang = Select(title="Language:") self._cooccur_words = TextInput( title="Words documents must contain (space separated):", value="", ) # NASTY-specific: self._search_filter = Select( title="Search filter:", options=["*"] + [search_filter.name for search_filter in SearchFilter], value="*", ) self._search_query = Select(title="Search query:") self._user_verified = Select(title="User verified:", options=["*", str(True), str(False)], value="*") # NEWS_CSV-specific: self._url_netloc = Select(title="Domain:") # MAXQDA_CODED_NEWS_CSV-specific: self._code_identifier = Select(title="Code identifier:") self._cumulate_subcodes = CheckboxGroup(labels=["Cumulate subcodes"], active=[1]) self._type_specific_widgets = { DatasetType.NASTY: column( row(self._search_filter, self._search_query, sizing_mode="stretch_width"), self._user_verified, sizing_mode="stretch_width", ), DatasetType.NEWS_CSV: column(self._url_netloc, sizing_mode="stretch_width"), DatasetType.MAXQDA_CODED_NASTY: column( self._code_identifier, self._cumulate_subcodes, sizing_mode="stretch_width", ), DatasetType.MAXQDA_CODED_NEWS_CSV: column( self._url_netloc, self._code_identifier, self._cumulate_subcodes, sizing_mode="stretch_width", ), } self._collapsed_widget = self._dataset_name self._expanded_widget = column( self._dataset_name, self._lang, row(), # Dummy value to be replaced in self._on_change_name() self._cooccur_words, sizing_mode="stretch_width", ) self.widget = row(self._hide_button, self._collapsed_widget, sizing_mode="stretch_width") self._callbacks: MutableSequence[Callable[[str, object, object], None]] = [] self._on_change_name()
def create(): det_data = {} roi_selection = {} upload_div = Div(text="Open .cami file:") def upload_button_callback(_attr, _old, new): with io.StringIO(base64.b64decode(new).decode()) as file: h5meta_list = pyzebra.parse_h5meta(file) file_list = h5meta_list["filelist"] filelist.options = file_list filelist.value = file_list[0] upload_button = FileInput(accept=".cami") upload_button.on_change("value", upload_button_callback) def update_image(index=None): if index is None: index = index_spinner.value current_image = det_data["data"][index] proj_v_line_source.data.update(x=np.arange(0, IMAGE_W) + 0.5, y=np.mean(current_image, axis=0)) proj_h_line_source.data.update(x=np.mean(current_image, axis=1), y=np.arange(0, IMAGE_H) + 0.5) image_source.data.update( h=[np.zeros((1, 1))], k=[np.zeros((1, 1))], l=[np.zeros((1, 1))], ) image_source.data.update(image=[current_image]) if auto_toggle.active: im_max = int(np.max(current_image)) im_min = int(np.min(current_image)) display_min_spinner.value = im_min display_max_spinner.value = im_max image_glyph.color_mapper.low = im_min image_glyph.color_mapper.high = im_max def update_overview_plot(): h5_data = det_data["data"] n_im, n_y, n_x = h5_data.shape overview_x = np.mean(h5_data, axis=1) overview_y = np.mean(h5_data, axis=2) overview_plot_x_image_source.data.update(image=[overview_x], dw=[n_x]) overview_plot_y_image_source.data.update(image=[overview_y], dw=[n_y]) if frame_button_group.active == 0: # Frame overview_plot_x.axis[1].axis_label = "Frame" overview_plot_y.axis[1].axis_label = "Frame" overview_plot_x_image_source.data.update(y=[0], dh=[n_im]) overview_plot_y_image_source.data.update(y=[0], dh=[n_im]) elif frame_button_group.active == 1: # Omega overview_plot_x.axis[1].axis_label = "Omega" overview_plot_y.axis[1].axis_label = "Omega" om = det_data["rot_angle"] om_start = om[0] om_end = (om[-1] - om[0]) * n_im / (n_im - 1) overview_plot_x_image_source.data.update(y=[om_start], dh=[om_end]) overview_plot_y_image_source.data.update(y=[om_start], dh=[om_end]) def filelist_callback(_attr, _old, new): nonlocal det_data det_data = pyzebra.read_detector_data(new) index_spinner.value = 0 index_spinner.high = det_data["data"].shape[0] - 1 update_image(0) update_overview_plot() filelist = Select() filelist.on_change("value", filelist_callback) def index_spinner_callback(_attr, _old, new): update_image(new) index_spinner = Spinner(title="Image index:", value=0, low=0) index_spinner.on_change("value", index_spinner_callback) plot = Plot( x_range=Range1d(0, IMAGE_W, bounds=(0, IMAGE_W)), y_range=Range1d(0, IMAGE_H, bounds=(0, IMAGE_H)), plot_height=IMAGE_H * 3, plot_width=IMAGE_W * 3, toolbar_location="left", ) # ---- tools plot.toolbar.logo = None # ---- axes plot.add_layout(LinearAxis(), place="above") plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="right") # ---- grid lines plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph image_source = ColumnDataSource( dict( image=[np.zeros((IMAGE_H, IMAGE_W), dtype="float32")], h=[np.zeros((1, 1))], k=[np.zeros((1, 1))], l=[np.zeros((1, 1))], x=[0], y=[0], dw=[IMAGE_W], dh=[IMAGE_H], )) h_glyph = Image(image="h", x="x", y="y", dw="dw", dh="dh", global_alpha=0) k_glyph = Image(image="k", x="x", y="y", dw="dw", dh="dh", global_alpha=0) l_glyph = Image(image="l", x="x", y="y", dw="dw", dh="dh", global_alpha=0) plot.add_glyph(image_source, h_glyph) plot.add_glyph(image_source, k_glyph) plot.add_glyph(image_source, l_glyph) image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") plot.add_glyph(image_source, image_glyph, name="image_glyph") # ---- projections proj_v = Plot( x_range=plot.x_range, y_range=DataRange1d(), plot_height=200, plot_width=IMAGE_W * 3, toolbar_location=None, ) proj_v.add_layout(LinearAxis(major_label_orientation="vertical"), place="right") proj_v.add_layout(LinearAxis(major_label_text_font_size="0pt"), place="below") proj_v.add_layout(Grid(dimension=0, ticker=BasicTicker())) proj_v.add_layout(Grid(dimension=1, ticker=BasicTicker())) proj_v_line_source = ColumnDataSource(dict(x=[], y=[])) proj_v.add_glyph(proj_v_line_source, Line(x="x", y="y", line_color="steelblue")) proj_h = Plot( x_range=DataRange1d(), y_range=plot.y_range, plot_height=IMAGE_H * 3, plot_width=200, toolbar_location=None, ) proj_h.add_layout(LinearAxis(), place="above") proj_h.add_layout(LinearAxis(major_label_text_font_size="0pt"), place="left") proj_h.add_layout(Grid(dimension=0, ticker=BasicTicker())) proj_h.add_layout(Grid(dimension=1, ticker=BasicTicker())) proj_h_line_source = ColumnDataSource(dict(x=[], y=[])) proj_h.add_glyph(proj_h_line_source, Line(x="x", y="y", line_color="steelblue")) # add tools hovertool = HoverTool(tooltips=[("intensity", "@image"), ("h", "@h"), ("k", "@k"), ("l", "@l")]) box_edit_source = ColumnDataSource(dict(x=[], y=[], width=[], height=[])) box_edit_glyph = Rect(x="x", y="y", width="width", height="height", fill_alpha=0, line_color="red") box_edit_renderer = plot.add_glyph(box_edit_source, box_edit_glyph) boxedittool = BoxEditTool(renderers=[box_edit_renderer], num_objects=1) def box_edit_callback(_attr, _old, new): if new["x"]: h5_data = det_data["data"] x_val = np.arange(h5_data.shape[0]) left = int(np.floor(new["x"][0])) right = int(np.ceil(new["x"][0] + new["width"][0])) bottom = int(np.floor(new["y"][0])) top = int(np.ceil(new["y"][0] + new["height"][0])) y_val = np.sum(h5_data[:, bottom:top, left:right], axis=(1, 2)) else: x_val = [] y_val = [] roi_avg_plot_line_source.data.update(x=x_val, y=y_val) box_edit_source.on_change("data", box_edit_callback) wheelzoomtool = WheelZoomTool(maintain_focus=False) plot.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), hovertool, boxedittool, ) plot.toolbar.active_scroll = wheelzoomtool # shared frame range frame_range = DataRange1d() det_x_range = DataRange1d() overview_plot_x = Plot( title=Title(text="Projections on X-axis"), x_range=det_x_range, y_range=frame_range, plot_height=400, plot_width=400, toolbar_location="left", ) # ---- tools wheelzoomtool = WheelZoomTool(maintain_focus=False) overview_plot_x.toolbar.logo = None overview_plot_x.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), ) overview_plot_x.toolbar.active_scroll = wheelzoomtool # ---- axes overview_plot_x.add_layout(LinearAxis(axis_label="Coordinate X, pix"), place="below") overview_plot_x.add_layout(LinearAxis(axis_label="Frame", major_label_orientation="vertical"), place="left") # ---- grid lines overview_plot_x.add_layout(Grid(dimension=0, ticker=BasicTicker())) overview_plot_x.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph overview_plot_x_image_source = ColumnDataSource( dict(image=[np.zeros((1, 1), dtype="float32")], x=[0], y=[0], dw=[1], dh=[1])) overview_plot_x_image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") overview_plot_x.add_glyph(overview_plot_x_image_source, overview_plot_x_image_glyph, name="image_glyph") det_y_range = DataRange1d() overview_plot_y = Plot( title=Title(text="Projections on Y-axis"), x_range=det_y_range, y_range=frame_range, plot_height=400, plot_width=400, toolbar_location="left", ) # ---- tools wheelzoomtool = WheelZoomTool(maintain_focus=False) overview_plot_y.toolbar.logo = None overview_plot_y.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), ) overview_plot_y.toolbar.active_scroll = wheelzoomtool # ---- axes overview_plot_y.add_layout(LinearAxis(axis_label="Coordinate Y, pix"), place="below") overview_plot_y.add_layout(LinearAxis(axis_label="Frame", major_label_orientation="vertical"), place="left") # ---- grid lines overview_plot_y.add_layout(Grid(dimension=0, ticker=BasicTicker())) overview_plot_y.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph overview_plot_y_image_source = ColumnDataSource( dict(image=[np.zeros((1, 1), dtype="float32")], x=[0], y=[0], dw=[1], dh=[1])) overview_plot_y_image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") overview_plot_y.add_glyph(overview_plot_y_image_source, overview_plot_y_image_glyph, name="image_glyph") def frame_button_group_callback(_active): update_overview_plot() frame_button_group = RadioButtonGroup(labels=["Frames", "Omega"], active=0) frame_button_group.on_click(frame_button_group_callback) roi_avg_plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(), plot_height=IMAGE_H * 3, plot_width=IMAGE_W * 3, toolbar_location="left", ) # ---- tools roi_avg_plot.toolbar.logo = None # ---- axes roi_avg_plot.add_layout(LinearAxis(), place="below") roi_avg_plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="left") # ---- grid lines roi_avg_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) roi_avg_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) roi_avg_plot_line_source = ColumnDataSource(dict(x=[], y=[])) roi_avg_plot.add_glyph(roi_avg_plot_line_source, Line(x="x", y="y", line_color="steelblue")) cmap_dict = { "gray": Greys256, "gray_reversed": Greys256[::-1], "plasma": Plasma256, "cividis": Cividis256, } def colormap_callback(_attr, _old, new): image_glyph.color_mapper = LinearColorMapper(palette=cmap_dict[new]) overview_plot_x_image_glyph.color_mapper = LinearColorMapper( palette=cmap_dict[new]) overview_plot_y_image_glyph.color_mapper = LinearColorMapper( palette=cmap_dict[new]) colormap = Select(title="Colormap:", options=list(cmap_dict.keys())) colormap.on_change("value", colormap_callback) colormap.value = "plasma" radio_button_group = RadioButtonGroup(labels=["nb", "nb_bi"], active=0) STEP = 1 # ---- colormap auto toggle button def auto_toggle_callback(state): if state: display_min_spinner.disabled = True display_max_spinner.disabled = True else: display_min_spinner.disabled = False display_max_spinner.disabled = False update_image() auto_toggle = Toggle(label="Auto Range", active=True, button_type="default") auto_toggle.on_click(auto_toggle_callback) # ---- colormap display max value def display_max_spinner_callback(_attr, _old_value, new_value): display_min_spinner.high = new_value - STEP image_glyph.color_mapper.high = new_value display_max_spinner = Spinner( title="Maximal Display Value:", low=0 + STEP, value=1, step=STEP, disabled=auto_toggle.active, ) display_max_spinner.on_change("value", display_max_spinner_callback) # ---- colormap display min value def display_min_spinner_callback(_attr, _old_value, new_value): display_max_spinner.low = new_value + STEP image_glyph.color_mapper.low = new_value display_min_spinner = Spinner( title="Minimal Display Value:", high=1 - STEP, value=0, step=STEP, disabled=auto_toggle.active, ) display_min_spinner.on_change("value", display_min_spinner_callback) def hkl_button_callback(): index = index_spinner.value setup_type = "nb_bi" if radio_button_group.active else "nb" h, k, l = calculate_hkl(det_data, index, setup_type) image_source.data.update(h=[h], k=[k], l=[l]) hkl_button = Button(label="Calculate hkl (slow)") hkl_button.on_click(hkl_button_callback) selection_list = TextAreaInput(rows=7) def selection_button_callback(): nonlocal roi_selection selection = [ int(np.floor(det_x_range.start)), int(np.ceil(det_x_range.end)), int(np.floor(det_y_range.start)), int(np.ceil(det_y_range.end)), int(np.floor(frame_range.start)), int(np.ceil(frame_range.end)), ] filename_id = filelist.value[-8:-4] if filename_id in roi_selection: roi_selection[f"{filename_id}"].append(selection) else: roi_selection[f"{filename_id}"] = [selection] selection_list.value = str(roi_selection) selection_button = Button(label="Add selection") selection_button.on_click(selection_button_callback) # Final layout layout_image = column( gridplot([[proj_v, None], [plot, proj_h]], merge_tools=False), row(index_spinner)) colormap_layout = column(colormap, auto_toggle, display_max_spinner, display_min_spinner) hkl_layout = column(radio_button_group, hkl_button) layout_overview = column( gridplot( [[overview_plot_x, overview_plot_y]], toolbar_options=dict(logo=None), merge_tools=True, ), frame_button_group, ) tab_layout = row( column( upload_div, upload_button, filelist, layout_image, row(colormap_layout, hkl_layout), ), column( roi_avg_plot, layout_overview, row(selection_button, selection_list), ), ) return Panel(child=tab_layout, title="Data Viewer")
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))
update_data(current_field) # # Set up layouts and add to document global buttons buttons = {} if 0 < data['field1'][-1] < 25.: color = 'success' elif 25. <= data['field1'][-1] < 50.: color = 'warning' else: color = 'danger' buttons[1] = Button( label=r"%s: %s %s" % (labels['field1']['label'], data['field1'][-1], labels['field1']['unit']), button_type=color) if 0 < data['field2'][-1] < 25.: color = 'success' elif 25. <= data['field2'][-1] < 50.: color = 'warning' else: color = 'danger' buttons[2] = Button( label=r"%s: %s %s" % (labels['field2']['label'], data['field2'][-1], labels['field2']['unit']), button_type=color) buttons[3] = Button( label="%s: %.1f %s" %
start=BETA_MIN, end=BETA2_MAX, step=BETA2_STEP) beta3 = Slider(title=BETA3_LABEL, value=BETA3_START, start=BETA_MIN, end=BETA3_MAX, step=BETA3_STEP) drate = Slider(title=DRATE_LABEL, value=DRATE_START, start=DRATE_MIN, end=DRATE_MAX, step=DRATE_STEP) button = Button(label="Reset", button_type="default") # text widgets intro = Div(text='', width=TEXT_WIDTH) summary = Div(text='', width=TEXT_WIDTH) stats = Div(text='', width=TEXT_WIDTH) notes = Div(text='', width=TEXT_WIDTH) # Assign widgets to the call back function # updates are on value_throtled because this is too slow for realtime updates for w in [ population, iinfections, period, period_stdev, latent, duration1, duration2, transition1, transition2, beta1, beta2, beta3, drate ]: w.on_change('value_throttled', update_data)
eeg.loc_sec = eeg.limit_sample_check(eeg.loc_sec + 10) # eeg.loc_sec += 10 eeg.update() def backward1sec(): eeg.loc_sec = eeg.limit_sample_check(eeg.loc_sec - 1) eeg.update() def backward10(eeg=eeg): eeg.loc_sec = eeg.limit_sample_check(eeg.loc_sec - 10) eeg.update() buttonF = Button(label="forward 10s") buttonF.on_click(forward10) buttonB = Button(label="backward 10s") buttonB.on_click(backward10) buttonF1 = Button(label=">") buttonF1.on_click(forward1sec) buttonB1 = Button(label="<") buttonB1.on_click(backward1sec) button5 = Button(label="spacer") kbr = KeyboardResponder() l = layouts.layout(
def test_widget(): from bokeh.models import Button test_widget = Button() return test_widget
#Should have validation that input from form is valid api_url = api_url + txt.value req = urllib.request.Request(api_url) s = ssl.SSLContext(ssl.PROTOCOL_SSLv23) response = urllib.request.urlopen(req, context=s) data = json.JSONDecoder().decode(response.read().decode('UTF-8')) erecord = data['metadata']['electronic_location_and_access'][0] #Only looks at first file, no validation url = erecord['uniform_resource_identifier'] rawframe = pandas.read_csv(url, sep=',', header=1) new_data = dict(x=rawframe.index.values,\ y=rawframe[list(rawframe)[0]]) p.title.text = erecord['electronic_name'][0] #Reads only first column, hard coding source.data = new_data # add a button widget and configure with the call back txt = TextInput(placeholder="Type 208 or 209") button = Button(label="Press Me") button.on_click(callback) # put the button and plot in a layout and add to the document column = column(p, txt, button) curdoc().add_root(column)
} datarej['x_rejected'] = x_rejected; datarej['y_rejected'] = y_rejected; datanon['x_nonrejected'] = x_nonrejected; datanon['y_nonrejected'] = y_nonrejected; dataall['x_original'] = x_original; dataall['y_fitted'] = y_fitted; // console.log(dataall['x_original']); // console.log(dataall['y_fitted']); sourcenon.change.emit(); sourcerej.change.emit(); sourceall.change.emit(); p.change.emit(); """) #slider = Slider(start=0.1, end=4, value=1, step=.1, title="power") #slider.js_on_change('value', callback) plot.xaxis.axis_label = 'x' plot.yaxis.axis_label = 'y' button = Button(label = "Plot Results", button_type = "primary") button.js_on_click(callback) layout = column(button, plot) #show(layout) save(layout)
def __init__(self): # plotting data for moving objects self.fig0_data = ColumnDataSource( data=dict(x=[], y=[], w=[], c=[], a=[])) self.fig1_data = ColumnDataSource( data=dict(x=[], y=[], w=[], c=[], a=[])) self.fig2_data = ColumnDataSource( data=dict(x=[], y=[], w=[], c=[], a=[])) self.fig0_lines_data = ColumnDataSource(data=dict(x=[], y=[])) self.fig1_lines_data = ColumnDataSource(data=dict(x=[], y=[])) self.fig2_lines_data = ColumnDataSource(data=dict(x=[], y=[])) # plotting data for fixed objects self.ramp_source0 = ColumnDataSource( data=dict(x=[TX1 - rampAddLength * COS, TX0], y=[TY1 + rampAddLength * SIN, TY0])) self.ramp_source1 = ColumnDataSource( data=dict(x=[TX1 - rampAddLength * COS, TX0], y=[TY1 + rampAddLength * SIN, TY0])) self.ramp_source2 = ColumnDataSource( data=dict(x=[TX1 - rampAddLength * COS, TX0], y=[TY1 + rampAddLength * SIN, TY0])) self.wall_source0 = ColumnDataSource( data=dict(x=[TX1 - rampAddLength * COS, TX1 - rampAddLength * COS], y=[TY1 + rampAddLength * SIN, TY0])) self.wall_source1 = ColumnDataSource( data=dict(x=[TX1 - rampAddLength * COS, TX1 - rampAddLength * COS], y=[TY1 + rampAddLength * SIN, TY0])) self.wall_source2 = ColumnDataSource( data=dict(x=[TX1 - rampAddLength * COS, TX1 - rampAddLength * COS], y=[TY1 + rampAddLength * SIN, TY0])) # put them in a list for easy access in functions self.fig_data = [self.fig0_data, self.fig1_data, self.fig2_data] self.fig_lines_data = [ self.fig0_lines_data, self.fig1_lines_data, self.fig2_lines_data ] self.ramp_sources = [ self.ramp_source0, self.ramp_source1, self.ramp_source2 ] self.wall_sources = [ self.wall_source0, self.wall_source1, self.wall_source2 ] self.time_display = [ ColumnDataSource(data=dict(x=[], y=[], t=[])), ColumnDataSource(data=dict(x=[], y=[], t=[])), ColumnDataSource(data=dict(x=[], y=[], t=[])) ] self.icon_display = [ ColumnDataSource(data=dict(x=[], y=[], img=[])), ColumnDataSource(data=dict(x=[], y=[], img=[])), ColumnDataSource(data=dict(x=[], y=[], img=[])) ] ############################################################################### ### Buttons ### ############################################################################### self.start_button = Button(label="Start", button_type="success", width=285) self.reset_button = Button(label="Reset", button_type="success", width=285) self.mode_selection = RadioGroup(labels=["one", "all"], active=0, inline=True) ############################################################################### ### Selections ### ############################################################################### self.object_select0 = Select(title="Object:", value="Sphere", name="obj0", options=[ "Sphere", "Hollow sphere", "Full cylinder", "Hollow cylinder" ]) self.object_select1 = Select(title="Object:", value="Full cylinder", name="obj1", options=[ "Sphere", "Hollow sphere", "Full cylinder", "Hollow cylinder" ]) self.object_select2 = Select(title="Object:", value="Hollow cylinder", name="obj2", options=[ "Sphere", "Hollow sphere", "Full cylinder", "Hollow cylinder" ]) ############################################################################### ### Sliders ### ############################################################################### # radius self.radius_slider0 = Slider(title="Radius [m]", value=2.0, start=1.0, end=maxR, step=0.5) self.radius_slider1 = Slider(title="Radius [m]", value=2.0, start=1.0, end=maxR, step=0.5) self.radius_slider2 = Slider(title="Radius [m]", value=2.0, start=1.0, end=maxR, step=0.5) # inner radius # end value dependent on selected radius size ## change from JavaScript to Pythohn for hide/show --> no css_classes needed! ## TODO: needs to be restructered! self.ri_slider0 = Slider( title="Inner radius [m]", value=0.5, start=0.0, end=2.0, step=0.5, visible=False) #, css_classes=["wall_slider", "obj1", "hidden"]) self.ri_slider1 = Slider( title="Inner radius [m]", value=0.5, start=0.0, end=2.0, step=0.5, visible=False) #, css_classes=["wall_slider", "obj2", "hidden"]) self.ri_slider2 = Slider( title="Inner radius [m]", value=1.5, start=0.0, end=2.0, step=0.5, visible=True) #, css_classes=["wall_slider", "obj3"]) # slider for the angle self.alpha_slider0 = Slider(title=u"\u03B1 [\u00B0]", value=20.0, start=5.0, end=alpha_max, step=1.0) self.alpha_slider1 = Slider(title=u"\u03B1 [\u00B0]", value=20.0, start=5.0, end=alpha_max, step=1.0) self.alpha_slider2 = Slider(title=u"\u03B1 [\u00B0]", value=20.0, start=5.0, end=alpha_max, step=1.0)
source.data = sources[year].data slider = Slider(start=years[0], end=years[-1], value=years[0], step=1, title="Year") slider.on_change('value', slider_update) def animate(): if button.label == '► Play': button.label = '❚❚ Pause' curdoc().add_periodic_callback(animate_update, 200) else: button.label = '► Play' curdoc().remove_periodic_callback(animate_update) button = Button(label='► Play', width=60) button.on_click(animate) layout = layout([ [plot], [slider, button], ], sizing_mode='scale_width') curdoc().add_root(layout) curdoc().title = "Gapminder"