def modify_doc(doc): with open('er_batch_size.pickle', 'rb') as handle: project_dict = pickle.load(handle) data = project_dict['bb'][0.1] source = ColumnDataSource(data) plot = figure(x_axis_type='linear', y_range=(-200, 200), y_axis_label='Improvement (%)', x_axis_label='Batch Size') plot.line('x', 'y', source=source) def callback(attr, old, new): global project_name if attr == 'active': data = project_dict[project_name_dict[new]][0.1] project_name = project_name_dict[new] else: new = float('{:2f}'.format(new)) data = project_dict[project_name][new] source.data = ColumnDataSource(data=data).data slider = Slider(start=0.1, end=1, value=0.1, step=0.01, title="Risk Threshold") slider.on_change('value', callback) radio_button_group = RadioButtonGroup( labels=er_project_list, active=0) radio_button_group.on_change('active', callback) doc.add_root(column(radio_button_group, slider, plot)) doc.theme = Theme(filename="../theme.yaml")
def test_basic(self) -> None: t = Theme(json={}) d = Document() beu._themes[d] = t beu._unset_temp_theme(d) assert d.theme is t assert d not in beu._themes
def _notebook_ui(self, doc): """ Shows and sets up the user interface. Parameters: ----------- doc : bokeh.Document Document instance to collect bokeh models in. """ # this throws a depreciation warning. doc.theme = Theme(json=yaml.load(""" attrs: Figure: background_fill_color: "#DDDDDD" outline_line_color: white toolbar_location: above height: 500 width: 800 Grid: grid_line_dash: [6, 4] grid_line_color: white """)) tab_fc = self._f_value_panel() tab_mi = self._mi_panel() tabs = Tabs(tabs=[tab_fc, tab_mi]) doc.add_root(tabs)
def bkapp(doc): plot = figure(x_axis_label='Temperature (Celsius)', y_range=(0, 200e-6), y_axis_label='Seebeck Coefficient (V/K)', title="Seebeck Coefficient vs Temperature") max_lines = 10 all_data = get_data(max_lines) for sample_name, data_dict in all_data.items(): source = ColumnDataSource(data_dict) plot.line('temp', 'seebeck', source=source, name=sample_name) def callback(attr, old, new): i = 0 for sample_name, data_dict in all_data.items(): line = plot.select_one({'name': sample_name}) if i < new: line.visible = True else: line.visible = False i += 1 # sample_names, source = get_data(new) # source.data = get_data(new) slider = Slider(start=1, end=max_lines, value=max_lines, step=1, title="Number of curves to plot") slider.on_change('value', callback) doc.add_root(column(slider, plot)) doc.theme = Theme(filename="theme.yml")
def test_apply_theme(self) -> None: t = Theme(json={}) d = Document() orig = d.theme beu._set_temp_theme(d, t) assert beu._themes[d] is orig assert d.theme is t
def init(self, doc): # Source must only be modified through a stream self.source = ColumnDataSource(data=self.data) self.colors[0] = 'cyan' #self.source = ColumnDataSource(data=self.data[self.scale]) # Enable theming theme = Theme( os.path.dirname(os.path.abspath(__file__)) + '/theme.yaml') doc.theme = theme self.doc = doc fig = figure(plot_width=600, plot_height=400, tools='xpan,xwheel_zoom, xbox_zoom, reset, save', title=self.title, x_axis_label=self.XAXIS, y_axis_label=self.ylabel) # Initialize plots for i, key in enumerate(self.keys): fig.line(source=self.source, x=self.x, y=key, color=self.colors[i], line_width=LINE_WIDTH, legend_label=key) band = Band(source=self.source, base=self.x, lower=key + 'lower', upper=key + 'upper', level='underlay', line_color=self.colors[i], line_width=1, line_alpha=0.2, fill_color=self.colors[i], fill_alpha=0.2) fig.add_layout(band) def switch_scale(attr, old, new): """Callback for RadioButtonGroup to switch tick scale and refresh document Args: attr: variable to be changed, in this case 'active' old: old index of active button new: new index of active button """ self.scale = self.scales[new] self.source.data = self.data[self.scale] self.timescales = RadioButtonGroup( labels=[str(scale) for scale in self.scales], active=self.scales.index(self.scale)) self.timescales.on_change('active', switch_scale) self.structure = layout([[self.timescales], [fig]]) self.doc.add_root(self.structure) self.fig = fig
def modify_doc(doc): """ This functioin will modify the document attached to the application """ df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource(data=data).data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) doc.add_root(column(slider, plot)) doc.theme = Theme(filename="theme.yaml")
def bkapp(doc): df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource.from_df(data) slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) doc.add_root(column(slider, plot)) #TODO: Fix theme.yaml path, findable from running anywhere. doc.theme = Theme(filename=os.path.join(Config.BASEDIR, 'web_app', 'bokeh', 'theme.yaml'))
def test_construct_empty_theme_from_file(self): with (tempfile.NamedTemporaryFile()) as file: # create and apply empty theme with no exception thrown file.file.write("".encode('utf-8')) file.file.flush() theme = Theme(filename=file.name) theme.apply_to_model(ThemedModel())
def add_figures(self, document): time_series = self.add_time_series() controls = self.add_slider() document.add_root(column(controls, time_series)) document.theme = Theme(filename="theme.yaml")
def define_custom_theme(background_fill_color, border_fill_color): theme = Theme(json={ 'attrs': { 'Figure': { 'background_fill_color': background_fill_color, 'border_fill_color': border_fill_color, 'outline_line_color': border_fill_color }, 'Axis': { 'axis_line_color': "white", 'axis_label_text_color': "white", 'major_label_text_color': "white", 'major_tick_line_color': "white", 'minor_tick_line_color': "white", 'minor_tick_line_color': "white" }, 'Grid': { 'grid_line_dash': [6, 4], 'grid_line_alpha': .3 }, 'Circle': { 'fill_color': 'lightblue', 'size': 10, }, 'Title': { 'text_color': "white" } } }) return theme
def bkapp(doc): df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource.from_df(data) slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) doc.add_root(column(slider, plot)) doc.theme = Theme(json=yaml.load(""" attrs: Figure: background_fill_color: "#DDDDDD" outline_line_color: white toolbar_location: above height: 500 width: 800 Grid: grid_line_dash: [6, 4] grid_line_color: white """, Loader=yaml.FullLoader))
def main(): plots = [ figure(title='Styles Demo {i}'.format(i=i + 1), plot_width=200, plot_height=200, tools='') for i in range(9) ] [plot.line(np.arange(10), np.random.random(10)) for plot in plots] button_bokeh = Button(label="Custom Style: Bokeh Button", css_classes=['custom_button_bokeh']) button_bokeh.name = 'button_text' button_bokeh.on_event(ButtonClick, on_button_click_event_callback) curdoc().add_root(button_bokeh) curdoc().add_root(gridplot(children=[plot for plot in plots], ncols=3)) cur_doc = curdoc() # cur_doc.on_event(DocumentUpdate, on_document_update_event_callback) cur_doc.on_event(DocumentPatchedEvent, on_document_patch_event_callback) cur_doc.theme = Theme( filename= "G:\\dt-boot\\dt-data-analysis-visual\\app\\api\\server_visual\\timeseries-multi\\dark-theme.yaml" ) cur_doc.on_session_destroyed(on_session_destroyed) # cur_doc.add_periodic_callback(on_periodic_callback, 1000) cur_doc.add_next_tick_callback(on_next_tick_callback)
def modify_doc(doc): tools = "pan,wheel_zoom,lasso_select,reset" fig = figure(title='Select points', plot_width=300, plot_height=200,tools=tools) import numpy as np x = np.linspace(0,10,100) y = np.random.random(100) + x import pandas as pd data = pd.DataFrame(dict(x=x, y=y)) # define data source src = ColumnDataSource(data) # define plot fig.circle(x='x', y='y', source=src) # define interaction def print_datapoints(): indices = src.selected.indices results = data.iloc[indices] print(results) resultsDict=results.to_dict()['x'] resultString=str(resultsDict) btn = Button(label='Selected points', button_type='success') btn.on_click(print_datapoints) doc.add_root(column(btn, fig)) doc.theme = Theme(filename="theme.yaml")
def metrics_doc(doc: Document) -> None: settings = Settings() logdir = settings.log_path / doc.session_context.request.arguments['model'][0].decode('utf-8') plots = get_plots() doc.add_root(row(plots.loss.plot, plots.score.plot)) doc.theme = Theme(filename="visualization/theme.yaml") threading.Thread(target=load_data_for_model, args=(doc, plots, logdir)).start()
def bkapp_red(doc): """ Bokeh App Arguments: doc {Bokeh Document} -- bokeh document Returns: Bokeh Document --bokeh document with plot and slider """ dataframe = sea_surface_temperature.copy() source = ColumnDataSource(data=dataframe) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Red App - Sea Surface Temperature at 43.18, -70.43") plot.line(x='time', y='temperature', source=source, line_color='red') def callback(_attr, _old, new): if new == 0: data = dataframe else: data = dataframe.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource.from_df(data) slider = Slider(start=0, end=30, value=0, step=1, title="Application Red") slider.on_change('value', callback) doc.theme = Theme(filename=os.path.join(cwd(), 'theme.yaml')) return doc.add_root(column(slider, plot))
def test_basic(self): t = Theme(json={}) d = Document() d._old_theme = t beu._unset_temp_theme(d) assert d.theme is t assert not hasattr(d, "_old_theme")
def modify_doc(doc): flask_args = doc.session_context.request.arguments unit_type = flask_args.get('unit_type')[0].decode("utf-8") df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label=f"Temperature ({unit_type})") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource(data=data).data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) doc.add_root(column(slider, plot)) doc.theme = Theme(filename="theme.yaml")
def __init__(self, *args, **kwargs): super(DirectoryHandler, self).__init__(*args, **kwargs) if 'filename' not in kwargs: raise ValueError('Must pass a filename to DirectoryHandler') src_path = kwargs['filename'] mainpy = os.path.join(src_path, 'main.py') if not os.path.exists(mainpy): raise ValueError("No 'main.py' in %s" % (src_path)) self._path = src_path self._mainpy = mainpy self._mainpy_handler = ScriptHandler(filename=self._mainpy) lifecycle = os.path.join(src_path, 'server_lifecycle.py') if os.path.exists(lifecycle): self._lifecycle = lifecycle self._lifecycle_handler = ServerLifecycleHandler( filename=self._lifecycle) else: self._lifecycle = None self._lifecycle_handler = Handler() # no-op handler self._theme = None themeyaml = os.path.join(src_path, 'theme.yaml') if os.path.exists(themeyaml): from bokeh.themes import Theme self._theme = Theme(filename=themeyaml)
def test_apply_theme(self): t = Theme(json={}) d = Document() orig = d.theme beu._set_temp_theme(d, t) assert d._old_theme is orig assert d.theme is t
def bkapp(doc): df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure( x_axis_type="datetime", y_range=(0, 25), y_axis_label="Temperature (Celsius)", title="Sea Surface Temperature at 43.18, -70.43", ) plot.line("time", "temperature", source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling("{0}D".format(new)).mean() source.data = ColumnDataSource(data=data).data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change("value", callback) doc.add_root(column(slider, plot)) doc.theme = Theme(filename="theme.yaml")
def modify_doc2(doc): import numpy as np import pandas as pd x = np.linspace(0, 10 * np.pi, 1000) noise = np.random.normal(0, 0.1, 1000) y = 1 - np.exp(-x) + noise df = pd.DataFrame({'x': x, 'y': y}) source = ColumnDataSource(data=df) plot = figure(x_axis_label='Time', y_axis_label='Amplitude') plot.line('x', 'y', source=source) def callback(attr, old, new): if new == 0: data = df else: # data = df.rolling('{0}D'.format(new)).mean() data = df['y'].rolling(new, center=True, min_periods=1).mean() source.data['y'] = data slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Samples") slider.on_change('value', callback) doc.add_root(column(slider, plot)) doc.theme = Theme(filename="theme.yaml")
def bkapp(doc): # Define app logic here df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = ColumnDataSource.from_df(data) slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days") slider.on_change('value', callback) # These should be kept somehow doc.add_root(column(slider, plot)) doc.theme = Theme(filename="theme.yaml")
def modify_doc(doc): with open('window_size.pickle', 'rb') as handle: project_dict = pickle.load(handle) data = project_dict['rollbar-gem'][1] source = ColumnDataSource(data) plot = figure(x_axis_type='linear', y_range=(0, 55), y_axis_label='Improvement (%)', x_axis_label='Risk Threshold') plot.line('x', 'y', source=source) def callback(attr, old, new): global project_name if attr == 'active': data = project_dict[project_name_dict[new]][1] project_name = project_name_dict[new] else: data = project_dict[project_name][new] source.data = ColumnDataSource(data=data).data slider = Slider(start=1, end=100, value=1, step=1, title="Window Size") slider.on_change('value', callback) radio_button_group = RadioButtonGroup(labels=project_list, active=0) radio_button_group.on_change('active', callback) doc.add_root(column(radio_button_group, slider, plot)) doc.theme = Theme(filename="../../theme.yaml")
def init_bokeh_figure(yml_path=None, **kwargs): """ Initialize a Bokeh Figure object. This code is fairly low level, and is used simply as a matter of convenience for supplying a default theme even without the user explicitly providing one. Kwargs are passed into the creation of the figure, and so further customization like title, axis limits, etc. should be supplied this way. Parameters ---------- yml_path : str or None, optional If None, uses the PySpecTools default bokeh styling. If a str is provided then it should correspond to the filepath to a YAML file. kwargs Kwargs are passed into the creation of the Figure object Returns ------- Bokeh Figure object """ if yml_path is None: # Use the default stylesheet yml_path = os.path.expanduser("~") + "/.pyspectools/bokeh.yml" # Set the document theme doc = curdoc() doc.theme = Theme(filename=yml_path) default_params = { "tools": "crosshair,pan,wheel_zoom,box_zoom,reset,box_select," "lasso_select", "outline_line_color": "black", "output_backend": "webgl", } default_params.update(**kwargs) fig = figure(**default_params) return fig
def test_apply_from_curdoc(self): t = Theme(json={}) curdoc().theme = t d = Document() orig = d.theme beu._set_temp_theme(d, beu.FromCurdoc) assert d._old_theme is orig assert d.theme is t
def test_single_model_with_no_document(self): p = SomeModel() assert p.document is None with beu.OutputDocumentFor([p], apply_theme=Theme(json={})): assert p.document is not None new_theme = p.document.theme assert p.document is not None assert p.document.theme is not new_theme
def bkapp(doc): dash = dashlayout.DashLayout() board = dash.dashboard() model = board.get_root() doc.add_root(model) doc.theme = Theme(filename="homepage/theme.yaml")
def profiler_doc(doc: Document) -> None: settings = Settings() model_name = doc.session_context.request.arguments['model'][0].decode('utf-8') logdir = settings.log_path / model_name plots = get_profiler_plots() doc.add_root(row(plots.full_epoch.plot)) doc.theme = Theme(filename="visualization/theme.yaml") threading.Thread(target=load_profiling_data, args=(doc, plots, logdir, model_name)).start()
def _init_doc(self, doc): self.doc = doc self.doc.title = "Explore Dashboard" with open(os.path.join(os.path.dirname(__file__), 'templates', 'index.html')) as f: index_template = Template(f.read()) doc.template = index_template self.doc.theme = Theme(os.path.join(os.path.dirname(__file__), 'theme.yaml')) self._init_plots() m_widgetbox = self._init_controls() # Create tabs if self.mode == "signal": exg_tab = Panel(child=self.exg_plot, title="ExG Signal") orn_tab = Panel(child=column([self.acc_plot, self.gyro_plot, self.mag_plot], sizing_mode='scale_width'), title="Orientation") fft_tab = Panel(child=self.fft_plot, title="Spectral analysis") self.tabs = Tabs(tabs=[exg_tab, orn_tab, fft_tab], width=400, sizing_mode='scale_width') self.recorder_widget = self._init_recorder() self.push2lsl_widget = self._init_push2lsl() self.set_marker_widget = self._init_set_marker() self.baseline_widget = CheckboxGroup(labels=['Baseline correction'], active=[0]) elif self.mode == "impedance": imp_tab = Panel(child=self.imp_plot, title="Impedance") self.tabs = Tabs(tabs=[imp_tab], width=500, sizing_mode='scale_width') banner = Div(text=""" <a href="https://www.mentalab.com"><img src= "https://images.squarespace-cdn.com/content/5428308ae4b0701411ea8aaf/1505653866447-R24N86G5X1HFZCD7KBWS/ Mentalab%2C+Name+copy.png?format=1500w&content-type=image%2Fpng" alt="Mentalab" width="225" height="39">""", width=1500, height=50, css_classes=["banner"], align='center', sizing_mode="stretch_width") heading = Div(text=""" """, height=2, sizing_mode="stretch_width") if self.mode == 'signal': layout = column([heading, banner, row(m_widgetbox, Spacer(width=10, height=300), self.tabs, Spacer(width=10, height=300), column(Spacer(width=170, height=50), self.baseline_widget, self.recorder_widget, self.set_marker_widget, self.push2lsl_widget), Spacer(width=50, height=300)), ], sizing_mode="stretch_both") elif self.mode == 'impedance': layout = column(banner, Spacer(width=600, height=20), row([m_widgetbox, Spacer(width=25, height=500), self.tabs]) ) self.doc.add_root(layout) self.doc.add_periodic_callback(self._update_fft, 2000) self.doc.add_periodic_callback(self._update_heart_rate, 2000) if self.stream_processor: self.stream_processor.subscribe(topic=TOPICS.filtered_ExG, callback=self.exg_callback) self.stream_processor.subscribe(topic=TOPICS.raw_orn, callback=self.orn_callback) self.stream_processor.subscribe(topic=TOPICS.device_info, callback=self.info_callback) self.stream_processor.subscribe(topic=TOPICS.marker, callback=self.marker_callback) self.stream_processor.subscribe(topic=TOPICS.env, callback=self.info_callback) self.stream_processor.subscribe(topic=TOPICS.imp, callback=self.impedance_callback)