def __init__(self, extent: list = None, **kwargs): pn.extension() self.max_height = 800 self.center = 0 self.min_height = -200 self.sea = False self.sea_contour = False self.sea_level_patch = None self.col = None # Check if image is loaded self.type_fluid = ["water", "lava", "slime"] self.name_fluid = self.type_fluid[0] self.fluid = None # Image to create the texture self.texture = None # resultant texture after masking with path if extent is not None: self.extent = extent self.load_fluid() self.animate = True self._anim = 0 # animation # Settings for sea level polygon self.path = None self.sea_level_polygon_alpha = 0.7 self.sea_level_polygon_line_thickness = 2. self.sea_level_polygon_line_color = mcolors.to_hex("blue") self.sea_zorder = 1000 self.sea_fill = True self._marker_contour_val = None self.side_flooding = False logger.info("TopoModule loaded successfully")
def init(json_loc, output_loc): global PARSED_JSON, OUTPUT_LOC pn.extension() PARSED_JSON = json.loads(open(json_loc, 'r', encoding='utf-8').read()) OUTPUT_LOC = output_loc print("Init") asyncio.create_task(get_apis_to_download())
def test_complex_use_case(): # Given pre_raw_css = "body {background: black;" pre_css_file = "https://somedomain.com/test.css" pre_js = "http://some/domain.com/test.js" pre_extension = "plotly" extension = "katex" # When pn.extension(pre_extension) pn.config.raw_css.append(pre_raw_css) pn.config.css_files.append(pre_css_file) pn.config.js_files = {"somejs": pre_js} backup_css_files = pn.config.css_files with TemporaryResources(extensions={extension}, include_panel_css=False): text = pn.io.resources.Resources().render() # Then assert "bokeh-" in text assert "bokeh-widgets" in text assert "bokeh-tables" in text assert ".panel-widget-box" not in text assert extension in text assert pre_raw_css not in text assert pre_css_file not in text assert pre_js not in text assert pre_extension not in text assert pn.config.raw_css == [pre_raw_css] assert pn.config.js_files == {"somejs": pre_js} assert pn.config.css_files == backup_css_files
def create_layout(self): pn.extension() title = pn.pane.Markdown(""" # Stock Index Correlation """, background='#007500') title.session_id = self.session_id output = interact(self.stockindex_model, stock='TSLA') output.session_id = self.session_id # df_info = output[1][0].object # df_widget = pn.widgets.DataFrame( # df_info, name='DataFrame', autosize_mode='fit_columns',width=900) # df_widget.session_id = self.session_id # Plot forecast and real data layout = interact(self.layout_vis, stock='TSLA') layout.session_id = self.session_id layout2 = interact(self.layout_vis2, stock='TSLA') layout2.session_id = self.session_id app_col = pn.Column(title, output[0], output[1][0], layout[1], width=900) app_row = pn.Row(app_col, layout2[1], margin=(25, 5, 25, 25), width=900) #, background='#007500') return app_row
def do_import(): try: import panel as pn from .gui import GUI css = """ .scrolling { overflow: scroll; } """ pn.config.raw_css.append( css) # add scrolling class from css (panel GH#383, GH#384) pn.extension() except ImportError: class GUI(object): def __repr__(self): raise RuntimeError( "Please install panel to use the GUI `conda " "install -c conda-forge panel==0.5.1`") except Exception as e: class GUI(object): def __repr__(self): raise RuntimeError( "Initialisation of GUI failed, even though " "panel is installed. Please update it " "to a more recent version (`conda install -c" " conda-forge panel==0.5.1`).") return GUI
def create_host_plots_clean(): pn.extension('mathjax') # load aiida if necessary profile = load_profile(profile_name) ase_atoms = prepare_plotting_structure() strucview = create_structure_plot(ase_atoms, static_plot=True) # create bandstructure plot bandstruc_plot = plot_bandstruc() # make DOS plot dos_plot, ymax = plot_dos() # add ef lines to bandstructure plot (needs to be done here since some values are otherwise not defined) add_ef_lines_bandstruc(bandstruc_plot, ymax) # put bandstructure and DOS plots together layout = pn.Row(bandstruc_plot, dos_plot) #struc_title = pn.pane.LaTeX("Thin film (6QL) of Sb$_2$Te$_3$") #host_plots = pn.Row(pn.Column(struc_title, strucview), layout) host_plots = pn.Row(strucview, layout) return host_plots
def visualize_heritage(self, db): import panel as pn import holoviews as hv pn.extension() # hv.extension("bokeh") dg = self.digraph(db) layout = { k: [v[1], v[0]] for k, v in hierarchy_pos(dg, vert_gap=1).items() } graph = hv.Graph.from_networkx(dg, layout) graph = graph.opts( node_alpha=0.2, node_hover_fill_color="red", xaxis=None, yaxis=None, toolbar=None, node_hover_alpha=1, node_size=20, invert_xaxis=False, tools=['hover'], directed=True, arrowhead_length=0.01, ) return pn.panel(graph, sizing_mode="stretch_both")
def init(json_loc, output_loc, api_names): global PARSED_JSON, OUTPUT_LOC pn.extension() PARSED_JSON = json.loads(open(json_loc, 'r', encoding='utf-8').read()) OUTPUT_LOC = output_loc docs = download_data(apis) tokenize_and_vectorize_files(docs)
def show_panel(plotter, return_viewer): """Take the active renderer(s) from a plotter and show them using ``panel``.""" try: import panel as pn except ImportError: # pragma: no cover raise ImportError('Install ``panel`` to use this feature') # check if panel extension has been set if not PANEL_EXTENSION_SET[0]: pn.extension('vtk') PANEL_EXTENSION_SET[0] = True # only set window size if explicitly set within the plotter sizing = {} if not plotter._window_size_unset: width, height = plotter.window_size sizing = {'width': width, 'height': height} axes_enabled = plotter.renderer.axes_enabled pan = pn.panel(plotter.ren_win, sizing_mode='stretch_width', orientation_widget=axes_enabled, enable_keybindings=False, **sizing) # if plotter.renderer.axes_enabled: # pan.axes = build_panel_axes() if hasattr(plotter.renderer, 'cube_axes_actor'): pan.axes = build_panel_bounds(plotter.renderer.cube_axes_actor) if return_viewer: return pan display.display_html(pan)
def __init__(self, extent: list = None): # call parents' class init, use greyscale colormap as standard and extreme color labeling pn.extension() if extent is not None: self.vmin = extent[4] self.vmax = extent[5] self.extent = extent self.frame = None # all possible type of gradient plots self.grad_type = [ 'Original', 'Gradient dx', 'Gradient dy', 'Gradient all', 'Laplacian', 'Lightsource', 'White background' ] self.active_stream = False self.active_vector = False self.vector = None self.stream = None self.current_grad = self.grad_type[0] # lightsource parameter self.azdeg = 315 self.altdeg = 4 self.ve = 0.25 self.set_lightsource() logger.info("GradientModule loaded successfully")
def interactive_scan(model, variables, params): param_widgets = [p.slider for p in params] variable_widgets = [p.checkbox for p in variables] adv = pn.widgets.Toggle(name='Advanced options') t = TimeClass() @pn.depends(adv, watch=True) def _reactive_widgets(self): if adv.value == True: return pn.Column(pn.Row(t.param)) else: return pn.Column() def panel(): expand_layout = pn.Column() return pn.Column( pn.panel(_reactive_widgets, expand=True, expand_layout=expand_layout), expand_layout) @pn.depends(*param_widgets, *variable_widgets, watch=True) def reactive_plot(*listening_to): return get_odesoln(model, variables, t, listening_to[:-len(variables)]) widgets = pn.Row(pn.Column(*param_widgets, adv), pn.Column(*variable_widgets)) window = pn.Row(reactive_plot, pn.Column(widgets, panel)) pn.extension() return window
def embedWindow(backend='k3d', verbose=True): """Use this function to control whether the rendering window is inside the jupyter notebook or as an independent external window""" global notebook_plotter, notebookBackend if not backend: notebookBackend = None notebook_plotter = None return else: try: get_ipython() except: notebookBackend = None notebook_plotter = None return notebookBackend = backend if backend == 'k3d': try: import k3d except: notebookBackend = None if verbose: print( 'embedWindow(verbose=True): could not load k3d module, try:' ) print('> pip install k3d # and if necessary:') print('> conda install nodejs') elif 'itk' in backend: # itkwidgets try: import itkwidgets except: notebookBackend = None if verbose: print( 'embedWindow(verbose=True): could not load itkwidgets module, try:' ) print('> pip install itkwidgets # and if necessary:') print('> conda install nodejs') elif backend == 'panel': try: if verbose: print( 'INFO: embedWindow(verbose=True), first import of panel module, this takes time...' ) import panel panel.extension('vtk') except: if verbose: print('embedWindow(verbose=True): could not load panel try:') print('> pip install panel # and/or') print('> conda install nodejs') else: print("Unknown backend", backend) raise RuntimeError()
def extension(): pn.extension('ace') pn.config.raw_css.append(css) try: import holoviews as hv hv.extension('bokeh') except ImportError: print("Cannot import holoviews, plotting will not work.")
def _set_css(self): """Define CSS properties. """ css = {} css[f".viewer-{self.viewer_id}"] = {} # css[f'.viewer-{self.viewer_id}']['border'] = '1px #9d9d9d solid !important' css_string = css_dict_to_string(css) pn.extension(raw_css=[css_string])
def load_notebook_assets(): pn.extension() pn.extension( js_files={"deck": deck, "mapbox": mapbox, "deck_json": deck_json}, css_files=[ "https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.0/mapbox-gl.css" ], )
def show(self, embed=False, initial_style=None): pn.extension() self.embed = embed # Apply initial styles if initial_style is None: initial_style = {} self.show_line_numbers = initial_style.get("line_numbers", self.show_line_numbers) self.highlight_style = initial_style.get("highlight_style", self.highlight_style) self.build() if "tab" in initial_style: tab_name = initial_style.get("tab", "sequential").lower() pass_name = initial_style.get("pass", self.initial_pass) ipass = self._find_pass_index(pass_name) if tab_name == "sequential": assert (pass_name != self.initial_pass ), "Sequential tab does not have Initial option" self._ui["seq_select"].value = pass_name self._shown_stages[0] = ipass - 1 self._shown_stages[1] = ipass elif tab_name == "single": self._ui["tabs"].active = 1 self._ui["sgl_select"].value = pass_name self._shown_stages[2] = ipass elif tab_name == "double": self._ui["tabs"].active = 2 pass2_name = initial_style.get("pass2", self.passes[0]) ipass2 = self._find_pass_index(pass2_name) self._ui["dbl_select_left"].value = pass_name self._ui["dbl_select_right"].value = pass2_name self._shown_stages[3] = ipass self._shown_stages[4] = ipass2 elif tab_name == "edit": self._ui["tabs"].active = 3 else: raise KeyError(f"Invalid tab name: {initial_style.get('tab')}") self.rebuild() if embed: return self.panel else: pn.config.raw_css = [ self.html_formatter.get_style_defs( f".highlight_{self.rndchars}"), """ pre { overflow-x: auto; white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word; } """, ] return self.panel.show("MLIR Code Pass Explorer")
def _validate_jupyter_backend(backend): """Validate that a jupyter backend is valid. Returns the normalized name of the backend. Raises if the backend is invalid. """ # Must be a string if backend is None: backend = 'none' backend = backend.lower() try: import IPython except ImportError: # pragma: no cover raise ImportError('Install IPython to display with pyvista in a notebook.') if backend == 'ipyvtk_simple': try: import ipyvtklink except ImportError: raise ImportError('Please install `ipyvtklink`. `ipyvtk_simple` ' 'is deprecated.') else: backend = 'ipyvtklink' if backend not in ALLOWED_BACKENDS: backend_list_str = ', '.join([f'"{item}"' for item in ALLOWED_BACKENDS]) raise ValueError(f'Invalid Jupyter notebook plotting backend "{backend}".\n' f'Use one of the following:\n{backend_list_str}') # verify required packages are installed if backend == 'pythreejs': try: import pythreejs except ImportError: # pragma: no cover raise ImportError('Please install `pythreejs` to use this feature.') if backend == 'ipyvtklink': try: import ipyvtklink except ImportError: # pragma: no cover raise ImportError('Please install `ipyvtklink` to use this feature.') if backend == 'panel': try: import panel except ImportError: # pragma: no cover raise ImportError('Please install `panel` to use this feature.') panel.extension('vtk') if backend == 'ipygany': # raises an import error when fail from pyvista.jupyter import pv_ipygany if backend == 'none': backend = None return backend
def serve(self, static_dirs=None, **kwargs): """ Wrapper for pn.serve, with the inclusion of the required static assets.""" static_dirs = {} if static_dirs is None else static_dirs assets_elvis = {'assets': os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, 'assets'))} kwargs.setdefault('title', self.title) css, js = self._get_assets("", self.theme) pn.extension(css_files=css, js_files=js) return pn.serve(self.app, static_dirs={**assets_elvis, **static_dirs}, **kwargs)
def main(method_num): # Method 1: Quickly create a web visualization with Python back-end # support. if method_num == 1: # NOTE: Documentation states, "Initializes the pyviz notebook extension # to allow plotting with bokeh and enable comms." It seems that # `panel.extension` is not required when generating web # visualizations with the `.show()` method. pn.extension() pn.interact(panel_wrapper).show() # Method 2: Adjust the layout of the quick creation in Method 1. if method_num == 2: i = pn.interact(panel_wrapper) text = "<br>\n# Random Walk as a Function of Standard Deviation" p = pn.Row(i[1][0], pn.Column(text, i[0][0])) p.show() # Method 3, 4, & 5: Explicitly build the panel objects. if method_num == 3 or method_num == 4 or method_num == 5: c_opts = ["default", "optimized", "calibrated", "variable"] dummy_catagory = pn.widgets.RadioButtonGroup(name="dummy_catagory", value="default", options=c_opts) stdev = pn.widgets.FloatSlider(name="stdev", value=0.03, start=0, end=0.1, step=0.01) @pn.depends(stdev, dummy_catagory) def reactive_panel(stdev, dummy_catagory): return panel_wrapper(stdev, dummy_catagory) text = "<br>\n# Random Walk as a Function of Standard Deviation" widgets = pn.Column(text, stdev, dummy_catagory) p_rw = pn.Row(reactive_panel, widgets) # Method 3: Deploy a web visualization with a Python server. if method_num == 3: p_rw.show() # Method 4: Deploy a web visualization with data embedded in HTML. # NOTE: This stand alone version works with the following web browsers: # - Chrome Version 80.0.3987.122 # - Microsoft Edge 41.16299.1480.0 # This stand alone version does not work with the following web # browsers: # - Internet Explorer Version 11.1685.16299.0. if method_num == 4: f_out = "test.html" p_rw.save(f_out, title="This is a test", embed=True, max_opts=10) # Method 5: Deploy a web visualization referencing json data files. if method_num == 5: f_out = "test_json.html" p_rw.save(f_out, title="This is a test", embed=True, max_opts=10, embed_json=True) return 0
def bk_worker(bokeh_port: int) -> None: pn.extension() server = bokeh.server.server.Server( {"/": modify_doc}, io_loop=tornado.ioloop.IOLoop(), allow_websocket_origin=[f"127.0.0.1:{bokeh_port}"], port=bokeh_port, ) server.start() server.io_loop.start()
def __init__(self, data): super().__init__() xr.set_options(display_style='html') pn.extension(raw_css=[CSS]) self.data = data self.panel = pn.pane.HTML(min_width=500, max_height=250, css_classes=['xrviz-scroll']) self.panel.object = "Description Section" self.setup()
def echarts_tree(self, label="Tree view"): from ..visualizations import echarts_graph import panel as pn pn.extension('echarts') echart = echarts_graph(self.to_echarts_series("root"), label) echart_pane = pn.pane.ECharts(echart, width=700, height=400, sizing_mode="stretch_both") return echart_pane
def _widget_sensor_bottom_slider(self): """ displays a widget to toggle between the currently active dataset while the sandbox is running Returns: """ pn.extension() widget = pn.widgets.IntSlider(name='offset bottom of the model ', start=-250, end=250, step=1, value=0) widget.param.watch(self._callback_bottom_slider, 'value', onlychanged=False) return widget
def test_does_not_include_pn_extension(): # Given pre_extension = "plotly" # When pn.extension(pre_extension) with TemporaryResources(): text = pn.io.resources.Resources().render() # Then assert pre_extension not in text assert _contains_bokeh_and_panel_resources(text)
def widget_mask_threshold(self): """ displays a widget to adjust the mask threshold value """ pn.extension() widget = pn.widgets.FloatSlider(name='mask threshold (values smaller than the set threshold will be masked)', start=0.0, end=1.0, step=0.01, value=self.mask_threshold) widget.param.watch(self._callback_mask_threshold, 'value', onlychanged=False) return widget
def __enter__(self): if self._extensions: pn.extension(*self._extensions) pn.config.raw_css = self._raw_css pn.config.js_files = self._js_files pn.config.css_files = [*self._panel_css_files, *self._css_files] exclude_extension = self._get_exclude_extension_func(self._extensions) Model.model_class_reverse_map = { name: model for name, model in self._backup_model_class_reverse_map.items() if not exclude_extension(name) }
def apply_theme(self, properties_dict): """ apply thematic changes to the chart based on the input properties dictionary. """ css = """ .custom-dropdown select, .custom-dropdown option {{ background-color: {0} !important; }} """ css = css.format(properties_dict["widgets"]["background_color"]) pn.extension(raw_css=[css]) self.chart.css_classes = ["custom-dropdown"]
def _widget_model_selector(self): """ displays a widget to toggle between the currently active dataset while the sandbox is running Returns: """ pn.extension() widget = pn.widgets.RadioButtonGroup(name='Model selector', options=list(self.block_dict.keys()), value=self.displayed_dataset_key, button_type='success') widget.param.watch(self._callback_selection, 'value', onlychanged=False) return widget
def embedWindow(backend='k3d', verbose=True): global notebook_plotter, notebookBackend if not backend: notebookBackend = None notebook_plotter = None return notebookBackend = backend if backend == 'k3d': try: get_ipython() except: notebookBackend = None return try: import k3d #if verbose: # print('INFO: embedWindow(verbose=True), importing k3d module') except: notebookBackend = None if verbose: print( 'embedWindow(verbose=True): could not load k3d module, try:' ) print('> pip install k3d # and/or') print('> conda install nodejs') elif backend == 'panel': try: get_ipython() if verbose: print( 'INFO: embedWindow(verbose=True), first import of panel module, this takes time...' ) import panel panel.extension('vtk') except: if verbose: print('embedWindow(verbose=True): could not load panel try:') print('> pip install panel # and/or') print('> conda install nodejs') else: print("Unknown backend", backend) raise RuntimeError()
def _set_css(self): css = {} css[f".log-widget-container-{self.widget_id}"] = {} css[f".log-widget-container-{self.widget_id}"][ "width"] = "98% !important" css[f".log-widget-container-{self.widget_id}"][ "background"] = "#f4f4f4" css[f".log-widget-container-{self.widget_id}"][ "border"] = "1px #eaeaea solid !important" css[f".log-widget-container-{self.widget_id}"]["overflow-y"] = "scroll" css[f".log-widget-container-{self.widget_id}"]["overflow-x"] = "hidden" css[f".log-widget-container-{self.widget_id}"]["border-radius"] = "0" css[f".log-widget-{self.widget_id}"] = {} css[f".log-widget-{self.widget_id}"]["width"] = "100% !important" css_string = css_dict_to_string(css) pn.extension(raw_css=[css_string])