示例#1
0
def interactive_logistic_regression(X,
                                    y,
                                    target_names=None,
                                    feature_names=None,
                                    stacked: bool = False):
    from panel import widgets
    import panel as pn

    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y,
                                                        stratify=y,
                                                        random_state=42)
    embedding = umap.UMAP(n_components=2, random_state=160290).fit_transform(
        np.concatenate([X_train, X_test]))

    def interactive_model(C, penalty, fit_intercept, intercept_scaling,
                          l1_ratio, class_weight):
        model = LogisticRegression(
            C=C,
            penalty=penalty,
            solver="saga",
            fit_intercept=fit_intercept,
            intercept_scaling=intercept_scaling,
            l1_ratio=l1_ratio,
            class_weight=class_weight,
            random_state=42,
        ).fit(X, y)
        return plot_model_evaluation(
            model,
            X_train,
            y_train,
            X_test,
            y_test,
            target_names=target_names,
            feature_names=feature_names,
            stacked=stacked,
            embedding=embedding,
        )

    c_slider = widgets.LiteralInput(value=1, name="C")
    penalty_tog = widgets.RadioButtonGroup(
        name="penalty", options=["none", "l1", "l2", "elasticnet"])
    fit_intercept = widgets.Toggle(name="fit_intercept")
    intercept_scaling = widgets.LiteralInput(value=1, name="intercept_scaling")
    l1_ratio = widgets.FloatSlider(end=1.0,
                                   start=0.0,
                                   value=0.5,
                                   name="l1_ratio")
    class_weight = widgets.LiteralInput(value=None, name="class_weight")
    return pn.interact(
        interactive_model,
        C=c_slider,
        penalty=penalty_tog,
        fit_intercept=fit_intercept,
        intercept_scaling=intercept_scaling,
        l1_ratio=l1_ratio,
        class_weight=class_weight,
    )
示例#2
0
                          numvals_weight=numvals_weight)
    return heatmap_plus_series(seriated, resample=resample)


# In[6]:

from functools import partial
import hvplot.pandas
import param
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
示例#3
0
文件: pyechem.py 项目: mmguar/echem
    def baseline(self):
        self.peak_currents = np.zeros(len(self.dfs))

        #eak_left = -0.34
        #eak_right = -0.28
        #eft_limit = 30

        steppp = self.dfs[0]["Potential"][0] - self.dfs[0]["Potential"][1]

        first_point = self.dfs[0]["Potential"].iloc[0]
        last_point = self.dfs[0]["Potential"].iloc[-1]

        peak_left_slider = pnw.FloatSlider(name='Peak Left',
                                           value=-0.35,
                                           start=last_point,
                                           end=first_point,
                                           step=0.01)
        peak_right_slider = pnw.FloatSlider(name='Peak Right',
                                            value=-0.25,
                                            start=last_point,
                                            end=first_point,
                                            step=0.01)
        limit_left_slider = pnw.IntSlider(name='Limit Left',
                                          value=10,
                                          start=0,
                                          end=len(self.dfs[0]["Potential"]) -
                                          int(0.1 / steppp))
        limit_right_slider = pnw.IntSlider(name='Limit Right',
                                           value=10,
                                           start=0,
                                           end=len(self.dfs[0]["Potential"]) -
                                           int(0.1 / steppp))
        time_step_slider = pnw.IntSlider(name='Time Step',
                                         value=0,
                                         start=0,
                                         end=len(self.dfs) - 1)

        @pn.depends(time_step_slider, peak_left_slider, peak_right_slider,
                    limit_left_slider, limit_right_slider)
        def max_current(time_stamp=time_step_slider.param.value,
                        a=peak_left_slider,
                        b=peak_right_slider,
                        c=limit_left_slider,
                        d=limit_right_slider):
            return pn.pane.Markdown(
                "peak current [A]: " +
                str("{:.3e}".format(self.peak_currents[0])))

        def update_sliders(time_stamp):

            peak_left_slider.start = float(
                decimal.Decimal(limit_left_slider.value * steppp +
                                self.dfs[time_stamp]["Potential"].iloc[-1] +
                                steppp).quantize(decimal.Decimal('.01'),
                                                 rounding=decimal.ROUND_UP))
            #print(limit_left_slider.value*steppp+dfs[time_stamp]["Potential"].iloc[-1])
            #print(float(decimal.Decimal(limit_left_slider.value*steppp+dfs[time_stamp]["Potential"].iloc[-1]+steppp).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)))
            #print(dfs[time_stamp]["Potential"].iloc[-(limit_left_slider.value+1)])
            peak_left_slider.end = peak_right_slider.value
            if (peak_left_slider.value > peak_left_slider.end):
                peak_left_slider.value = peak_left_slider.end
            if (peak_left_slider.value < peak_left_slider.start):
                peak_left_slider.value = peak_left_slider.start
            peak_right_slider.end = round(
                +self.dfs[time_stamp]["Potential"].iloc[0] -
                limit_right_slider.value * steppp, 2)
            if (peak_right_slider.value > peak_right_slider.end):
                peak_right_slider.value = peak_right_slider.end
            if (peak_right_slider.value < peak_right_slider.start):
                peak_right_slider.value = peak_right_slider.start
            max_current.value = self.peak_currents[time_stamp]

        def interact_frame(time_stamp=0,
                           peak_left=peak_left_slider.value,
                           peak_right=peak_right_slider.value,
                           left_limit=limit_left_slider.value,
                           right_limit=limit_right_slider.value):

            peak_removed = [None] * len(self.dfs)
            removed = [None] * len(self.dfs)
            fit = [None] * len(self.dfs)
            baseline = [None] * len(self.dfs)

            for i, meas in enumerate(self.dfs):

                peak_removed[i] = self.dfs[i].loc[((self.dfs[i].Potential <= peak_left)) | (self.dfs[i].Potential >= peak_right ),\
                                            ['Potential', 'Diff']]
                removed[i] = pd.concat([
                    self.dfs[i].iloc[0:right_limit],
                    self.dfs[i].iloc[-left_limit:]
                ])  #['Potential', 'Diff'])
                baseline[i] = pd.concat([
                    peak_removed[i].iloc[right_limit:-left_limit],
                    peak_removed[i].iloc[right_limit:-left_limit]
                ])
                fit[i] = np.polynomial.polynomial.polyfit(
                    peak_removed[i]['Potential'][right_limit:-left_limit],
                    peak_removed[i]['Diff'][right_limit:-left_limit], 1)
                for j in self.dfs[i].index:

                    self.dfs[i].at[j,
                                   'Fit'] = np.polynomial.polynomial.polyval(
                                       self.dfs[i].loc[j]['Potential'], fit[i])
                    if (self.dfs[i].at[j, 'Potential'] > peak_left) and (
                            self.dfs[i].at[j, 'Potential'] < peak_right):
                        self.dfs[i].at[
                            j, 'Peak'] = abs(self.dfs[i].loc[j]['Diff'] -
                                             self.dfs[i].loc[j]['Fit'])
                self.peak_currents[i] = self.dfs[i]['Peak'].max()

            plot_title = 'Time' + str(self.time_stamps[time_stamp])

            measurement_list = [
                hv.Points(data=self.dfs[time_stamp],
                          kdims=[('Potential', 'Potential [V]'),
                                 ('Diff', 'Current [A]')],
                          vdims=[])
            ]

            fit_list = [
                hv.Points(data=self.dfs[time_stamp],
                          kdims=[('Potential', 'Potential [V]'),
                                 ('Fit', 'Current [A]')],
                          vdims=[])
            ]

            fit_list2 = [
                hv.Points(data=peak_removed[time_stamp],
                          kdims=[('Potential', 'Potential [V]'),
                                 ('Diff', 'Current [A]')],
                          vdims=[]).opts(color="r")
            ]

            fit_list3 = [
                hv.Points(data=removed[time_stamp],
                          kdims=[('Potential', 'Potential [V]'),
                                 ('Diff', 'Current [A]')],
                          vdims=[]).opts(color="y")
            ]

            fit_list4 = [
                hv.Points(data=baseline[time_stamp],
                          kdims=[('Potential', 'Potential [V]'),
                                 ('Diff', 'Current [A]')],
                          vdims=[]).opts(color="purple")
            ]

            overlay = hv.Overlay(measurement_list + fit_list + fit_list2 +
                                 fit_list3 + fit_list4)
            overlay = overlay.redim.label(x='Potential [V]', y='Current [A]')
            update_sliders(time_stamp)
            return overlay

        reactive_baseline = pn.bind(interact_frame, time_step_slider,
                                    peak_left_slider, peak_right_slider,
                                    limit_left_slider, limit_right_slider)

        widgets = pn.Column("<br>\n## Baseline set:", peak_left_slider,
                            peak_right_slider, limit_left_slider,
                            limit_right_slider, max_current)
        occupancy = pn.Row(reactive_baseline, widgets)
        time_column = pn.Column("<br>\n## Time stamp:", time_step_slider)
        pn_overlay = pn.Column(time_column, occupancy)
        interact_frame()
        return pn_overlay
示例#4
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,
        ]
示例#5
0
def predictions_dashboard(path):
    """Dashboard for viewing results from epitopepredict runs."""

    #folder_input = pn.widgets.TextInput(name='path', value='../zaire_test', width=400,width_policy='fit')
    #reload_btn = pn.widgets.Button(name='reload',width=100,button_type='primary')

    names = web.get_file_lists(path)
    if names is None:
        return
    preds = web.get_predictors(path, name=names[0])
    print(preds)
    seqname = pnw.Select(name='name', value=names[0], options=names)
    cutoff_slider = pnw.FloatSlider(name='cutoff',
                                    value=.95,
                                    start=.75,
                                    end=.99,
                                    step=0.01)
    cutoff_method = pnw.Select(name='cutoff method',
                               value='default',
                               options=['default', 'rank'])
    n_select = pnw.FloatSlider(name='n', value=1, start=1, end=8, step=1)
    plot_select = pnw.Select(name='plot view',
                             value='tracks',
                             options=['tracks', 'sequence'])
    table_select = pnw.Select(name='table view',
                              value='promiscuous',
                              options=['promiscuous', 'binders'])
    colorseq_box = pnw.Checkbox(name='color sequences', value=False)

    header = pn.pane.Markdown('__total sequences: %s__' % len(names),
                              css_classes=['main'])
    tables = pn.Tabs(width=900)
    plot = pn.pane.Bokeh(width=800)
    debug = pn.pane.Markdown('test',
                             style={
                                 'font-size': '10pt',
                                 'background-color': 'yellow'
                             })
    summary_plot = pn.pane.Bokeh()
    summary_table_tabs = pn.Tabs()
    recalc_button = pnw.Button(name='recalculate', width=200)

    def update_banner():
        """Update the banner"""

        fullpath = os.path.abspath(path)
        banner = pn.Row(
            pn.pane.Markdown(
                '<h4>epitopepredict: %s</h4> [help](%s) version %s' %
                (fullpath, helppage, __version__),
                css_classes=['divheader'],
                sizing_mode='stretch_width'))
        return banner

    def update_header(target, event):
        names = web.get_file_lists(event.new)
        target.object = "_total sequences: %s_" % str(len(names))
        return

    def callback_getpath(event):
        path = os.path.getcwd()
        folder.value = path

    def update_plot(preds, name, cutoff, n, kind):
        """Plot data view"""

        if kind == 'tracks':
            p = plotting.bokeh_plot_tracks(preds,
                                           name=name,
                                           cutoff=cutoff,
                                           n=n,
                                           width=1000,
                                           title=name)
            plot.object = p
        elif kind == 'sequence':
            p = plotting.bokeh_plot_sequence(preds,
                                             name=name,
                                             cutoff=cutoff,
                                             n=n,
                                             width=1000,
                                             title=name,
                                             color_sequence=colorseq_box.value)
            plot.object = p
        return p

    def update_tables(preds, name, n):
        """Tabular views of results"""

        P = preds[0]
        view = table_select.value
        tables.clear()
        for P in preds:
            if view == 'promiscuous':
                df = P.promiscuous_binders(n=n, name=name)
            else:
                df = P.get_binders(name=name)
            res = df.to_html(classes="tinytable sortable")
            div = '<div class="scrollingArea">%s</div>' % res
            tables.append((P.name, div))
            #tables.append((P.name,pn.pane.HTML('<p>hddsadsadsasda</p>',width=700)))
        return

    def update(event):
        """Update all elements"""

        name = seqname.value
        n = n_select.value
        cutoff = cutoff_slider.value
        kind = plot_select.value
        debug.object = name
        preds = web.get_predictors(path, name=name)
        update_plot(preds, name=name, cutoff=cutoff, n=n, kind=kind)
        update_tables(preds, name, n)
        return

    def update_summary(path):
        """Summary info for folder"""

        data = web.get_summary_tables(path)
        df = pd.concat(data, sort=True).reset_index()
        #plot = plotting.bokeh_summary_plot(df)
        #summary_plot.object = plot
        summary_table_tabs.clear()
        a = web.aggregate_summary(data)
        div = web.get_scrollable_table(a)
        summary_table_tabs.append(('all', div))
        names = list(data.keys())
        for n in names:
            df = data[n]
            res = df.to_html(classes="tinytable sortable")
            div = '<div class="scrollingArea">%s</div>' % res
            summary_table_tabs.append((n, div))
        return

    @pn.depends(seqname.param.value, n_select.param.value)
    def download_link(name, n):
        if preds is None:
            return
        df = preds[0].promiscuous_binders(n=n, name=name)
        df.to_csv()
        return pn.Pane(HTML('<a>download</a>'), width=700)

    info = pn.pane.Markdown(web.get_readme())
    banner = update_banner()
    update_summary(path)
    #reload_btn.param.watch(load_predictors, 'clicks')
    #reload_btn.param.trigger()
    seqname.param.watch(update, 'value')
    cutoff_slider.param.watch(update, 'value')
    n_select.param.watch(update, 'value')
    table_select.param.watch(update, 'value')
    plot_select.param.watch(update, 'value')
    seqname.param.trigger('options', 'value')

    top = pn.Row(header)  #,download_link)
    left = pn.Column(plot, tables, margin=10, sizing_mode='stretch_width')
    right = pn.Column(seqname,
                      cutoff_slider,
                      cutoff_method,
                      n_select,
                      plot_select,
                      table_select,
                      colorseq_box,
                      css_classes=['widget-box'],
                      width=200)
    center = pn.Row(left, right)
    #bottom = pn.Row(table)
    main = pn.Column(top, center)
    summarypane = pn.Column(recalc_button, (pn.Row(summary_table_tabs)))
    tabs = pn.Tabs(('summary', summarypane), ('sequence', main),
                   ('about', info))
    #tabs.append()
    app = pn.Column(banner, tabs, sizing_mode='stretch_width')
    return app