class posteriorDashboard(param.Parameterized): """ Dashboard for the posterior view data should be dictionary of model objects and should be set on instantiation along with the name variable needs to be set with the posterior variables list after instantiation returns a panel row with the parameter controls and the plots """ data = param.Dict(precedence=-1) variable = param.Selector(None) plot_type = param.Selector(inputs, default=inputs[0], doc='Type of Plot:') percentage = param.Number(default=100, bounds=(10, 100), step=10, doc='Percentage of Data:') @param.depends('variable', 'plot_type', 'data', 'percentage') def plot(self): return posterior_density_plot(variable=self.variable, data=self.data, percent=self.percentage, plottype=self.plot_type) def panel(self): return pn.Row(self.param, self.plot, sizing_mode='scale_both')
class AdsFairnessExplorer(param.Parameterized): protected_features = [GENDER, AGE] ad_types = ['All', 'Kitchen & Home', 'Office Products', 'Dating Sites', 'Clothing & Shoes', 'Betting', 'Musical Instruments', 'Grocery', 'DIY & Tools', 'Toys & Games', 'Media (BMVD)', 'Jewellery & Watches', 'Health & Beauty', 'Sports & Outdoors', 'Pet Supplies', 'Console & Video Games', 'Consumer Electronics', 'Automotive', 'Computer Software', 'Garden & Outdoor living', 'Baby Products'] protected_feature = param.Selector(sorted(protected_features), default=GENDER) ad_category = param.Selector(sorted(ad_types), default='All') @param.depends('protected_feature', "ad_category") def make_view(self): state = fetch_all_models_metrics_for_feature_on_dataset(self.protected_feature, self.ad_category) total_records_count = reduce(lambda acc, model_stats: model_stats["total_count"] + acc, state.values(), 0) plotted_records_count = reduce(lambda acc, model_stats: model_stats["plot_count"] + acc, state.values(), 0) num_models = len(state.values()) html_stats_div = lambda s: f"""<p style="text-align: center; margin-top: 3rem;">{s}</p>""" stats_text = html_stats_div(f"{self.ad_category} ad category has {plotted_records_count / num_models:.2f} records of {total_records_count / num_models:.0f} records in total on an average") gspec = pn.GridSpec(sizing_mode="stretch_both", align="center") # background="gray" gspec[:15, :2] = chart_for_metric(state, FPR, fpr_opts) gspec[:15, 2:4] = chart_for_metric(state, EOD, gfm_opts) gspec[:15, 4:6] = chart_for_metric(state, AOD, gfm_opts) gspec[15, :] = stats_text return gspec
class Stats(param.Parameterized): year = param.Selector() metric = param.Selector(default='Images') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._stats_path = None self.df = None self.get_data() # Set some default for the params now that we have data. self.param.year.objects = [2016, 2017, 2018, 2019, 2020] self.year = 2020 self.param.metric.objects = self.df.select_dtypes(include='float64').columns.tolist() self.metric = 'Total Hours' @param.depends('year', 'metric') def plot(self): self.get_data() year = self.year metric = self.metric df2 = self.df.query('Year == @year').copy() df2 = df2.reset_index().sort_values(by=['Unit', 'Week']).set_index(['Week']) title = '{} {}={}'.format( year, metric.title().replace('_', ' '), int(df2[metric].sum()) ) return df2.hvplot.bar( y=metric, stacked=True, by='Unit', title=title, rot=90 ) def widget_box(self): return pn.WidgetBox( pn.Param( self.param, widgets={ 'year': pn.widgets.RadioButtonGroup, 'metric': pn.widgets.RadioBoxGroup, } ), ) def get_data(self): logger.debug(f'Getting recent stats from {BASE_URL}') self._stats_path = download_file(f'{BASE_URL}', cache='update', show_progress=False, pkgname='panoptes') stats_df = pd.read_csv(self._stats_path).convert_dtypes(convert_integer=False) self.df = stats_df.sort_index()
class NGLViewer(pn.pane.HTML): """The [NGL Viewer](https://github.com/nglviewer/ngl) can be used to show and analyse pdb molecule structures""" pdb_string = param.String() rcsb_id = param.String() representation = param.Selector( default="ribbon", objects=REPRESENTATIONS, ) color_scheme = param.Selector(default="chainid", objects=COLOR_SCHEMES) spin = param.Boolean(default=False) priority = 0 _rename = dict( pn.pane.HTML._rename, pdb_string=None, rcsb_id=None, representation=None, spin=None, color_scheme=None, ) def __init__(self, **params): super().__init__(**params) self.load_string = """ stage = new NGL.Stage("viewport"); stage.loadFile()""" self._update_object_from_parameters() @param.depends("representation", "spin", "color_scheme", watch=True) def _update_object_from_parameters(self): html = f"""\ <div id="viewport" style="width:100%; height:100%;"></div> <script> {self.load_string}.then(function(o){{ o.addRepresentation("{self.representation}", {{colorScheme: "{self.color_scheme}"}}); o.autoView(); }} ); stage.setSpin({'true' if self.spin else 'false'}); </script> """ self.object = html @param.depends("pdb_string", watch=True) def _update_object_from_pdb_string(self): self.load_string = f""" var PDBString = `{self.pdb_string}`; stage = new NGL.Stage("viewport"); stage.loadFile( new Blob([PDBString], {{type: 'text/plain'}}), {{ ext:'pdb'}} )""" self._update_object_from_parameters() @param.depends("rcsb_id", watch=True) def _update_object_from_rcsb_id(self): self.load_string = f""" stage = new NGL.Stage("viewport"); stage.loadFile("rcsb://{self.rcsb_id}")""" self._update_object_from_parameters()
class Style(Controls): cnorm = param.Selector(default='linear', objects=['linear', 'log', 'eq_hist']) color = param.String(default=None) cmap = param.Selector(default=None, label='Colormap', objects=COLORMAPS) alpha = param.Magnitude(default=1)
class FlexBox(ListLike, ReactiveHTML): align_content = param.Selector(default='flex-start', objects=[ 'normal', 'flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly', 'stretch', 'start', 'end', 'baseline', 'first baseline', 'last baseline' ], doc=""" Defines how a flex container's lines align when there is extra space in the cross-axis.""") align_items = param.Selector(default='flex-start', objects=[ 'stretch', 'flex-start', 'flex-end', 'center', 'baseline', 'first baseline', 'last baseline', 'start', 'end', 'self-start', 'self-end' ], doc=""" Defines the default behavior for how flex items are laid out along the cross axis on the current line.""") flex_direction = param.Selector( default='row', objects=['row', 'row-reverse', 'column', 'column-reverse'], doc=""" This establishes the main-axis, thus defining the direction flex items are placed in the flex container.""") flex_wrap = param.Selector(default='wrap', objects=['nowrap', 'wrap', 'wrap-reverse'], doc=""" Whether and how to wrap items in the flex container.""") justify_content = param.Selector(default='flex-start', objects=[ 'flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly', 'start', 'end', 'left', 'right' ], doc=""" Defines the alignment along the main axis.""") _template = (Path(__file__).parent / 'flexbox.html').read_text('utf-8') def __init__(self, *objects, **params): if 'sizing_mode' not in params: direction = params.get('flex_direction', self.flex_direction) if direction.startswith('row'): params['sizing_mode'] = 'stretch_width' else: params['sizing_mode'] = 'stretch_height' super().__init__(objects=list(objects), **params)
class SuperMarketController(FruitStallController): """ This controller extends the Fruit Stall into a Supermarket, also offering users a selection of milk and cheeses. """ title = 'Supermarket' milk = param.Selector(default='semi-skimmed', objects=['full-fat', 'semi-skimmed', 'skimmed'], doc='Select fat content for the milk.') cheese = param.Selector(default='Jong Belegen', objects=['Jong Belegen', 'Brie', 'Reblouchon'], doc='Jong Belegen is highly recommended.') def __init__(self, **params): super(FruitStallController, self).__init__(**params)
class FruitStallController(param.Parameterized): """ This controller lets the user choose a type of fruit, set the amount and then buy some. The docstring has two lines. Which is ignored. Lets try some whitespace. This is the next line after the whitespace. """ title = 'Fruit Stall' random_attribute = 10 # not shown in GUI hidden_param = param.Boolean( precedence=-1, doc= 'This parameter is documented but due to low precedence not shown in documentation.' ) fruit = param.Selector(default='apple', objects=['apple', 'pear', 'banana'], doc='Select type of fruit to buy.') quantity = param.Integer(5, bounds=(0, None), doc='Number of selected fruit to buy.') price = param.Number(0., constant=True, bounds=(0, None), doc='Price of the fruit per piece.') button = param.Action(lambda x: print('You bought fruit'), doc='Press this button to buy some fruit!', label='Make Purchase') def __init__(self, **params): super(FruitStallController, self).__init__(**params) @param.depends('fruit', watch=True) def _update_price(self): price_list = {'apple': 1.30, 'pear': 1.55, 'banana': 2.00} self.price = price_list[self.fruit]
class IndicatorView(View): """ The IndicatorView renders the latest field value as a Panel Indicator. """ indicator = param.Selector(objects=_INDICATORS, doc=""" The name of the panel Indicator type.""") label = param.String(doc=""" A custom label to use for the Indicator.""") view_type = 'indicator' def __init__(self, **params): super().__init__(**params) name = params.get('label', params.get('field', '')) self.kwargs['name'] = name def get_panel(self): return self.indicator(**self._get_params()) def _get_params(self): params = dict(self.kwargs) if 'data' in self.indicator.param: params['data'] = self.get_data() else: value = self.get_value() if (not isinstance(value, (type(None), str)) and np.isnan(value)): value = None params['value'] = value return params
class ChoroplethMapAppService(BaseMapApp): maillageChoice = param.ObjectSelector(default=maillage[0], objects=maillage) selector = param.Selector(objects=["red", "yellow", "green"]) num = param.Number() def __init__(self, **params): self.type = TypeVizEnum.CHOROPLETH_MAP super(ChoroplethMapAppService, self).__init__(**params) def getConfigTracePanel(self, **params): self.configTracePanel = pn.Column(self.param.maillageChoice, self.param.selector, self.param.num) return super().getConfigTracePanel() def getVizConfig(self): self.configVizPanel.append() return super().getConfigVizPanel() def getView(self): # customize defaut options return super().getView() @param.depends('maillageChoice', 'selector', 'num', watch=True) def changeProperties(self): if not self.silently: self.refreshViz() self.silently = False def createOverlay(self, **kwargs): return super().createOverlay(**kwargs)
class RadioButtonGroup(_RadioGroupBase, _ButtonBase): """ The `RadioButtonGroup` widget allows selecting from a list or dictionary of values using a set of toggle buttons. It falls into the broad category of single-value, option-selection widgets that provide a compatible API and include the `RadioBoxGroup`, `Select`, and `DiscreteSlider` widgets. Reference: https://panel.holoviz.org/reference/widgets/RadioButtonGroup.html :Example: >>> RadioButtonGroup( ... name='Plotting library', options=['Matplotlib', 'Bokeh', 'Plotly'], ... button_type='success' ... ) """ orientation = param.Selector(default='horizontal', objects=['horizontal', 'vertical'], doc=""" Button group orientation, either 'horizontal' (default) or 'vertical'.""" ) _widget_type = _BkRadioButtonGroup _supports_embed = True
class NotificationAreaBase(ReactiveHTML): notifications = param.List(item_type=Notification) position = param.Selector(default='bottom-right', objects=[ 'bottom-right', 'bottom-left', 'bottom-center', 'top-left', 'top-right', 'top-center', 'center-center', 'center-left', 'center-right']) _clear = param.Integer(default=0) _notification_type = Notification _template = """ <div id="pn-notifications" class="notifications" style="position: absolute; bottom: 0; ${position}: 0;"> ${notifications} </div> """ __abstract = True def __init__(self, **params): super().__init__(**params) self._notification_watchers = {} def send(self, message, duration=3000, type=None, background=None, icon=None): """ Sends a notification to the frontend. """ notification = self._notification_type( message=message, duration=duration, notification_type=type, notification_area=self, background=background, icon=icon ) self._notification_watchers[notification] = ( notification.param.watch(self._remove_notification, '_destroyed') ) self.notifications.append(notification) self.param.trigger('notifications') return notification def error(self, message, duration=3000): return self.send(message, duration, type='error') def info(self, message, duration=3000): return self.send(message, duration, type='info') def success(self, message, duration=3000): return self.send(message, duration, type='success') def warning(self, message, duration=3000): return self.send(message, duration, type='warning') def clear(self): self._clear += 1 self.notifications[:] = [] def _remove_notification(self, event): if event.obj in self.notifications: self.notifications.remove(event.obj) event.obj.param.unwatch(self._notification_watchers.pop(event.obj))
class TextEditor(Widget): """ TextEditor widget allow editing text using the quill.js library. """ disabled = param.Boolean(default=False, doc=""" Whether the editor is disabled.""") mode = param.Selector(default='toolbar', objects=['bubble', 'toolbar'], doc=""" Whether to display a toolbar or a bubble menu on highlight.""") toolbar = param.ClassSelector(default=True, class_=(list, bool), doc=""" Toolbar configuration either as a boolean toggle or a configuration specified as a list.""") placeholder = param.String( doc="Placeholder output when the editor is empty.") value = param.String(doc="State of the current text in the editor") _rename = {"value": "text"} def _get_model(self, doc, root=None, parent=None, comm=None): if self._widget_type is None: self._widget_type = lazy_load('panel.models.quill', 'QuillInput', isinstance(comm, JupyterComm), root) return super()._get_model(doc, root, parent, comm)
def __init__(self, report_from_set_up, initial_values): """Set initial values based on previous stage""" # Add elements as parameters for label, element in ELEMENT_OPTIONS.items(): self.param._add_parameter( element, param.Integer(0, label=label, bounds=(0, 100))) self.param._add_parameter( f"{element}_quality", param.Selector(QUALITY_OPTIONS, label=f"{label} Quality"), ) super().__init__() # Initialize parameter values self.report_from_set_up = report_from_set_up self.model_result = None self._state = state.get_user_state().setdefault(APP, {}) self.element_widgets = self.layout_element_widgets() self.visible_elements = {} self._initialize_qualities( reservoir_quality={ ELEMENT_OPTIONS[k]: initial_values["reservoir_quality"] for k in initial_values["composition"] }, default=initial_values["reservoir_quality"], ) self._initialize_composition( composition={ ELEMENT_OPTIONS[k]: v for k, v in initial_values["composition"].items() })
class Global(Base): plan = param.String() case = param.Selector() builder = param.String() runner = param.String() # TODO: link to instance counts in groups total_instances = param.Integer() # TODO: add ui widget for key/value maps instead of using Dict param type build_config = param.Dict(default={}, allow_None=True) run_config = param.Dict(default={}, allow_None=True) def set_manifest(self, manifest): if manifest is None: return print('manifest:', manifest) self.plan = manifest['name'] cases = [tc['name'] for tc in manifest['testcases']] self.param['case'].objects = cases print('global config updated manifest. cases:', self.param['case'].objects) if len(cases) != 0: self.case = cases[0] if 'defaults' in manifest: print('manifest defaults', manifest['defaults']) if self.builder == '': self.builder = manifest['defaults'].get('builder', '') if self.runner == '': self.runner = manifest['defaults'].get('runner', '')
class ApplyCmapTransform(Transform, WebAppTransform): """ This transform takes data from a specified field, applies a norm and color map, and adds the resulting colors in a new column """ fields = param.Selector(doc='Fields to choose from to apply cmap to') field = param.String(doc='Name of the field to apply colors to') cmap = param.ClassSelector(Colormap) norm = param.ClassSelector(Normalize) color_column = param.String('color', doc='Name of the added color column') # default_color = transform_type = 'color' def __init__(self, **params): super().__init__(**params) #temporariy self.param['fields'].objects = ['deltaG', 'pfact'] self.fields = 'deltaG' def apply(self, table): values = table[self.fields] colors = self.cmap(self.norm(values), bytes=True) colors_hex = rgb_to_hex(colors) table[self.color_column] = colors_hex return table @param.depends('cmap', 'fields', 'norm', watch=True) def _updated(self): print('cmap transform updated trigger') self.updated = True
class CheckButtonGroup(_CheckGroupBase, _ButtonBase): """ The `CheckButtonGroup` widget allows selecting between a list of options by toggling the corresponding buttons. It falls into the broad category of multi-option selection widgets that provide a compatible API and include the `MultiSelect`, `CrossSelector` and `CheckBoxGroup` widgets. Reference: https://panel.holoviz.org/reference/widgets/CheckButtonGroup.html :Example: >>> CheckButtonGroup( ... name='Regression Models', value=['Lasso', 'Ridge'], ... options=['Lasso', 'Linear', 'Ridge', 'Polynomial'] ... ) """ orientation = param.Selector(default='horizontal', objects=['horizontal', 'vertical'], doc=""" Button group orientation, either 'horizontal' (default) or 'vertical'.""" ) _widget_type = _BkCheckboxButtonGroup
class CheckButtonGroup(_CheckGroupBase, _ButtonBase): orientation = param.Selector(default='horizontal', objects=['horizontal', 'vertical'], doc=""" Button group orientation, either 'horizontal' (default) or 'vertical'.""") _widget_type = _BkCheckboxButtonGroup
class Inputs(param.Parameterized): input_file = param.FileSelector(path=r".\sample_data\\*.csv", doc="A .csv file selector for input data") x_field = param.Selector(doc="A field selector for longitude") y_field = param.Selector(doc="A field selector for latitude") id_field = param.Selector(doc="A field selector for the identifier") data = None def __init__(self, **params): super().__init__(**params) if self.param.input_file.default: self.input_file = self.param.input_file.default self._update_inputs() @param.depends("input_file", watch=True) def _update_inputs(self): if self.input_file in FILE_STORE: df = FILE_STORE[self.input_file].copy(deep=True) else: df = pd.read_csv(self.input_file) FILE_STORE[self.input_file] = df.copy(deep=True) numeric_cols = list(df.select_dtypes(include=["float64"]).columns) columns = [x for i, x in enumerate(df.columns) if x != "Unnamed: 0"] self.param.x_field.objects = numeric_cols if "lng" in numeric_cols: self.x_field = "lng" elif numeric_cols: self.x_field = numeric_cols[0] self.param.y_field.objects = numeric_cols if "lat" in numeric_cols: self.y_field = "lat" elif numeric_cols: self.y_field = numeric_cols[0] self.param.id_field.objects = columns if "comName" in columns: self.id_field = "comName" elif columns: self.id_field = columns[0] self.data = df
class RadioButtonGroup(_RadioGroupBase, _ButtonBase): orientation = param.Selector(default='horizontal', objects=['horizontal', 'vertical'], doc=""" Button group orientation, either 'horizontal' (default) or 'vertical'.""") _widget_type = _BkRadioButtonGroup _supports_embed = True
class P(param.Parameterized): e = param.Selector([5, 6, 7]) f = param.Selector(default=10) h = param.Selector(default=None) g = param.Selector([7, 8]) i = param.Selector([9], default=7, check_on_set=False) s = param.Selector(OrderedDict(one=1, two=2, three=3), default=3) d = param.Selector(opts, default=opts['B'])
class StructurePropertyVisualizer(param.Parameterized): x = param.Selector(objects=plot_dict, default='CO2 Henry coefficient') y = param.Selector(objects=plot_dict, default='CO2 parasitic energy (coal)') color = param.Selector(objects=OrderedDict(plot_dict), default='Geometric Void Fraction') msg = pn.pane.HTML("") _plot = None # reference to current plot @param.depends('x', 'y', 'color') def plot(self): selected = [self.x, self.y, self.color] unique = set(selected) if len(unique) < len(selected): self.msg.object = "<b style='color:red;'>Warning: {} contains duplicated selections.</b>".format(", ".join( [config.quantities[s]['label'] for s in selected])) return self._plot self._plot, self.msg.object = get_plot(self.x, self.y, self.color) return self._plot
class RoomOccupancy(param.Parameterized): data = pd.read_csv('./datatest.csv') data['date'] = data.date.astype('datetime64[ns]') data = data.set_index('date') variable = param.Selector(objects=list(data.columns)) window = param.Integer(default=10, bounds=(1, 20)) sigma = param.Number(default=10, bounds=(0, 20)) def view(self): return find_outliers(self.variable, self.window, self.sigma)
class StructurePropertyVisualizer(param.Parameterized): x = param.Selector(objects=quantities.keys(), default='Largest Included Sphere Diameter') y = param.Selector(objects=quantities.keys(), default='Geometric Void Fraction') color = param.Selector(objects=quantities.keys(), default='Density') msg = pn.pane.HTML("") _plot = None # reference to current plot @param.depends('x', 'y', 'color') def plot(self): selected = [self.x, self.y, self.color] unique = set(selected) if len(unique) < len(selected): self.msg.object = "<b style='color:red;'>Warning: you are asking to show the same value twice!</b>" return self._plot self._plot, self.msg.object = get_plot(self.x, self.y, self.color) return self._plot
class StructurePropertyVisualizer(param.Parameterized): preset = config.presets['default'] x = param.Selector(objects=plot_dict, default=preset['x']) y = param.Selector(objects=plot_dict, default=preset['y']) clr = param.Selector(objects=OrderedDict(plot_dict), default=preset['clr']) msg = pn.pane.HTML("") _plot = None # reference to current plot @param.depends('x', 'y', 'clr') def plot(self): selected = [self.x, self.y, self.clr] unique = set(selected) if len(unique) < len(selected): self.msg.object = "<b style='color:red;'>Warning: {} contains duplicated selections.</b>".format( ", ".join([config.quantities[s]['label'] for s in selected])) return self._plot self._plot, self.msg.object = get_plot(self.x, self.y, self.clr) return self._plot
class ParameterSets(param.Parameterized): """ Allows selection from sets of pre-defined parameters saved in YAML. Assumes the YAML file returns a list of groups of values. """ examples_filename = param.Filename("attractors.yml") current = param.Callable(lambda: None, precedence=-1) remember_this_one = param.Action(lambda x: x._remember()) load = param.Action(lambda x: x._load()) randomize = param.Action(lambda x: x._randomize()) sort = param.Action(lambda x: x._sort()) save = param.Action(lambda x: x._save(), precedence=0.8) example = param.Selector(objects=[[]], precedence=-1) def __init__(self,**params): super(ParameterSets,self).__init__(**params) self._load() self.attractors = OrderedDict(sorted([(k,v(name=k + " parameters")) for k,v in concrete_descendents(Attractor).items()])) for k in self.attractors: self.attractor(k, *self.args(k)[0]) def _load(self): with open(self.examples_filename,"r") as f: vals = yaml.safe_load(f) assert(vals and len(vals)>0) self.param.example.objects=vals self.example = vals[0] def _save(self): with open(self.examples_filename,"w") as f: yaml.dump(self.param.example.objects,f) def __call__(self): return self.example def _randomize(self): npr.shuffle(self.param.example.objects) def _sort(self): self.param.example.objects = list(sorted(self.param.example.objects)) def _add_item(self, item): self.param.example.objects += [item] ; self.example=item def _remember(self): vals = self.current().vals() self._add_item(vals) def args(self, name): return [v[1:] for v in self.param.example.objects if v[0]==name] def attractor(self, name, *args): """Factory function to return an Attractor object with the given name and arg values""" attractor = self.attractors[name] fn_params = ['colormap'] + attractor.sig() attractor.param.set_param(**dict(zip(fn_params, args))) return attractor
class GVTS(param.Parameterized): source = param.Selector(objects=gvts.tile_sources, label='Web Map Tile Services') @param.depends('source') def view(self): return self.source.opts(active_tools=['pan', 'wheel_zoom']) def panel(self): return pn.Column( pn.panel(self.param, expand_button=False, show_name=False), self.view)
class HeatMapPlot(BondiaPlot, param.Parameterized): """ Base class for common features used in heat map plots. Attributes ---------- transpose Transpose the plot if True. Default `True`. log True for logarithmic color map (z-values). Default `False`. colormap_range (optional, if using datashader) Select limits of color map values (z-values). Default `None`. serverside_rendering True to use datashader. Automatically selects colormap for every zoom level, sends pre-rendered images to client. Default `True`. """ # parameters transpose = param.Boolean(default=False) logarithmic_colorscale = param.Boolean(default=False) serverside_rendering = param.Selector() colormap_range = param.Range(constant=False) def __init__(self, name: str, activated: bool = True, **params): BondiaPlot.__init__(self, name, activated) param.Parameterized.__init__(self, **params) self.colormap_range = self.zlim if hasattr(self, "zlim") else (-5, 5) # TODO: for some reason this has to be done before panel.serve # See https://discourse.holoviz.org/t/panel-serve-with-num-procs-breaks-if-importing-datashade/1353 from holoviews.operation.datashader import datashade, rasterize self.param["serverside_rendering"].objects = [ None, rasterize, datashade ] self.serverside_rendering = rasterize @param.depends("serverside_rendering", watch=True) def update_serverside_rendering(self): # TODO: for some reason this has to be done before panel.serve # See https://discourse.holoviz.org/t/panel-serve-with-num-procs-breaks-if-importing-datashade/1353 from holoviews.operation.datashader import datashade # Disable colormap range selection if using datashader (because it uses auto values) self.param[ "colormap_range"].constant = self.serverside_rendering == datashade def make_selection(self, data, key): objects = list(data.index_map[key]) default = data.index_map[key][0] return objects, default
class priorDashboard(param.Parameterized): """ Dashboard for the prior view data should be dictionary of model objects and should be set on instantiation along with the name variable needs to be set with the prior variables list after instantiation returns a panel row with the parameter controls and the plots """ # precedence less than one means it is not a user displayed option. Set through initial params passed data = param.Dict(precedence=-1) variable = param.Selector(None) plot_type = param.Selector(inputs, default=inputs[0]) @param.depends('variable', 'plot_type', 'data') def plot(self): return prior_density_plot(variable=self.variable, data=self.data, plottype=self.plot_type) def panel(self): return pn.Row(self.param, self.plot, sizing_mode='scale_both')
class Inputs(param.Parameterized): input_file = param.FileSelector( path=".\sample_data\*.csv", doc="A .csv file selector for input data" ) x_field = param.Selector(doc="A field selector for longitude") y_field = param.Selector(doc="A field selector for latitude") id_field = param.Selector(doc="A field selector for the identifier") data = None @param.depends("input_file", watch=True) def update_inputs(self): df = pd.read_csv(self.input_file) numeric_cols = list(df.select_dtypes(include=["float64"]).columns) columns = [x for i, x in enumerate(df.columns) if x != "Unnamed: 0"] self.param.x_field.objects = numeric_cols self.x_field = numeric_cols[0] self.param.y_field.objects = numeric_cols self.x_field = numeric_cols[0] self.param.id_field.objects = columns self.id_field = columns[0] self.data = df