Exemplo n.º 1
0
 def build_gui(self):
     self.x_select = pnw.Select(name="x-Axis",
                                options=list(self.data.columns),
                                value=self.data.columns[0],
                                width=self.width // 2,
                                height=50)
     self.x_select.param.watch(self.update_plot, "value")
     second_select_index = 1 if len(self.data.columns) > 1 else 0
     self.y_select = pnw.Select(
         name="y-Axis",
         options=list(self.data.columns),
         value=self.data.columns[second_select_index],
         width=self.width // 2,
         height=50)
     self.y_select.param.watch(self.update_plot, "value")
     self.combine_selections = pnw.RadioBoxGroup(
         name="Combine selections",
         options=["None", "Or", "And"],
         value="None",
         width=self.width,
         inline=True)
     self.combine_selections.param.watch(self.update_plot, "value")
     p = self.scatter_plot()
     legend = pn.Row("<p style='color:#B22222';>Selected in current</p>",
                     "<p style='color:#FF00FF';>Selected in another</p>",
                     "<p style='color:#808080';>Not selected</p>")
     self.gui = pn.Column(
         pn.Row(self.x_select, self.y_select),
         pn.Row("Combine selections with: ", self.combine_selections),
         legend, p)
Exemplo n.º 2
0
class PanelWithEbandsRobot(BaseRobotPanel):  #, metaclass=abc.ABCMeta):
    """
    Mixin class for panels with a robot that owns a list of of |ElectronBands|
    """

    # Widgets to plot ebands.
    ebands_plotter_mode = pnw.Select(
        name="Plot Mode",
        value="gridplot",
        options=["gridplot", "combiplot", "boxplot",
                 "combiboxplot"])  # "animate",
    ebands_plotter_btn = pnw.Button(name="Plot", button_type='primary')
    ebands_df_checkbox = pnw.Checkbox(name='With Ebands DataFrame',
                                      value=False)

    # Widgets to plot edos.
    edos_plotter_mode = pnw.Select(name="Plot Mode",
                                   value="gridplot",
                                   options=["gridplot", "combiplot"])
    edos_plotter_btn = pnw.Button(name="Plot", button_type='primary')

    def get_ebands_plotter_widgets(self):
        return pn.Column(self.ebands_plotter_mode, self.ebands_df_checkbox,
                         self.ebands_plotter_btn)

    @param.depends("ebands_plotter_btn.clicks")
    def on_ebands_plotter_btn(self):
        if self.ebands_plotter_btn.clicks == 0: return
        ebands_plotter = self.robot.get_ebands_plotter()
        plot_mode = self.ebands_plotter_mode.value
        plotfunc = getattr(ebands_plotter, plot_mode, None)
        if plotfunc is None:
            raise ValueError("Don't know how to handle plot_mode: %s" %
                             plot_mode)

        fig = plotfunc(**self.fig_kwargs)
        col = pn.Column(self._mp(fig), sizing_mode='scale_width')
        if self.ebands_df_checkbox.value:
            df = ebands_plotter.get_ebands_frame(with_spglib=True)
            col.append(self._df(df))

        return pn.Row(col, sizing_mode='scale_width')

    def get_edos_plotter_widgets(self):
        return pn.Column(self.edos_plotter_mode, self.edos_plotter_btn)

    @param.depends("edos_plotter_btn.clicks")
    def on_edos_plotter_btn(self):
        if self.edos_plotter_btn.clicks == 0: return
        edos_plotter = self.robot.get_edos_plotter()
        plot_mode = self.edos_plotter_mode.value
        plotfunc = getattr(edos_plotter, plot_mode, None)
        if plotfunc is None:
            raise ValueError("Don't know how to handle plot_mode: %s" %
                             plot_mode)

        fig = plotfunc(**self.fig_kwargs)
        return pn.Row(pn.Column(self._mp(fig)), sizing_mode='scale_width')
Exemplo n.º 3
0
def sequence_alignment_viewer(filename=None):
    """Sequence alignment viewer"""
    
    title = pn.pane.Markdown()
    aln_btn = pnw.Button(name='align',width=100,button_type='primary')
    file_input = pnw.FileInput(name='load file',width=100,accept='.fa,.fasta,.faa')
    aligner_sel = pnw.Select(name='aligner',value='muscle',options=['muscle','clustal','maaft'],width=100)
    highlight_sel = pnw.Select(name='highlight mode',value='default',options=['default',''],width=100)
    rowheight_sl = pnw.IntSlider(name='row height',value=10,start=5,end=20,width=120)
    seq_pane = pn.pane.HTML(name='sequences',height=200,css_classes=['scrollingArea'])
    bokeh_pane = pn.pane.Bokeh()

    def update_title(filename):
        title.object = '### Sequence aligner: %s' %filename
        
    def update_file(event):        
        nonlocal seqtext
        seqtext = file_input.value.decode('utf-8')
        title.object = file_input.filename
        update_title(file_input.filename)
        return

    def align(event):
        #this function does the alignment
        nonlocal seqtext        
        if seqtext is not None:
            sequences = SeqIO.parse(io.StringIO(seqtext),format='fasta')
        elif filename is not None:    
            sequences = SeqIO.parse(filename, format='fasta')
        else:      
            return
        sequences = list(sequences)
        #print (sequences)
        aligner = aligner_sel.value
        if aligner == 'muscle':
            aln = utils.muscle_alignment(sequences)    
        elif aligner == 'clustal':
            aln = utils.clustal_alignment(sequences)
        elif aligner == 'mafft':
            aln = utils.mafft_alignment(sequences)
        if aln is None:
            bokeh_pane.object = plotters.plot_empty('%s not installed?' %aligner,900)
        else:
            #the bokeh pane is then updated with the new figure
            bokeh_pane.object = plotters.plot_sequence_alignment(aln, row_height=rowheight_sl.value)  
        return 
   
    seqtext = None
    file_input.param.watch(update_file,'value')
    rowheight_sl.param.watch(align,'value')
    aln_btn.param.watch(align, 'clicks')
    aln_btn.param.trigger('clicks')
    update_title(filename)
    side = pn.Column(aln_btn,file_input,aligner_sel,highlight_sel,rowheight_sl,seq_pane,css_classes=['form'],width=200,margin=20)   
    app = pn.Column(title,pn.Row(side, bokeh_pane), sizing_mode='stretch_width',width_policy='max',margin=20)
    return app
Exemplo n.º 4
0
    def __init__(
        self,
        df,
        *,
        feature_aliases=None,
        describe=True,
        x_label="timestamp",
        port=5006,
        websocket_origin=49179,
        sample_rate=1.0,
        plot_width=600,
        plot_height=400,
        **params,
    ):

        BasePanel.__init__(
            self,
            df,
            feature_aliases=feature_aliases,
            port=port,
            websocket_origin=websocket_origin,
            sample_rate=sample_rate,
        )
        self.plot_width = plot_width
        self.plot_height = plot_height
        self.describe = describe
        self.x_label = x_label

        tags = sorted(list(df.columns))
        tag = tags[0]
        bounds = self.tag_bounds[tag]

        # widget objects
        self.feature = pnw.Select(value=tag, options=tags, name="Ticker")
        self.description = pnw.Select(
            value=self.feature_aliases[tag],
            options=sorted(list(self.feature_aliases.values())),
            name="Company",
        )
        self.tag_range = pnw.RangeSlider(start=bounds[0],
                                         end=bounds[1],
                                         value=bounds,
                                         name="Feature Range")
        self.log_scale = pnw.Checkbox(
            name="Log scale",
            value=False,
        )

        pm.Parameterized.__init__(self, **params)
Exemplo n.º 5
0
def class_area_histogram_with_select(record_stats_list, class_map=None, width=500, height=500):
    """Creates histograms for areas from a list of record_stats."""
    # gui
    # remove the first entry from the class_map, because the background class is not explicit part of the annotaitons
    unique_labels = sorted(pd.unique(record_stats_list[0]["label"]))
    for record_stats in record_stats_list[1:]:
        if not all(pd.unique(sorted(record_stats["label"])) == unique_labels):
            raise ValueError("All dataframes in the records_stats_list need to have the same set of unique values.")
    options = pd.unique(record_stats_list[0]["label"])
    options.sort()
    if class_map is not None:
        options = np.vectorize(class_map.get_id)(options)
    class_dropdown = pnw.Select(options=options.tolist())
    bins_slider = pnw.IntSlider(name="Bins", start=10, end=100, step=5)
    checkbox_normalized = pnw.Checkbox(name="Normalized", value=False)

    @pn.depends(class_dropdown.param.value, bins_slider.param.value, checkbox_normalized.param.value)
    def _draw_histogram(class_label, bins, normalized):
        nonlocal class_map
        nonlocal width
        nonlocal height
        nonlocal record_stats_list
        class_label = class_label if class_map is None else class_map.get_name(class_label)
        return pn.Row(*[draw_area_histogram(record_stats, class_label, class_map, bins, normalized, width, height) for record_stats in record_stats_list])

    return pn.Column(class_dropdown, pn.Row(bins_slider, checkbox_normalized), _draw_histogram)
Exemplo n.º 6
0
    def build_gui(self):
        "Builds the basic gui for the gallery."
        self.btn_prev = pnw.Button(name="<", width=int(2 * self.width / 6))
        self.btn_next = pnw.Button(name=">", width=int(2 * self.width / 6))
        self.current = pnw.TextInput(value="1", width=int(self.width / 6))
        self.image_count = pn.Row("/" + str(self.num_entries),
                                  width=int(self.width / 6))
        self.gui_image_selection_controlls = pn.Row(self.btn_prev,
                                                    self.current,
                                                    self.image_count,
                                                    self.btn_next,
                                                    align="center",
                                                    height=50)

        if self.sort_cols is not None:
            self.sorter = pnw.Select(name="Sort by", options=self.sort_cols)
            self.sorter.param.watch(self.update_sorting, "value")
            self.sort_order = pnw.CheckButtonGroup(
                name="Options", options=["Desc.", "Drop duplicates"])
            self.sort_order.param.watch(self.update_sorting, "value")
            self.sort_gui = pn.Row(self.sorter, self.sort_order)
        if self.sort_cols is not None:
            self.gui_controlls = pn.Column(self.sort_gui,
                                           self.gui_image_selection_controlls)
        else:
            self.gui_controlls = self.gui_image_selection_controlls

        self.btn_prev.on_click(self._previous)
        self.btn_next.on_click(self._next)
        self.current.param.watch(self._number_input, "value")

        self._image = pn.Row(
            self.get_image_by_index(int(self.current.value) - 1),
            align="center")
        self.gui = pn.Column(self.gui_controlls, self.image)
Exemplo n.º 7
0
    def build_precison_recall_overview(self, data):
        if len(data) == 1:
            return pn.Column("<h1> No information available</h1>")
        class_select = pnw.Select(
            options=[key for key in data.keys() if key != "map"])

        @pn.depends(class_select.param.value)
        def _plot(class_name):
            heading = pn.Row("<h1>AP - " +
                             str(data[class_name]["ap"].round(4)) + "</h1>",
                             align="center")
            table_data = {
                "AP": [
                    round(data[class_name][iou_key]["ap"], 4)
                    for iou_key in data[class_name].keys() if iou_key != "ap"
                ]
            }
            table_df = pd.DataFrame(table_data).T
            table_df.columns = [
                iou_key for iou_key in data[class_name].keys()
                if iou_key != "ap"
            ]
            table_df.index.names = ["iou"]
            overview_table = table_from_dataframe(table_df)
            return pn.Column(
                heading, pn.Row(overview_table, align="center"),
                self.plot_precision_recall_curves_for_class(
                    data[class_name], class_name))

        return pn.Column(class_select, _plot)
Exemplo n.º 8
0
    def __init__(self, plot, tabs):
        """Initialize form.

        :param plot: IsothermPlot instance for validation of results.
        :param tabs: Panel tabs instance for triggering tab switching.
        """

        # new fields
        self.inp_composition_type = pw.Select(
            name='Composition type',
            options=['Select'] + QUANTITIES['composition_type']['names'])
        self.inp_composition_type.param.watch(self.on_change_composition_type,
                                              'value')
        self.inp_concentration_units = pw.AutocompleteInput(
            name='Concentration Units',
            options=QUANTITIES['concentration_units']['names'],
            placeholder='Molarity (mol/l)',
            case_sensitive=False,
            disabled=True,
            **restrict_kwargs)

        super().__init__(plot, tabs)

        # override fields
        self.inp_adsorbates = Adsorbates(show_controls=True, )
        self.inp_isotherm_data = pw.TextAreaInput(
            name='Isotherm Data',
            height=200,
            placeholder=config.MULTI_COMPONENT_EXAMPLE)

        # modified prefill function
        self.btn_prefill.on_click(self.on_click_prefill)

        # create layout
        self.layout = pn.Column(
            pn.pane.HTML('<h2>Isotherm Digitizer</h2>'),
            self.inp_digitizer,
            self.inp_doi,
            pn.pane.HTML('<hr>'),
            self.inp_source_type,
            pn.Row(pn.pane.HTML("""Attach Figure Graphics"""),
                   self.inp_figure_image),
            self.inp_measurement_type,
            self.inp_adsorbent,
            self.inp_adsorbates.column,
            self.inp_temperature,
            self.inp_isotherm_type,
            pn.Row(self.inp_pressure_units, self.inp_saturation_pressure),
            self.inp_pressure_scale,
            self.inp_adsorption_units,
            pn.Row(self.inp_composition_type, self.inp_concentration_units),
            pn.pane.HTML("""We recommend the
                <b><a href='https://apps.automeris.io/wpd/' target="_blank">WebPlotDigitizer</a></b>
                for data extraction."""),
            self.inp_isotherm_data,
            self.inp_tabular,
            pn.Row(self.btn_plot, self.btn_prefill, self.inp_json),
            self.out_info,
        )
Exemplo n.º 9
0
class PhononBandsPlotterPanel(AbipyParameterized):

    phbands_plotter_mode = pnw.Select(
        name="Plot Mode",
        value="gridplot",
        options=["gridplot", "combiplot", "boxplot",
                 "combiboxplot"])  # "animate",
    phbands_plotter_units = pnw.Select(
        name="Units", value="eV", options=["eV", "meV", "Ha", "cm-1", "Thz"])
    phbands_plotter_btn = pnw.Button(name="Plot", button_type='primary')

    def __init__(self, plotter, **params):
        super().__init__(**params)
        self.plotter = plotter

    @param.depends("phbands_plotter_btn.clicks")
    def on_phbands_plot_btn(self):
        if self.phbands_plotter_btn.clicks == 0: return
        plot_mode = self.phbands_plotter_mode.value
        plotfunc = getattr(self.plotter, plot_mode, None)
        if plotfunc is None:
            raise ValueError("Don't know how to handle plot_mode: %s" %
                             plot_mode)

        fig = plotfunc(units=self.phbands_plotter_units.value,
                       **self.fig_kwargs)
        df = self.plotter.get_phbands_frame(with_spglib=True)
        return pn.Row(pn.Column(self._mp(fig), self._df(df)),
                      sizing_mode='scale_width')

    def get_panel(self):
        """Return tabs with widgets to interact with the |PhononBandsPlotter|."""
        tabs = pn.Tabs()
        ws = pn.Column(self.phbands_plotter_mode, self.phbands_plotter_units,
                       self.phbands_plotter_btn)
        tabs.append(("PhbandsPlotter",
                     pn.Row(ws,
                            self.on_phbands_plot_btn,
                            sizing_mode='scale_width')))

        return tabs
Exemplo n.º 10
0
def plot_all(data, alp=True, var='h_li'):
    """
    Scatter plot with x=lon, y=lat.
    Interactivity for missing data and color.
    
    """

    # Static plot
    def scatter(data=data, alp=alp, var=var):
        clean = data[data.loc[:, var] < 1e+38].hvplot.scatter(x='longitude',
                                                              y='latitude',
                                                              c=var,
                                                              s=1,
                                                              alpha=0.2,
                                                              cmap='viridis',
                                                              hover=False)
        missing = data[data.loc[:, var] > 1e+38].hvplot.scatter(
            x='longitude',
            y='latitude',
            c='red',
            s=1,
            alpha=0.2 if alp == True else 0,
            hover=False)
        return (clean * missing)

    # Widgets
    var = pnw.Select(name='Color', value='h_li', options=list(data.columns))
    alp = pnw.Checkbox(value=True, name='Missing data (red)')
    text = "<br>\n# All ATL06 data for the selected area\nSelect a color variable and whether to show missing data"

    # Interactive plot
    @pn.depends(var, alp)
    def reactive(var, alp):
        return (scatter(data, alp, var))

    # Layout
    widgets = pn.Column(text, var, alp)
    image = pn.Row(reactive, widgets)
    return (image)
Exemplo n.º 11
0
    def _new_display(self):
        track = self.track
        beads = list(track.beads.keys())
        if not beads:
            return pn.Pane("No beads in this track")

        sel = pnw.Select(
            name="Plot",
            value="cleancycles",
            options=["cleanbeads", "cleancycles", "cycles", "peaks"])
        lst = pnw.DiscreteSlider(name="Beads", value=beads[0], options=beads)
        pane = pn.Pane(hv.Div(""))

        def _show(_):
            dmap = getattr(track, sel.value).display.display()
            pane.object = dmap[lst.value]

        lst.param.watch(_show, "value")
        sel.param.watch(_show, "value")
        col = pn.Column(pn.Row(lst, sel), pane)
        _show(None)
        return col
Exemplo n.º 12
0
    def plot_additional_stats_matplotlib(self, class_data, class_name):
        # histograms
        ious = sorted([iou for iou in class_data.keys() if iou != "ap"])
        iou_selector = pnw.Select(name="IOU", options=ious, value=0.5)

        @pn.depends(iou_selector.param.value)
        def _plot_additional_stats_matplotlib(iou):
            nonlocal class_data
            nonlocal self
            data = class_data[iou]
            fig = plt.figure(constrained_layout=False, figsize=(16, 9))
            row_coords = self.generate_grid_coodinates(3)[::-1]
            col_coords = self.generate_grid_coodinates(4)[::-1]
            coord_combinations = list(itertools.product(
                col_coords, row_coords))

            for index, hist_key in enumerate([
                    'center_distances',
                    'y_center_offsets',
                    'x_center_offsets',
                    'used_scatter',
                    'unused_gt_mask_areas_normalized',
                    'used_gt_mask_areas_normalized',
                    'unused_scatter',
                    'center_distances',
                    'y_center_offsets',
                    'xoffset_vs_yoffset_scatter',
                    'center_distance_vs_unused_gt_mask_area_scatter',
                    "center_distance_vs_unused_pred_mask_area_scatter",
            ]):
                row_coord = coord_combinations[index][0]
                col_coord = coord_combinations[index][1]
                self.histogramm_plot(fig, data, hist_key, row_coord[0],
                                     row_coord[1], col_coord[0], col_coord[1])
            plt.close()
            return pn.pane.Matplotlib(fig, width=self.width)

        return pn.Column(iou_selector, _plot_additional_stats_matplotlib)
Exemplo n.º 13
0
    def build_precison_recall_overview(self, data):
        if len(data) == 1:
            return pn.Column("<h1> No information available</h1>")
        class_select = pnw.Select(
            options=[key for key in data.keys() if key != "map"])

        @pn.depends(class_select.param.value)
        def _plot(class_name):
            heading = pn.Row("<h1>AP - " +
                             str(data[class_name]["ap"].round(4)) + "</h1>",
                             align="center")
            table_data = {
                "AP": [
                    round(data[class_name][iou_key]["ap"], 4)
                    for iou_key in data[class_name].keys() if iou_key != "ap"
                ]
            }
            table_df = pd.DataFrame(table_data).T
            table_df.columns = [
                iou_key for iou_key in data[class_name].keys()
                if iou_key != "ap"
            ]
            table_df.index.names = ["iou"]
            overview_table = table_from_dataframe(table_df)
            precision_recall_curves = self.plot_precision_recall_curves_for_class_matplotlib(
                data[class_name], class_name)
            additional_stats_plot = self.plot_additional_stats_matplotlib(
                data[class_name], class_name)
            ap_and_additional_stats_accordion = pn.Accordion(
                ("AP",
                 pn.Column(class_select, heading,
                           pn.Row(overview_table, align="center"),
                           precision_recall_curves)),
                ("Additioanl stats", additional_stats_plot),
                active=self.accordion_active)
            return pn.Column(ap_and_additional_stats_accordion)

        return pn.Column(_plot, width=self.width)
Exemplo n.º 14
0
class FlowPanel(AbipyParameterized):
    """
    """
    verbose = pn.widgets.IntSlider(start=0, end=10, step=1, value=0)

    engine = pn.widgets.Select(value="fdp",
                               options=[
                                   'dot', 'neato', 'twopi', 'circo', 'fdp',
                                   'sfdp', 'patchwork', 'osage'
                               ])
    dirtree = pn.widgets.Checkbox(name='Dirtree', value=False)
    graphviz_btn = pn.widgets.Button(name="Show graph", button_type='primary')

    status_btn = pn.widgets.Button(name="Show status", button_type='primary')
    history_btn = pn.widgets.Button(name="Show history", button_type='primary')
    debug_btn = pn.widgets.Button(name="Debug", button_type='primary')
    events_btn = pn.widgets.Button(name="Events", button_type='primary')
    corrections_btn = pn.widgets.Button(name="Corrections",
                                        button_type='primary')
    handlers_btn = pn.widgets.Button(name="Handlers", button_type='primary')

    vars_text = pn.widgets.TextInput(
        name='Abivars',
        placeholder='Enter list of variables separated by comma')
    vars_btn = pn.widgets.Button(name="Show Variables", button_type='primary')

    dims_btn = pn.widgets.Button(name="Show Dimensions", button_type='primary')

    structures_btn = pn.widgets.Button(name="Show Structures",
                                       button_type='primary')
    structures_io_checkbox = pn.widgets.CheckBoxGroup(
        name='Input/Output Structure',
        value=['output'],
        options=['input', 'output'],
        inline=True)

    # Widgets to plot ebands.
    ebands_btn = pn.widgets.Button(name="Show Ebands", button_type='primary')
    ebands_plotter_mode = pnw.Select(
        name="Plot Mode",
        value="gridplot",
        options=["gridplot", "combiplot", "boxplot",
                 "combiboxplot"])  # "animate",
    ebands_plotter_btn = pnw.Button(name="Plot", button_type='primary')
    ebands_df_checkbox = pnw.Checkbox(name='With Ebands DataFrame',
                                      value=False)
    ebands_ksamp_checkbox = pn.widgets.CheckBoxGroup(
        name='Input/Output Structure',
        value=["with_path", "with_ibz"],
        options=['with_path', 'with_ibz'],
        inline=True)

    #TODO: Implement widget for selected_nids(flow, options),
    #radio_group = pn.widgets.RadioButtonGroup(
    #   name='Radio Button Group', options=['Biology', 'Chemistry', 'Physics'], button_type='success')

    def __init__(self, flow, **params):
        super().__init__(**params)
        self.flow = flow

    @param.depends('status_btn.clicks')
    def on_status_btn(self):
        if self.status_btn.clicks == 0: return
        stream = StringIO()
        self.flow.show_status(stream=stream, verbose=self.verbose.value)
        return pn.Row(bkw.PreText(text=stream.getvalue()))

    @param.depends('history_btn.clicks')
    def on_history_btn(self):
        if self.history_btn.clicks == 0: return
        stream = StringIO()
        #flow.show_history(status=options.task_status, nids=selected_nids(flow, options),
        #                  full_history=options.full_history, metadata=options.metadata)
        self.flow.show_history(stream=stream)
        return pn.Row(bkw.PreText(text=stream.getvalue()))

    @param.depends('graphviz_btn.clicks')
    def on_graphviz_btn(self):
        """
        """
        if self.graphviz_btn.clicks == 0: return
        node = self.flow
        if self.dirtree.value:
            graph = node.get_graphviz_dirtree(engine=self.engine.value)
        else:
            graph = node.get_graphviz(engine=self.engine.value)
        return pn.Column(graph)

    @param.depends('debug_btn.clicks')
    def on_debug_btn(self):
        if self.debug_btn.clicks == 0: return
        #TODO https://github.com/ralphbean/ansi2html ?
        stream = StringIO()
        #flow.debug(status=options.task_status, nids=selected_nids(flow, options))
        self.flow.debug(stream=stream)
        return pn.Row(bkw.PreText(text=stream.getvalue()))

    @param.depends('events_btn.clicks')
    def on_events_btn(self):
        if self.events_btn.clicks == 0: return
        stream = StringIO()
        self.flow.show_events(stream=stream)
        #flow.show_events(status=options.task_status, nids=selected_nids(flow, options))
        return pn.Row(bkw.PreText(text=stream.getvalue()))

    @param.depends('corrections_btn.clicks')
    def on_corrections_btn(self):
        if self.corrections_btn.clicks == 0: return
        stream = StringIO()
        self.flow.show_corrections(stream=stream)
        #flow.show_corrections(status=options.task_status, nids=selected_nids(flow, options))
        return pn.Row(bkw.PreText(text=stream.getvalue()))

    @param.depends('handlers_btn.clicks')
    def on_handlers_btn(self):
        #if self.handlers_btn.clicks == 0: return
        stream = StringIO()
        #if options.doc:
        #    flowtk.autodoc_event_handlers()
        #else:
        #show_events(self, status=None, nids=None, stream=sys.stdout):
        self.flow.show_event_handlers(verbose=self.verbose.value,
                                      stream=stream)
        return pn.Row(bkw.PreText(text=stream.getvalue()))

    @param.depends('vars_btn.clicks')
    def on_vars_btn(self):
        if self.vars_btn.clicks == 0: return
        if not self.vars_text.value: return
        varnames = [s.strip() for s in self.vars_text.value.split(",")]
        df = self.flow.compare_abivars(
            varnames=varnames,  # nids=selected_nids(flow, options),
            printout=False,
            with_colors=False)
        return pn.Row(self._df(df))

    @param.depends('dims_btn.clicks')
    def on_dims_btn(self):
        if self.dims_btn.clicks == 0: return
        df = self.flow.get_dims_dataframe(  # nids=selected_nids(flow, options),
            printout=False,
            with_colors=False)
        return pn.Row(self._df(df), sizing_mode="scale_width")

    @param.depends('structures_btn.clicks')
    def on_structures_btn(self):
        if self.structures_btn.clicks == 0: return
        what = ""
        if "input" in self.structures_io_checkbox.value: what += "i"
        if "output" in self.structures_io_checkbox.value: what += "o"
        dfs = self.flow.compare_structures(
            nids=None,  # select_nids(flow, options),
            what=what,
            verbose=self.verbose.value,
            with_spglib=False,
            printout=False,
            with_colors=False)

        return pn.Row(self._df(dfs.lattice), sizing_mode="scale_width")

    @param.depends('ebands_plotter_btn.clicks')
    def on_ebands_btn(self):
        if self.ebands_plotter_btn.clicks == 0: return

        df, ebands_plotter = self.flow.compare_ebands(
            nids=None,  # select_nids(flow, options),
            with_path="with_path" in self.ebands_ksamp_checkbox.value,
            with_ibz="with_ibz" in self.ebands_ksamp_checkbox.value,
            verbose=self.verbose.value,
            with_spglib=False)

        if ebands_plotter is None:
            return

        plot_mode = self.ebands_plotter_mode.value
        plotfunc = getattr(ebands_plotter, plot_mode, None)
        if plotfunc is None:
            raise ValueError("Don't know how to handle plot_mode: %s" %
                             plot_mode)

        fig = plotfunc(**self.fig_kwargs)
        col = pn.Column(self._mp(fig))
        if self.ebands_df_checkbox.value:
            col.append(self._df(df))

        return pn.Row(col)  #, sizing_mode='scale_width')

    def get_panel(self):
        """Return tabs with widgets to interact with the flow."""
        tabs = pn.Tabs()
        app = tabs.append
        #row = pn.Row(bkw.PreText(text=self.ddb.to_string(verbose=self.verbose.value), sizing_mode="scale_both"))
        app(("Status", pn.Row(self.status_btn, self.on_status_btn)))
        app(("History", pn.Row(self.history_btn, self.on_history_btn)))
        app(("Events", pn.Row(self.events_btn, self.on_events_btn)))
        app(("Corrections",
             pn.Row(self.corrections_btn, self.on_corrections_btn)))
        app(("Handlers", pn.Row(self.handlers_btn, self.on_handlers_btn)))
        app(("Structures",
             pn.Row(
                 pn.Column(self.structures_io_checkbox, self.structures_btn),
                 self.on_structures_btn)))
        ws = pn.Column(self.ebands_plotter_mode, self.ebands_ksamp_checkbox,
                       self.ebands_df_checkbox, self.ebands_plotter_btn)
        app(("Ebands", pn.Row(ws, self.on_ebands_btn)))
        app(("Abivars",
             pn.Row(pn.Column(self.vars_text, self.vars_btn),
                    self.on_vars_btn)))
        app(("Dims", pn.Row(pn.Column(self.dims_btn), self.on_dims_btn)))
        app(("Debug", pn.Row(self.debug_btn, self.on_debug_btn)))
        app(("Graphviz",
             pn.Row(pn.Column(self.engine, self.dirtree, self.graphviz_btn),
                    self.on_graphviz_btn)))
        return tabs
Exemplo n.º 15
0
# helper functions
def select_event_subset(df, e):
    """
    Return only the rows of df which belong to the requested event.
    """
    return df[df['event'] == e]


def get_ax():
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    return fig, ax


# declare variable widgets
athlete_name = pnw.Select(name='Athlete',
                          options=list(individual_events['Name'].unique()))
event_distance = pnw.RadioButtonGroup(name='Event', value=ALL_EVENTS_NAME)
start_position = pnw.RadioButtonGroup(name='Start Position')
position_gain_loss = pnw.RadioButtonGroup(name='Position Gain/Loss')
athlete_races = pnw.DataFrame()
athlete_races_single_event = pnw.DataFrame()
athlete_laptimes = pnw.DataFrame()
athlete_laptimes_single_event = pnw.DataFrame()


def athlete_name_changed(event):
    """
    Triggering event is athlete_name.value
    """
    athlete_races.value = individual_events[individual_events['Name'] ==
                                            event.new]
Exemplo n.º 16
0
        if self.p.normalize:
            dr = data.ravel()
            data = (data - dr.mean()) / dr.std() * 2**16

        vmin, vmax = zscale(data.ravel())

        new_data = data.clip(vmin, vmax)

        label = element.label
        # make an exact copy of the element with all settings, just with different data and label:
        element = element.clone((xs, ys, new_data), label=label)
        return element


channel = pnw.IntSlider(name='Channel', value=1, start=1, end=15)
zslice = pnw.Select(name='Slice', options=[])


class CubeViewer(param.Parameterized):

    channel = param.Integer()
    zslice = param.ObjectSelector()

    def __init__(self,
                 data_dir,
                 imgtype='cubes',
                 xaxis=None,
                 yaxis=None,
                 colorbar=True,
                 toolbar='below',
                 height=400):
Exemplo n.º 17
0
class PlotManager(param.Parameterized):
    db_manager = DataBaseManager()
    endpoint = widgets.TextInput(name="Server endpoint",
                                 value="http://*****:*****@param.depends("datasource.value", "x_val.value", "y_val.value",
                   "z_val.value", "color.value", "size.value",
                   "endpoint.value", "extra.value")
    def _url(self):
        url = self._get_url()

        self.url_widget.value = url

        return pn.pane.Str("")

    @param.depends("button.clicks", watch=True)
    def _update_iframe(self):
        iframe = (
            '<iframe width="800" height="600" scrolling="yes" frameBorder="0"'
            'scrolling="no" src="{}"></iframe>').format(self.url_widget.value)
        self.display.object = iframe

    def _get_url(self):
        url = "%s?" % self.endpoint.value
        ds_str = "datasource=%s&" % self.datasource.value
        url += "" if self.datasource.value is None else ds_str
        url += "" if self.x_val.value is None else "x=%s" % self.x_val.value
        url += "" if self.y_val.value is None else "&y=%s" % self.y_val.value
        url += "" if self.z_val.value is None else "&z=%s" % self.z_val.value
        url += "" if self.color.value is None else "&color=%s" % self.color.value
        url += "" if self.size.value is None else "&size=%s" % self.size.value
        url += "" if self.extra.value is None else "&%s" % self.extra.value
        return url

    @param.depends("db_manager.connect_btn.clicks", watch=True)
    def populate_datasources(self):
        if self.db_manager.connected:
            datasources = [None] + list(
                sorted(self.db_manager.get_table_names()))
            self.datasource.options = datasources

        return pn.pane.Str()

    @param.depends("datasource.value", watch=True)
    def populate_widgets(self):
        if self.db_manager.connected:
            columns = list(
                sorted(self.db_manager.get_column_names(
                    self.datasource.value)))
            self.x_val.options = [None] + columns
            self.y_val.options = [None] + columns
            self.z_val.options = [None] + columns
            self.color.options = [None] + columns
            self.size.options = [None] + columns
        return pn.pane.Str()

    @property
    def url(self):
        return self._get_url()

    def panel(self):
        controls = pn.Column(
            pn.Row(self.datasource, self.endpoint),
            pn.Row(self.x_val, self.y_val, self.z_val,
                   self.db_manager.connect_btn),
            pn.Row(self.color, self.size, self.extra))
        plot_dash = pn.Column(
            pn.pane.Markdown("# Plot manager"), controls,
            pn.Row(self.button, pn.pane.Markdown("**Target url**"),
                   self.url_widget), self.display, self.populate_widgets,
            self.populate_datasources, self._url, self._update_iframe)
        return plot_dash
        return pn.Tabs(("Plot manager", plot_dash),
                       ("DB connection", self.db_manager.panel()))
Exemplo n.º 18
0
def genome_features_viewer(gff_file, ref_file=None, plot_width=900):
    """Gene feature viewer app"""
    
    if gff_file is None:
        return
    
    features = utils.gff_to_features(gff_file)
    df = utils.features_to_dataframe(features)
    
    loc_pane = pnw.TextInput(name='location',value='',width=150)
    search_pane = pnw.TextInput(name='find_gene',value='',width=220)
    slider = pnw.IntSlider(name='start',start=0,end=10000,step=500,value=1,width=plot_width)
    xzoom_slider = pnw.IntSlider(name='zoom',start=1,end=500,value=100,step=5,width=100)
    chrom_select = pnw.Select(name='chrom',width=220)
    left_button = pnw.Button(name='<',width=40)
    right_button = pnw.Button(name='>',width=40)
    
    feature_pane = pn.pane.Bokeh(height=100,margin=10)
    seq_pane = pn.pane.Bokeh(height=50,margin=10)
    debug_pane = pn.pane.Str('debug',width=200,style={'background':'yellow','margin': '4pt'})
    
    if ref_file is not None:
        seqlen = utils.get_fasta_length(ref_file)
        slider.end = seqlen
    else:
        slider.end = int(df.end.max())

    def search_features(event):
        """Find a feature"""
        
        term = search_pane.value        
        feats = utils.gff_to_features(gff_file)
        df = utils.features_to_dataframe(feats)    
        df['gene'] = df.gene.fillna('')
        f = df[df.gene.str.contains(term)].iloc[0]
        #debug_pane.object = str(f.start)
        slider.value = int(f.start)-100
        update(event)
        return   
    
    def pan(event):
        p = feature_pane.object
        rng = p.x_range.end-p.x_range.start        
        inc = int(rng/10)
        print (event.obj.name)
        if event.obj.name == '<':
            slider.value = int(slider.value) - inc        
        else:
            slider.value = int(slider.value) + inc   
        update(event)
        return
    
    def update(event):      
        print (event.obj.name)
        if event.obj.name in ['start', 'zoom']:
            xzoom = xzoom_slider.value*200
            start = int(slider.value)
            N = xzoom/2
            end = int(start+N)
            loc_pane.value = str(start)+':'+str(end)            
        elif event.obj.name == 'location':            
            vals = loc_pane.value.split(':')
            start = int(vals[0])
            end = int(vals[1])
            slider.value = start        
            
        #debug_pane.object=type(start)
        p = feature_pane.object
        p.x_range.start = start
        p.x_range.end = end
        if ref_file:
            sequence = utils.get_fasta_sequence(ref_file, start, end)
            seq_pane.object = plotters.plot_sequence(sequence, plot_width, plot_height=50,fontsize='9pt',xaxis=False)            
        return
        
    slider.param.watch(update,'value',onlychanged=True)
    #slider.param.trigger('value')    
    xzoom_slider.param.watch(update,'value')       
    search_pane.param.watch(search_features,'value')    
    loc_pane.param.watch(update,'value',onlychanged=True)    
    left_button.param.watch(pan,'clicks')
    right_button.param.watch(pan,'clicks')
    #debug_pane.object = utils.get_fasta_names(ref_file)[0] 
    if ref_file != None:
        chrom_select.options = utils.get_fasta_names(ref_file)
    #plot
    p = feature_pane.object = plotters.plot_features(features, 0, 10000, plot_width=plot_width, tools="", rows=4)
    
    #side = pn.Column(file_input,css_classes=['form'],width=200,margin=20)
    top = pn.Row(loc_pane,xzoom_slider,search_pane,chrom_select,left_button,right_button)
    main = pn.Column(feature_pane, seq_pane, sizing_mode='stretch_width')
    app = pn.Column(top,slider,main,debug_pane, sizing_mode='stretch_width',width_policy='max',margin=20)
    return app
Exemplo n.º 19
0
def categorical_2d_histogram_with_gui(data: pd.DataFrame, category_cols=None, hist_cols=None, width=500, height=500):
    """Creates a categorical_2d_histogram for a dataframe, where each option (except width, height and color_mapper) of the categorical_2d_histogram can be set with gui elements.
    If the input is a list all dataframes need to have the same cols as the first dataframe in the list"""
    if category_cols is None and isinstance(data, pd.DataFrame):
        category_cols = data.columns.tolist()
    elif category_cols is None and isinstance(data, list):
        category_cols = data[0].columns.tolist()
    if hist_cols is None and isinstance(data, pd.DataFrame):
        hist_cols = [col_name for col_name in data.columns if is_numeric_dtype(data[col_name])]
    elif hist_cols is None and isinstance(data, list):
        hist_cols = [col_name for col_name in data[0].columns if is_numeric_dtype(data[0][col_name])]
    x_select = pnw.Select(name="X-Axis", options=hist_cols)
    y_select = pnw.Select(name="Y-Axis", options=category_cols)

    axis_selector = pn.Row(x_select, y_select, width=width)

    x_is_categorical = pnw.Checkbox(name="X is categorical", value=False)
    x_bins = pnw.IntInput(name="Bins", start=1, end=500, value=10, disabled=False)
    if isinstance(data, pd.DataFrame):
        x_range_start=data[x_select.value].min()
        x_range_end=data[x_select.value].max()
        x_range_end=x_range_end if x_range_end > x_range_start else x_range_end*1.1
        x_range_step=(x_range_end - x_range_start) / 50
    elif isinstance(data, list):
        x_range_start=min(df[x_select.value].min() for df in data)
        x_range_end=max(df[x_select.value].max() for df in data)
        x_range_end=x_range_end if x_range_end > x_range_start else x_range_end*1.1
        x_range_step=(x_range_end - x_range_start) / 50
    x_range = pnw.RangeSlider(name="X-Axis Range", start=x_range_start, end=x_range_end, step=x_range_step, disabled=False)

    x_axis_configuration = pn.Row(x_range, x_bins, width=width)

    normalize_rows = pnw.Checkbox(name="Normalize rows", value=False)
    x_precision = pnw.IntInput(name="Precision", start=0, end=10, value=2, disabled=False)

    additional_parameters = pn.Row(x_is_categorical, normalize_rows, x_precision, width=width)

    config_gui = pn.Column(axis_selector, additional_parameters, x_axis_configuration, align="center")

    @pn.depends(y_select.param.value, x_select.param.value, x_bins.param.value_throttled, x_range.param.value_throttled, x_is_categorical.param.value, normalize_rows.param.value, x_precision.param.value)
    def _plot(category_col, hist_col, bins, range, x_is_categorical, normalize_rows, precision):
        if x_is_categorical:
            x_range.disabled = True
            x_precision.disabled = True
            x_bins.disabled = True
        else:
            x_range.disabled = False
            x_precision.disabled = False
            x_bins.disabled = False

        if isinstance(data, pd.DataFrame):
            if data[hist_col].min() != x_range.start or data[hist_col].max() != x_range.end:
                x_range.start = data[hist_col].min()
                x_range.end = data[hist_col].max() if data[hist_col].max() > x_range.start else data[hist_col].max()*1.1
                x_range.value = (x_range.start, x_range.end)
                x_range.step = (x_range.end-x_range.start)/50
        elif isinstance(data, list):
            if min(df[hist_col].min() for df in data) != x_range.start or max(df[hist_col].max() for df in data) != x_range.end:
                x_range.start = min(df[hist_col].min() for df in data)
                x_range.end = max(df[hist_col].max() for df in data) if max(df[hist_col].max() for df in data) > x_range.start else max(df[hist_col].max() for df in data)*1.1
                x_range.value = (x_range.start, x_range.end)
                x_range.step = (x_range.end-x_range.start)/50
        range = x_range.value

        if isinstance(data, list):
            plot = pn.Row(*categorical_2d_histogram(data, category_col, hist_col, bins, range, normalize_rows, precision, color_mapper=None, hist_col_is_categorical=x_is_categorical, width=width, height=height))
        elif isinstance(data, pd.DataFrame):
            plot = pn.Row(categorical_2d_histogram(data, category_col, hist_col, bins, range, normalize_rows, precision, color_mapper=None, hist_col_is_categorical=x_is_categorical, width=width, height=height))
        return plot

    return pn.Column(config_gui, _plot)
Exemplo n.º 20
0
class StructurePanel(AbipyParameterized):
    """
    Panel with widgets to interact with an AbiPy Structure
    """
    verbose = param.Integer(0, bounds=(0, None), doc="Verbosity Level")

    # Convert widgets.
    output_format = pnw.Select(
        name="format",
        value="abinit",
        options="abinit,cif,xsf,poscar,qe,siesta,wannier90,cssr,json".split(
            ","))

    # Spglib widgets
    spglib_symprec = pnw.Spinner(name="symprec",
                                 value=0.01,
                                 start=0.0,
                                 end=None,
                                 step=0.01)
    spglib_angtol = pnw.Spinner(name="angtol",
                                value=5,
                                start=0.0,
                                end=None,
                                step=1)

    # K-path widgets
    kpath_format = pnw.Select(name="format",
                              value="abinit",
                              options=["abinit", "siesta", "wannier90"])
    line_density = pnw.Spinner(name="line density",
                               value=10,
                               step=5,
                               start=0,
                               end=None)

    # Viewer widgets.
    viewer_btn = pnw.Button(name="View structure", button_type='primary')
    viewer = pnw.Select(
        name="Viewer",
        value="vesta",
        options=["vesta", "xcrysden", "vtk", "matplotlib", "mayavi"])

    # Mp-match
    mp_match_btn = pnw.Button(name="Connect to Materials Project",
                              button_type='primary')

    # Mp-search
    #mp_search_btn = pnw.Button(name="Connect to Materials Project", button_type='primary')
    #mp_api_key

    # GS input generator widgets.
    gs_input_btn = pnw.Button(name="Generate input", button_type='primary')
    gs_type = pnw.Select(name="GS type", value="scf", options=["scf", "relax"])
    kppra = pnw.Spinner(name="kppra", value=1000, step=1000, start=0, end=None)

    label2mode = {
        "unpolarized": 'unpolarized',
        "polarized": 'polarized',
        "anti-ferromagnetic": "afm",
        "non-collinear with magnetism": "spinor",
        "non-collinear, no magnetism": "spinor_nomag",
    }

    spin_mode = pnw.Select(name="SpinMode",
                           value="unpolarized",
                           options=list(label2mode.keys()))

    def __init__(self, structure, **params):
        super().__init__(**params)
        self.structure = structure

    @param.depends("output_format.value")
    def convert(self):
        return pn.Row(bkw.PreText(text=self.structure.convert(
            fmt=self.output_format.value)),
                      sizing_mode='stretch_width')

    @param.depends("spglib_symprec.value", "spglib_angtol.value")
    def spglib_summary(self):
        s = self.structure.spget_summary(
            symprec=self.spglib_symprec.value,
            angle_tolerance=self.spglib_angtol.value)
        return pn.Row(bkw.PreText(text=s, sizing_mode='stretch_width'))

    @param.depends("kpath_format.value", "line_density.value")
    def get_kpath(self):
        s = self.structure.get_kpath_input_string(
            fmt=self.kpath_format.value, line_density=self.line_density.value)
        return pn.Row(bkw.PreText(text=s, sizing_mode='stretch_width'))

    @param.depends("viewer_btn.clicks")
    def view(self):
        if self.viewer_btn.clicks == 0: return

        import panel as pn

        #view = self.structure.get_jsmol_view()
        #from ipywidgets_bokeh import IPyWidget
        #view = IPyWidget(widget=view) #, width=800, height=300)
        #from IPython.display import display
        #display(view)
        #return pn.Row(display(view))
        #return pn.panel(view)

        js_files = {
            'ngl':
            'https://cdn.jsdelivr.net/gh/arose/[email protected]/dist/ngl.js'
        }
        pn.extension(comms='ipywidgets', js_files=js_files)
        view = self.structure.get_ngl_view()
        return pn.panel(view)

        #pn.config.js_files["ngl"]="https://cdn.jsdelivr.net/gh/arose/[email protected]/dist/ngl.js"
        #pn.extension()

        html = """<div id="viewport" style="width:100%; height:100%;"></div>
        <script>
        stage = new NGL.Stage("viewport");
        stage.loadFile("rcsb://1NKT.mmtf", {defaultRepresentation: true});
        </script>"""

        #        html = """
        #         <script>
        #    document.addeventlistener("domcontentloaded", function () {
        #      var stage = new ngl.stage("viewport");
        #      stage.loadfile("rcsb://1crn", {defaultrepresentation: true});
        #    });
        #  </script>"""

        #        html = """
        #<script>
        #document.addeventlistener("domcontentloaded", function () {
        #    // create a `stage` object
        #    var stage = new NGL.Stage("viewport");
        #    // load a PDB structure and consume the returned `Promise`
        #    stage.loadFile("rcsb://1CRN").then(function (component) {
        #    // add a "cartoon" representation to the structure component
        #    component.addRepresentation("cartoon");
        #    // provide a "good" view of the structure
        #    component.autoView();
        #  });
        #});
        #</script>"""

        ngl_pane = pn.pane.HTML(html, height=500, width=500)
        return pn.Row(ngl_pane)

        view = self.structure.get_ngl_view()
        #return self.structure.crystaltoolkitview()
        #import nglview as nv
        #view = nv.demo(gui=False)

        #from bokeh.models import ColumnDataSource
        #from bokeh.io import show, curdoc
        #from bokeh.models.widgets import Button, TextInput
        #from bokeh.layouts import layout, widgetbox
        #from jsmol_bokeh_extension import JSMol
        #script_source = ColumnDataSource()

        #info = dict(
        #    height="100%",
        #    width="100%",
        #    serverURL="https://chemapps.stolaf.edu/jmol/jsmol/php/jsmol.php",
        #    use="HTML5",
        #    j2sPath="https://chemapps.stolaf.edu/jmol/jsmol/j2s",
        #    script=
        #    "background black;load https://chemapps.stolaf.edu/jmol/jsmol-2013-09-18/data/caffeine.mol",
        #)

        #applet = JSMol(
        #    width=600,
        #    height=600,
        #    script_source=script_source,
        #    info=info,
        #)

        #button = Button(label='Execute')
        #inp_script = TextInput(value='background white;')

        #def run_script():
        #    script_source.data['script'] = [inp_script.value]

        #button.on_click(run_script)
        #ly = layout([applet, widgetbox(button, inp_script)])
        #show(ly)
        #curdoc().add_root(ly)

        return pn.Row(applet)
        return self.structure.visualize(appname=self.viewer.value)

    @param.depends("gs_input_btn.clicks")
    def on_gs_input_btn(self):
        if self.gs_input_btn.clicks == 0: return
        from abipy.abio.factories import gs_input
        from abipy.data.hgh_pseudos import HGH_TABLE

        gs_inp = gs_input(self.structure,
                          HGH_TABLE,
                          kppa=self.kppra.value,
                          ecut=8,
                          spin_mode=self.label2mode[self.spin_mode.value],
                          smearing=None)
        gs_inp.pop_vars(("charge", "chksymbreak"))
        gs_inp.set_vars(ecut="?? # depends on pseudos",
                        nband="?? # depends on pseudos")

        if self.gs_type.value == "relax":
            gs_inp.set_vars(optcell=2, ionmov=2, ecutsm=0.5, dilatmx=1.05)

        gs_inp.set_mnemonics(False)
        return html_with_copy_to_clipboard(gs_inp._repr_html_())

    @param.depends("mp_match_btn.clicks")
    def on_mp_match_btn(self):
        if self.mp_match_btn.clicks == 0: return
        from abipy.core.structure import mp_match_structure
        mp = mp_match_structure(self.structure,
                                api_key=None,
                                endpoint=None,
                                final=True)
        if not mp.structures:
            raise RuntimeError("No structure found in MP database")

        return pn.Column(self._df(mp.lattice_dataframe),
                         sizing_mode='stretch_width')

    #@param.depends("mp_search_btn.clicks")
    #def on_mp_search_btn(self):
    #    if self.mp_search_btn.clicks == 0: return
    #    from abipy.core.structure import mp_search
    #    chemsys_formula_id = self.stucture.formula
    #    mp = mp_search(chemsys_formula_id, api_key=None, endpoint=None, final=True)
    #    if not mp.structures:
    #        raise RuntimeError("No structure found in MP database")

    #    return pn.Column(self._df(mp.lattice_dataframe), sizing_mode='stretch_width')

    def get_panel(self):
        """Build panel with widgets to interact with the structure either in a notebook or in a bokeh app"""
        tabs = pn.Tabs()
        app = tabs.append
        row = pn.Row(
            bkw.PreText(text=self.structure.to_string(verbose=self.verbose),
                        sizing_mode="scale_both"))
        app(("Summary", row))
        ws = pn.Column('# Spglib options', self.spglib_symprec,
                       self.spglib_angtol)
        app(("Spglib", pn.Row(ws, self.spglib_summary)))
        ws = pn.Column('# K-path options', self.kpath_format,
                       self.line_density)
        app(("Kpath", pn.Row(ws, self.get_kpath)))
        app(("Convert",
             pn.Row(pn.Column("# Convert structure", self.output_format),
                    self.convert)))
        app(("View",
             pn.Row(
                 pn.Column("# Visualize structure", self.viewer,
                           self.viewer_btn), self.view)))
        ws = pn.Column('# Generate GS input', self.gs_type, self.spin_mode,
                       self.kppra, self.gs_input_btn)
        app(("GS-input", pn.Row(ws, self.on_gs_input_btn)))
        app(("MP-match",
             pn.Row(pn.Column(self.mp_match_btn), self.on_mp_match_btn)))

        return tabs
import panel.widgets as pnw
import plotly.graph_objects as go

pn.extension("plotly")

files = os.listdir('data')
AAFMG = []
for f in files:
    data = pd.read_csv('data/' + f)
    data['Symbol'] = f.replace('.csv', '')
    AAFMG.append(data)
AAFMG = pd.concat(AAFMG)
AAFMG['Date'] = pd.to_datetime(AAFMG['Date'])

# Create Widget Components
symbol = pnw.Select(name='symbol',
                    options=['AAPL', 'AMZN', 'FB', 'GOOGL', 'MSFT'])
value = pnw.RadioButtonGroup(
    name='value',
    options=['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'])
window = pnw.IntSlider(name='window', start=7, end=365, value=30)
date_range = pnw.DateRangeSlider(name='date range',
                                 start=datetime.datetime(1980, 12, 12),
                                 end=datetime.datetime(2020, 4, 1),
                                 value=(datetime.datetime(2017, 4, 1),
                                        datetime.datetime(2020, 4, 1)))


# Define Reactive Plot Function
@pn.depends(symbol, value, window, date_range)
def reactive_plot(symbol, value, window, date_range):
    df = AAFMG.loc[AAFMG['Symbol'] == symbol]
Exemplo n.º 22
0
import panel.widgets as pnw
import datetime
import pandas as pd

import us.states as uss

pn.extension()
pn.config.sizing_mode = "stretch_width"

stats_w = pnw.DataFrame(pd.DataFrame(), name='stats')
counties_w = pnw.DataFrame(pd.DataFrame(), name='counties')

sort_cols = [
    'Confirmed', 'Deaths', 'Active', 'county', 'pop2019', 'fraction_confirmed',
    'death_rate'
]
state_w = pnw.Select(name='state',
                     options=uss.states(),
                     value='Alabama',
                     disabled=False)

sortby_w = pnw.Select(name='sort on column',
                      options=sort_cols,
                      value='fraction_confirmed',
                      disabled=False)

ascending_w = pnw.Checkbox(name='Sort Ascending', value=False, disabled=False)

date_w = pnw.DatePicker(name='date',
                        value=datetime.date.today() - datetime.timedelta(1),
                        disabled=False)
Exemplo n.º 23
0
def bam_viewer(bam_file, ref_file, gff_file=None, width=1000, height=200, color='gray'):
    """Bam viewer widget.
    
    Args:
        bam_file: sorted bam file
        ref_file: reference sequence in fasta format
        gff_file: optional genomic features file
    """
    slider = pnw.IntSlider(name='location',start=1,end=10000,value=500,step=500,width=300)
    main_pane = pn.pane.Bokeh(height=100)
    cov_pane = pn.pane.Bokeh(height=60)
    loc_pane = pn.pane.Str(50,width=250,style={'margin': '4pt'})
    feat_pane = pn.pane.Bokeh(height=60)
    ref_pane = pn.pane.Bokeh(height=60)
    xzoom_slider = pnw.IntSlider(name='x zoom',start=50,end=8000,value=1000,step=10,width=100)
    yzoom_slider = pnw.IntSlider(name='y zoom',start=10,end=100,value=20,step=5,width=100)#,orientation='vertical')
    panleft_btn = pnw.Button(name='<',width=50,button_type='primary')
    panright_btn = pnw.Button(name='>',width=50,button_type='primary')
    chroms_select = pnw.Select(name='Chromosome', options=[], width=250)
    colorby = pnw.Select(name='Color by', options=['quality','pair orientation','read strand'], width=180)
    search_pane = pnw.TextInput(name='search',width=200)
    trans_option = pnw.Checkbox(name='show translation')
    debug_pane = pn.pane.Markdown()
    
    def pan_right(event):
        plot = main_pane.object
        plot.x_range
        start = slider.value 
        loc = slider.value+100    
        slider.value=loc
        update(event)
        return

    def pan_left(event):
        loc = slider.value-100
        if loc<1:
            return
        slider.value=loc
        update(event)
        return

    def update_features():
        """Load features"""

        if gff_file is None:
            return        
        ext = os.path.splitext(gff_file)[1]        
        if ext in ['.gff','.gff3']:
            feats = utils.gff_to_features(gff_file)
        elif ext in ['.gb','.gbff']:
            feats = utils.genbank_to_features(gff_file)
        p = feat_pane.object = plotters.plot_features(feats, 
                                                  plot_width=width, plot_height=100)
        return p

    def search_features(event):
        """Find a feature"""
        
        term = search_pane.value        
        feats = utils.gff_to_features(gff_file)
        df = utils.features_to_dataframe(feats)    
        df['gene'] = df.gene.fillna('')
        f = df[df.gene.str.contains(term)].iloc[0]
        debug_pane.object = str(f.start)
        slider.value = int(f.start)
        update(event)
        return
    
    def update_ref(filename, start, end):
        """Update reference sequence"""

        if filename == None:
            return
        seqlen = utils.get_fasta_length(filename)
        slider.end = seqlen
        refseq = Fasta(filename)
        chroms = list(refseq.keys())
        chroms_select.options = chroms
        key = chroms[0]
        seq = refseq[key][int(start):int(end)].seq
        ref_pane.object = plotters.plot_sequence(seq, plot_height=50,fontsize='9pt',xaxis=False)
        return
    
    def update(event):
        """Update viewers on widget change"""

        xzoom = xzoom_slider.value
        yzoom = yzoom_slider.value
        start = slider.value     
        N = xzoom/2
        end = start+N
        chrom = utils.get_chrom(bam_file)
        loc_pane.object = '%s:%s-%s' %(chrom,start,int(end))
        cov = utils.get_coverage(bam_file,chrom,start,end)
        cov_pane.object = plotters.plot_coverage(cov,plot_width=width)
        main_pane.object = plotters.plot_bam_alignment(bam_file,chrom,start,end,height=yzoom,plot_width=width,plot_height=height)        
        update_ref(ref_file, start, end)
        if feature_plot:
            feature_plot.x_range.start = start
            feature_plot.x_range.end = end
        debug_pane.object = ''
        return

    slider.param.watch(update, 'value')
    xzoom_slider.param.watch(update, 'value')
    yzoom_slider.param.watch(update, 'value')
    panright_btn.param.watch(pan_right, 'clicks')
    panleft_btn.param.watch(pan_left, 'clicks')
    search_pane.param.watch(search_features, 'value')
    feature_plot = update_features()
    
    #initialise slider
    slider.param.trigger('value')
    
    #menus = pn.Row(bam_input, ref_input, gff_input)
    top = pn.Row(slider,xzoom_slider,yzoom_slider,panleft_btn,panright_btn,loc_pane)
    bottom = pn.Row(chroms_select, search_pane,colorby,trans_option)
    app = pn.Column(top,cov_pane,main_pane,ref_pane,feat_pane,bottom,debug_pane)
    return app
Exemplo n.º 24
0
df['mfr'] = [x.split()[0] for x in df.name]
df.loc[df.mfr == 'chevy', 'mfr'] = 'chevrolet'
df.loc[df.mfr == 'chevroelt', 'mfr'] = 'chevrolet'
df.loc[df.mfr == 'maxda', 'mfr'] = 'mazda'
df.loc[df.mfr == 'mercedes-benz', 'mfr'] = 'mercedes'
df.loc[df.mfr == 'toyouta', 'mfr'] = 'toyota'
df.loc[df.mfr == 'vokswagen', 'mfr'] = 'volkswagen'
df.loc[df.mfr == 'vw', 'mfr'] = 'volkswagen'
del df['name']

columns = sorted(df.columns)
discrete = [x for x in columns if df[x].dtype == object]
continuous = [x for x in columns if x not in discrete]
quantileable = [x for x in continuous if len(df[x].unique()) > 20]

x = pnw.Select(name='X-Axis', value='mpg', options=quantileable)
y = pnw.Select(name='Y-Axis', value='hp', options=quantileable)
size = pnw.Select(name='Size', value='None', options=['None'] + quantileable)
color = pnw.Select(name='Color', value='None', options=['None'] + quantileable)


@pn.depends(x.param.value, y.param.value, color.param.value, size.param.value)
def create_figure(x, y, color, size):
    opts = dict(cmap='rainbow',
                width=800,
                height=600,
                padding=0.1,
                line_color='black')
    if color != 'None':
        opts['color'] = color
    if size != 'None':
Exemplo n.º 25
0
def map_dash():
    """Map dashboard"""
    # Create the map
    map_pane = pn.pane.plot.Folium(sizing_mode="scale_both", min_width=800)

    # Initialize map at Joshua Tree in July
    unit = 'JOTR'
    month = 7
    coords = get_coords(unit, parks)
    bnds = get_bounds(unit, boundaries)
    traffic = get_traffic(unit, traffic_data)
    visitors = get_visitors(unit, month, publicUse)
    map_pane.object = makeMap(unit, month, coords, bnds, visitors, traffic)

    # Create the dropdown menus for month and visitors
    month_buttons = pnw.RadioButtonGroup(name='Month',
                                         options=list(month_dict.keys()),
                                         button_type='primary',
                                         value='July')
    traffic_checkbox = pnw.Checkbox(name='Display traffic counters',
                                    value=True)
    park_select = pnw.Select(name='Where do you want to go?',
                             options=list(park_dict.keys()),
                             value='Joshua Tree NP')

    # Trigger map updates
    def update_map(event):
        month = month_dict[month_buttons.value]
        unit = park_dict[park_select.value]
        coords = get_coords(unit, parks)
        bnds = get_bounds(unit, boundaries)
        traffic = get_traffic(unit, traffic_data)
        visitors = get_visitors(unit, month, publicUse)
        map_pane.object = makeMap(unit,
                                  month,
                                  coords,
                                  bnds,
                                  visitors,
                                  traffic,
                                  useTraffic=traffic_checkbox.value)
        return

    # Updates
    month_buttons.param.watch(update_map, 'value')
    month_buttons.param.trigger('value')
    park_select.param.watch(update_map, 'value')
    park_select.param.trigger('value')
    traffic_checkbox.param.watch(update_map, 'value')
    traffic_checkbox.param.trigger('value')

    # Fully return the map
    app = pn.Column(month_buttons,
                    traffic_checkbox,
                    park_select,
                    map_pane,
                    width_policy='fit')
    return app


#pn.extension()

#app = map_dash()
#app.servable()
#server = app.show(threaded=True)
Exemplo n.º 26
0
    def __init__(self, plot, tabs):  # pylint: disable=redefined-outer-name
        """Initialize form.

        :param plot: IsothermPlot instance for validation of results.
        :param tabs: Panel tabs instance for triggering tab switching.
        """
        self.plot = plot
        self.tabs = tabs

        # isotherm metadata
        self.inp_doi = pw.TextInput(name='Article DOI',
                                    placeholder='10.1021/jacs.9b01891')
        self.inp_doi.param.watch(self.on_change_doi, 'value')
        self.inp_temperature = pw.TextInput(name='Temperature',
                                            placeholder='303')
        self.inp_adsorbent = pw.AutocompleteInput(
            name='Adsorbent Material',
            options=QUANTITIES['adsorbents']['names'],
            placeholder='Zeolite 5A',
            case_sensitive=False,
            **restrict_kwargs)
        self.inp_isotherm_type = pw.Select(
            name='Isotherm type',
            options=['Select'] + QUANTITIES['isotherm_type']['names'])
        self.inp_measurement_type = pw.Select(
            name='Measurement type',
            options=['Select'] + QUANTITIES['measurement_type']['names'])
        self.inp_pressure_scale = pw.Checkbox(
            name='Logarithmic pressure scale')
        self.inp_isotherm_data = pw.TextAreaInput(
            name='Isotherm Data',
            height=200,
            placeholder=config.SINGLE_COMPONENT_EXAMPLE)
        self.inp_figure_image = pw.FileInput(name='Figure snapshot')

        # units metadata
        self.inp_pressure_units = pw.Select(
            name='Pressure units',
            options=['Select'] + QUANTITIES['pressure_units']['names'])
        self.inp_pressure_units.param.watch(self.on_change_pressure_units,
                                            'value')
        self.inp_saturation_pressure = pw.TextInput(
            name='Saturation pressure [bar]', disabled=True)
        self.inp_adsorption_units = pw.AutocompleteInput(
            name='Adsorption Units',
            options=QUANTITIES['adsorption_units']['names'],
            placeholder='mmol/g',
            case_sensitive=False,
            **restrict_kwargs)

        # digitizer info
        self.inp_source_type = pw.TextInput(name='Source description',
                                            placeholder='Figure 1a')
        self.inp_tabular = pw.Checkbox(
            name='Tabular Data (i.e., not digitized from a graphical source)')
        self.inp_digitizer = pw.TextInput(name='Digitized by',
                                          placeholder='Your full name')

        # fill form from JSON upload
        self.inp_json = pw.FileInput(name='Upload JSON Isotherm')

        # buttons
        self.btn_prefill = pn.widgets.Button(
            name='Prefill (default or from JSON)', button_type='primary')
        self.btn_prefill.on_click(self.on_click_prefill)
        self.out_info = bw.PreText(
            text='Press "Plot" in order to download json.')
        self.inp_adsorbates = Adsorbates(show_controls=False, )
        self.btn_plot = pn.widgets.Button(name='Plot', button_type='primary')
        self.btn_plot.on_click(self.on_click_plot)

        for inp in self.required_inputs:
            inp.css_classes = ['required']

        # create layout
        self.layout = pn.Column(
            pn.pane.HTML('<h2>Isotherm Digitizer</h2>'),
            self.inp_digitizer,
            self.inp_doi,
            pn.pane.HTML('<hr>'),
            self.inp_source_type,
            pn.Row(pn.pane.HTML("""Attach Figure Graphics"""),
                   self.inp_figure_image),
            self.inp_measurement_type,
            self.inp_adsorbent,
            self.inp_adsorbates.column,
            self.inp_temperature,
            self.inp_isotherm_type,
            pn.Row(self.inp_pressure_units, self.inp_saturation_pressure),
            self.inp_pressure_scale,
            self.inp_adsorption_units,
            pn.pane.HTML("""We recommend the
                <b><a href='https://apps.automeris.io/wpd/' target="_blank">WebPlotDigitizer</a></b>
                for data extraction."""),
            self.inp_isotherm_data,
            self.inp_tabular,
            pn.Row(self.btn_plot, self.btn_prefill, self.inp_json),
            self.out_info,
        )
Exemplo n.º 27
0
def scatter_plot_with_gui(dataframe: pd.DataFrame, x_cols: list = None, y_cols: list = None, color_cols: list=None, with_hist: bool=True, width=500, height=500):
    x_cols = list(dataframe.columns) if x_cols is None else x_cols
    y_cols = list(dataframe.columns) if y_cols is None else y_cols

    divider = 2

    if color_cols is not None:
        divider = 3
        color_select = pnw.Select(name="Color", options=color_cols, height=50, width=width//divider)

    x_select = pnw.Select(name="X-Axis", options=x_cols, height=50, width=width//divider)
    y_select = pnw.Select(name="Y-Axis", options=y_cols, height=50, width=width//divider)

    if color_cols is None:
        gui = pn.Column(pn.Row(x_select, y_select), None)
    else:
        gui = pn.Column(pn.Row(x_select, y_select, color_select), None)

    def plot(event):
        x_col = x_select.value
        y_col = y_select.value
        df_copy = dataframe.copy()
        if color_cols is not None:
            color_col = color_select.value
            df_copy[color_col] = df_copy[color_col].astype(str)
        source = ColumnDataSource(df_copy)

        if color_cols is not None:
            if 3 <= df_copy[color_col].nunique() <= 20:
                colors = Category20[df_copy[color_col].nunique()]
            else:
                colors = viridis(df_copy[color_col].nunique())
        else:
            colors="navy"
        tooltips = [(color_col, f"@{color_col}")] if color_cols is not None else None

        p = figure(width=width, height=height-50, x_axis_label=x_col, y_axis_label=y_col, tooltips=tooltips)
        # radius = min(df_copy[x_col].max()-df_copy[x_col].min(), df_copy[y_col].max()-df_copy[y_col].min())/75 * max(1, np.log(max(df_copy[x_col].max()-df_copy[x_col].min(), df_copy[y_col].max()-df_copy[y_col].min()))/20)
        if color_cols is not None:
            for index, entry in enumerate(df_copy[color_col].unique()):
                local_source = df_copy[df_copy[color_col] == entry]
                p.scatter(x=x_col, y=y_col, legend_label=entry, source=local_source, color=colors[index])
            p.js_on_event(events.DoubleTap, toggle_legend_js(p))
            p.legend.click_policy="hide"
        else:
            p.scatter(x=x_col, y=y_col, source=source)

        if with_hist:
            hist_x = histogram(df_copy[x_col].values, 30, remove_tools=True, height=height//5, width=width)
            hist_x.x_range = p.x_range
            hist_y = histogram(df_copy[y_col].values, 30, remove_tools=True, orientation="vertical", width=width//5, height=height//7*6)
            hist_y.y_range = p.y_range
            gui[-1] = gridplot([[hist_x, None], [p, hist_y]], merge_tools=True)
        else:
            gui[-1] = p
    plot(None)

    if color_cols is not None:
        color_select.param.watch(plot, "value")
    x_select.param.watch(plot, "value")
    y_select.param.watch(plot, "value")

    return gui
Exemplo n.º 28
0
    def _update_widgets_panel(self):
        self._default_component[self.component_type] = self.component

        component = None
        controls = None
        if self.component is pn.pane.HoloViews:
            component = pn.pane.HoloViews(_create_hvplot())
        if self.component is pn.pane.ECharts:
            # Issue https://github.com/holoviz/panel/issues/1817
            component = pn.pane.ECharts(_create_echarts_plot(),
                                        min_height=400,
                                        min_width=200,
                                        sizing_mode="stretch_both")
        if self.component is pnw.Ace:
            py_code = inspect.getsource(_create_hvplot)
            component = pnw.Ace(
                value=py_code,
                sizing_mode="stretch_width",
                language="python",
                height=400,
                theme=self._ace_theme,
            )
        elif self.component is pnw.AutocompleteInput:
            component = pnw.AutocompleteInput(
                name="Autocomplete Input",
                options=["Biology", "Chemistry", "Physics"],
                placeholder="Write something here",
            )
        elif self.component is pnw.Button:
            component = pnw.Button(name="Click me", button_type="primary")
        elif self.component is pnw.CheckBoxGroup:
            component = pnw.CheckBoxGroup(
                name="Checkbox Group",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                inline=True,
            )
        elif self.component is pnw.CheckButtonGroup:
            component = pnw.CheckButtonGroup(
                name="Check Button Group",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                button_type="success",
            )
        elif self.component is pnw.Checkbox:
            component = pnw.Checkbox(name="Checkbox")
        elif self.component is pnw.ColorPicker:
            component = pnw.ColorPicker(name="Color Picker", value="#DF3874")
        elif self.component is pnw.CrossSelector:
            component = pnw.CrossSelector(
                name="Fruits",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                height=300,
            )
        elif self.component is pnw.DataFrame:
            component = self.component(name="Hello")
            component.value = get_dataframe()
            component.formatters = get_default_formatters(component.value)
            controls = pn.Spacer()
        elif self.component is pnw.DatePicker:
            component = pnw.DatePicker(name="Date Picker")
            # Issue: https://github.com/holoviz/panel/issues/1810
            # component.start = date(2020, 1, 20)
            # component.end = date(2020, 2, 20)
            # component.value = date(2020, 2, 18)
        elif self.component is pnw.DateRangeSlider:
            component = self.component(name="Hello")
            component.start = date(2020, 1, 20)
            component.end = date(2020, 2, 20)
            component.value = (date(2020, 2, 18), date(2020, 2, 20))
        elif self.component is pnw.DateSlider:
            component = self.component(name="Hello")
            component.start = date(2020, 1, 20)
            component.end = date(2020, 2, 20)
            component.value = date(2020, 2, 18)
        elif self.component is pnw.DatetimeInput:
            component = self.component(name="Hello")
            component.value = datetime(2020, 2, 18, 1, 2, 3)
        elif self.component is pnw.DatetimeRangeInput:
            component = self.component(
                name="Hello",
                start=datetime(2020, 1, 20),
                end=datetime(2020, 2, 20),
                value=(datetime(2020, 2, 18), datetime(2020, 2, 20)),
            )
        elif self.component is pnw.DiscretePlayer:
            component = pnw.DiscretePlayer(
                name="Discrete Player",
                options=[2, 4, 8, 16, 32, 64, 128],
                value=32,
                loop_policy="loop",
            )
        elif self.component is pnw.DiscreteSlider:
            component = pnw.DiscreteSlider(name="Discrete Slider",
                                           options=[2, 4, 8, 16, 32, 64, 128],
                                           value=32)
        elif self.component is pnw.FileDownload:
            component = pnw.FileDownload(file="README.md",
                                         filename="README.md")
        elif self.component is pnw.FileInput:
            component = pnw.FileInput(accept=".csv,.json")
        elif self.component is pnw.FileSelector:
            component = pnw.FileSelector(name="Hello", max_height=400)
        elif self.component is pnw.FloatInput:
            component = pnw.FloatInput(name="FloatInput",
                                       value=5.0,
                                       step=1e-1,
                                       start=0,
                                       end=1000)
        elif self.component is pnw.FloatSlider:
            component = pnw.FloatSlider(name="Float Slider",
                                        start=0,
                                        end=3.141,
                                        step=0.01,
                                        value=1.57)
        elif self.component is pnw.IntInput:
            component = pnw.IntInput(name="IntInput",
                                     value=5,
                                     step=2,
                                     start=0,
                                     end=1000)
        elif self.component is pnw.IntRangeSlider:
            component = pnw.IntRangeSlider(name="Integer Range Slider",
                                           start=0,
                                           end=100,
                                           value=(8, 40),
                                           step=2)
        elif self.component is pnw.IntSlider:
            component = pnw.IntSlider(name="Integer Slider",
                                      start=0,
                                      end=20,
                                      step=2,
                                      value=4)
        elif self.component is pnw.LiteralInput:
            component = pnw.LiteralInput(name="Literal Input (dict)",
                                         value={"key": [1, 2, 3]},
                                         type=dict)
        elif self.component is pnw.MenuButton:
            menu_items = [
                ("Option A", "a"),
                ("Option B", "b"),
                ("Option C", "c"),
                None,
                ("Help", "help"),
            ]
            component = pnw.MenuButton(name="Dropdown",
                                       items=menu_items,
                                       button_type="primary")
        elif self.component is pnw.MultiChoice:
            component = pnw.MultiChoice(
                name="MultiSelect",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
            )
        elif self.component is pnw.MultiSelect:
            component = pnw.MultiSelect(
                name="MultiSelect",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                size=8,
            )
        elif self.component is pnw.PasswordInput:
            component = pnw.PasswordInput(name="Password Input",
                                          placeholder="Enter a string here...")
        elif self.component is pnw.Player:
            component = pnw.Player(name="Player",
                                   start=0,
                                   end=100,
                                   value=32,
                                   loop_policy="loop")
        elif self.component is pnw.Progress:
            component = pnw.Progress(name="Progress", value=20, width=200)
        elif self.component is pnw.RadioBoxGroup:
            component = pnw.RadioBoxGroup(
                name="RadioBoxGroup",
                options=["Biology", "Chemistry", "Physics"],
                inline=True)
        elif self.component is pnw.RadioButtonGroup:
            component = pnw.RadioButtonGroup(
                name="Radio Button Group",
                options=["Biology", "Chemistry", "Physics"],
                button_type="success",
            )
        elif self.component is pnw.RangeSlider:
            component = pnw.RangeSlider(
                name="Range Slider",
                start=0,
                end=math.pi,
                value=(math.pi / 4.0, math.pi / 2.0),
                step=0.01,
            )
        elif self.component is pnw.Select:
            component = pnw.Select(name="Select",
                                   options=["Biology", "Chemistry", "Physics"])
        elif self.component is pnw.StaticText:
            component = pnw.StaticText(name="Static Text", value="A string")
        elif self.component is pnw.TextAreaInput:
            component = pnw.input.TextAreaInput(
                name="Text Area Input", placeholder="Enter a string here...")
        elif self.component is pnw.TextInput:
            component = pnw.TextInput(name="Text Input",
                                      placeholder="Enter a string here...")
        elif self.component == pnw.Toggle:
            component = pnw.Toggle(name="Toggle", button_type="success")
        elif self.component == pnw.VideoStream:
            component = pnw.VideoStream(name="Video Stream",
                                        sizing_mode="stretch_width",
                                        height=300)
        if not component:
            component = self.component(name="Hello")
        if not controls:
            controls = component.controls()
        controls.margin = 0
        self._component_panel[:] = [
            pn.pane.Markdown("## " + component.__class__.name + " " +
                             self.component_type),
            component,
            pn.layout.Divider(),
            pn.pane.Markdown("## Parameters"),
            controls,
        ]
Exemplo n.º 29
0
import panel as pn
from panel.interact import interact, interactive, fixed, interact_manual
from panel import widgets

shift = widgets.FloatSlider(start=0.,
                            end=5,
                            step=0.1,
                            value=0.1,
                            name="Shift weight")
nums = widgets.FloatSlider(start=0.,
                           end=5,
                           step=0.1,
                           value=0.3,
                           name="Values weight")
resample = widgets.LiteralInput(value=None, name="Resample")
resample = widgets.Select(options={"Day": "D", "Week": "W", "Month": "M"})
columns = widgets.MultiSelect(options=df.columns.values.tolist(),
                              value=df.columns.values.tolist(),
                              name="Series")
columns.height = 300
columns.width = 200

dates = widgets.DateRangeSlider(start=df.index[0],
                                end=df.index[-1],
                                name="Date range",
                                value=(df.index[0], df.index[-1]))
widget, plot = interact(metaplot,
                        shift_weight=shift,
                        numvals_weight=nums,
                        dates=dates,
                        columns=columns,
Exemplo n.º 30
0
ppp = pn.pane.HoloViews()


def b(event):

    ppp.object = rand_df()


rb.on_click(b)

w_tab = pn.Column(rb, ppp, css_classes=['panel-widget-box'], margin=0)

#Histogram and descriptive statistics

variable = pnw.Select(name='Select',
                      options=['rating', 'desc_length', 'price', 'vintage'],
                      width=75)
limits = pnw.RangeSlider(name='Limits',
                         start=80,
                         end=100,
                         value=(80, 100),
                         step=1,
                         orientation='horizontal')
bins = pnw.IntSlider(name='bins',
                     value=20,
                     start=10,
                     end=100,
                     orientation='vertical',
                     width=50)