Esempio n. 1
0
def plotnorm(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
             tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
    """ Make a light-weight norm figure """

    fields = ['zs', 'sizes', 'colors', 'abssnr', 'key', 'snrs']

    if not circleinds: circleinds = range(len(data['snrs']))

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    norm = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='SNR observed',
                  y_axis_label='SNR expected', tools=tools, webgl=True)
    norm.circle('abssnr', 'zs', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        norm.cross('abssnr', 'zs', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        norm.circle('abssnr', 'zs', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = norm.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = norm.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return norm
Esempio n. 2
0
def performance():
    plot = Figure(x_axis_type="datetime", tools="save", toolbar_location=None, plot_width=1000, plot_height=300)
    l1 = plot.line(x="time", y="power_out", source=source_perfomance, line_color="green", name="local")
    plot.add_tools(HoverTool(renderers=[l1]))
    plot.select(dict(type=HoverTool)).tooltips = [("Date", "@hover_time"), ("Performance", "@power_out")]
    l2 = plot.line(x="time", y="avg_perf", source=source_perfomance, line_color="red", name="global")
    plot.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.title = "Plant Performance"
    return plot
Esempio n. 3
0
def plotdmt(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
            tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=950, plot_height=500):
    """ Make a light-weight dm-time figure """

    fields = ['dm', 'time', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    dm = [data['dm'][i] for i in inds]
    dm_min = min(min(dm), max(dm)/1.2)
    dm_max = max(max(dm), min(dm)*1.2)
    time = [data['time'][i] for i in inds]
    time_min = min(time)
    time_max = max(time)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    dmt = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='Time (s; relative)',
                 y_axis_label='DM (pc/cm3)', x_range=(time_min, time_max), y_range=(dm_min, dm_max), 
                 webgl=True, tools=tools)
    dmt.circle('time', 'dm', size='sizes', fill_color='colors', line_color=None, fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        dmt.cross('time', 'dm', size='sizes', fill_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        dmt.circle('time', 'dm', size='sizes', line_color='colors', fill_color='colors', line_alpha=0.5, fill_alpha=0.2, source=sourceedge)
    hover = dmt.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
#        url = '{}/cands_{}_sc@scan-seg@seg-i@candint-dm@[email protected]'.format(url_path, fileroot)
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = dmt.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return dmt
Esempio n. 4
0
def plotstat(data, circleinds=None, crossinds=None, edgeinds=None, url_path=None, fileroot=None, 
             tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
    """ Make a light-weight stat figure """

    fields = ['imkur', 'specstd', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    specstd = [data['specstd'][i] for i in inds]
    specstd_min = min(specstd)
    specstd_max = max(specstd)
    imkur = [data['imkur'][i] for i in inds]
    imkur_min = min(imkur)
    imkur_max = max(imkur)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    stat = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='Spectral std',
                  y_axis_label='Image kurtosis', x_range=(specstd_min, specstd_max), 
                  y_range=(imkur_min, imkur_max), tools=tools, webgl=True)
    stat.circle('specstd', 'imkur', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        stat.cross('specstd', 'imkur', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        stat.circle('specstd', 'imkur', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = stat.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = stat.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return stat
Esempio n. 5
0
def plotloc(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
            tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
    """ Make a light-weight loc figure """

    fields = ['l1', 'm1', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    l1 = [data['l1'][i] for i in inds]
    l1_min = min(l1)
    l1_max = max(l1)
    m1 = [data['m1'][i] for i in inds]
    m1_min = min(m1)
    m1_max = max(m1)

    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems() if key in fields}))
    loc = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="left", x_axis_label='l1 (rad)', y_axis_label='m1 (rad)',
                 x_range=(l1_min, l1_max), y_range=(m1_min,m1_max), tools=tools, webgl=True)
    loc.circle('l1', 'm1', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems() if key in fields}))
        loc.cross('l1', 'm1', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems() if key in fields}))
        loc.circle('l1', 'm1', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = loc.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = loc.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return loc
Esempio n. 6
0
 def makeplot():
     p = Figure(plot_width=800, plot_height=200,tools="hover,pan",title=None)
     p.scatter(x, y, radius=radii,
            fill_color=colors, fill_alpha=0.6,
            line_color='gray', source=source)
     hover = p.select(dict(type=HoverTool))
     hover.tooltips = OrderedDict([
         ("radius", "@radius")])
     p.xgrid.grid_line_color = None
     p.ygrid.grid_line_color = None
     return p
Esempio n. 7
0
def set_hover_tool_ctry(p: Figure):
    """Display a little sign when moving mouse over a point in the series"""
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = dict([
        # ("index", "$index"),
        # ("(xx,yy)", "(@x, @y)"),
        ("País", "@pais"),
        ("Fecha", "@date_str"),
        (f"Total activos", "@n_active_str"),
        (f"Total confirmados", "@n_or_est @est_label"),
        (f"Total recuperados", "@n_recovered_str"),
        (f"Total muertes", "@n_deaths_str"),
    ])
Esempio n. 8
0
def set_hover_tool(p: Figure, klass: str):
    """Display a little sign when moving mouse over a point in the series"""
    hover = p.select(dict(type=HoverTool))

    total_data = f"@n_{klass}"
    if klass == 'confirmed':
        total_data = "@n_or_est @est_label"

    hover.tooltips = dict([
        # ("index", "$index"),
        # ("(xx,yy)", "(@x, @y)"),
        ( "País", "@pais"),
        ("Fecha", "@date_str"),
        (f"Total {TRANSL[klass]}", total_data),
    ])
Esempio n. 9
0
def map():
    x_range = (-10000000, -11000000)
    y_range = (3500000, 5200000)

    plot = Figure(
        tools=TOOLS, title="Power Plant Locations", plot_width=1000, plot_height=500, x_range=x_range, y_range=y_range
    )
    plot.add_tile(STAMEN_TONER)
    plot.axis.visible = False
    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = None
    m1 = plot.circle(x="lat", y="lon", source=source_map_bwr, size="size", fill_alpha=0, line_width=2, color="red")
    m2 = plot.square(x="lat", y="lon", source=source_map_pwr, size="size", fill_alpha=0, line_width=2, color="red")
    plot.select(dict(type=HoverTool)).tooltips = [("Plant Name", "@name"), ("Reactor and Containment", "@type")]

    return plot
Esempio n. 10
0
def plotCorrelation(res):
    from bokeh.models import HoverTool,ColumnDataSource
    from bokeh.plotting import Figure
    width=600
    height=600
    plot = Figure(title='',title_text_font_size="11pt",
            plot_width=width, plot_height=height,
           x_axis_label='method1',y_axis_label='method2',
           tools="pan, wheel_zoom, resize, hover, reset, save",
           background_fill="#FAFAFA")

    x=res['perc_x']
    y=res['perc_y']
    source = ColumnDataSource(data=dict(x=x,y=y, protein=res.locus_tag))
    plot.circle(x,y, color='blue', line_color='gray',fill_alpha=0.5, size=10, source=source)
    hover = plot.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ("binders1", "@x"),
        ("binders2", "@y"),
        ("protein", "@protein"),
    ])
    js,html = embedPlot(plot)
    return html
Esempio n. 11
0
def plotdmt(data,
            circleinds=[],
            crossinds=[],
            edgeinds=[],
            url_path=None,
            fileroot=None,
            tools="hover,tap,pan,box_select,wheel_zoom,reset",
            plot_width=950,
            plot_height=500):
    """ Make a light-weight dm-time figure """

    fields = ['dm', 'time', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    dm = [data['dm'][i] for i in inds]
    dm_min = min(min(dm), max(dm) / 1.2)
    dm_max = max(max(dm), min(dm) * 1.2)
    time = [data['time'][i] for i in inds]
    time_min = min(time)
    time_max = max(time)

    source = ColumnDataSource(
        data=dict({(key,
                    tuple([value[i] for i in circleinds if i not in edgeinds]))
                   for (key, value) in data.iteritems() if key in fields}))
    dmt = Figure(plot_width=plot_width,
                 plot_height=plot_height,
                 toolbar_location="left",
                 x_axis_label='Time (s; relative)',
                 y_axis_label='DM (pc/cm3)',
                 x_range=(time_min, time_max),
                 y_range=(dm_min, dm_max),
                 output_backend='webgl',
                 tools=tools)
    dmt.circle('time',
               'dm',
               size='sizes',
               fill_color='colors',
               line_color=None,
               fill_alpha=0.2,
               source=source)

    if crossinds:
        sourceneg = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in crossinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        dmt.cross('time',
                  'dm',
                  size='sizes',
                  fill_color='colors',
                  line_alpha=0.3,
                  source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in edgeinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        dmt.circle('time',
                   'dm',
                   size='sizes',
                   line_color='colors',
                   fill_color='colors',
                   line_alpha=0.5,
                   fill_alpha=0.2,
                   source=sourceedge)
    hover = dmt.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        #        url = '{}/cands_{}_sc@scan-seg@seg-i@candint-dm@[email protected]'.format(url_path, fileroot)
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = dmt.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return dmt
Esempio n. 12
0
                <span style="font-size: 17px; font-weight: bold; color: #696">@stype</span>
                <span style="font-size: 15px; font-weight: bold; color: #696">type</span>
            </div>
            <div>
                <span style="font-size: 15px; font-weight: bold; color: #696">D = </span>
                <span style="font-size: 15px; font-weight: bold; color: #696;">@r</span>
                <span style="font-size: 15px; font-weight: bold; color: #696;"> pc</span>
            </div>
            <div>
                <span style="font-size: 15px; font-weight: bold; color: #696">C = </span>
                <span style="font-size: 15px; font-weight: bold; color: #696;">@complete</span>
            </div>
        </div>
        """)
plot1.add_tools(hover)
hover = plot1.select(dict(type=HoverTool))
plot1.x_range = Range1d(-50, 50, bounds=(-50, 50))
plot1.y_range = Range1d(-50, 50, bounds=(-50, 50))
plot1.background_fill_color = "black"
plot1.background_fill_alpha = 1.0
plot1.yaxis.axis_label = 'Yield'
plot1.xaxis.axis_label = ' '
plot1.xaxis.axis_line_width = 0
plot1.yaxis.axis_line_width = 0
plot1.xaxis.axis_line_color = 'black'
plot1.yaxis.axis_line_color = 'black'
plot1.border_fill_color = "black"
plot1.min_border_left = 80

# main glyphs for planet circles
star_syms = plot1.circle('x', 'y', source=star_points, name="star_points_to_hover", \
Esempio n. 13
0
def plotTracks(preds,tag,n=3,title=None,width=820,height=None,
                seqdepot=None,bcell=None,exp=None):
    """Plot epitopes as parallel tracks"""

    from bokeh.models import Range1d,HoverTool,FactorRange,Grid,GridPlot,ColumnDataSource
    from bokeh.plotting import Figure

    alls=1
    if title == None:
        title=tag
    for m in preds:
        alls += len(preds[m].data.groupby('allele'))
    if height==None:
        height = 130+10*alls
    yrange = Range1d(start=0, end=alls+3)
    plot = Figure(title=title,title_text_font_size="11pt",plot_width=width,
                  plot_height=height, y_range=yrange,
                y_axis_label='allele',
                tools="xpan, xwheel_zoom, resize, hover, reset, save",
                background_fill="#FAFAFA",
                toolbar_location="below")
    h=3
    if bcell != None:
        plotBCell(plot, bcell, alls)
    if seqdepot != None:
        plotAnnotations(plot,seqdepot)
    if exp is not None:
        plotExp(plot, exp)

    #plotRegions(plot)

    #lists for hover data
    #we plot all rects at once
    x=[];y=[];allele=[];widths=[];clrs=[];peptide=[]
    predictor=[];position=[];score=[];leg=[]
    l=80
    for m in preds:
        pred = preds[m]
        cmap = mpl.cm.get_cmap(colormaps[m])
        df = pred.data
        sckey = pred.scorekey
        pb = pred.getPromiscuousBinders(data=df,n=n)
        if len(pb) == 0:
            continue
        l = pred.getLength()
        grps = df.groupby('allele')
        alleles = grps.groups.keys()
        if len(pb)==0:
            continue
        c=colors[m]
        leg.append(m)

        for a,g in grps:
            b = pred.getBinders(data=g)
            b = b[b.pos.isin(pb.pos)] #only promiscuous
            b.sort('pos',inplace=True)
            scores = b[sckey].values
            score.extend(scores)
            pos = b['pos'].values
            position.extend(pos)
            x.extend(pos+(l/2.0)) #offset as coords are rect centers
            widths.extend([l for i in scores])
            clrs.extend([c for i in scores])
            y.extend([h+0.5 for i in scores])
            alls = [a for i in scores]
            allele.extend(alls)
            peptide.extend(list(b.peptide.values))
            predictor.extend([m for i in scores])
            h+=1

    source = ColumnDataSource(data=dict(x=x,y=y,allele=allele,peptide=peptide,
                                    predictor=predictor,position=position,score=score))
    plot.rect(x,y, width=widths, height=0.8,
         #x_range=Range1d(start=1, end=seqlen+l),
         color=clrs,line_color='gray',alpha=0.7,source=source)

    hover = plot.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ("allele", "@allele"),
        ("position", "@position"),
        ("peptide", "@peptide"),
        ("score", "@score"),
        ("predictor", "@predictor"),
    ])

    seqlen = pred.data.pos.max()+l
    plot.set(x_range=Range1d(start=0, end=seqlen+1))
    plot.xaxis.major_label_text_font_size = "8pt"
    plot.xaxis.major_label_text_font_style = "bold"
    plot.ygrid.grid_line_color = None
    plot.yaxis.major_label_text_font_size = '0pt'
    plot.xaxis.major_label_orientation = np.pi/4

    #js,html = embedPlot(plot)
    script, div = embedPlot(plot)
    return script, div
Esempio n. 14
0
from bokeh.plotting import Figure
from bokeh.models import BoxSelectTool, ColumnDataSource, HBox
from bokeh.io import curdoc
import numpy

#x0,y0=numpy.meshgrid(1,1,indexing='xy')
#circleSource=ColumnDataSource(data={'x':[numpy.ravel(x0)*10.0],'y':[numpy.ravel(y0)*10.0]})

x0=numpy.random.rand(10)
y0=numpy.random.rand(10)
circleSource=ColumnDataSource(data=dict(x=x0*10.0,y=y0*10.0))

p=Figure(x_range=[-10,10], y_range=[0,10], plot_width=400, plot_height=400,tools="crosshair, box_select, wheel_zoom")
#p.circle('x','y',source=circleSource,size=10,color="navy")
p.scatter(x0,y0,size=10,color="navy")
p.select(BoxSelectTool).select_every_mousemove = False


p2=Figure(x_range=[-10,10], y_range=[0,10], plot_width=400, plot_height=400,tools="crosshair, box_select, wheel_zoom")
p2.scatter('x','y',source=circleSource,size=10,color="navy",name="scatter")
p2.select(BoxSelectTool).select_every_mousemove = False
renderer = p2.select(dict(name="scatter"))
scatter_ds = renderer[0].data_source

figs=HBox(children=[p,p2])
curdoc().add_root(HBox(children=[figs],width=800))

def updateSelection(attrname, old, new):
    inds=numpy.array(new['1d']['indices'])
    #print(inds)
    numpy.savetxt('selInds.txt',inds,fmt='%d')
Esempio n. 15
0
class BokehPlot(object):
    def __init__(self, device, points_list, *, title = 'My title', show_notes = True, update_data = True):
        self.device = device
        self.points_list = points_list
        self.title = title
        self.units = {}
        self.show_notes = show_notes

        self.lst = self.points_list

        self.multi_states = self.device.multi_states
        self.binary_states = self.device.binary_states
        self.analog_units = self.device.analog_units

        plot = self.build_plot()

        self.device.properties.network.bokeh_document.add_plot(plot)
        if update_data:
            self.device.properties.network.bokeh_document.add_periodic_callback(self.update_data, 100)   
        print('Chart created, please reload your web page to see changes')
        
     # Get data
    def read_lst(self):
        df = self.device[self.lst]
        try:
            df = df.fillna(method='ffill').fillna(method='bfill').replace(['inactive', 'active'], [0, 1])
        except TypeError:
            df = df.fillna(method='ffill').fillna(method='bfill')
                                      
        df = df.reset_index()
        df['name'] = 'nameToReplace'
        df['units'] = 'waiting for refresh'
        df['time_s'] = df['index'].apply(str)
        return df

    def read_notes(self):
        notes_df = self.device.notes.reset_index()
        notes_df['value'] = -5
        notes_df['desc'] = 'Notes'
        notes_df['time_s'] = notes_df['index'].apply(str)
        return notes_df

    def build_plot(self):        
        df = self.read_lst()
        notes_df = self.read_notes()

        TOOLS = "hover,resize,save,pan,box_zoom,wheel_zoom,reset"
        #plot_width=800, plot_height=600,
        self.p = Figure(x_axis_type="datetime", title = self.title, tools = TOOLS)

        if self.show_notes:
            self.notes_source = ColumnDataSource(
                    data=dict(
                        x = notes_df['index'],
                        y = notes_df['value'],
                        time = notes_df['time_s'],
                        desc = notes_df['desc'],
                        units = notes_df[0]
                    )
                )

            self.p.asterisk('x', 
                            'y',
                            source = self.notes_source,
                            name = 'Notes',
                            color = "#%06x" % random.randint(0x000000, 0x777777), 
                            legend='Notes',
                            size = 40) 

        self.p.legend.location = 'top_left'
        self.p.extra_y_ranges = {"bool": Range1d(start=0, end=1.1),
                                 "enum": Range1d(start=0, end=10)}
        self.p.add_layout(LinearAxis(y_range_name="bool"), 'left')
        self.p.add_layout(LinearAxis(y_range_name="enum"), 'right')
                            
        hover = self.p.select(dict(type=HoverTool))
        hover.tooltips = OrderedDict([
            ('name', '@desc'),
            ('value', '@y'),
            ('units', '@units'),
            ('time', '@time'),
        ])

        self.sources = {}               
        for each in self.lst:
            
            try:
                df['name'] = df['name'].replace('nameToReplace', ('%s / %s' % (each, self.device[each]['description'])))            
            except TypeError:
                continue
            self.sources[each] = ColumnDataSource(
                            data=dict(
                            x = df['index'],
                            y = df[each],
                            time = df['time_s'],
                            name = df['name'],
                            units = df['units']
                        )
                    )

            if each in self.binary_states:
                self.p.circle('x', 
                            'y',
                            source = self.sources[each],
                            name = each,
                            color = "#%06x" % random.randint(0x000000, 0x777777),
                            legend=each,
                            y_range_name="bool",
                            size = 10)
            elif each in self.multi_states:
                self.p.diamond('x', 
                            'y',
                            source = self.sources[each],
                            name = each,
                            color = "#%06x" % random.randint(0x000000, 0x777777), 
                            legend=each,
                            y_range_name="enum",
                            size = 20)            
            else:
                self.p.line('x',
                            'y',
                            source = self.sources[each],
                            name = each,
                            color = "#%06x" % random.randint(0x000000, 0x777777),
                            legend=each,
                            line_width = 2)
            
        return self.p
    
    def update_data(self):
        if self.device.properties.network._started:           
            df = self.read_lst()
            for renderer in self.p.renderers:
                name = renderer.name
                if name in self.points_list:
                    glyph_renderer = renderer
                    df['name'] = ('%s / %s' % (name, self.device[name]['description']))
                    glyph_renderer.data_source.data['x'] = df['index']
                    glyph_renderer.data_source.data['y'] = df[name]
                    glyph_renderer.data_source.data['desc'] = df['name']
                    glyph_renderer.data_source.data['time'] = df['time_s']
                    if name in self.multi_states:
                        glyph_renderer.data_source.data['units'] = [self.multi_states[name][int(math.fabs(x-1))] for x in df[name]]
                    elif name in self.binary_states:
                        glyph_renderer.data_source.data['y'] = df[name]
                        glyph_renderer.data_source.data['units'] = [self.binary_states[name][int(x/1)] for x in df[name]]
                    else:
                        df['units'] = self.analog_units[name]
                        glyph_renderer.data_source.data['units'] = df['units']
                elif name == 'Notes':
                    notes_df = self.read_notes()
                    glyph_renderer = renderer
                    glyph_renderer.data_source.data['x'] = notes_df['index']
                    glyph_renderer.data_source.data['y'] = notes_df['value']
                    glyph_renderer.data_source.data['desc'] = notes_df['desc']
                    glyph_renderer.data_source.data['units'] = notes_df[0]
                    glyph_renderer.data_source.data['time'] = notes_df['time_s']
Esempio n. 16
0
# marking the Hover point
p.circle('x1',
         'y1',
         source=source,
         name="data",
         radius=0.0186,
         hover_fill_color={
             'field': 'peakcount',
             'transform': mapper
         },
         fill_color=None,
         line_color=None,
         line_width=3,
         hover_line_color='red')

taptool = p.select(type=TapTool)
taptool.callback = OpenURL(url=url)

## px.circle('x1','y1', source = source_comp, radius = 0.015,
##         fill_color = 'lightgray', line_color='black', line_width=0.3)

# bokeh.pydata.org/en/latest/docs/reference/models/annotations.html
xcolor_bar = ColorBar(color_mapper=mapper,
                      label_standoff=-13,
                      major_label_text_font_style="bold",
                      padding=26,
                      major_label_text_align='right',
                      major_label_text_font_size="10pt",
                      location=(0, 0))

p.add_layout(xcolor_bar, 'left')
Esempio n. 17
0
fig = Figure(plot_height=700, plot_width=700, title="",
           tools=TOOLS, toolbar_location="above",
           x_range=new_x_factors[:top_n.value],  y_range=new_y_factors[:top_n.value])

fig.add_tools(hover)

update(None, None, None) # initial load of the data
rects = fig.rect(x="x", y="y", source=source, color="color", width=0.95, height=0.95, name="glyphs")
fig.xaxis.major_label_orientation = np.pi/4
fig.yaxis.major_label_orientation = np.pi/4
fig.xgrid.visible = False
fig.ygrid.visible = False

url = "https://www.wikidata.org/wiki/@wikidataID"
taptool = fig.select(type=TapTool)
taptool.callback = OpenURL(url=url)

renderer = fig.select(name="glyphs")[0]
renderer.selection_glyph = renderer.glyph
renderer.nonselection_glyph = renderer.glyph
renderer.hover_glyph = renderer.glyph

# table_columns = [TableColumn(field="x", title="X-axis facts"),
#                  TableColumn(field="y", title="Y-axis facts"),
#                  TableColumn(field="raw", title="Counts")]
# data_table = DataTable(source=source, columns=table_columns, width=400, height=600)


top_n.on_change('value', update)
dictionary_selector.on_change('value', update)
Esempio n. 18
0
from bokeh.plotting import Figure, show
from scipy import misc
from bokeh.io import curdoc
from bokeh.models import HBox, VBoxForm, VBox, ColumnDataSource, BoxSelectTool
import numpy
from bokeh.models.widgets import Slider

imageRaw = numpy.random.rand(256,256)
source = ColumnDataSource(data={'image': [imageRaw]})


p = Figure(x_range=[0, 10], y_range=[0, 10],plot_width=400,plot_height=400,
           tools="crosshair, box_select, pan, reset, resize, save, wheel_zoom")
p.image(image="image", x=[0], y=[0], dw=[10], dh=[10],source=source)
p.select(BoxSelectTool).select_every_mousemove=False
imageFFT = numpy.fft.fft2(imageRaw)
imageFFT=numpy.fft.fftshift(imageFFT)

x,y=numpy.meshgrid(range(imageFFT.shape[1]),range(imageFFT.shape[0]),indexing='xy')
x = x - imageFFT.shape[1]/2
y = y - imageFFT.shape[0]/2
r = numpy.sqrt(x*x+y*y) # units are pixels
theta = numpy.arctan2(x,y)
fband=[16,16]
SF = numpy.exp(-((r-fband[0])**2/(2.0*fband[1]*fband[1])))  
#SF=numpy.ones(r.shape)    
    
#ori=45*(numpy.pi/180.0)
#oband=[ori*0.95, ori*1.05]
oband=[numpy.pi/4.0, numpy.pi/8.0]
t1 = numpy.angle(numpy.exp(complex(0,1)*(theta-oband[0]))) # center it
Esempio n. 19
0
df_now = b_cohorts.copy()
source = ColumnDataSource(data=b_cohorts[b_cohorts['pname'] == 'product 1'])

p = Figure(
    plot_width=1000,
    plot_height=800,
    x_axis_location="below",
    y_axis_label='cohort',
    x_axis_label='months Since Initial Order',
    y_range=list(df_now.epoch.unique())[::-1],
    x_range=[0.5, 36.5],
    tools="pan,resize,box_zoom,hover,save,wheel_zoom,reset",
)

hover = p.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
    ('initial purchare', '@epoch'),
    ('months after IP', '@counts'),
    ('percentage', '@percents%'),
])

# customize plot
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "10pt"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi / 3

p.rect('counts',
Esempio n. 20
0
def plotall(data, circleinds=[], crossinds=[], edgeinds=[], htmlname=None, noiseplot=None, url_path='plots', fileroot=None):
    """ Create interactive plot (preserving links between panels) from data dictionary

    data has keys of snr, time, dm, sizes, key and more.
    Optional index arguments are used to filter full data set.
    This can be used to remove bad segments or apply different symbols to subsets.
    url_path is path difference to png files for taptool. ('../plots' for jupyter notebook, 'plots' for public page)
    fileroot is the sdm file name used as root for all png files.
    """

    # set up data dictionary
    if not circleinds: circleinds = calcinds(data, np.abs(data['snrs']).min())
    if not crossinds: crossinds = calcinds(data, -1*np.abs(data['snrs']).min())

    TOOLS = "hover,tap,pan,box_select,wheel_zoom,reset"

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    dm = [data['dm'][i] for i in inds]
    dm_min = min(min(dm), max(dm)/1.2)
    dm_max = max(max(dm), min(dm)*1.2)
    time = [data['time'][i] for i in inds]
    time_min = min(time)
    time_max = max(time)
    l1 = [data['l1'][i] for i in inds]
    l1_min = min(l1)
    l1_max = max(l1)
    m1 = [data['m1'][i] for i in inds]
    m1_min = min(m1)
    m1_max = max(m1)
    specstd = [data['specstd'][i] for i in inds]
    specstd_min = min(specstd)
    specstd_max = max(specstd)
    imkur = [data['imkur'][i] for i in inds]
    imkur_min = min(imkur)
    imkur_max = max(imkur)

    # create figures
    dmt = Figure(plot_width=950, plot_height=500, toolbar_location="left", x_axis_label='Time (s; relative)',
                 y_axis_label='DM (pc/cm3)', x_range=(time_min, time_max), y_range=(dm_min, dm_max), 
                 webgl=True, tools=TOOLS)
    loc = Figure(plot_width=450, plot_height=400, toolbar_location="left", x_axis_label='l1 (rad)', y_axis_label='m1 (rad)',
                 x_range=(l1_min, l1_max), y_range=(m1_min,m1_max), tools=TOOLS, webgl=True)
    stat = Figure(plot_width=450, plot_height=400, toolbar_location="left", x_axis_label='Spectral std',
                  y_axis_label='Image kurtosis', x_range=(specstd_min, specstd_max), 
                  y_range=(imkur_min, imkur_max), tools=TOOLS, webgl=True)
    norm = Figure(plot_width=450, plot_height=400, toolbar_location="left", x_axis_label='SNR observed',
                  y_axis_label='SNR expected', tools=TOOLS, webgl=True)

    # create positive symbol source and add glyphs
    source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) 
                                           for (key, value) in data.iteritems()}))
    dmt.circle('time', 'dm', size='sizes', fill_color='colors', line_color=None, fill_alpha=0.2, source=source)
    loc.circle('l1', 'm1', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)
    stat.circle('specstd', 'imkur', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)
    norm.circle('abssnr', 'zs', size='sizes', line_color=None, fill_color='colors', fill_alpha=0.2, source=source)

    # create negative symbol source and add glyphs
    if crossinds:
        sourceneg = ColumnDataSource(data = dict({(key, tuple([value[i] for i in crossinds]))
                                                  for (key, value) in data.iteritems()}))
        dmt.cross('time', 'dm', size='sizes', fill_color='colors', line_alpha=0.3, source=sourceneg)
        loc.cross('l1', 'm1', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)
        stat.cross('specstd', 'imkur', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)
        norm.cross('abssnr', 'zs', size='sizes', line_color='colors', line_alpha=0.3, source=sourceneg)

    # create linked symbol source and add glyphs
    if edgeinds:
        sourceedge = ColumnDataSource(data = dict({(key, tuple([value[i] for i in edgeinds]))
                                                   for (key, value) in data.iteritems()}))
        dmt.circle('time', 'dm', size='sizes', line_color='colors', fill_color='colors', line_alpha=0.5, fill_alpha=0.2, source=sourceedge)
        loc.circle('l1', 'm1', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)
        stat.circle('specstd', 'imkur', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)
        norm.circle('abssnr', 'zs', size='sizes', line_color='colors', fill_color='colors', source=sourceedge, line_alpha=0.5, fill_alpha=0.2)

    hover = dmt.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = loc.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = stat.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = norm.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = dmt.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = loc.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = stat.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = norm.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

# this approach does not preserve links between panels
#    dmt = plotdmt(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS) # maybe add size?
#    loc = plotloc(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)
#    stat = plotstat(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)
#    norm = plotnorm(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)

    # arrange figures
    top = HBox(dmt, width=950)
    middle = HBox(loc, stat, width=950)
    if noiseplot:
        bottom = HBox(norm, noiseplot, width=950)
    else:
        bottom = HBox(norm, width=950)
    combined = VBox(top, middle, bottom, width=950)

    if htmlname:
        output_file(htmlname)
        save(combined)
    else:
        return combined
Esempio n. 21
0
              'transform': xmapper
          },
          fill_color=None,
          line_color=None,
          line_width=3,
          hover_line_color='red')

px.circle('x1',
          'y1',
          source=source_comp,
          radius=0.015,
          fill_color='lightgray',
          line_color='black',
          line_width=0.3)

taptool = px.select(type=TapTool)
taptool.callback = OpenURL(url=url)

# bokeh.pydata.org/en/latest/docs/reference/models/annotations.html
xcolor_bar = ColorBar(color_mapper=xmapper,
                      label_standoff=-13,
                      major_label_text_font_style="bold",
                      padding=26,
                      major_label_text_align='right',
                      major_label_text_font_size="10pt",
                      location=(0, 0))

px.add_layout(xcolor_bar, 'left')

# ======
# WSIGMA
Esempio n. 22
0
# set up the main plot and do its tweaks
bullseye_plot = Figure(plot_height=800,
                       plot_width=800,
                       x_axis_type=None,
                       y_axis_type=None,
                       tools="pan,reset,save,tap,box_zoom,wheel_zoom",
                       outline_line_color='#1D1B4D',
                       x_range=[-50, 50],
                       y_range=[-50, 50],
                       toolbar_location='right')
hover = HoverTool(names=["star_points_to_hover"],
                  mode='mouse',
                  tooltips=get_tooltip.tooltip())
bullseye_plot.add_tools(hover)
hover = bullseye_plot.select(dict(type=HoverTool))
sp.set_bullseye_plot_options(bullseye_plot)

star_syms = bullseye_plot.circle('x', 'y', source=star_points, name="star_points_to_hover", \
      fill_color='color', line_color='color', radius=0.5, line_alpha='alpha', fill_alpha='alpha')
star_syms.selection_glyph = Circle(fill_alpha=0.8,
                                   fill_color="#F59A0A",
                                   radius=2.0,
                                   line_color='#BAD8FF',
                                   line_width=2)

# this is not currently being used - it is intended to show the image of each system
plot2 = Figure(plot_height=800,
               plot_width=800,
               x_axis_type=None,
               y_axis_type=None,
Esempio n. 23
0
class BokehPlot(object):
    def __init__(self,
                 device,
                 points_list,
                 *,
                 title='My title',
                 show_notes=True,
                 update_data=True):
        self.device = device
        self.points_list = points_list
        self.title = title
        self.units = {}
        self.show_notes = show_notes

        self.lst = self.points_list

        self.multi_states = self.device.multi_states
        self.binary_states = self.device.binary_states
        self.analog_units = self.device.analog_units

        plot = self.build_plot()

        self.device.properties.network.bokeh_document.add_plot(plot)
        if update_data:
            self.device.properties.network.bokeh_document.add_periodic_callback(
                self.update_data, 100)
        print('Chart created, please reload your web page to see changes')

    # Get data
    def read_lst(self):
        df = self.device[self.lst]
        try:
            df = df.fillna(method='ffill').fillna(method='bfill').replace(
                ['inactive', 'active'], [0, 1])
        except TypeError:
            df = df.fillna(method='ffill').fillna(method='bfill')

        df = df.reset_index()
        df['name'] = 'nameToReplace'
        df['units'] = 'waiting for refresh'
        df['time_s'] = df['index'].apply(str)
        return df

    def read_notes(self):
        notes_df = self.device.notes.reset_index()
        notes_df['value'] = -5
        notes_df['desc'] = 'Notes'
        notes_df['time_s'] = notes_df['index'].apply(str)
        return notes_df

    def build_plot(self):
        df = self.read_lst()
        notes_df = self.read_notes()

        TOOLS = "hover,resize,save,pan,box_zoom,wheel_zoom,reset"
        #plot_width=800, plot_height=600,
        self.p = Figure(x_axis_type="datetime", title=self.title, tools=TOOLS)

        if self.show_notes:
            self.notes_source = ColumnDataSource(
                data=dict(x=notes_df['index'],
                          y=notes_df['value'],
                          time=notes_df['time_s'],
                          desc=notes_df['desc'],
                          units=notes_df[0]))

            self.p.asterisk('x',
                            'y',
                            source=self.notes_source,
                            name='Notes',
                            color="#%06x" % random.randint(0x000000, 0x777777),
                            legend='Notes',
                            size=40)

        self.p.legend.location = 'top_left'
        self.p.extra_y_ranges = {
            "bool": Range1d(start=0, end=1.1),
            "enum": Range1d(start=0, end=10)
        }
        self.p.add_layout(LinearAxis(y_range_name="bool"), 'left')
        self.p.add_layout(LinearAxis(y_range_name="enum"), 'right')

        hover = self.p.select(dict(type=HoverTool))
        hover.tooltips = OrderedDict([
            ('name', '@desc'),
            ('value', '@y'),
            ('units', '@units'),
            ('time', '@time'),
        ])

        self.sources = {}
        for each in self.lst:

            try:
                df['name'] = df['name'].replace(
                    'nameToReplace',
                    ('%s / %s' % (each, self.device[each]['description'])))
            except TypeError:
                continue
            self.sources[each] = ColumnDataSource(data=dict(x=df['index'],
                                                            y=df[each],
                                                            time=df['time_s'],
                                                            name=df['name'],
                                                            units=df['units']))

            if each in self.binary_states:
                self.p.circle('x',
                              'y',
                              source=self.sources[each],
                              name=each,
                              color="#%06x" %
                              random.randint(0x000000, 0x777777),
                              legend=each,
                              y_range_name="bool",
                              size=10)
            elif each in self.multi_states:
                self.p.diamond('x',
                               'y',
                               source=self.sources[each],
                               name=each,
                               color="#%06x" %
                               random.randint(0x000000, 0x777777),
                               legend=each,
                               y_range_name="enum",
                               size=20)
            else:
                self.p.line('x',
                            'y',
                            source=self.sources[each],
                            name=each,
                            color="#%06x" % random.randint(0x000000, 0x777777),
                            legend=each,
                            line_width=2)

        return self.p

    def update_data(self):
        if self.device.properties.network._started:
            df = self.read_lst()
            for renderer in self.p.renderers:
                name = renderer.name
                if name in self.points_list:
                    glyph_renderer = renderer
                    df['name'] = ('%s / %s' %
                                  (name, self.device[name]['description']))
                    glyph_renderer.data_source.data['x'] = df['index']
                    glyph_renderer.data_source.data['y'] = df[name]
                    glyph_renderer.data_source.data['desc'] = df['name']
                    glyph_renderer.data_source.data['time'] = df['time_s']
                    if name in self.multi_states:
                        glyph_renderer.data_source.data['units'] = [
                            self.multi_states[name][int(math.fabs(x - 1))]
                            for x in df[name]
                        ]
                    elif name in self.binary_states:
                        glyph_renderer.data_source.data['y'] = df[name]
                        glyph_renderer.data_source.data['units'] = [
                            self.binary_states[name][int(x / 1)]
                            for x in df[name]
                        ]
                    else:
                        df['units'] = self.analog_units[name]
                        glyph_renderer.data_source.data['units'] = df['units']
                elif name == 'Notes':
                    notes_df = self.read_notes()
                    glyph_renderer = renderer
                    glyph_renderer.data_source.data['x'] = notes_df['index']
                    glyph_renderer.data_source.data['y'] = notes_df['value']
                    glyph_renderer.data_source.data['desc'] = notes_df['desc']
                    glyph_renderer.data_source.data['units'] = notes_df[0]
                    glyph_renderer.data_source.data['time'] = notes_df[
                        'time_s']
Esempio n. 24
0
           plot_width=800,
           title="",
           #toolbar_location=None,
           tools=[hover,"tap","pan,wheel_zoom,box_zoom,reset,resize,save"],
           toolbar_location="below",  #http://bokeh.pydata.org/en/latest/docs/user_guide/tools.html
           )
p.circle(x="x",
         y="y",
         source=source,
         size=7,
         color="color",
         line_color=None,
         fill_alpha="alpha")

url = "http://www.lagou.com/jobs/@positionId.html"
taptool = p.select(type=TapTool)
taptool.callback = OpenURL(url=url)

# TapSelectTool  click link
# what is  fill_alpha,why  is it string? try in jupyter
# open url http://bokeh.pydata.org/en/0.11.1/docs/user_guide/interaction.html#customjs-for-widgets


def select_movies():
    '''
    这是核心所在,使用用户的输入来筛选匹配的电影
    这里是起步的地方,最先应当构建这部分
    '''
    salaryAvg_val = salaryAvg.value
    city_val = city.value
    positionType_val = positionType.value
Esempio n. 25
0
              text_font_style='bold',
              text_color='white')
glyph5 = Text(x=0.255,
              y=-0.19,
              text="label",
              text_font_size='9pt',
              text_font_style='bold',
              text_color='white')
snr_plot.add_glyph(textlabel, glyph2)
snr_plot.add_glyph(textlabel, glyph3)
snr_plot.add_glyph(textlabel, glyph4)
snr_plot.add_glyph(textlabel, glyph5)
snr_plot.add_glyph(textlabel, glyph)

#hovertool
hover = snr_plot.select(dict(type=HoverTool))
from math import log
#logobj = [log(y,10) for y in co]
#logobj = [round(y,4) for y in logobj]
#logobj = np.asarray(logobj)
hover.tooltips = [('object', '@co{int}'), ('zodi', '@cz{int}'),
                  ('dark current', '@cD{int}'), ('read noise', '@cR{int}'),
                  ('thermal', '@cth{int}')]

ptab1 = Panel(child=snr_plot, title='Spectrum')
#ptab2 = Panel(child=exp_plot, title='Exposure Time')
ptabs = Tabs(tabs=[ptab1])
show(ptabs)

################################
#  PROGRAMS
Esempio n. 26
0
def plotloc(data,
            circleinds=[],
            crossinds=[],
            edgeinds=[],
            url_path=None,
            fileroot=None,
            tools="hover,tap,pan,box_select,wheel_zoom,reset",
            plot_width=450,
            plot_height=400):
    """ Make a light-weight loc figure """

    fields = ['l1', 'm1', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    l1 = [data['l1'][i] for i in inds]
    l1_min = min(l1)
    l1_max = max(l1)
    m1 = [data['m1'][i] for i in inds]
    m1_min = min(m1)
    m1_max = max(m1)

    source = ColumnDataSource(
        data=dict({(key,
                    tuple([value[i] for i in circleinds if i not in edgeinds]))
                   for (key, value) in data.iteritems() if key in fields}))
    loc = Figure(plot_width=plot_width,
                 plot_height=plot_height,
                 toolbar_location="left",
                 x_axis_label='l1 (rad)',
                 y_axis_label='m1 (rad)',
                 x_range=(l1_min, l1_max),
                 y_range=(m1_min, m1_max),
                 tools=tools,
                 output_backend='webgl')
    loc.circle('l1',
               'm1',
               size='sizes',
               line_color=None,
               fill_color='colors',
               fill_alpha=0.2,
               source=source)

    if crossinds:
        sourceneg = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in crossinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        loc.cross('l1',
                  'm1',
                  size='sizes',
                  line_color='colors',
                  line_alpha=0.3,
                  source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in edgeinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        loc.circle('l1',
                   'm1',
                   size='sizes',
                   line_color='colors',
                   fill_color='colors',
                   source=sourceedge,
                   line_alpha=0.5,
                   fill_alpha=0.2)

    hover = loc.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = loc.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return loc
Esempio n. 27
0
def plotstat(data,
             circleinds=None,
             crossinds=None,
             edgeinds=None,
             url_path=None,
             fileroot=None,
             tools="hover,tap,pan,box_select,wheel_zoom,reset",
             plot_width=450,
             plot_height=400):
    """ Make a light-weight stat figure """

    fields = ['imkur', 'specstd', 'sizes', 'colors', 'snrs', 'key']

    if not circleinds: circleinds = range(len(data['snrs']))

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    specstd = [data['specstd'][i] for i in inds]
    specstd_min = min(specstd)
    specstd_max = max(specstd)
    imkur = [data['imkur'][i] for i in inds]
    imkur_min = min(imkur)
    imkur_max = max(imkur)

    source = ColumnDataSource(
        data=dict({(key,
                    tuple([value[i] for i in circleinds if i not in edgeinds]))
                   for (key, value) in data.iteritems() if key in fields}))
    stat = Figure(plot_width=plot_width,
                  plot_height=plot_height,
                  toolbar_location="left",
                  x_axis_label='Spectral std',
                  y_axis_label='Image kurtosis',
                  x_range=(specstd_min, specstd_max),
                  y_range=(imkur_min, imkur_max),
                  tools=tools,
                  output_backend='webgl')
    stat.circle('specstd',
                'imkur',
                size='sizes',
                line_color=None,
                fill_color='colors',
                fill_alpha=0.2,
                source=source)

    if crossinds:
        sourceneg = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in crossinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        stat.cross('specstd',
                   'imkur',
                   size='sizes',
                   line_color='colors',
                   line_alpha=0.3,
                   source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in edgeinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        stat.circle('specstd',
                    'imkur',
                    size='sizes',
                    line_color='colors',
                    fill_color='colors',
                    source=sourceedge,
                    line_alpha=0.5,
                    fill_alpha=0.2)

    hover = stat.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = stat.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return stat
Esempio n. 28
0
def plotnorm(data,
             circleinds=[],
             crossinds=[],
             edgeinds=[],
             url_path=None,
             fileroot=None,
             tools="hover,tap,pan,box_select,wheel_zoom,reset",
             plot_width=450,
             plot_height=400):
    """ Make a light-weight norm figure """

    fields = ['zs', 'sizes', 'colors', 'abssnr', 'key', 'snrs']

    if not circleinds: circleinds = range(len(data['snrs']))

    source = ColumnDataSource(
        data=dict({(key,
                    tuple([value[i] for i in circleinds if i not in edgeinds]))
                   for (key, value) in data.iteritems() if key in fields}))
    norm = Figure(plot_width=plot_width,
                  plot_height=plot_height,
                  toolbar_location="left",
                  x_axis_label='SNR observed',
                  y_axis_label='SNR expected',
                  tools=tools,
                  output_backend='webgl')
    norm.circle('abssnr',
                'zs',
                size='sizes',
                line_color=None,
                fill_color='colors',
                fill_alpha=0.2,
                source=source)

    if crossinds:
        sourceneg = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in crossinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        norm.cross('abssnr',
                   'zs',
                   size='sizes',
                   line_color='colors',
                   line_alpha=0.3,
                   source=sourceneg)

    if edgeinds:
        sourceedge = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in edgeinds]))
                       for (key, value) in data.iteritems() if key in fields}))
        norm.circle('abssnr',
                    'zs',
                    size='sizes',
                    line_color='colors',
                    fill_color='colors',
                    source=sourceedge,
                    line_alpha=0.5,
                    fill_alpha=0.2)

    hover = norm.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = norm.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

    return norm
Esempio n. 29
0
y_axis = Select(title='Y Axis', options=sorted(axis_map.keys()), value='Expected ROI')


# Create Column Data Source that will be used by the plot
source = ColumnDataSource(data=dict(x=[], y=[], color=[], title=[], year=[], revenue=[]))

hover = HoverTool(tooltips=[('Interest Rate', '@interest_rate%'),
                            ('Payments / Income', '@payments_to_income%'),
                            ('FICO', '@fico')
                            ])

p = Figure(plot_height=600, plot_width=800, title='', toolbar_location=None, tools=[hover])
p.circle(x='x', y='y', source=source, size=7, color='blue', line_color=None, alpha=0.8)

# Remove scientific notation
yaxis = p.select(dict(type=Axis, layout='left'))[0]
yaxis.formatter.use_scientific = False

p.xaxis[0].formatter = yaxis.formatter


def select_notes():
    """
    Filters the dataframe into notes that satisfy all constraints in web app
    """
    selected = df[
        (df.annual_inc >= min_income.value * 1000) &
        (df.default_prob <= max_default.value) &
        (df.estimated_roi >= minimum_roi.value) &
        (df.payments_to_income <= max_payments_to_income.value)
    ]
Esempio n. 30
0
def plotall(data,
            circleinds=[],
            crossinds=[],
            edgeinds=[],
            htmlname=None,
            noiseplot=None,
            url_path='plots',
            fileroot=None):
    """ Create interactive plot (preserving links between panels) from data dictionary

    data has keys of snr, time, dm, sizes, key and more.
    Optional index arguments are used to filter full data set.
    This can be used to remove bad segments or apply different symbols to subsets.
    url_path is path difference to png files for taptool. ('../plots' for jupyter notebook, 'plots' for public page)
    fileroot is the sdm file name used as root for all png files.
    """

    # set up data dictionary
    if not circleinds: circleinds = calcinds(data, np.abs(data['snrs']).min())
    if not crossinds:
        crossinds = calcinds(data, -1 * np.abs(data['snrs']).min())

    TOOLS = "hover,tap,pan,box_select,wheel_zoom,reset"

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    dm = [data['dm'][i] for i in inds]
    dm_min = min(min(dm), max(dm) / 1.2)
    dm_max = max(max(dm), min(dm) * 1.2)
    time = [data['time'][i] for i in inds]
    time_min = min(time)
    time_max = max(time)
    l1 = [data['l1'][i] for i in inds]
    l1_min = min(l1)
    l1_max = max(l1)
    m1 = [data['m1'][i] for i in inds]
    m1_min = min(m1)
    m1_max = max(m1)
    specstd = [data['specstd'][i] for i in inds]
    specstd_min = min(specstd)
    specstd_max = max(specstd)
    imkur = [data['imkur'][i] for i in inds]
    imkur_min = min(imkur)
    imkur_max = max(imkur)

    # create figures
    dmt = Figure(plot_width=950,
                 plot_height=500,
                 toolbar_location="left",
                 x_axis_label='Time (s; relative)',
                 y_axis_label='DM (pc/cm3)',
                 x_range=(time_min, time_max),
                 y_range=(dm_min, dm_max),
                 output_backend='webgl',
                 tools=TOOLS)
    loc = Figure(plot_width=450,
                 plot_height=400,
                 toolbar_location="left",
                 x_axis_label='l1 (rad)',
                 y_axis_label='m1 (rad)',
                 x_range=(l1_min, l1_max),
                 y_range=(m1_min, m1_max),
                 tools=TOOLS,
                 output_backend='webgl')
    stat = Figure(plot_width=450,
                  plot_height=400,
                  toolbar_location="left",
                  x_axis_label='Spectral std',
                  y_axis_label='Image kurtosis',
                  x_range=(specstd_min, specstd_max),
                  y_range=(imkur_min, imkur_max),
                  tools=TOOLS,
                  output_backend='webgl')
    norm = Figure(plot_width=450,
                  plot_height=400,
                  toolbar_location="left",
                  x_axis_label='SNR observed',
                  y_axis_label='SNR expected',
                  tools=TOOLS,
                  output_backend='webgl')

    # create positive symbol source and add glyphs
    source = ColumnDataSource(
        data=dict({(key,
                    tuple([value[i] for i in circleinds if i not in edgeinds]))
                   for (key, value) in data.iteritems()}))
    dmt.circle('time',
               'dm',
               size='sizes',
               fill_color='colors',
               line_color=None,
               fill_alpha=0.2,
               source=source)
    loc.circle('l1',
               'm1',
               size='sizes',
               line_color=None,
               fill_color='colors',
               fill_alpha=0.2,
               source=source)
    stat.circle('specstd',
                'imkur',
                size='sizes',
                line_color=None,
                fill_color='colors',
                fill_alpha=0.2,
                source=source)
    norm.circle('abssnr',
                'zs',
                size='sizes',
                line_color=None,
                fill_color='colors',
                fill_alpha=0.2,
                source=source)

    # create negative symbol source and add glyphs
    if crossinds:
        sourceneg = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in crossinds]))
                       for (key, value) in data.iteritems()}))
        dmt.cross('time',
                  'dm',
                  size='sizes',
                  fill_color='colors',
                  line_alpha=0.3,
                  source=sourceneg)
        loc.cross('l1',
                  'm1',
                  size='sizes',
                  line_color='colors',
                  line_alpha=0.3,
                  source=sourceneg)
        stat.cross('specstd',
                   'imkur',
                   size='sizes',
                   line_color='colors',
                   line_alpha=0.3,
                   source=sourceneg)
        norm.cross('abssnr',
                   'zs',
                   size='sizes',
                   line_color='colors',
                   line_alpha=0.3,
                   source=sourceneg)

    # create linked symbol source and add glyphs
    if edgeinds:
        sourceedge = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in edgeinds]))
                       for (key, value) in data.iteritems()}))
        dmt.circle('time',
                   'dm',
                   size='sizes',
                   line_color='colors',
                   fill_color='colors',
                   line_alpha=0.5,
                   fill_alpha=0.2,
                   source=sourceedge)
        loc.circle('l1',
                   'm1',
                   size='sizes',
                   line_color='colors',
                   fill_color='colors',
                   source=sourceedge,
                   line_alpha=0.5,
                   fill_alpha=0.2)
        stat.circle('specstd',
                    'imkur',
                    size='sizes',
                    line_color='colors',
                    fill_color='colors',
                    source=sourceedge,
                    line_alpha=0.5,
                    fill_alpha=0.2)
        norm.circle('abssnr',
                    'zs',
                    size='sizes',
                    line_color='colors',
                    fill_color='colors',
                    source=sourceedge,
                    line_alpha=0.5,
                    fill_alpha=0.2)

    hover = dmt.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = loc.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = stat.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = norm.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = dmt.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = loc.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = stat.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = norm.select(type=TapTool)
        taptool.callback = OpenURL(url=url)


# this approach does not preserve links between panels
#    dmt = plotdmt(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS) # maybe add size?
#    loc = plotloc(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)
#    stat = plotstat(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)
#    norm = plotnorm(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)

# arrange figures
    top = Row(dmt, width=950)
    middle = Row(loc, stat, width=950)
    if noiseplot:
        bottom = Row(norm, noiseplot, width=950)
    else:
        bottom = Row(norm, width=950)
    combined = Column(top, middle, bottom, width=950)

    if htmlname:
        output_file(htmlname)
        save(combined)
    else:
        return combined
Esempio n. 31
0
# Build state bar chart
state_bar_chart = Bar(build_state_data(), label="state",
                      values='complaint_count', toolbar_location=None,
                      title="Complaints by State", width=1300, height=200,
                      ylabel="", xlabel="", color="#2cb34a")

# Build zip code scatter plot
zip_data = build_zip_data()
zip_source.data = dict(x = zip_data["median_income"],
                       y = zip_data["complaint_count"])
zip_scatter_plot = Figure(plot_height=500, plot_width=1000,
                          title="Complaints by Median Income",
                          title_text_font_size='14pt', x_range=Range1d(0,100000))
zip_scatter_plot.circle(x="x", y="y", source=zip_source, size=4,
                        color="#addc91", line_color=None, fill_alpha="0.95")
zip_xaxis = zip_scatter_plot.select(dict(type=Axis, layout="below"))[0]
zip_xaxis.formatter.use_scientific = False

# Build the data table
columns = [
    TableColumn(field="labels", title="Label"),
    TableColumn(field="data", title="Data")
]

data_table = DataTable(source=table_source, columns=columns,
                       height=150, width=250)
table_source.data = build_data_table()

### Step 4: Construct the document

# The Bar() function automatically adds the chart as a root object
Esempio n. 32
0
# plot 2: create a color spectrum with a hover-over tool to inspect hex codes
brightness = 0.8 # at the moment this is hard-coded. Change if you want brighter/darker colors
crx = list(range(1,1001)) # the resolution is 1000 colors
cry = [ 5 for i in range(len(crx)) ]
crcolor, crRGBs = generate_color_range(1000,brightness) # produce spectrum

# make data source object to allow information to be displayed by hover tool
crsource = ColumnDataSource(data=dict(x = crx, y = cry, crcolor = crcolor, RGBs = crRGBs))

tools2 = 'reset, save, hover'

# create second plot
p2 = Figure(x_range=(0,1000), y_range=(0,10), plot_width=600, plot_height=150, tools=tools2, title = 'hover over color')
color_range1 = p2.rect(x='x', y='y', width=1, height=10, color='crcolor', source=crsource)
# set up hover tool to show color hex code and sample swatch
hover = p2.select(dict(type=HoverTool))
hover.tooltips = [
                   ('color', '$color[hex, rgb, swatch]:crcolor'),
                   ('RGB levels', '@RGBs')
                    ]

# get rid of axis details for cleaner look
p1.ygrid.grid_line_color = None
p1.xgrid.grid_line_color = None
p1.axis.axis_line_color  = None
p1.axis.major_label_text_color = None
p1.axis.major_tick_line_color = None
p1.axis.minor_tick_line_color = None

p2.ygrid.grid_line_color = None
p2.xgrid.grid_line_color = None