Ejemplo n.º 1
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)
Ejemplo n.º 2
0
def test_app():
    """Test dashboard"""
    
    def refresh(event):
        plot1.object = plotters.test1(cols=col_sl.value,rows=row_sl.value, plot_width=600)
        plot2.object = plotters.test2(rows=row_sl.value, plot_width=600)
        return
    from . import __version__
    title = pn.pane.Markdown('# pybioviz v%s test plots' %__version__)
    plot1 = pn.pane.Bokeh()   
    plot2 = pn.pane.Bokeh()
    col_sl = pnw.IntSlider(name='cols',value=30,start=5,end=200,step=1)
    col_sl.param.watch(refresh, 'value')
    row_sl = pnw.IntSlider(name='rows',value=10,start=5,end=100,step=1)
    row_sl.param.watch(refresh, 'value')
    col_sl.param.trigger('value')    
    app = pn.Column(title,col_sl,row_sl,plot1,plot2)
    return app
Ejemplo 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
Ejemplo n.º 4
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',
Ejemplo n.º 5
0
import panel.widgets as pnw
from matplotlib.backends.backend_agg import FigureCanvas
from matplotlib.figure import Figure

DATA_URL = (
    "https://raw.githubusercontent.com/LuisM78/Occupancy-detection-data/master/datatraining.txt"
)

data = pd.read_csv(DATA_URL)
data["date"] = data.date.astype("datetime64[ns]")
data = data.set_index("date")

variable = pnw.RadioButtonGroup(name="variable",
                                value="Temperature",
                                options=list(data.columns))
window = pnw.IntSlider(name="window", value=10, start=1, end=60)


def mpl_plot(avg, highlight):
    fig = Figure()
    FigureCanvas(fig)  # not needed in mpl >= 3.1
    ax = fig.add_subplot()
    avg.plot(ax=ax)
    if len(highlight):
        highlight.plot(style="o", ax=ax)
    return fig


def find_outliers(variable="Temperature",
                  window=30,
                  sigma=10,
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]
    df = df.sort_values('Date')
    df['MA'] = df[value].rolling(window=window).mean()
    df = df.loc[(df['Date'] >= date_range[0]) & (df['Date'] <= date_range[1])]
Ejemplo n.º 7
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
Ejemplo n.º 8
0
                  window=30,
                  sigma=10,
                  view_fn=mpl_plot):
    avg = data[variable].rolling(window=window).mean()
    residual = data[variable] - avg
    std = residual.rolling(window=window).std()
    outliers = (np.abs(residual) > std * sigma)
    return view_fn(avg, avg[outliers])


pn.extension()
pn.interact(find_outliers)

text = "<br>\n# Room Occupancy\nSelect the variable, and the time window for smoothing"

kw = dict(window=(1, 60), variable=sorted(list(data.columns)), sigma=(1, 20))
i = pn.interact(find_outliers, **kw)

p = pn.Row(i[1][0], pn.Column(text, i[0][0], i[0][1]))

variable = pnw.RadioButtonGroup(name='variable',
                                value='Temperature',
                                options=list(data.columns))
window = pnw.IntSlider(name='window', value=10, start=1, end=60)

reactive_outliers = pn.bind(find_outliers, variable, window, 10)

widgets = pn.Column("<br>\n# Room occupancy", variable, window)
occupancy = pn.Row(reactive_outliers, widgets)
occupancy.servable()
Ejemplo n.º 9
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
Ejemplo n.º 10
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,
        ]
Ejemplo n.º 11
0
import hvplot.pandas
import pandas as pd
import panel as pn
import panel.widgets as pnw

pn.extension()
from bokeh.sampledata.autompg import autompg

autompgi = autompg.interactive()

year = pnw.IntSlider(start=70, end=82, value=70, name="Year")

out = (
    autompgi[autompgi["yr"] == year]
    .groupby("origin")
    .mean()
    .hvplot("origin", "mpg", kind="bar", ylim=(0, 50))
)

pn.pane.HoloViews(out).servable()
Ejemplo n.º 12
0
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)


def cb(event):
    if event.new == 'price':
        limits.value = (int(wine['price'].min()), int(wine['price'].max()))
        limits.start = int(wine['price'].min())
        limits.end = int(wine['price'].max())
        limits.step = 50

    elif event.new == 'rating':
        limits.value = (int(wine['rating'].min()), int(wine['rating'].max()))
        limits.start = int(wine['rating'].min())
        limits.end = int(wine['rating'].max())
Ejemplo n.º 13
0
pn.extension()

def f(x):
    return x

interact(f, x=10)
interact(f, x=True)
interact(f, x='Hello there!')

@interact(x=True, y=1.0)
def g(x, y):
    return (x, y)
g

layout = interact(f, x=10)

pn.Column('**A custom interact layout**', pn.Row(layout[0], layout[1]))

def h(p, q):
    return (p, q)

interact(h, p=5, q=fixed(20))

interact(f, x=widgets.IntSlider(start=-10,end=30,step=1,value=10))






Ejemplo n.º 14
0
    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