def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() reset = ResetTool() self.lasso_select = LassoSelectTool( renderers=self.circles, # default = all available renderers select_every_mousemove=False, # to enhance performance ) self.lasso_select.overlay.line_alpha=0.9 self.lasso_select.overlay.line_color="black" self.lasso_select.overlay.fill_alpha=0.2 self.lasso_select.overlay.fill_color="grey" hover = self._get_hover_tool() self.tools = ( pan, box_zoom, self.lasso_select, box_select, crosshair, save, reset, tap, wheel_zoom ) self.plot.add_tools(*self.tools)
def bottom_graph(self, source, ads): """Generate the bottom graphs (isotherm display).""" graph = figure(tools="pan,wheel_zoom,tap,reset", active_scroll="wheel_zoom", plot_width=400, plot_height=250, x_range=(-0.1, 1), y_range=(-0.1, 1), title='Isotherms {0}'.format(ads)) rend = graph.multi_line('x', 'y', source=source, alpha=0.6, line_width=3, hover_line_alpha=1.0, hover_line_color="black", line_color='color') # Make clicking a graph oben the NIST database url = "https://adsorption.nist.gov/isodb/index.php?DOI=@doi#biblio" graph.add_tools(TapTool(renderers=[rend], callback=OpenURL(url=url))) graph.add_tools( HoverTool(show_arrow=False, line_policy='nearest', tooltips=[ ('Label', '@labels'), ('T (K)', '@temp'), ])) graph.xaxis.axis_label = 'Pressure (bar)' graph.yaxis.axis_label = 'Uptake (mmol/g)' return graph
def create_viewer(title, y_range, toolbar_location=None, toolbar_sticky=False, tools="", plot_width=annotatorSettings.viewerWidth, plot_height=annotatorSettings.defaultViewerHeights, x_axis_type='datetime', add_tools=True): viewer = figure( title=title, tools=tools, plot_width=plot_width, plot_height=plot_height, toolbar_location=toolbar_location, # toolbar_sticky=False, x_axis_type=x_axis_type, y_range=y_range, ) viewer.xaxis.formatter = DatetimeTickFormatter( years=["%F %T"], months=["%F %T"], days=["%F %T"], hours=["%F %T"], hourmin=["%F %T"], minutes=["%F %T"], minsec=["%F %T"], seconds=["%F %T"], milliseconds=["%F %T.%3N"], ) # Create tools to add to ekgViewer. wheel_zoom = WheelZoomTool() tap_tool = TapTool() resizeTool = ResizeTool() box_select = BoxSelectTool(dimensions="width") hover = HoverTool( point_policy='snap_to_data', line_policy='nearest', tooltips=[ ("index", "$index"), ("Time", "@x{%F %T.%3N %Z}"), ("Value", "@y"), # ("Time", '@time'), ], formatters={"x": "datetime"}, ) if add_tools: viewer.add_tools(hover, box_select, tap_tool, resizeTool) viewer.toolbar.active_drag = box_select viewer.toolbar.active_scroll = wheel_zoom viewer.toolbar.active_tap = tap_tool return viewer
def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() lasso_select = LassoSelectTool( select_every_mousemove=False, # enhance performance ) code = """ var projections = require("core/util/projections"); var x = special_vars.x var y = special_vars.y var coords = projections.wgs84_mercator.inverse([x, y]) return coords[%d].toFixed(2) """ tooltips = ''' <style> .bk-tooltip>div:not(:nth-child(-n+5)) {{ display:none; }} .bk-tooltip>div {{ background-color: #dff0d8; padding: 5px; }} </style> <b>STATION: </b> @{STNNBR} <br /> <b>LON: </b> @X_WMTS{custom} <br /> <b>LAT: </b> @Y_WMTS{custom} <br /> ''' hover = HoverTool(toggleable=True, mode='mouse', tooltips=tooltips, renderers=[self.env.wmts_map_scatter], formatters={ 'X_WMTS': CustomJSHover(code=code % 0), 'Y_WMTS': CustomJSHover(code=code % 1), }) tools = (pan, box_zoom, lasso_select, hover, crosshair, tap, wheel_zoom) self.env.wmts_map.add_tools(*tools) # set defaults self.env.wmts_map.toolbar.active_drag = pan self.env.wmts_map.toolbar.active_inspect = [crosshair, hover] self.env.wmts_map.toolbar.active_scroll = wheel_zoom self.env.wmts_map.toolbar.active_tap = None
def makedoc(doc): source = ColumnDataSource(dataframe) image_holder = ColumnDataSource({ 'image': [], 'x': [], 'y': [], 'dx': [], 'dy': [] }) tools = [ ResetTool(), PanTool(), WheelZoomTool(), TapTool(), BoxSelectTool(), PolySelectTool(), UndoTool(), RedoTool() ] pca = figure(title='PCA', x_range=[minx - 0.05 * rangex, maxx + 0.05 * rangex], y_range=[miny - 0.05 * rangey, maxy + 0.05 * rangey], sizing_mode='scale_both', tools=tools) glyphs = pca.circle(source=source, x='x', y='y') sel = figure(title='Selected image', x_range=[0, 1], y_range=[0, 1], sizing_mode='scale_both') image_canvas = sel.image_rgba('image', 'x', 'y', 'dx', 'dy', source=image_holder) def load_selected(attr, old, new): print('new index: ', new.indices) if len(new.indices) == 1: # could be empty selection update_image_canvas_single(new.indices[0], data=dataframe, source=image_holder) elif len(new.indices) > 1: update_image_canvas_multi(new.indices, data=dataframe, source=image_holder) glyphs.data_source.on_change('selected', load_selected) fig = row([pca, sel], sizing_mode='stretch_both') doc.title = 'Bokeh microscopium app' doc.add_root(fig)
def _set_tools(self): wheel_zoom = WheelZoomTool() pan = PanTool() box_zoom = BoxZoomTool() box_select = BoxSelectTool() crosshair = CrosshairTool() tap = TapTool() save = SaveTool() reset = ResetTool() # TODO: add only to one plot, maybe with n_plot self.lasso_select = LassoSelectTool( renderers=self.circles, # default all available renderers select_every_mousemove=False, # enhance performance ) tooltips = ''' <style> .bk-tooltip>div:not(:nth-child(-n+5)) {{ display:none; }} /* .bk-tooltip-custom + .bk-tooltip-custom {{ display: none; sometimes everything is hidden with this }} */ .bk-tooltip>div {{ background-color: #dff0d8; padding: 5px; }} </style> <b>INDEX: </b> @INDEX <br> <b>{x}: </b> @{x} <br> <b>{x}_FLAG_W: </b> @{x}_FLAG_W <br> <b>{y}: </b> @{y} <br> <b>{y}_FLAG_W: </b> @{y}_FLAG_W <br> '''.format(x=self.x, y=self.y) hover = HoverTool( # TODO: try to make this toggleable renderers=self.circles, toggleable=True, mode='mouse', tooltips=tooltips, ) tools = ( pan, box_zoom, self.lasso_select, box_select, crosshair, save, reset, tap, wheel_zoom ) self.plot.add_tools(*tools)
def bottom_graph(self, source, ads): """Generate the bottom graphs (isotherm display).""" graph = figure(tools="pan,wheel_zoom,reset", active_scroll="wheel_zoom", plot_width=400, plot_height=250, x_range=(-0.01, 0.01), y_range=(-0.01, 0.01), title='Isotherms {0}'.format(ads)) rend = graph.multi_line('x', 'y', source=source, alpha=0.6, line_width=3, hover_line_alpha=1.0, hover_line_color="black", line_color='color') # Make clicking a graph open the NIST database graph.add_tools( HoverTool(show_arrow=False, line_policy='nearest', tooltips="""Click for details""")) graph.add_tools( TapTool(renderers=[rend], callback=CustomJS(args={ 'tp': load_details().render(), }, code=load_details_js()))) source.selected.js_on_change( 'indices', CustomJS( code= 'if (cb_obj.indices.length == 0) document.getElementById("iso-details").style.display = \"none\"' )) graph.xaxis.axis_label = 'Pressure (bar)' graph.yaxis.axis_label = 'Uptake (mmol/g)' return graph
def create_bar_chart(days, w=900, h=300): data = get_data(days) xfactor = [str(x + 1) for x in range(days)] source = ColumnDataSource(data) p = figure( title="Count per day", plot_width=w, plot_height=h, x_range=xfactor, y_range=(0, 100), toolbar_location="above", outline_line_color='black', ) p.vbar(x='days', bottom=0, top='ct', source=source, width=0.8, color=None, fill_color='colors') p.xgrid.grid_line_color = None p.ygrid.grid_line_color = "grey" p.ygrid.grid_line_alpha = 0.25 p.yaxis.axis_label = "Count" p.xaxis.axis_label = "Days" p.xaxis.major_tick_line_color = None TOOLTIPS = [ ("Day", "@days"), ("No.", "@ct"), ("color", "$color[swatch]:colors"), ] hovertool = HoverTool(tooltips=TOOLTIPS) p.add_tools(hovertool) taptool = TapTool(callback=OpenURL(url='../../scatter')) p.add_tools(taptool) return p
def __create_tools(cls, **hoverkwargs): return [ TapTool(), BoxSelectTool(dimensions='width'), BoxSelectTool(dimensions='height'), BoxSelectTool(), WheelZoomTool(), BoxZoomTool(), ResetTool(), SaveTool(), HoverTool(tooltips=[('workflow', '@Workflow'), ('activity', '@Activity'), ('result', '@Result'), ('duration', '@DurationStr'), ('started', '@StartedOnTimestampStr'), ('ended', '@EndedOnTimeStampStr')], formatters={ 'started': 'printf', 'ended': 'printf' }, show_arrow=True, **hoverkwargs) ]
from bokeh.plotting import figure from bokeh.embed import components from bokeh.models.tools import TapTool from bokeh.models.tools import HoverTool from bokeh.models.tools import ResetTool from bokeh.models.tools import SaveTool from bokeh.models.tools import BoxZoomTool from bokeh.models import DatetimeTickFormatter import numpy as np from datetime import datetime from .utils import eval_code TOOLS = [ TapTool(), BoxZoomTool(), HoverTool(), ResetTool(), SaveTool(), ] FIG_WIDTH, FIG_HEIGHT = 500, 300 def create_data_plot(f): """Create plot of x [I] vs y [B/G]. f: Function object """ try:
qosMarkers = mainViewer.circle(x=[], y=[], color='red', y_range_name='qosRange') annotation = mainViewer.line(x=[], y=[], color='navy', visible=True, line_width=3) ppgDataSource = ppgLine.data_source ppgLineMarkersDataSource = ppgLineMarkers.data_source qosDataSource = qosMarkers.data_source annotatedDataSource = annotation.data_source #### Describe how selected data are handled. #### selected_circle = Circle(fill_color='navy', visible=True) nonselected_circle = Circle(fill_color='navy', visible=False) ppgLineMarkers.selection_glyph = selected_circle ppgLineMarkers.nonselection_glyph = nonselected_circle wheel_zoom = WheelZoomTool() tap_tool = TapTool() box_select = BoxSelectTool(dimensions="width") hover = HoverTool( point_policy='snap_to_data', line_policy='nearest', tooltips=[ ("index", "$index"), ("Value", "@y"), # ("desc", "@desc"), ("Time", '@time'), ("Note", "@notes"), ], renderers=[ qosMarkers, ppgLineMarkers, ]
def __init__(self, dataset, parameters): self.dataset = dataset # Set up the controls self.specials = Selector( name="Specials", kind="specials", css_classes=["specials"], entries={ "Color-magnitude diagram": "cmd", "Period vs. radius": "pr", "Period vs. transit duration": "pdt", }, default="Color-magnitude diagram", ) self.data = Selector( name="Datasets", kind="datasets", css_classes=["data"], entries={"TOI Catalog": "toi", "Confirmed Planets": "confirmed"}, default="Confirmed Planets", ) self.xaxis = Selector( name="Build-Your-Own", kind="parameters", css_classes=["build-your-own"], entries=parameters, default="ra", title="X Axis", ) self.yaxis = Selector( kind="parameters", css_classes=["build-your-own"], entries=parameters, default="dec", title="Y Axis", ) self.size = Selector( name="Sides", kind="parameters", css_classes=["sides"], entries=parameters, default="dist", title="Marker Size", none_allowed=True, ) self.color = Selector( kind="parameters", css_classes=["sides"], entries=parameters, default="dist", title="Marker Color", none_allowed=True, ) # Set up the plot self.source = ColumnDataSource( data=dict(x=[], y=[], size=[], color=[]) ) self.plot = figure( plot_height=600, plot_width=700, title="", tooltips=[("TIC ID", "@ticid")], sizing_mode="scale_both", ) self.plot.circle( x="x", y="y", source=self.source, size="size", color=linear_cmap( field_name="color", palette=Viridis256, low=0, high=1 ), line_color=None, ) self.plot.add_tools( BoxSelectTool(), BoxZoomTool(), LassoSelectTool(), PanTool(), PolySelectTool(), TapTool(), WheelZoomTool(), WheelPanTool(), ZoomInTool(), ZoomOutTool(), HoverTool(), CrosshairTool(), ResetTool(), ) # Register the callback for control in [ self.specials, self.data, self.xaxis, self.yaxis, self.size, self.color, ]: control.widget.on_change("value", self.callback) # Load and display the data self.callback(None, None, None)
x=timepts, au=au, p1=p1, raw_lp_decim_p1=p1, p2=p2, raw_lp_decim_p2=p2)) # Create the tools for the toolbar ts_cnt = np.arange(3) cross = [CrosshairTool() for n in ts_cnt] hover = [ HoverTool(tooltips=[('time', '$x'), ('sample', '@x')]), HoverTool(tooltips=[('time', '$x'), ('val', '@p1'), ('raw', '@raw_lp_decim_p1')]), HoverTool(tooltips=[('time', '$x'), ('val', '@p2'), ('raw', '@raw_lp_decim_p2')]) ] xzoom = [BoxZoomTool(dimensions=['width']) for n in ts_cnt] xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt] xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt] xtsel = [TapTool() for n in ts_cnt] xpan = [PanTool(dimensions=['width']) for n in ts_cnt] save = [SaveTool() for n in ts_cnt] reset = [ResetTool() for n in ts_cnt] tools = [[ cross[n], hover[n], xpan[n], xzoom[n], xwzoom[n], xsel[n], xtsel[n], save[n], reset[n] ] for n in ts_cnt] data_update_in_progress = False play_all_button = Button(label='Play', button_type='success', width=60) play_all_button.on_click(play_all) play_all_sox_button = Button(label='Play sox', button_type='success', width=60) play_all_sox_button.on_click(play_all_sox) audio_first_checkbox = CheckboxGroup(labels=['audio first'], active=[0])
def setup_plot( self, x_axis_type="linear", y_axis_type="linear", x_flip=False, y_flip=False, ): # Set up the plot self.plot = figure( plot_height=620, min_width=600, title="", x_axis_type=x_axis_type, y_axis_type=y_axis_type, tools="", sizing_mode="stretch_both", ) # Enable Bokeh tools self.plot.add_tools(PanTool(), TapTool(), ResetTool()) # Axes orientation and labels self.plot.x_range.flipped = x_flip self.plot.y_range.flipped = y_flip self.plot.xaxis.axis_label = self.xaxis.value self.plot.yaxis.axis_label = self.yaxis.value # Plot the data self.plot.circle( x="x", y="y", source=self.source, size="size", color=linear_cmap(field_name="color", palette=Viridis256, low=0, high=1), line_color=None, ) # -- HACKZ -- # Update the plot element in the HTML layout if hasattr(self.parent, "layout"): self.parent.layout.children[0].children[-1] = self.plot # Make the cursor a grabber when panning code_pan_start = """ Bokeh.grabbing = true var elm = document.getElementsByClassName('bk-canvas-events')[0] elm.style.cursor = 'grabbing' """ code_pan_end = """ if(Bokeh.grabbing) { Bokeh.grabbing = false var elm = document.getElementsByClassName('bk-canvas-events')[0] elm.style.cursor = 'grab' } """ self.plot.js_on_event("panstart", CustomJS(code=code_pan_start)) self.plot.js_on_event("panend", CustomJS(code=code_pan_end)) # Add a hover tool w/ a pointer cursor code_hover = """ if((Bokeh.grabbing == 'undefined') || !Bokeh.grabbing) { var elm = document.getElementsByClassName('bk-canvas-events')[0] if (cb_data.index.indices.length > 0) { elm.style.cursor = 'pointer' Bokeh.pointing = true } else { if((Bokeh.pointing == 'undefined') || !Bokeh.pointing) elm.style.cursor = 'grab' else Bokeh.pointing = false } } """ self.plot.add_tools( HoverTool( callback=CustomJS(code=code_hover), tooltips=[("TIC ID", "@ticid")], ))
def prepare_plot(self, plot_width=700, plot_height=None, zoom=None, map_type='carto_light', title=None, **kwargs): """ Create the actual plot object (stored in `self.plot`). Parameters: plot_width (int): desired plot width, in pixels plot_height (int): desired plot height, will be calculated automatically if not supplied zoom (int): zoom factor for Google Maps, will be calculated automatically if not supplied map_type (string): 'satellite', 'roadmap', or 'hybrid' title (string or tuple): if string, title is added to plot; if tuple, the first value is the title, and second value is a dict of kwargs kwargs: any options passed to Bokeh GMapPlot (title, etc.) """ self._validate_workflow('prepare_plot') zoom_level, lat_center, lng_center, auto_plot_height = gmaps_utils.estimate_zoom( plot_width, x_bounds=(self.xmin, self.xmax), y_bounds=(self.ymin, self.ymax)) if plot_height is None: plot_height = auto_plot_height if zoom is None: zoom = zoom_level if title is not None: if isinstance(title, str): title = Title(text=title) if isinstance(title, (list, tuple)): title, title_kwargs = title title = Title(text=title, **title_kwargs) if map_type in ('satellite', 'roadmap', 'terrain', 'hybrid'): if self.api_key is None: raise ValueError( 'Class must be instantiated with Google Maps API key to use map_type `{}`' .format(map_type)) map_options = GMapOptions(lat=lat_center, lng=lng_center, map_type=map_type, zoom=zoom) self.plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options, plot_width=plot_width, plot_height=plot_height, title=title, **kwargs) self.plot.api_key = self.api_key self.plot.add_tools(WheelZoomTool(), ResetTool(), PanTool(), TapTool()) elif map_type in bokeh_utils.get_tile_source(None): x_rng, y_rng = self.xmax - self.xmin, self.ymax - self.ymin x_range = Range1d(start=coordinate_utils.coord_to_webmercator( self.xmin - (x_rng * self.padding), precision=self.precision, longitude=True), end=coordinate_utils.coord_to_webmercator( self.xmax + (x_rng * self.padding), precision=self.precision, longitude=True)) y_range = Range1d(start=coordinate_utils.coord_to_webmercator( self.ymin - (y_rng * self.padding), precision=self.precision, longitude=False), end=coordinate_utils.coord_to_webmercator( self.ymax + (y_rng * self.padding), precision=self.precision, longitude=False)) self.plot = Plot(x_range=x_range, y_range=y_range, frame_width=plot_width, frame_height=plot_height, title=title, **kwargs) self.plot.add_tile(bokeh_utils.get_tile_source(map_type)) self.plot.add_tools(WheelZoomTool(), ResetTool(), PanTool(), TapTool()) xformatter = MercatorTickFormatter(dimension="lon") xticker = MercatorTicker(dimension="lon") xaxis = LinearAxis(formatter=xformatter, ticker=xticker, axis_line_alpha=0.1, minor_tick_line_alpha=0.1, major_tick_line_alpha=0.1, major_label_text_alpha=0.5) self.plot.add_layout(xaxis, 'below') yformatter = MercatorTickFormatter(dimension="lat") yticker = MercatorTicker(dimension="lat") yaxis = LinearAxis(formatter=yformatter, ticker=yticker, axis_line_alpha=0.1, minor_tick_line_alpha=0.1, major_tick_line_alpha=0.1, major_label_text_alpha=0.5) self.plot.add_layout(yaxis, 'left') else: raise ValueError('Invalid map_type.') for source_label, source in self.sources.items(): source = self._create_columndatasource(source) for widget_name in self.widgets.keys(): widget_dict = self.widgets[widget_name] if widget_dict['source'] == source_label: widget_dict['filter'].args['source'] = source for callback_list in widget_dict[ 'widget'].js_property_callbacks.values(): for callback in callback_list: callback.args['source'] = source if source_label in self.views: self.views[source_label].source = source self.columndatasources[source_label] = source self.validation['prepare_plot'] = True return self
RoadRunner it may seem confusing, but sensor 6 acts as the diffrentiator * Kasios and Radiance are the major contributors for AGOC-3A * Major contributor to Appluimonia is Indigo. Radiance may also be a minor contributor """, width=1000, height=450) curdoc().add_root(responsibility_pretext) chemicalFactoryPlot = figure(title="Methylosmolene Responsibility", plot_width=1000, plot_height=750, x_range=(50, 130), y_range=(-10, 60)) chemicalFactoryPlot.title.text_color = '#E74C3C' chemicalFactoryPlot.add_tools(TapTool()) factory_source = ColumnDataSource( data=dict(x=factory_loc_x, y=factory_loc_y, names=factory_names)) factories = chemicalFactoryPlot.square(x='x', y='y', size=15, fill_color='black', source=factory_source) factories_labels = LabelSet(x='x', y='y', text='names', level='glyph', x_offset=8, y_offset=8, render_mode='canvas', text_font_size='10pt',
def make_explorer(data_file, explorer_type='Customised'): #explorer_type options: 'Customised', 'Small', 'Big' def go_back(): som.revert_active_learning() groove_map_info.update( pd.DataFrame( get_winners(features, names, som, palette_names), columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour'])) for i in range(94): new_X = groove_map_info['X'][i] new_Y = groove_map_info['Y'][i] source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]}) def reset(): som.reset_active_learning() groove_map_info.update( pd.DataFrame( get_winners(features, names, som, palette_names), columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour'])) for i in range(94): new_X = groove_map_info['X'][i] new_Y = groove_map_info['Y'][i] source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]}) def pan_python_callback(): print('pan callback executed') for i in range(94): if source.data['X'][i] != groove_map_info['X'][i]: old_coordinates = [ int(round(groove_map_info['X'][i], 0)), int(round(groove_map_info['Y'][i], 0)) ] new_X = round(source.data['X'][i], 0) + round( random.uniform(-0.2, 0.2), 2) new_Y = round(source.data['Y'][i], 0) + round( random.uniform(-0.2, 0.2), 2) # source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]}) groove_map_info.at[i, 'X'] = new_X groove_map_info.at[i, 'Y'] = new_Y new_coordinates = [int(round(new_X, 0)), int(round(new_Y, 0))] print("Groove = ", source.data['GrooveName'][i]) print("New coordinates = ", new_coordinates) print("Old coordinates =", old_coordinates) groove = features[i] som.update_active_learning_nurnberger_local( groove, new_coordinates, old_coordinates) groove_map_info.update( pd.DataFrame( get_winners(features, names, som, palette_names), columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour'])) for i in range(94): new_X = groove_map_info['X'][i] new_Y = groove_map_info['Y'][i] source.patch({'X': [(i, new_X)], 'Y': [(i, new_Y)]}) print('Done') def make_audio_panel(explorer_type): PLAY_TEST_AUDIO = """ var index = selector.active; var labels = ['A', 'B', 'C', 'D', 'E']; var filename = path + labels[index] + '.mp3'; audio_player.stop_audio(); audio_player.play_audio(filename); """ STOPCODE = """ audio_player.stop_audio(); """ if explorer_type == 'Small': test_audio_path = 'Groove-Explorer-2/static/Test Audio/Groove Explorer Part 1 - Small/' if explorer_type == 'Customised': test_audio_path = 'Groove-Explorer-2/static/Test Audio/Groove Explorer Part 2 - Customisable/' labels = ['A', 'B', 'C', 'D', 'E'] audio_selector = RadioGroup(labels=labels, height_policy="auto", sizing_mode='scale_width', active=0) play_button = Button(label='Play') play_button.js_on_click( CustomJS(args=dict(selector=audio_selector, path=test_audio_path), code=PLAY_TEST_AUDIO)) stop_button = Button(label='Stop') stop_button.js_on_click(CustomJS(code=STOPCODE)) audio_panel = column(audio_selector, play_button, stop_button) return audio_panel PLAY_FROM_EXPLORER = """ var selected = source.selected.indices; var groovename = source.data['GrooveName'][selected[0]]; var palette = source.data['PaletteName'][selected[0]]; var filetype = ".mp3"; var filename = path + palette + '/' + groovename + '.mp3' audio_player.stop_audio(); audio_player.play_audio(filename); """ hover = HoverTool() hover.tooltips = [ ('Name', '@GrooveName'), ('Palette', '@PaletteName'), ] TOOLS = "crosshair, wheel_zoom, pan, reset" if explorer_type in ['Small', 'Customised']: dim = 12 som, features, names, palette_names = setup_SOM(data_file, dim) if explorer_type == 'Small': explorer_audio_path = "Groove-Explorer-2/static/Part 1 MP3 - Seperate Folders/" som.weights = np.load( "Groove-Explorer-2/SOM_Weights_MLR_3M_Part1.npy") elif explorer_type == 'Customised': explorer_audio_path = "Groove-Explorer-2/static/Part 3 MP3 - Seperate Folders/" som.weights = np.load( "Groove-Explorer-2/SOM_Weights_MLR_2M_Part3.npy") groove_map_info = pd.DataFrame( get_winners(features, names, som, palette_names), columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour']) source = ColumnDataSource(groove_map_info) explorer = figure(x_range=(-1, dim), y_range=(-1, dim), tools=TOOLS, title='Groove Explorer 2') audio_selector = make_audio_panel(explorer_type) elif explorer_type == 'Big': dim = 28 som, features, names, palette_names = setup_SOM(data_file, dim) explorer_audio_path = "Groove-Explorer-2/static/Big_Dataset_Reduced/" som.weights = np.load( "Groove-Explorer-2/SOM_Weights_MLR_3M_BIG_s3-5_28x28.npy") groove_map_info = pd.DataFrame( get_winners(features, names, som, palette_names), columns=['GrooveName', 'PaletteName', 'X', 'Y', 'Colour']) source = ColumnDataSource(groove_map_info) explorer = figure(x_range=(-1, dim), y_range=(-1, dim), tools=TOOLS, title='Groove Explorer 2', plot_width=700, plot_height=700) explorer.add_tools(hover) explorer.add_tools( TapTool(callback=CustomJS(code=PLAY_FROM_EXPLORER, args=dict(source=source, path=explorer_audio_path)))) renderer = explorer.circle(source=source, x='X', y='Y', color='Colour', fill_alpha=0.6, size=15, hover_fill_color='yellow', hover_alpha=1, nonselection_alpha=0.6) if explorer_type == 'Customised': point_drag = PointDrawTool(renderers=[renderer], add=False) explorer.add_tools(point_drag) explorer.on_event(PanEnd, pan_python_callback) go_back_button = Button(label='Undo Customize') reset_button = Button(label='Reset Customization') go_back_button.on_click(go_back) reset_button.on_click(reset) return row(column(explorer, go_back_button, reset_button), audio_selector) elif explorer_type == 'Small': return row(explorer, audio_selector) elif explorer_type == 'Big': return explorer
# create widgets expt_select = Select(title='Experiment:', options=expts, value=expts[0]) refresh = Button(label='Update') div = Div(width=1000) # hover tools hover = HoverTool(tooltips=[('variable', '@variable'), ('start', '@time_start{%F}'), ('end', '@time_end{%F}'), ('run', '@run'), ('file', '@ncfile')], formatters={ 'time_start': 'datetime', 'time_end': 'datetime' }) tap = TapTool() box_select = BoxSelectTool() tools = [hover, box_select, tap, 'pan', 'box_zoom', 'wheel_zoom', 'reset'] df = get_data(expt_select.value) freqs = df.frequency.unique() cmap = factor_cmap('frequency', palette=bokeh.palettes.Category10[10], factors=freqs) cds = ColumnDataSource(df, callback=print_selected(div)) p = figure(y_range=df.variable.unique(), x_range=(df.iloc[0].time_start, df.iloc[-1].time_end), title=expt_select.value, tools=tools) cmap = factor_cmap('frequency',
ppgViewer.extra_y_ranges = {"qosRange": Range1d(start=-1.1, end=1.1)} ppgViewer.xaxis.formatter = DatetimeTickFormatter( years=["%D %T"], months=["%D %T"], days=["%D %T"], hours=["%D %T"], hourmin=["%D %T"], minutes=["%D %T"], minsec=["%D %T"], seconds=["%D %T"], milliseconds=["%D %T.%3N"], ) # Create tools to add to ppgViewer. wheel_zoom = WheelZoomTool() tap_tool = TapTool() resizeTool = ResizeTool() box_select = BoxSelectTool(dimensions="width") hover = HoverTool( point_policy='snap_to_data', line_policy='nearest', tooltips=[ ("index", "$index"), ("Value", "@y"), ("Time", '@time'), ], ) # Create tools to add to ekgViewer. wheel_zoom_ekg = WheelZoomTool() tap_tool_ekg = TapTool()