Exemplo n.º 1
0
	def mass_plotting(self, filename):


		data_dict = self.data_generation(filename)
		self.data_test(data_dict)
		name_check = data_dict["gen_info"]["DATA FILES"]
		attr_id = name_check[1][4][:-3] + "_" + name_check[2][2]

		TOOLS="pan,wheel_zoom,box_zoom,reset, hover, previewsave"
		figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log",
			title = attr_id, tools = TOOLS)

		figure_obj.yaxis.axis_label = data_dict["data"][0]["y_unit"]
		figure_obj.xaxis.axis_label = data_dict["data"][0]["x_unit"]

		hover = figure_obj.select(dict(type = HoverTool))
		hover.tooltips=[("Value:", "$top")]

		hist, edges = np.histogram(data_dict["data"][0]["y"],  bins = data_dict["data"][0]["x"])
		source = ColumnDataSource(data = dict(top = hist, left = edges[:-1], right = edges[1:], 
					x_unit = data_dict["data"][0]["x_unit"], y_unit = data_dict["data"][0]["y_unit"],
					edges = edges))
		#hist = figure_obj.Histogram(source )
		figure_obj.quad(top = "top", bottom = 0, left = "left" , right = "right", source = source)

		matplot_button = Button(label = "create matplotlib plot")

		matplot_button.on_click(lambda source_list = source:
							self.matplotlib_export_ms(source_list))


		return Panel(child = hplot(figure_obj, matplot_button), title = attr_id)
    def knit_html(self,es):
        #col1
        fig1 = figure(width=250,height=250)
        vis_bokeh.draw_1d_hist_from_es("dummy1",0,35,30,es,"run*",ax=fig1) #changes fig1, but also returns it

        fig2=figure(width=250,height=250)
        xmin,xmax = 0,65
        xbins = 20
        xname = "hcalEnergy"
        ymin,ymax = 0,65
        ybins = 20
        yname = "muonHits"
        vis_bokeh.draw_2d_hist_from_es(xname,xmin,xmax,xbins,yname,ymin,ymax,ybins,es,
                                         index="run*",ax=fig2)
        fig_column1 = vplot(fig1,fig2)

        #col2
        fig3 = figure(width=250,height=250)
        fig3=vis_bokeh.draw_1d_hist_from_es("dummy23",0,100,30,es,"run*",ax=fig3,hist_drawer="classic")
        fig4 = figure(width=250,height=250)
        fig4=vis_bokeh.draw_1d_hist_from_es("dummy45",0,40,30,es,"run*",ax=fig4)
        fig_column2 = vplot(fig3,fig4)

        fig_grid = hplot(fig_column1,fig_column2)
        
        return vis_bokeh.fig_to_html(fig_grid)
Exemplo n.º 3
0
def bokeh_subplot(x, y, title, xlabel, ylabel):
    bk.plotting.output_file("subplot_data.html")
    s1 = bk.plotting.figure(title=title[0], x_axis_label=xlabel[0], y_axis_label=ylabel[0])
    s1.circle(x[0], y[0], size=5, color='firebrick', alpha=0.5)
    s1.line(x[1], y[1], alpha=0.5, line_width=2, line_dash="dashed")

    s2 = bk.plotting.figure(title=title[1], x_axis_label=xlabel[1], y_axis_label=ylabel[1])
    s2.circle(x[1], y[1], size=5, color='olive', alpha=0.5)
    s2.patch(x[1], y[1], alpha=0.5, line_width=2)

    p = hplot(s1, s2)

    bk.plotting.show(p)
Exemplo n.º 4
0
def main():
    # list all plots
    # put in a selector by name
    # when selected, load that module
    # join output of that module to curdoc()
    print(sys.path[:3])
    import gliderops
    import gliderops.plots
    print(dir(gliderops.plots))
    import gliderops.plots.plot_timeseries as plot_timeseries
    plot_this = plot_timeseries.plot()
    master_layout = hplot(plot_this)

    curdoc().add_root(master_layout)
 def knit_html(self,es):
     
     figs = []
     for i in range(len(self.hists)):
         figs.append(
             [self.make_figure(hist,model,es,"run*") for hist,model in zip(self.hists[i],self.models[i])]
             )
     hrows = [hplot(*row) for row in figs]
     grid = vplot(*hrows)
         
         
         
     
     return vis_bokeh.fig_to_html(grid)
Exemplo n.º 6
0
    def init_bokeh_table(self):
        time_format = bokeh_tables.NumberFormatter(format='0,0.00000')

        name_template = ('<a id="function<%= ids %>", style="cursor:pointer">'
                         '<%- names %></a>')
        name_format = (bokeh_tables.
                       HTMLTemplateFormatter(template=name_template))

        time_plot_template = ('<svg width="100" height="10">'
                              '<rect width="<%= plot_inline_times%>"'
                              'height="10" style="fill:rgb(255, 0, 0);"/>'
                              '<rect x="<%= plot_inline_times%>"'
                              'width="<%= plot_extra_times %>"'
                              'height="10" style="fill:rgb(255, 160, 160);"/>'
                              '</svg>')
        time_plot_format = (bokeh_tables.
                            HTMLTemplateFormatter(template=time_plot_template))

        columns = [bokeh_tables.TableColumn(title="Function",
                                            field="names",
                                            formatter=name_format),
                   bokeh_tables.TableColumn(title="Total time (s)",
                                            field="times",
                                            formatter=time_format,
                                            default_sort="descending"),
                   bokeh_tables.TableColumn(title="Inline time (s)",
                                            field="inlinetimes",
                                            formatter=time_format,
                                            default_sort="descending"),
                   bokeh_tables.TableColumn(title="Time plot",
                                            sortable=False,
                                            formatter=time_plot_format)]

        bokeh_table = bokeh_tables.DataTable(source=self.table_data,
                                             columns=columns,
                                             # Would be nice if width could
                                             # be automatic but this appears
                                             # to be broken in firefox and
                                             # chrome.
                                             width=620,
                                             height=27 + 15 * 25,
                                             selectable=False,
                                             row_headers=False)

        self.bokeh_table = bokeh_table

        comms_target = bokeh_util.serialization.make_id()
        self.bokeh_comms_target = comms_target
        self.bokeh_table_div = notebook_div(hplot(bokeh_table), comms_target)
    def _init_plot(self):
        # get recoating data
        query = "SELECT MAX(ReplacementDate) AS ReplacementDate, SegmentPosition" \
                "       FROM MirrorRecoating" \
                "       GROUP BY SegmentPosition ORDER BY ReplacementDate, SegmentPosition"
        df = pd.read_sql(query, db.engine)

        # add missing segment positions
        missing_positions = [p for p in range(1, 92) if p not in df.SegmentPosition.values]
        df_missing = pd.DataFrame(dict(SegmentPosition=missing_positions,
                                       ReplacementDate=len(missing_positions) * [datetime.date(1970, 1, 1)]))
        df = df.append(df_missing, ignore_index=True)

        # sort by date (in descending order)
        df.sort_values(by='ReplacementDate', ascending=False, inplace=True)

        # add cumulative number of replacements since one recoating period ago
        start = self.now - datetime.timedelta(self.RECOATING_PERIOD)
        recoatings = len(df[df.ReplacementDate >= start])
        df['RecoatingsSinceYearStart'] = [max(recoatings - i, 0) for i in range(0, 91)]

        # add days since recoating
        df['DaysSinceReplacement'] = [(self.now - d).days for d in df.ReplacementDate.values]

        # add segment position coordinates
        df['SegmentPositionX'] = [self.mirror_positions[m][0] for m in df.SegmentPosition]
        df['SegmentPositionY'] = [self.mirror_positions[m][1] for m in df.SegmentPosition]
        df['SegmentPositionCornerXs'] = [self._segment_corners(m)[0] for m in df.SegmentPosition]
        df['SegmentPositionCornerYs'] = [self._segment_corners(m)[1] for m in df.SegmentPosition]

        # create data source
        source = ColumnDataSource(df)

        table = self._table(source)
        replacement_plot = self._replacement_plot(source)
        segment_plot = self._segment_plot(source)

        srp = vplot(replacement_plot, segment_plot)

        self.plot = hplot(table, srp)
Exemplo n.º 8
0
def plot_table_by_time(table):
    plots = []
    table = table.set_index('time')
    for col in table:
        s = table[col]
        s.dropna(inplace=True)
        if not np.isscalar(s.values[0]):
            # replace with the sum
            s = s.apply(np.sum)
        x_range = plots[0].x_range if plots else None
        fig = figure(title=col, x_axis_type='datetime', x_range=x_range)
        fig.line(s.index, s, line_width=2)
        fig.circle(s.index, s, fill_color='white', size=8)
        plots.append(fig)

    ncols = int(np.ceil(np.sqrt(len(plots))))
    nrows = int(np.ceil(len(plots) / ncols))
    rows = [hplot(*plots[row*ncols:(row+1)*ncols]) for row in range(nrows)]
    plot = vplot(*rows)
    print('plot = %s' % plot)
    script, div = components(plot)
    return {'plot_div': div, 'plot_resources': PLOT_RESOURCES,
            'plot_script': script, 'bokeh_version': bokeh.__version__}
Exemplo n.º 9
0
        data['x'] = [];
        data['y'] = [];
    }
    else {
        if (mode == 'Linear') { interp = linear; }
        else if (mode == 'Step (before)') { interp = step; step.set('mode', 'before'); }
        else if (mode == 'Step (center)') { interp = step; step.set('mode', 'center'); }
        else if (mode == 'Step (after)')  { interp = step; step.set('mode', 'after');  }

        for (i=0; i < %d; i++) {
            data['x'][i] = i * dx
            data['y'][i] = interp.compute(data['x'][i])
        }
    }

    source.trigger('change')

""" % (N, N))

mode = Select(title='Interpolation Mode',
              value='None',
              options=[
                  'None', 'Linear', 'Step (before)', 'Step (center)',
                  'Step (after)'
              ],
              callback=callback)

output_file("transform_interpolator.html", title="Example Transforms")

show(vplot(hplot(mode), p))
Exemplo n.º 10
0
def nb_view_patches(Yr, A, C, b, f, d1, d2, image_neurons=None, thr=0.99):
    '''
    Interactive plotting utility for ipython notbook

    Parameters
    -----------
    Yr: np.ndarray
        movie
    A,C,b,f: np.ndarrays
        outputs of matrix factorization algorithm

    d1,d2: floats
        dimensions of movie (x and y)

    image_neurons: np.ndarray
        image to be overlaid to neurons (for instance the average)

    thr: double
        threshold regulating the extent of the displayed patches


    '''
    colormap = cm.get_cmap("jet")  # choose any matplotlib colormap here
    grayp = [mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))]
    nr, T = C.shape
    nA2 = np.sum(np.array(A)**2, axis=0)
    b = np.squeeze(b)
    f = np.squeeze(f)
    #Y_r = np.array(spdiags(1/nA2,0,nr,nr)*(A.T*np.matrix(Yr-b[:,np.newaxis]*f[np.newaxis] - A.dot(C))) + C)
    Y_r = np.array(spdiags(1 / nA2, 0, nr, nr) * (A.T * np.matrix(Yr) - (A.T *
                                                                         np.matrix(b[:, np.newaxis])) * np.matrix(f[np.newaxis]) - (A.T.dot(A)) * np.matrix(C)) + C)

    bpl.output_notebook()
    x = np.arange(T)
    z = np.squeeze(np.array(Y_r[:, :].T)) / 100
    k = np.reshape(np.array(A), (d1, d2, A.shape[1]), order='F')
    if image_neurons is None:
        image_neurons = np.nanmean(k, axis=2)

    fig = plt.figure()
    coors = plot_contours(coo_matrix(A), image_neurons, thr=thr)
    plt.close()
#    cc=coors[0]['coordinates'];
    cc1 = [cor['coordinates'][:, 0] for cor in coors]
    cc2 = [cor['coordinates'][:, 1] for cor in coors]
    c1 = cc1[0]
    c2 = cc2[0]
    npoints = range(len(c1))

    source = ColumnDataSource(data=dict(x=x, y=z[:, 0], z=z))
    source2 = ColumnDataSource(data=dict(x=npoints, c1=c1, c2=c2, cc1=cc1, cc2=cc2))

    plot = bpl.figure(plot_width=600, plot_height=300)
    plot.line('x', 'y', source=source, line_width=1, line_alpha=0.6)

    callback = CustomJS(args=dict(source=source, source2=source2), code="""
            var data = source.get('data');
            var f = cb_obj.get('value')-1
            x = data['x']
            y = data['y']
            z = data['z']

            for (i = 0; i < x.length; i++) {
                y[i] = z[i][f]
            }

            var data2 = source2.get('data');
            c1 = data2['c1'];
            c2 = data2['c2'];
            cc1 = data2['cc1'];
            cc2 = data2['cc2'];

            for (i = 0; i < c1.length; i++) {
                   c1[i] = cc1[f][i]
                   c2[i] = cc2[f][i]
            }
            source2.trigger('change');
            source.trigger('change');

        """)

    slider = bokeh.models.Slider(start=1, end=Y_r.shape[
                                 0], value=1, step=1, title="Neuron Number", callback=callback)
    xr = Range1d(start=0, end=image_neurons.shape[1])
    yr = Range1d(start=image_neurons.shape[0], end=0)
    plot1 = bpl.figure(x_range=xr, y_range=yr, plot_width=300, plot_height=300)
    plot1.image(image=[image_neurons[::-1, :]], x=0,
                y=image_neurons.shape[0], dw=d2, dh=d1, palette=grayp)
    plot1.patch('c1', 'c2', alpha=0.6, color='purple', line_width=2, source=source2)

    layout = vform(slider, hplot(plot1, plot))

    bpl.show(layout)

    return Y_r
Exemplo n.º 11
0
def plotHistogram(fileName,
                  initData,
                  stations,
                  dateRange,
                  bokehPlaceholderId='bokehContent'):
    data = {
        'xs': [initData['bins']],
        'ys': [initData['values']],
        'ss': [1, 2],
        'es': [3, 4]
    }  #ss and es are for test purposes we'll add  other values of the controlles e.g. age, usertype, Gender coming fetshed from initdata

    source = ColumnDataSource(data=data)
    stations.insert(0, "All")
    selectSS = Select(title="Start Station:", value="All", options=stations)
    selectES = Select(title="End Station:", value="All", options=stations)

    selectUT = Select(title="User Type:",
                      value="All",
                      options=["All", "Subscriber", "Customer"])
    selectGender = Select(title="Gender:",
                          value="All",
                          options=["All", "Male", "Female"])
    sliderAge = Slider(start=8, end=100, value=30, step=5, title="Age")

    startDP = DatePicker(title="Start Date:",
                         min_date=dateRange[0],
                         max_date=dateRange[1],
                         value=dateRange[0])
    endDP = DatePicker(title="End Date:",
                       min_date=dateRange[0],
                       max_date=dateRange[1],
                       value=dateRange[1])
    binSize = TextInput(value="15", title="Bin Size (Days):")
    AddButton = Toggle(label="Add", type="success")
    DeleteButton = Toggle(label="delete", type="success")

    columns = [
        TableColumn(field="ss", title="Start Station"),
        TableColumn(field="es", title="End Station")
    ]  # add other columns contains values of other controllers
    data_table = DataTable(source=source,
                           columns=columns,
                           width=650,
                           height=300)

    model = dict(source=source,
                 selectSS=selectSS,
                 selectES=selectES,
                 startDP=startDP,
                 endDP=endDP,
                 binSize=binSize,
                 selectUT=selectUT,
                 selectGender=selectGender,
                 sliderAge=sliderAge)
    plot = Figure(plot_width=650, plot_height=400, x_axis_type="datetime")
    plot.multi_line('xs',
                    'ys',
                    source=source,
                    line_width='width',
                    line_alpha=0.6,
                    line_color='color')

    callback = CustomJS(args=model,
                        code="""
            //alert("callback");
            var startStation = selectSS.get('value');
            var endStation = selectES.get('value');
            var startDate = startDP.get('value');
            
            if ( typeof(startDate) !== "number")
                startDate = startDate.getTime();
                
            var endDate = endDP.get('value');
            
            if ( typeof(endDate) !== "number")
                endDate = endDate.getTime();            
            
            var binSize = binSize.get('value');
            //alert(startStation + " " + endStation + " " + startDate + " " + endDate + " " + binSize);
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                    if(xmlhttp.status == 200){
                        var data = source.get('data');
                        var result = JSON.parse(xmlhttp.responseText);
                        var temp=[];
                        
                        for(var date in result.x) {
                            temp.push(new Date(result.x[date]));
                        }
                        
                        data['xs'].push(temp);
                        data['ys'].push(result.y);
                        source.trigger('change');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {ss:startStation, es:endStation, sd:startDate, ed:endDate, bs: binSize};
        url = "/histogram?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)

    AddButton.callback = callback
    #DeleteButton.on_click(callback1)
    layout1 = vform(startDP, endDP, binSize)
    layout2 = vform(plot, DeleteButton, data_table)
    layout3 = vform(selectSS, selectES, selectUT, selectGender, sliderAge,
                    AddButton)
    layout = hplot(layout1, layout2, layout3)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
Exemplo n.º 12
0
               plot_width=400,plot_height=400,
               x_range=[0,10], y_range=[0,10])
filterPlot.image(image=[customFilter],x=[0],y=[0],dw=[10],dh=[10],palette="Spectral11")#,palette=myColorMapperAu.palette)
filterPlot.axis.visible=None

outputPlot=Figure(title="filtered image",
               plot_width=400,plot_height=400,
               x_range=[0,10], y_range=[0,10])
outputPlot.image(image=[realFilteredImage],x=[0],y=[0],dw=[10],dh=[10])#,palette=myColorMapperGrey.palette)
outputPlot.axis.visible=None


#http://bokeh.pydata.org/en/0.10.0/docs/user_guide/layout.html
#p=gridplot([ [inputPlot,inputFFTPlot], [filterPlot,outputPlot] ])
#p=gridplot([ [inputPlot,None], [filterPlot,None] ])
p=hplot(inputPlot,filterPlot,outputPlot)
#p=hplot(inputPlot,filterPlot)

#set up the slider widgets
#text = TextInput(title="title", value="Put your title here")
spatialFreq = Slider(title="Spatial Frequency (cycles/image)", value=1.0, start=0.0, end=10.0)
bandwidthSF = Slider(title ="spatial frequency bandwidth",value=1.0,start=0.1,end=5.0)
orientation = Slider(title="Orientation (deg)", value=45.0, start=0.0, end =360.0)
bandwidthOri = Slider(title ="orientation bandwidth",value=1.0,start=0.1,end=5.0)
inputs = VBoxForm(children=[spatialFreq,bandwidthSF,orientation,bandwidthOri])

#set up callbacks
#one for each input (text, sf, ori) 

#define the action  mechanism
#def updateText(attrname, old, new):
Exemplo n.º 13
0
def plot():
    fig = Figure(title='Timeseries', x_axis_type='datetime', tools = TOOLS, plot_width = 800)
    timeticks = DatetimeTickFormatter(formats=dict(seconds =["%b%d %H:%M:%S"],
                                                   minutes =["%b%d %H:%M"],
                                                   hours =["%b%d %H:%M"],
                                                   days  =["%b%d %H:%M"],
                                                   months=["%b%d %H:%M"],
                                                   years =["%b%d %H:%M %Y"]))
    fig.xaxis.formatter = timeticks

    platformIDs = get_glidernames()
    select_platformID = Select(title = 'PlatformID',
                               value = platformIDs[0],
                               options = platformIDs)
    select_sensor = Select(title = 'Sensors',
                           value = 'm_depth',
                           options = get_sensornames(platformIDs[0]))
    select_chunkation = Select(title = 'Chunkation',
                               value = 'file',
                               options = ['24hr', 'file'])

    button_prev_chunk = Button(label = '<')
    label_chunk_index = TextInput(value = '0')
    button_next_chunk = Button(label = '>')
    hbox_chunk = HBox(button_prev_chunk, label_chunk_index, button_next_chunk) #TODO log this as a bokeh bug
    hbox_chunk = HBox(label_chunk_index)

    onclick_controls = [button_prev_chunk, button_next_chunk]
    onchange_controls = [select_platformID,select_sensor, select_chunkation]#, label_chunk_index]

    source = ColumnDataSource(data=dict(x=[], y=[]))

    fig.line('x', 'y', source=source )
    fig.circle('x', 'y', source=source, alpha = 0.2)

    def update_plot(attrib, old, new):
        sensorname = select_sensor.value
        print('UPDATE!')

        if attrib == 'button_click':
            chunk_index = button_next_chunk.clicks - button_prev_chunk.clicks
            label_chunk_index.value = str( chunk_index )
        else:
            chunk_index = int(label_chunk_index.value)
            button_prev_chunk.clicks = 0
            button_next_chunk.clicks = chunk_index

        try:
            sensor = mongoman.mongo_fetch(util.DB,
                                          select_platformID.value,
                                          {'name':sensorname})[0]
        except IndexError:
            print('{} does not exist for {} in this range'.format(sensorname, select_platformID.value))
            return
        except Exception as e:
            print(e)
            return
        #sensor = Sensor(sensorname,'arbit',[(0,0),(1,1),(2,2),(3,3)],'noparse',['fake'])

        select_sensor.options = get_sensornames(select_platformID.value)

        x,y = sensor.xylist()
        times = [s*10**3 for s in x] #seconds to milliseconds
        source.data = dict(x=times, y=y)

        if select_chunkation.value == 'file':
            tstart,tend,chunk_ID = truncate_filechunk(chunk_index, select_platformID.value)
        elif select_chunkation.value == '24hr':
            hr = 86400
            c = abs(chunk_index)
            t = util.time()
            tstart = t-(c+1)*hr
            tend = t-c*hr
            chunk_ID = '{} {} {}'.format(select_platformID.value, util.e2ts(min(x)), sensorname)
        else:
            tstart, tend = None,None

        fig.x_range.start = tstart*1000
        fig.x_range.end   = tend*1000   #converts to s to ms

        fig.yaxis.axis_label = '{} ({})'.format(sensorname,sensor.units)
        if sensorname == 'm_depth':
            fig.y_range.start = 1000
            fig.y_range.end   = 0
        else:
            fig.y_range.start = None
            fig.y_range.end   = None


        fig.title = '{} {} '.format(chunk_ID, sensorname)

    def button_callback():
        update_plot('button_click',None,None)

    for val in onchange_controls:
        val.on_change('value',update_plot)
    for val in onclick_controls:
        val.on_click(button_callback)

    control_box = vform(*onchange_controls, hbox_chunk)
    layout = vplot( hplot(fig, button_prev_chunk, button_next_chunk, control_box ),
                    TextInput())
    return layout
Exemplo n.º 14
0
row2, col2 = dem_map.convertToRowCol(utm2)
print(row2,col2)

from bokeh.plotting import figure, output_file, show
from bokeh.io import hplot
output_file("lines.html", title="line plot example")

dh, dw = dem_map.elevations.shape
print dw,dh
# create a new plot with a title and axis labels
s1 = figure(title="simple line example", x_axis_label='x', y_axis_label='y', x_range=[0, 250], y_range=[250, 500])
s2 = figure(title="simple line example", x_axis_label='x', y_axis_label='y', x_range=[0, 250], y_range=[250, 500])

# add a line renderer with legend and line thickness
s1.image(image=[dem_map.elevations[::-1,:]], dw=dw, dh=dh, palette="Spectral11")
s2.image(image=[dem_map.obstacles[::-1,:]], dw=dw, dh=dh)
# show the results

final = P.aStarCompletePath([0, 0, 1], [ap1, ap2], 'tuple', [s1, s2], dh)

if len(final)>0:
    for elt in final[0]:
        s1.circle(elt[1], dh - elt[0], fill_color="yellow", line_color="yellow")
        s2.circle(elt[1], dh-elt[0], fill_color="yellow", line_color="yellow")
s1.circle([col1, col2], [dh - row1, dh - row2], fill_color="orange", line_color="orange")
s2.circle([col1, col2], [dh - row1, dh - row2], fill_color="orange", line_color="orange")

print final

p = hplot(s1, s2)
show(p)
Exemplo n.º 15
0
from bokeh.models.widgets import Button
from bokeh.client import push_session
from bokeh.plotting import figure, curdoc
from bokeh.io import vform, hplot

figure_obj = figure()
button = Button(label="this thing")

hplot(figure_obj, button)

session = push_session(curdoc())
session.show()
session.loop_until_closed()
Exemplo n.º 16
0
from bokeh.models import HoverTool

from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
from bokeh.io import output_file, show, vform, vplot, hplot


from assocplots.misc import mock_data_generation


data_m = np.genfromtxt('HIP_MEN_chr_pos_rs_pval.txt', dtype=None, names=['chr', 'pos', 'snp', 'pval'])
data_w = np.genfromtxt('HIP_WOMEN_chr_pos_rs_pval.txt', dtype=None, names=['chr', 'pos', 'snp', 'pval'])


# data_m, data_w = mock_data_generation(M=100000, seed=42)
# data_m['pval'] /= 500000.*np.exp(-(data_m['pos']-10000.)**2/50000.0) * (data_m['chr']=='4') * np.random.rand(len(data_m)) + 1.

from assocplots.interactive import *

# cut1, cut2, data = data_reduce(data_m, data_w, N=5000)
cut1, cut2, data = data_reduce_fast(data_m, data_w, N=1000)

p1,p2,p3,p4,pq1 = mann_only_interactive(data, cut1, cut2)
show(vplot(p1,p2))
show(hplot(pq1,p4))
show(p4)


from assocplots.htmloutput import *
write_to_html([p1,p2,pq1,p4], filename='output.html', title='Title')
Exemplo n.º 17
0
def plotHistogram(fileName, initData, stations, dateRange, bokehPlaceholderId='bokehContent'):
    data = {'xs':[initData['bins']], 'ys':[initData['values']],'ss':[1,2], 'es':[3,4] }#ss and es are for test purposes we'll add  other values of the controlles e.g. age, usertype, Gender coming fetshed from initdata 

    source = ColumnDataSource(data=data)
    stations.insert(0, "All")
    selectSS = Select(title="Start Station:", value="All", options=stations)
    selectES = Select(title="End Station:", value="All", options=stations)
    
    selectUT = Select(title="User Type:", value="All", options=["All", "Subscriber", "Customer"])
    selectGender = Select(title="Gender:", value="All", options=["All", "Male", "Female"])
    sliderAge = Slider(start=8, end=100, value=30, step=5, title="Age")    
    
    startDP = DatePicker(title="Start Date:", min_date=dateRange[0] ,max_date=dateRange[1], value=dateRange[0])
    endDP = DatePicker(title="End Date:", min_date=dateRange[0] ,max_date=dateRange[1], value=dateRange[1])
    binSize = TextInput(value="15", title="Bin Size (Days):")
    AddButton = Toggle(label="Add", type="success")
    DeleteButton = Toggle(label="delete", type="success")
    
    
    columns = [TableColumn(field="ss", title="Start Station"),TableColumn(field="es", title="End Station")]# add other columns contains values of other controllers
    data_table = DataTable(source=source, columns=columns, width=650, height=300)
    
    model = dict(source=source, selectSS = selectSS, selectES = selectES, startDP = startDP, endDP = endDP, binSize = binSize,selectUT=selectUT,selectGender=selectGender,sliderAge=sliderAge)
    plot = Figure(plot_width=650, plot_height=400, x_axis_type="datetime")
    plot.multi_line('xs', 'ys', source=source, line_width='width', line_alpha=0.6, line_color='color')
    
    callback = CustomJS(args=model, code="""
            //alert("callback");
            var startStation = selectSS.get('value');
            var endStation = selectES.get('value');
            var startDate = startDP.get('value');
            
            if ( typeof(startDate) !== "number")
                startDate = startDate.getTime();
                
            var endDate = endDP.get('value');
            
            if ( typeof(endDate) !== "number")
                endDate = endDate.getTime();            
            
            var binSize = binSize.get('value');
            //alert(startStation + " " + endStation + " " + startDate + " " + endDate + " " + binSize);
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                    if(xmlhttp.status == 200){
                        var data = source.get('data');
                        var result = JSON.parse(xmlhttp.responseText);
                        var temp=[];
                        
                        for(var date in result.x) {
                            temp.push(new Date(result.x[date]));
                        }
                        
                        data['xs'].push(temp);
                        data['ys'].push(result.y);
                        source.trigger('change');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {ss:startStation, es:endStation, sd:startDate, ed:endDate, bs: binSize};
        url = "/histogram?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)
        
    
    AddButton.callback = callback
    #DeleteButton.on_click(callback1)
    layout1 = vform (startDP,endDP,binSize)
    layout2 = vform(plot,DeleteButton,data_table)
    layout3 = vform(selectSS, selectES,selectUT,selectGender,sliderAge,AddButton)
    layout = hplot(layout1,layout2,layout3)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html  
Exemplo n.º 18
0
    def plotting(self):

        #Tools = [hover, TapTool(), BoxZoomTool(), BoxSelectTool(), PreviewSaveTool(), ResetTool()]
        TOOLS = "crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave"

        tab_plots = []
        #output_file("test.html")
        self.all_elements = []
        self.elements_comparison = []

        for attr_id, i in zip(self.attribute_ids,
                              range(len(self.attribute_ids))):
            """
			create plots for each datafile and put them in a tab.
			"""
            list_of_datasets = getattr(self, attr_id)
            y_axis_units = [x["y_unit"] for x in list_of_datasets]
            x_axis_units = [x["x_unit"] for x in list_of_datasets]

            figure_obj = figure(plot_width=1000,
                                plot_height=800,
                                y_axis_type="log",
                                title=attr_id,
                                tools=TOOLS)
            #figure_obj.axes.major_label_text_font_size("12pt")
            #figure_obj.major_label_text_font_size("12pt")

            setattr(self, attr_id + "_" + "figure_obj", figure_obj)

            figure_obj.yaxis.axis_label = y_axis_units[0]
            figure_obj.xaxis.axis_label = x_axis_units[0]

            if not all(x == y_axis_units[0] for x in y_axis_units):
                for unit, data in zip(y_axis_units, list_of_datasets):
                    if not unit == y_axis_units[0]:
                        figure_obj.extra_y_ranges = {
                            "foo":
                            Range1d(start=np.amin(data["data"]["y"]),
                                    end=np.amax(data["data"]["y"]))
                        }
                        figure_obj.add_layout(
                            LogAxis(y_range_name="foo", axis_label=unit),
                            "right")
                        break

            if not all(x == x_axis_units[0] for x in x_axis_units):
                for unit, data in zip(x_axis_units, list_of_datasets):
                    if not unit == x_axis_units[0]:
                        figure_obj.extra_x_ranges = {
                            "bar":
                            Range1d(start=np.amin(data["data"]["x"]),
                                    end=np.amax(data["data"]["x"]))
                        }
                        figure_obj.add_layout(
                            LinearAxis(x_range_name="bar", axis_label=unit),
                            "above")
                        break

            figure_obj.xaxis.axis_label = list_of_datasets[0]["x_unit"]
            colour_list = Spectral11 + RdPu9 + Oranges9
            colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]

            list_of_elements = []

            for dataset, color_index in zip(list_of_datasets, colour_indices):

                self.all_elements.append(
                    dataset["sample element"])  #strip isotope number
                color = colour_list[color_index]

                source = ColumnDataSource(
                    data=dataset["data"]
                )  #Datastructure for source of plotting

                setattr(self,
                        attr_id + "_" + dataset["sample element"] + "_source",
                        source)  #Source element generalized for all plotting

                list_of_elements.append(dataset["sample element"])

                figure_obj.line(
                    "x",
                    "y",
                    source=getattr(
                        self,
                        attr_id + "_" + dataset["sample element"] + "_source"),
                    line_width=2,
                    line_color=color,
                    legend=dataset["sample element"],
                    name=dataset["sample element"],
                )

            hover = figure_obj.select_one(HoverTool).tooltips = [
                ("element", "@element"), ("(x,y)", "($x, $y)")
            ]

            radio_group = RadioGroup(labels=list_of_elements, active=0)
            """
			Need to fetch default variables from input file and replace DEFAULT

			Block of code produces the layout of buttons and callbacks
			"""

            #Calculations on the dataset
            text_input_rsf = TextInput(value="default",
                                       title="RSF (at/cm^3): ")
            do_integral_button = Button(label="Calibration Integral")
            smoothing_button = Button(label="Smoothing on selected curve")

            text_input_sputter = TextInput(value="default",
                                           title="Sputter speed: float unit")
            text_input_crater_depth = TextInput(
                value="default", title="Depth of crater in: float")

            radio_group.on_change("active", lambda attr, old, new: None)

            text_input_xval_integral = TextInput(
                value="0", title="x-value for calibration integral ")
            text_input_yval_integral = TextInput(
                value="0", title="y-value for calibration integral ")

            #Save files for later use
            save_flexDPE_button = Button(label="Save element for FlexPDE")
            save_all_flexDPE_button = Button(
                label="Save all elements for FlexPDE")

            #Pointers to methods on click / change handlers
            do_integral_button.on_click(
                lambda identity=self.attribute_ids[i], radio=radio_group, x_box
                =text_input_xval_integral, y_box=text_input_yval_integral: self
                .integrate(identity, radio, x_box, y_box))

            smoothing_button.on_click(lambda identity=self.attribute_ids[
                i], radio=radio_group: self.smoothing(identity, radio))

            save_flexDPE_button.on_click(lambda identity=self.attribute_ids[
                i], radio=radio_group: self.write_to_flexPDE(identity, radio))

            save_all_flexDPE_button.on_click(
                lambda identity=self.attribute_ids[i], radio=radio_group: self.
                write_all_to_flexPDE(identity, radio))

            text_input_rsf.on_change(
                "value",
                lambda attr, old, new, radio=radio_group, identity=self.
                attribute_ids[i], text_input=text_input_rsf, which="rsf": self.
                update_data(identity, radio, text_input, new, which))

            text_input_sputter.on_change(
                "value",
                lambda attr, old, new, radio=radio_group, identity=self.
                attribute_ids[i], text_input=
                text_input_sputter, which="sputter": self.update_data(
                    identity, radio, text_input, new, which))

            text_input_crater_depth.on_change(
                "value",
                lambda attr, old, new, radio=radio_group, identity=self.
                attribute_ids[i], text_input=text_input_crater_depth, which=
                "crater_depth": self.update_data(identity, radio, text_input,
                                                 new, which))

            #Initialization of actual plotting.
            tab_plots.append(
                Panel(child=hplot(
                    figure_obj,
                    vform(radio_group, save_flexDPE_button,
                          save_all_flexDPE_button),
                    vform(text_input_rsf, smoothing_button, text_input_sputter,
                          text_input_crater_depth),
                    vform(text_input_xval_integral, text_input_yval_integral,
                          do_integral_button)),
                      title=attr_id))
        """
		Check to see if one or more element exists in the samples and creat a comparison plot for each 
		of those elements.
		"""

        for element in self.all_elements:
            checkers = list(self.all_elements)
            checkers.remove(element)
            if element in checkers and not element in self.elements_comparison:
                self.elements_comparison.append(element)
        """create plots for each element that is to be compared """

        for comparison_element in self.elements_comparison:

            colour_list = Spectral11 + RdPu9 + Oranges9
            colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]
            figure_obj = figure(plot_width=1000,
                                plot_height=800,
                                y_axis_type="log",
                                title=comparison_element,
                                tools=TOOLS)
            #figure_obj.xaxis.major_label_text_font_size("12pt")
            #figure_obj.yaxis.major_label_text_font_size("12pt")

            y_axis_units = []
            x_axis_units = []

            comparison_datasets = []

            for attr_id, color_index in zip(self.attribute_ids,
                                            colour_indices):

                list_of_datasets = getattr(self, attr_id)

                for dataset in list_of_datasets:

                    if dataset["sample element"] == comparison_element:
                        comparison_datasets.append(dataset)
                        y_axis_units.append(dataset["y_unit"])
                        x_axis_units.append(dataset["x_unit"])

            figure_obj.xaxis.axis_label = comparison_datasets[-1]["x_unit"]
            figure_obj.yaxis.axis_label = comparison_datasets[-1]["y_unit"]

            if not all(x == y_axis_units[-1] for x in y_axis_units):
                for unit, data in zip(y_axis_units, comparison_datasets):
                    if not unit == y_axis_units[-1]:
                        figure_obj.extra_y_ranges = {
                            "foo":
                            Range1d(start=np.amin(data["data"]["y"]),
                                    end=np.amax(data["data"]["y"]))
                        }
                        figure_obj.add_layout(
                            LogAxis(y_range_name="foo", axis_label=unit),
                            "right")
                        break

            if not all(x == x_axis_units[-1] for x in x_axis_units):
                for unit, data in zip(x_axis_units, comparison_datasets):
                    if not unit == x_axis_units[-1]:
                        figure_obj.extra_x_ranges = {
                            "bar":
                            Range1d(start=np.amin(data["data"]["x"]),
                                    end=np.amax(data["data"]["x"]))
                        }
                        figure_obj.add_layout(
                            LinearAxis(x_range_name="bar", axis_label=unit),
                            "above")
                        break

            for attr_id, color_index in zip(self.attribute_ids,
                                            colour_indices):

                list_of_datasets = getattr(self, attr_id)

                for dataset in list_of_datasets:

                    if dataset["sample element"] == comparison_element:
                        color = colour_list[color_index]
                        """
						Logic that ensures that plots get put with correspoinding axes. 
						"""
                        if dataset["x_unit"] != x_axis_units[-1] or dataset[
                                "y_unit"] != y_axis_units[-1]:

                            if dataset["x_unit"] != x_axis_units[
                                    -1] and dataset["y_unit"] != y_axis_units[
                                        -1]:

                                figure_obj.line(
                                    "x",
                                    "y",
                                    source=getattr(
                                        self, attr_id + "_" +
                                        dataset["sample element"] + "_source"),
                                    line_width=2,
                                    line_color=color,
                                    legend=attr_id,
                                    x_range_name="bar",
                                    y_range_name="foo")

                            elif dataset["x_unit"] != x_axis_units[-1]:

                                figure_obj.line(
                                    "x",
                                    "y",
                                    source=getattr(
                                        self, attr_id + "_" +
                                        dataset["sample element"] + "_source"),
                                    line_width=2,
                                    line_color=color,
                                    legend=attr_id,
                                    x_range_name="bar")

                            else:

                                figure_obj.line(
                                    "x",
                                    "y",
                                    source=getattr(
                                        self, attr_id + "_" +
                                        dataset["sample element"] + "_source"),
                                    line_width=2,
                                    line_color=color,
                                    legend=attr_id,
                                    y_range_name="foo")

                        else:
                            figure_obj.line(
                                "x",
                                "y",
                                source=getattr(
                                    self, attr_id + "_" +
                                    dataset["sample element"] + "_source"),
                                line_width=2,
                                line_color=color,
                                legend=attr_id)

            tab_plots.append(Panel(child=figure_obj, title=comparison_element))

        tabs = Tabs(tabs=tab_plots)

        session = push_session(curdoc())
        session.show()
        session.loop_until_closed()
Exemplo n.º 19
0
from bokeh.models import HoverTool

from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
from bokeh.io import output_file, show, vform, vplot, hplot

from assocplots.misc import mock_data_generation

data_m = np.genfromtxt('HIP_MEN_chr_pos_rs_pval.txt',
                       dtype=None,
                       names=['chr', 'pos', 'snp', 'pval'])
data_w = np.genfromtxt('HIP_WOMEN_chr_pos_rs_pval.txt',
                       dtype=None,
                       names=['chr', 'pos', 'snp', 'pval'])

# data_m, data_w = mock_data_generation(M=100000, seed=42)
# data_m['pval'] /= 500000.*np.exp(-(data_m['pos']-10000.)**2/50000.0) * (data_m['chr']=='4') * np.random.rand(len(data_m)) + 1.

from assocplots.interactive import *

# cut1, cut2, data = data_reduce(data_m, data_w, N=5000)
cut1, cut2, data = data_reduce_fast(data_m, data_w, N=1000)

p1, p2, p3, p4, pq1 = mann_only_interactive(data, cut1, cut2)
show(vplot(p1, p2))
show(hplot(pq1, p4))
show(p4)

from assocplots.htmloutput import *
write_to_html([p1, p2, pq1, p4], filename='output.html', title='Title')
Exemplo n.º 20
0
def nb_view_patches3d(Yr, A, C, b, f, dims, image_type='mean',
                      max_projection=False, axis=0, thr=0.99, denoised_color=None):
    '''
    Interactive plotting utility for ipython notbook

    Parameters
    -----------
    Yr: np.ndarray
        movie

    A,C,b,f: np.ndarrays
        outputs of matrix factorization algorithm

    dims: tuple of ints
        dimensions of movie (x, y and z)

    image_type: 'mean', 'max' or 'corr'
        image to be overlaid to neurons (average, maximum or nearest neigbor correlation)

    max_projection: boolean
        plot max projection along specified axis if True, plot layers if False

    axis: int (0, 1 or 2)
        axis along which max projection is performed or layers are shown

    thr: double
        threshold regulating the extent of the displayed patches

    denoised_color: string or None
        color name (e.g. 'red') or hex color code (e.g. '#F0027F')

    '''
    d, T = Yr.shape
    order = list(range(4))
    order.insert(0, order.pop(axis))
    Yr = Yr.reshape(dims + (-1,), order='F').transpose(order).reshape((d, T), order='F')
    A = A.reshape(dims + (-1,), order='F').transpose(order).reshape((d, -1), order='F')
    dims = tuple(np.array(dims)[order[:3]])
    d1, d2, d3 = dims
    colormap = cm.get_cmap("jet")  # choose any matplotlib colormap here
    grayp = [mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))]
    nr, T = C.shape
    nA2 = np.sum(np.array(A)**2, axis=0)
    b = np.squeeze(b)
    f = np.squeeze(f)
    Y_r = np.array(spdiags(old_div(1, nA2), 0, nr, nr) *
                   (A.T * np.matrix(Yr) - (A.T * np.matrix(b[:, np.newaxis])) *
                    np.matrix(f[np.newaxis]) - (A.T.dot(A)) * np.matrix(C)) + C)

    bpl.output_notebook()
    x = np.arange(T)
    z = old_div(np.squeeze(np.array(Y_r[:, :].T)), 100)
    k = np.reshape(np.array(A), dims + (A.shape[1],), order='F')
    source = ColumnDataSource(data=dict(x=x, y=z[:, 0], y2=old_div(C[0], 100), z=z, z2=old_div(C.T, 100)))

    if max_projection:
        if image_type == 'corr':
            image_neurons = [(local_correlations(
                Yr.reshape(dims + (-1,), order='F'))[:, ::-1]).max(i)
                for i in range(3)]
        elif image_type in ['mean', 'max']:
            tmp = [({'mean': np.nanmean, 'max': np.nanmax}[image_type]
                    (k, axis=3)[:, ::-1]).max(i) for i in range(3)]
        else:
            raise ValueError("image_type must be 'mean', 'max' or 'corr'")

#         tmp = [np.nanmean(k.max(i), axis=2) for i in range(3)]
        image_neurons = np.nan * np.ones((int(1.05 * (d1 + d2)), int(1.05 * (d1 + d3))))
        image_neurons[:d2, -d3:] = tmp[0][::-1]
        image_neurons[:d2, :d1] = tmp[2].T[::-1]
        image_neurons[-d1:, -d3:] = tmp[1]
        offset1 = image_neurons.shape[1] - d3
        offset2 = image_neurons.shape[0] - d1
        coors = [plot_contours(coo_matrix(A.reshape(dims + (-1,), order='F').max(i)
                                          .reshape((old_div(np.prod(dims), dims[i]), -1), order='F')),
                               tmp[i], thr=thr) for i in range(3)]
        pl.close()
        cc1 = [[cor['coordinates'][:, 0] + offset1 for cor in coors[0]],
               [cor['coordinates'][:, 1] for cor in coors[2]],
               [cor['coordinates'][:, 0] + offset1 for cor in coors[1]]]
        cc2 = [[cor['coordinates'][:, 1] for cor in coors[0]],
               [cor['coordinates'][:, 0] for cor in coors[2]],
               [cor['coordinates'][:, 1] + offset2 for cor in coors[1]]]
        c1x = cc1[0][0]
        c2x = cc2[0][0]
        c1y = cc1[1][0]
        c2y = cc2[1][0]
        c1z = cc1[2][0]
        c2z = cc2[2][0]
        source2 = ColumnDataSource(data=dict(  # x=npointsx, y=npointsy, z=npointsz,
            c1x=c1x, c1y=c1y, c1z=c1z,
            c2x=c2x, c2y=c2y, c2z=c2z, cc1=cc1, cc2=cc2))
        callback = CustomJS(args=dict(source=source, source2=source2), code="""
                var data = source.get('data');
                var f = cb_obj.get('value')-1
                y = data['y']
                y2 = data['y2']
                for (i = 0; i < y.length; i++) {
                    y[i] = data['z'][i][f];
                    y2[i] = data['z2'][i][f];
                }

                var data2 = source2.get('data');
                c1x = data2['c1x'];
                c2x = data2['c2x'];
                c1y = data2['c1y'];
                c2y = data2['c2y'];
                c1z = data2['c1z'];
                c2z = data2['c2z'];
                cc1 = data2['cc1'];
                cc2 = data2['cc2'];
                for (i = 0; i < c1x.length; i++) {
                       c1x[i] = cc1[0][f][i]
                       c2x[i] = cc2[0][f][i]
                }
                for (i = 0; i < c1y.length; i++) {
                       c1y[i] = cc1[1][f][i]
                       c2y[i] = cc2[1][f][i]
                }
                for (i = 0; i < c1z.length; i++) {
                       c1z[i] = cc1[2][f][i]
                       c2z[i] = cc2[2][f][i]
                }
                source2.trigger('change');
                source.trigger('change');
            """)

    else:
        if image_type == 'corr':
            image_neurons = local_correlations(Yr.reshape(dims + (-1,), order='F'))[:, ::-1]
        elif image_type in ['mean', 'max']:
            image_neurons = {'mean': np.nanmean, 'max': np.nanmax}[image_type](k, axis=3)[:, ::-1]
        else:
            raise ValueError('image_type must be mean, max or corr')

        cmap = bokeh.models.mappers.LinearColorMapper([mpl.colors.rgb2hex(m)
                                                       for m in colormap(np.arange(colormap.N))])
        cmap.high = image_neurons.max()
        coors = get_contours3d(A, dims, thr=thr)
        pl.close()
        cc1 = [[l[:, 0] for l in n['coordinates']] for n in coors]
        cc2 = [[l[:, 1] for l in n['coordinates']] for n in coors]
        linit = int(round(coors[0]['CoM'][0]))  # pick initl layer in which first neuron lies
        c1 = cc1[0][linit]
        c2 = cc2[0][linit]
        source2 = ColumnDataSource(data=dict(c1=c1, c2=c2, cc1=cc1, cc2=cc2))
        x = list(range(d2))
        y = list(range(d3))
        source3 = ColumnDataSource(
            data=dict(im1=[image_neurons[linit]], im=image_neurons, xx=[x], yy=[y]))

        callback = CustomJS(args=dict(source=source, source2=source2), code="""
                var data = source.get('data');
                var f = slider_neuron.get('value')-1;
                var l = slider_layer.get('value')-1;
                y = data['y']
                y2 = data['y2']
                for (i = 0; i < y.length; i++) {
                    y[i] = data['z'][i][f];
                    y2[i] = data['z2'][i][f];
                }

                var data2 = source2.get('data');
                c1 = data2['c1'];
                c2 = data2['c2'];
                for (i = 0; i < c1.length; i++) {
                       c1[i] = data2['cc1'][f][l][i];
                       c2[i] = data2['cc2'][f][l][i];
                }
                source2.trigger('change');
                source.trigger('change');
            """)

        callback_layer = CustomJS(args=dict(source=source3, source2=source2), code="""
                var f = slider_neuron.get('value')-1;
                var l = slider_layer.get('value')-1;
                var im1 = source.get('data')['im1'][0];
                for (var i = 0; i < source.get('data')['xx'][0].length; i++) {
                    for (var j = 0; j < source.get('data')['yy'][0].length; j++){
                        im1[i][j] = source.get('data')['im'][l][i][j];
                    }
                }
                var data2 = source2.get('data');
                c1 = data2['c1'];
                c2 = data2['c2'];
                for (i = 0; i < c1.length; i++) {
                       c1[i] = data2['cc1'][f][l][i];
                       c2[i] = data2['cc2'][f][l][i];
                }
                source.trigger('change');
                source2.trigger('change');
            """)

    plot = bpl.figure(plot_width=600, plot_height=300)
    plot.line('x', 'y', source=source, line_width=1, line_alpha=0.6)
    if denoised_color is not None:
        plot.line('x', 'y2', source=source, line_width=1, line_alpha=0.6, color=denoised_color)
    slider = bokeh.models.Slider(start=1, end=Y_r.shape[0], value=1, step=1,
                                 title="Neuron Number", callback=callback)
    xr = Range1d(start=0, end=image_neurons.shape[1] if max_projection else d3)
    yr = Range1d(start=image_neurons.shape[0] if max_projection else d2, end=0)
    plot1 = bpl.figure(x_range=xr, y_range=yr, plot_width=300, plot_height=300)

    if max_projection:
        plot1.image(image=[image_neurons[::-1, :]], x=0,
                    y=image_neurons.shape[0], dw=image_neurons.shape[1], dh=image_neurons.shape[0], palette=grayp)
        plot1.patch('c1x', 'c2x', alpha=0.6, color='purple', line_width=2, source=source2)
        plot1.patch('c1y', 'c2y', alpha=0.6, color='purple', line_width=2, source=source2)
        plot1.patch('c1z', 'c2z', alpha=0.6, color='purple', line_width=2, source=source2)
        layout = vform(slider, hplot(plot1, plot))
    else:
        slider_layer = bokeh.models.Slider(start=1, end=d1, value=linit + 1, step=1,
                                           title="Layer", callback=callback_layer)
        callback.args['slider_neuron'] = slider
        callback.args['slider_layer'] = slider_layer
        callback_layer.args['slider_neuron'] = slider
        callback_layer.args['slider_layer'] = slider_layer
        plot1.image(image='im1', x=[0], y=[d2], dw=[d3], dh=[d2],
                    color_mapper=cmap, source=source3)
        plot1.patch('c1', 'c2', alpha=0.6, color='purple', line_width=2, source=source2)
        layout = vform(slider, slider_layer, hplot(plot1, plot))

    bpl.show(layout)

    return Y_r
Exemplo n.º 21
0
def nb_view_patches(Yr,A,C,b,f,d1,d2,image_neurons=None,thr = 0.99):
    
    colormap =cm.get_cmap("jet") #choose any matplotlib colormap here
    grayp = [mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))]
    nr,T = C.shape
    nA2 = np.sum(np.array(A)**2,axis=0)
    Y_r = np.array(spdiags(1/nA2,0,nr,nr)*(A.T*np.matrix(Yr-b[:,np.newaxis]*f[np.newaxis] - A.dot(C))) + C)  

    
    bpl.output_notebook()
    x = np.arange(T)
    z=np.squeeze(np.array(Y_r[:,:].T))/100
    k=np.reshape(np.array(A),(d1,d2,A.shape[1]),order='F')
    if image_neurons is None:    
        image_neurons=np.sum(k,axis=2)  
    
    fig = plt.figure()
    coors = plot_contours(coo_matrix(A),image_neurons,thr = thr)
    plt.close()
#    cc=coors[0]['coordinates'];
    cc1=[cor['coordinates'][:,0] for cor in coors]
    cc2=[cor['coordinates'][:,1] for cor in coors]
    c1=cc1[0]
    c2=cc2[0]
    npoints=range(len(c1))
    
    source = ColumnDataSource(data=dict(x=x, y=z[:,0], z=z))    
    source2 = ColumnDataSource(data=dict(x=npoints,c1=c1,c2=c2,cc1=cc1,cc2=cc2))
    
    xr = Range1d(start=0,end=image_neurons.shape[1])
    yr = Range1d(start=image_neurons.shape[0],end=0)
    
    plot = bpl.figure(plot_width=600, plot_height=300)
    plot.line('x', 'y', source=source, line_width=1, line_alpha=0.6)
    
    callback = CustomJS(args=dict(source=source,source2=source2), code="""
            var data = source.get('data');
            var f = cb_obj.get('value')
            x = data['x']
            y = data['y']
            z = data['z']
            
            for (i = 0; i < x.length; i++) {
                y[i] = z[i][f-1]             
            }
            
            var data2 = source2.get('data');
            c1 = data2['c1'];
            c2 = data2['c2'];
            cc1 = data2['cc1'];
            cc2 = data2['cc2'];
            
            for (i = 0; i < c1.length; i++) {            
                   c1[i] = cc1[f][i]
                   c2[i] = cc2[f][i]            
            }
            source2.trigger('change');
            source.trigger('change');
            
        """)
    
    
    slider = Slider(start=1, end=Y_r.shape[0], value=1, step=1, title="Neuron Number", callback=callback)
    
    plot1 = bpl.figure(x_range=xr, y_range=yr,plot_width=300, plot_height=300)
    plot1.image(image=[image_neurons[::-1,:]], x=0, y=image_neurons.shape[0], dw=d2, dh=d1, palette=grayp)
    plot1.patch('c1','c2',alpha=0.6, color='red',line_width=2,source=source2)
        
    
    layout = vform(slider, hplot(plot1,plot))
    
    bpl.show(layout)
    
    return Y_r
Exemplo n.º 22
0
    global layout
    global energy_per_capita

    new_df = data_changed(energy_per_capita)
    if new_df is not None:
        energy_per_capita = new_df
        plots_box.children[0] = create_line(energy_per_capita)
        plots_box.children[1] = create_bar(energy_per_capita)


line = create_line(energy_per_capita)
bar = create_bar(energy_per_capita)
desc1 = Paragraph(text="""
This example shows live integration between bokeh server and Excel using
XLWings.""")
desc2 = Paragraph(text="""
*** YOU MUST HAVE EXCEL and XLWINGS INSTALLED ON YOUR MACHINE FOR IT TO WORK ***
""")
desc3 = Paragraph(text="""
It opens this plots window and an excel spreadsheet instance with the
values being plotted. When user changes the values on the excel spreadsheet
the plots will be updated accordingly. It's not required to save the spreadsheet for the plots to update.
""")
plots_box = hplot(line, bar)
layout = vplot(desc1, desc2, desc3, plots_box)
curdoc().add_root(layout)
curdoc().add_periodic_callback(update, 500)

session.show()  # open the document in a browser
session.loop_until_closed()  # run forever
Exemplo n.º 23
0
def build_app(list_cursor):
	'''function to build 2nd page Bokeh app with interactions'''

	#create a list of years for sample size years
	years = [str(i) for i in range(1992,2015,2)]
	years.insert(1,str(1993)); years.insert(3,str(1995)) #the odd ducks
	col_lab_sam = ['Sample Size - ' + i for i in years] #sample column labels
	col_lab_var = ['Variable Name - ' + i for i in years] #variable column labels
	col_lab_qtxt = ['Question Text - ' + i for i in years] #question text column labels
	col_lab_res = ['Response Options - ' + i for i in years] #response options column labels

	#to handle CAMS waves
	years_c = [str(i) for i in range(2001,2014,2)]
	col_lab_sam_c = ['Sample Size- ' + i + ' CAMS' for i in years_c]
	col_lab_var_c = ['Variable Name- ' + i + ' CAMS' for i in years_c]
	col_lab_qtxt_c = ['Question Text - ' + i + ' CAMS' for i in years_c]
	col_lab_res_c = ['Response Options - ' + i + ' CAMS' for i in years_c]

	#create results data table

	l_id = []; l_q = []; l_g = []; l_n = []; l_sample = []
	l_var = [];	l_qtext = []; l_res = []; l_cac = []; l_years = []
	i = 1
	
	for table_cursor in list_cursor:
		for doc in table_cursor:
			l_id.append(str(i))
			i += 1
			l_q.append(doc['Question Text - First Wave Available'])
			l_g.append(doc['Database Section'])
			l_n.append(doc['General Notes'])
			l_cac.append(doc['CAC Label'])			
			if doc['Database Section'] != 'CAMS':
				l_sample.append([int(doc[lab]) if doc[lab] is not '' else 0 for lab in col_lab_sam])
				l_var.append([doc[lab] for lab in col_lab_var])
				l_qtext.append([doc[lab] for lab in col_lab_qtxt])
				l_res.append([doc[lab] for lab in col_lab_res])
				l_years.append(years)
			else:
				l_sample.append([int(doc[lab]) if doc[lab] is not '' else 0 for lab in col_lab_sam_c])
				l_var.append([doc[lab] for lab in col_lab_var_c])
				l_qtext.append([doc[lab] for lab in col_lab_qtxt_c])
				l_res.append([doc[lab] for lab in col_lab_res_c])
				l_years.append(years_c)

	table_source = ColumnDataSource(data=dict(_id = l_id, question = l_q, gray = l_g, notes = l_n, \
		Sample = l_sample, var = l_var, qtext = l_qtext, res = l_res, \
		cac = l_cac, years = l_years))

	columns = [TableColumn(field = '_id', title = "ID", width=5),\
	TableColumn(field = 'cac', title = 'CAC Label',width=70),\
	TableColumn(field = 'gray', title = 'Sections',width=80),\
	TableColumn(field = 'question', title = "Question Text",width =150),\
	TableColumn(field = 'notes', title = "Notes",width = 50)]

	data_table = DataTable(source=table_source, columns=columns, selectable = True, fit_columns = True)

	
	#create selected item table data (only display after callback)
	table_source_2 = ColumnDataSource(data=dict(years = years, var = ['na']*len(years),\
		qtext = ['na']*len(years), res = ['na']*len(years)))
	
	columns_2 = [TableColumn(field = 'years', title = 'Wave',width=3),\
	TableColumn(field = 'var', title = 'Variable',width=3),\
	TableColumn(field = 'qtext', title = 'Question Text',width=100),\
	TableColumn(field = 'res', title = 'Response Options',width=100)]

	data_table_2 = DataTable(source=table_source_2, columns=columns_2, selectable = True, fit_columns = True)

	
	#create data for circle/line graphs	(only display after callback)
	bar_data = dict(Years= years, SampleSize = [0]*len(years)) #place-holding zeros  
	bar_source = ColumnDataSource(data = bar_data)
	
	#draw line and circle graphs in two tabs
	hover = HoverTool(tooltips=[("wave","@Years"),\
		("Sample Size", "@SampleSize")])
	p1 = gen_fig('circle', bar_source, tool=hover)	
	tab1 = Panel(child=p1, title="circle")
	p2 = gen_fig('line', bar_source)
	tab2 = Panel(child=p2, title="line")
	tabs = Tabs(tabs=[ tab1, tab2 ])

	#requires (bar_source, table_source, table_source_2)
	callback = """
	var br_data = source.get('data');
	var tbl_data = s2.get('data');
	var tbl2_data = s3.get('data');
	var f = cb_obj.get('value');
	var i = tbl_data['_id'].indexOf(f);
	br_data['SampleSize'] = tbl_data['Sample'][i];
	br_data['Years'] = tbl_data['years'][i];
	tbl2_data['years'] = tbl_data['years'][i];;
	tbl2_data['var'] = tbl_data['var'][i];
	tbl2_data['qtext'] = tbl_data['qtext'][i];
	tbl2_data['res'] = tbl_data['res'][i];
	source.trigger('change');
	s3.trigger('change');
	dt2.trigger('change');"""

	#Select ID
	id_select = Select(title='Select an ID from the table above',\
		value ='select',options=['None']+l_id,\
		callback = CustomJS(\
			args = dict(source=bar_source, s2=table_source, dt2 = data_table_2, s3 = table_source_2),\
			code = callback))

	html = file_html(vform(data_table,id_select,hplot(tabs,data_table_2)), CDN, "data_table")

	return html
Exemplo n.º 24
0
time.sleep(1)
times.append((datetime.datetime.now() - loop_start).total_seconds())
currents.append(float(bop.interface.query("MEAS:CURR?")))
fields.append(mag.field)

# Initiate immediate current change after recording time
bop.interface.write(":CURR:LEV:IMM 5.2")

for i in range(50):
    times.append((datetime.datetime.now() - loop_start).total_seconds())
    currents.append(float(bop.interface.query("MEAS:CURR?")))
    fields.append(mag.field)

bop.current = 0

p1 = figure(title="Magnetic Field vs. Time",
            x_axis_label='Time (s)',
            y_axis_label='Field (G)')
p1.circle(times, fields, color="firebrick")
p1.line(times, fields, color="firebrick")

p2 = figure(title="BOP Current vs. Time",
            x_axis_label='Time (s)',
            y_axis_label='BOP Sense Current (A)')
p2.circle(times, currents, color="firebrick")
p2.line(times, currents, color="firebrick")

q = hplot(p1, p2)
output_file("BOP-Plots.html")
show(q)
Exemplo n.º 25
0
	def plotting(self):



		#Tools = [hover, TapTool(), BoxZoomTool(), BoxSelectTool(), PreviewSaveTool(), ResetTool()]
		TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave"


		tab_plots = []
		#output_file("test.html")
		self.all_elements = []
		self.elements_comparison = []

		for attr_id, i in zip(self.attribute_ids, range(len(self.attribute_ids))):
			
			"""
			create plots for each datafile and put them in a tab.
			"""
			list_of_datasets = getattr(self, attr_id)
			y_axis_units = [x["y_unit"] for x in list_of_datasets]
			x_axis_units = [x["x_unit"] for x in list_of_datasets]

			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log",
			title = attr_id, tools = TOOLS)
			#figure_obj.axes.major_label_text_font_size("12pt")
			#figure_obj.major_label_text_font_size("12pt")
			
			setattr(self, attr_id+"_"+"figure_obj",figure_obj)

			figure_obj.yaxis.axis_label = y_axis_units[0]
			figure_obj.xaxis.axis_label = x_axis_units[0]

			if not all(x == y_axis_units[0] for x in y_axis_units):
				for unit, data in zip(y_axis_units, list_of_datasets): 
					if not unit == y_axis_units[0]:
						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(data["data"]["y"]),
						end = np.amax(data["data"]["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[0] for x in x_axis_units):
				for unit, data in zip(x_axis_units, list_of_datasets): 
					if not unit == x_axis_units[0]:
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(data["data"]["x"]),
						end = np.amax(data["data"]["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break



			figure_obj.xaxis.axis_label = list_of_datasets[0]["x_unit"]
			colour_list = Spectral11 + RdPu9 + Oranges9
			colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]

			list_of_elements = []

			for dataset, color_index in zip(list_of_datasets, colour_indices):

				self.all_elements.append(dataset["sample element"]) #strip isotope number 
				color = colour_list[color_index]

				source = ColumnDataSource(data = dataset["data"]) #Datastructure for source of plotting

				setattr(self, attr_id+"_"+dataset["sample element"]+"_source", source) #Source element generalized for all plotting				


				list_of_elements.append(dataset["sample element"])

				figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]
								+"_source"), line_width = 2, line_color = color, 
								legend = dataset["sample element"], name = dataset["sample element"],
								 )

			hover = figure_obj.select_one(HoverTool).tooltips = [("element", "@element"), ("(x,y)", "($x, $y)")]

			radio_group = RadioGroup(labels = list_of_elements, active=0)

			"""
			Need to fetch default variables from input file and replace DEFAULT

			Block of code produces the layout of buttons and callbacks
			"""

			
			#Calculations on the dataset
			text_input_rsf = TextInput(value = "default", title = "RSF (at/cm^3): ")
			do_integral_button = Button(label = "Calibration Integral")
			smoothing_button = Button(label = "Smoothing on selected curve")

			text_input_sputter = TextInput(value = "default", title = "Sputter speed: float unit")
			text_input_crater_depth = TextInput(value = "default", title = "Depth of crater in: float")
			

			radio_group.on_change("active", lambda attr, old, new: None)

			text_input_xval_integral = TextInput(value = "0", title = "x-value for calibration integral ")
			text_input_yval_integral = TextInput(value = "0", title = "y-value for calibration integral ")

			#Save files for later use
			save_flexDPE_button = Button(label = "Save element for FlexPDE")
			save_all_flexDPE_button = Button(label = "Save all elements for FlexPDE")


			#Pointers to methods on click / change handlers
			do_integral_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group, 
										x_box = text_input_xval_integral, y_box = text_input_yval_integral: 
										self.integrate(identity, radio, x_box, y_box))

			smoothing_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group: 
									self.smoothing(identity, radio) )

			save_flexDPE_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group: 
										self.write_to_flexPDE(identity, radio))

			save_all_flexDPE_button.on_click(lambda identity = self.attribute_ids[i], radio = radio_group:
											self.write_all_to_flexPDE(identity, radio))

			text_input_rsf.on_change("value", lambda attr, old, new, radio = radio_group, 
								identity = self.attribute_ids[i], text_input = text_input_rsf, which = "rsf":
								self.update_data(identity, radio, text_input, new, which))


			text_input_sputter.on_change("value", lambda attr, old, new, radio = radio_group, 
								identity = self.attribute_ids[i], text_input = text_input_sputter, which = "sputter":
								self.update_data(identity, radio, text_input, new, which))

			text_input_crater_depth.on_change("value", lambda attr, old, new, radio = radio_group, 
								identity = self.attribute_ids[i], text_input = text_input_crater_depth, which = "crater_depth":
								self.update_data(identity, radio, text_input, new, which))


			#Initialization of actual plotting. 
			tab_plots.append(Panel(child = hplot(figure_obj, 
										   vform(radio_group, save_flexDPE_button, save_all_flexDPE_button), 
										   vform(text_input_rsf, smoothing_button, text_input_sputter, text_input_crater_depth),
										   vform(text_input_xval_integral, text_input_yval_integral, do_integral_button)),
										   title = attr_id))


		"""
		Check to see if one or more element exists in the samples and creat a comparison plot for each 
		of those elements.
		"""
		
		for element in self.all_elements:
			checkers = list(self.all_elements)
			checkers.remove(element)
			if element in checkers and not element in self.elements_comparison:
				self.elements_comparison.append(element)

		"""create plots for each element that is to be compared """
	
		for comparison_element in self.elements_comparison: 

			colour_list = Spectral11 + RdPu9 + Oranges9
			colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]
			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log", title = comparison_element, tools = TOOLS)
			#figure_obj.xaxis.major_label_text_font_size("12pt")
			#figure_obj.yaxis.major_label_text_font_size("12pt")
			

			y_axis_units = []
			x_axis_units = []

			comparison_datasets = []


			for attr_id, color_index in zip(self.attribute_ids, colour_indices):

				list_of_datasets = getattr(self, attr_id)

				for dataset in list_of_datasets:

					if dataset["sample element"] == comparison_element:
						comparison_datasets.append(dataset)
						y_axis_units.append(dataset["y_unit"])
						x_axis_units.append(dataset["x_unit"])

			figure_obj.xaxis.axis_label = comparison_datasets[-1]["x_unit"]
			figure_obj.yaxis.axis_label = comparison_datasets[-1]["y_unit"]

			if not all(x == y_axis_units[-1] for x in y_axis_units):
				for unit, data in zip(y_axis_units, comparison_datasets): 
					if not unit == y_axis_units[-1]:
						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(data["data"]["y"]),
						end = np.amax(data["data"]["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[-1] for x in x_axis_units):
				for unit, data in zip(x_axis_units, comparison_datasets): 
					if not unit == x_axis_units[-1]:
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(data["data"]["x"]),
						end = np.amax(data["data"]["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break


			for attr_id, color_index in zip(self.attribute_ids, colour_indices):

				list_of_datasets = getattr(self, attr_id)

				for dataset in list_of_datasets:

					if dataset["sample element"] == comparison_element:
						color = colour_list[color_index]

						"""
						Logic that ensures that plots get put with correspoinding axes. 
						"""
						if dataset["x_unit"] != x_axis_units[-1] or dataset["y_unit"] != y_axis_units[-1]:

							if dataset["x_unit"] != x_axis_units[-1] and dataset["y_unit"] != y_axis_units[-1]:

								figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
								line_color = color, legend = attr_id, x_range_name = "bar", y_range_name = "foo")

							elif dataset["x_unit"] != x_axis_units[-1]:

								figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
								line_color = color, legend = attr_id, x_range_name = "bar")

							else: 

								figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
								line_color = color, legend = attr_id, y_range_name = "foo")

						else: 
							figure_obj.line("x", "y", source = getattr(self, attr_id+"_"+dataset["sample element"]+"_source"), line_width = 2, 
							line_color = color, legend = attr_id)
						


			tab_plots.append(Panel(child = figure_obj, title = comparison_element))	

		tabs = Tabs(tabs = tab_plots)

		session = push_session(curdoc())
		session.show()
		session.loop_until_closed()
Exemplo n.º 26
0
    def initialize_plot(self, ranges=None):
        ranges = self.compute_ranges(self.layout, self.keys[-1], None)
        plots = [[] for i in range(self.rows)]
        passed_plots = []
        tab_titles = {}
        insert_rows, insert_cols = [], []
        adjoined = False
        for r, c in self.coords:
            subplot = self.subplots.get((r, c), None)
            if subplot is not None:
                shared_plots = passed_plots if self.shared_axes else None
                subplots = subplot.initialize_plot(ranges=ranges, plots=shared_plots)

                # Computes plotting offsets depending on
                # number of adjoined plots
                offset = sum(r >= ir for ir in insert_rows)
                if len(subplots) > 2:
                    adjoined = True
                    # Add pad column in this position
                    insert_cols.append(c)
                    if r not in insert_rows:
                        # Insert and pad marginal row if none exists
                        plots.insert(r+offset, [None for _ in range(len(plots[r]))])
                        # Pad previous rows
                        for ir in range(r):
                            plots[ir].insert(c+1, None)
                        # Add to row offset
                        insert_rows.append(r)
                        offset += 1
                    # Add top marginal
                    plots[r+offset-1] += [subplots.pop(-1), None]
                elif len(subplots) > 1:
                    adjoined = True
                    # Add pad column in this position
                    insert_cols.append(c)
                    # Pad previous rows
                    for ir in range(r):
                        plots[r].insert(c+1, None)
                    # Pad top marginal if one exists
                    if r in insert_rows:
                        plots[r+offset-1] += 2*[None]
                else:
                    # Pad top marginal if one exists
                    if r in insert_rows:
                        plots[r+offset-1] += [None] * (1+(c in insert_cols))
                plots[r+offset] += subplots
                if len(subplots) == 1 and c in insert_cols:
                    plots[r+offset].append(None)
                passed_plots.append(subplots[0])

            if self.tabs:
                if isinstance(self.layout, Layout):
                    tab_titles[r, c] = ' '.join(self.paths[r,c])
                else:
                    dim_vals = zip(self.layout.kdims, self.paths[r, c])
                    tab_titles[r, c] = ', '.join([d.pprint_value_string(k)
                                                  for d, k in dim_vals])

        # Replace None types with empty plots
        # to avoid bokeh bug
        if adjoined:
            plots = layout_padding(plots)

        # Determine the most appropriate composite plot type
        # If the object cannot be displayed in a single layout
        # it will be split into Tabs, for 1-row or 1-column
        # Layouts we use the vplot and hplots.
        # If there is a table and multiple rows and columns
        # everything will be forced to a vertical layout
        if self.tabs:
            panels = [Panel(child=child, title=tab_titles.get(r, c))
                      for r, row in enumerate(plots)
                      for c, child in enumerate(row)
                      if child is not None]
            layout_plot = Tabs(tabs=panels)
        elif len(plots) == 1 and not adjoined:
            layout_plot = vplot(hplot(*plots[0]))
        elif len(plots[0]) == 1:
            layout_plot = vplot(*[p[0] for p in plots])
        else:
            layout_plot = gridplot(plots)

        self.handles['plot'] = layout_plot
        self.handles['plots'] = plots
        self.drawn = True

        return self.handles['plot']
    min_interval=timedelta(100),
)
y_range = Range1d(start=0, end=40, bounds=(0, 60))
y_range_extra = Range1d(start=300, end=700, bounds=(200, 1000))
###### -- end -- ########

plot_extra = figure(
    x_axis_type="datetime",
    x_range=x_range,
    y_range=y_range,
    title=
    "Multiple ranges x:(2000/1/1, 2006/12/31), y1:(10, 60), y2:(200, 1000)")
plot_extra.line(x, apple_y, color='lightblue')
plot_extra.extra_y_ranges = {'goog': y_range_extra}
plot_extra.line(x, google_y, color='pink', y_range_name='goog')
plot_extra.add_layout(
    LinearAxis(y_range_name="goog", major_label_text_color='pink'), 'left')

# Tweak the formats to make it all readable
plots = [
    plot_default, plot_range, plot_range_un, plot_range_rev,
    plot_cat_autobounded, plot_cat_unbounded, plot_cat_bounded, plot_extra
]
for plot in plots:
    plot.title_text_font_size = '12pt'

show(
    vplot(plot_default, hplot(plot_range, plot_range_un, plot_range_rev),
          hplot(plot_cat_unbounded, plot_cat_autobounded, plot_cat_bounded),
          plot_extra))
Exemplo n.º 28
0
 def getFigure(self):
     return hplot(self.figure, self.gaugefigure)
Exemplo n.º 29
0
p21.patch('u21x','u21y',source=source1,line_width = 2,line_alpha = 0.6,color = (62,6,148),legend = "U")
p21.patch('b21x','b21y',source=source1,line_width = 2,line_alpha = 0.6,color = "blue",legend = "B")
p21.patch('v21x','v21y',source=source1,line_width = 2,line_alpha = 0.6,color = "violet",legend = "V")
p21.patch('r21x','r21y',source=source1,line_width = 2,line_alpha = 0.6,color = "red",legend = "R")

p21.xgrid.grid_line_color = None
p21.ygrid.grid_line_color = None


menu = [("U", "item_1"), ("V", "item_2"), ("B","item_3"), ("R", "item_4")]
dropdown = Dropdown(label="U", menu=menu)
select = Select( value="U - U", options=["U - U", "U - B", "U - V", "U - R", "B - U", "B - B", "B - V", "B - R", "V - U", "V - B", "V - V","V - R", "R - U", "R - B", "R - V", "R - R"])

layout_p2 = vform(slider,p2)
layout_p22 = vform(select,p21)
layout1 = hplot(layout_p2,layout_p22)

tab2 = Panel(child=layout1, title="filters")

tab3 = Panel(child=p3, title = "Detailed Plot")


#.........................................Transmission passbands........................
#ux_pass = np.arange(300,425,5)
#uy_pass = [0.00,0.016,0.068,0.167,0.287,0.423,0.560,0.673,0.772,0.841,0.905,0.943,0.981,0.993,1.000,0.989,0.916,0.804,0.625,0.423,0.238,0.114,0.051,0.019,0.000]

#bx_pass = np.arange(360,570,10)
#by_pass = [0.0,0.030,0.134,0.567,0.920,0.978,1.000,0.978,0.935,0.853,0.740,0.640,0.536,0.424,0.325,0.235,0.150,0.095,0.043,0.009,0.0]

#vx_pass = np.arange(470,710,10)
#vy_pass = [0.000,0.030,0.163,0.458,0.780,0.967,1.000,0.973,0.898,0.792,0.684,0.574,0.461,0.359,0.270,0.197,0.135,0.081,0.045,0.025,0.017,0.013,0.009,0.000]
Exemplo n.º 30
0
	def plotting(self):

		if self.debug:
			self.debug_file = open("debug_output.txt", "w")
			self.debug_file.write("Initialized plotting subroutine \n")
			 

		TOOLS="pan,wheel_zoom,box_zoom,reset,hover,previewsave"

		tab_plots = []
		self.all_elements = []
		self.elements_comparison = []

		for filename in self.filenames:
			if "ITO" in filename:
				tab_plots.append(self.mass_plotting(filename))
				continue
	
			data_dict = self.data_generation(filename)
			self.data_test(data_dict)

			name_check = data_dict["gen_info"]["DATA FILES"]
			attr_id = name_check[1][4][:-3] + "_" + name_check[2][2]
			self.attribute_ids.append(attr_id)

			attr_extra_y_ranges = False
			attr_extra_x_ranges = False

			local_source_line = []

			"""
			create plots for each datafile and put them in a tab.
			"""

			y_axis_units = [x["y_unit"] for x in data_dict["data"]]
			x_axis_units = [x["x_unit"] for x in data_dict["data"]]

			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log",
			title = attr_id, tools = TOOLS)
			#figure_obj.axes.major_label_text_font_size("12pt")
			#figure_obj.major_label_text_font_size("12pt")

			hover = figure_obj.select(dict(type = HoverTool))
			hover.tooltips = [
							("Element:", "@element"),
							("(x, y):", "($x, $y)")]

			self.figure_data.append((figure_obj, data_dict))
		
			figure_obj.yaxis.axis_label = y_axis_units[0]
			figure_obj.xaxis.axis_label = x_axis_units[0]

			if not all(x == y_axis_units[0] for x in y_axis_units):
				for unit, dataset in zip(y_axis_units, data_dict["data"]): 
					if not unit == y_axis_units[0]:
						
						extra_y_ranges_exists = attr_extra_y_ranges
						extra_y_ranges_exists = True

						if self.debug:
							  
							self.debug_file.write("Added extra y-axis for file_id: %s, element: %s | New length %g \n" 
								%(attr_id, dataset["sample_element"], len(figure_obj.yaxis)))
							 

						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(dataset["y"]),
						end = np.amax(dataset["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[0] for x in x_axis_units):
				for unit, dataset in zip(x_axis_units, data_dict["data"]): 
					if not unit == x_axis_units[0]:
						
						extra_x_ranges_exists = attr_extra_x_ranges
						extra_x_ranges_exists = True
						
						if self.debug:
							  
							self.debug_file.write("Added extra x-axis for file_id: %s, element: %s. | New length %g \n" 
								%(attr_id, dataset["sample_element"], len(figure_obj.yaxis)))
							 
			
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(dataset["x"]),
						end = np.amax(dataset["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break

			figure_obj.xaxis.axis_label = x_axis_units[0]
			colour_list = Spectral11 + RdPu9 + Oranges9
			colour_indices = [0, 2, 8, 10, 12, 14, 20, 22, 1, 3, 9, 11, 13, 15]


			list_of_elements = []
			source_list = []
			line_list = []

			for dataset, color_index in zip(data_dict["data"], colour_indices):

				self.all_elements.append(dataset["sample_element"]) #strip isotope number 
				color = colour_list[color_index]

				source = ColumnDataSource(data = dataset) #Datastructure for source of plotting

				self.source_test(source)

				list_of_elements.append(dataset["sample_element"])
				line_glyph = figure_obj.line("x", "y", source = source, 
							line_width = 2,
							line_color = color, 
							legend = dataset["sample_element"])

				if self.debug:
					self.debug_file.write("Create line object on figure %s  at %s \n" %(id(figure_obj), id(line_glyph)))
					 

				line_list.append(line_glyph)
				source_list.append(source)

			local_source_line.append([[source, line] for source, line in zip(source_list, line_list)])
			self.source_line.append(local_source_line)

			#Calculations on the dataset
			text_input_rsf = TextInput(value = "default", title = "RSF or SF (at/cm^3): ")
			do_integral_button = Button(label = "Calibration integral")
			smoothing_button = Button(label = "smth selct elem")
			matplot_button = Button(label = "Create matplotlib fig")

			text_input_sputter = TextInput(value = "default", title = "Sputter speed: number unit")
			text_input_crater_depth = TextInput(value = "default", title = "Depth of crater in: number unit")
			


			radio_group = RadioGroup(labels = list_of_elements, active=0)


			text_input_xval_integral = TextInput(value = "0", title = "x-delimiter ")
			text_input_dose = TextInput(value = "0", title = "Dose[cm^-2] ")

			#Save files for later use
			save_flexDPE_button = Button(label = "Save element for FlexPDE")
			save_all_flexDPE_button = Button(label = "Save all elements for FlexPDE")
			save_textfile_button = Button(label = "Sava Data in textfile")

			#Pointers to methods on click / change handlers
			radio_group.on_change("active", lambda attr, old, new: None)

			matplot_button.on_click(lambda source_list = source_list:
										self.matplotlib_export(source_list))
			
			do_integral_button.on_click(lambda 
											source_list = source_list, 
											line_list = line_list, 
											source_line = self.source_line,
											figure_data = self.figure_data,
											data_dict = data_dict,
											radio = radio_group,
											x_box = text_input_xval_integral, 
											dose = text_input_dose,
											extra_y_ranges = attr_extra_y_ranges: 
										self.integrate(data_dict, source_list, line_list, source_line, figure_data, radio, x_box, dose, extra_y_ranges))

			smoothing_button.on_click(lambda 
										source_list = source_list,
										radio = radio_group, 
										data_dict = data_dict,
										x_box = text_input_xval_integral: 
									self.smoothing(source_list, data_dict, radio, x_box) )

			save_flexDPE_button.on_click(lambda 
											source_list = source_list,
											attrname = attr_id,
											radio = radio_group: 
										self.write_to_flexPDE(source_list, attrname, radio))

			save_all_flexDPE_button.on_click(lambda 
												source_list = source_list, 
												attrname = attr_id:
												self.write_all_to_flexPDE(source_list, attrname))

			save_textfile_button.on_click(lambda 
											data_dict = data_dict, 
											source_list = source_list,
											attrname = attr_id,
											radio = radio_group:
											self.write_new_datafile(data_dict, source_list, attrname,radio))


			text_input_rsf.on_change("value", lambda attr, old, new, 
												radio = radio_group, 
												data_dict = data_dict,
												figure = figure_obj,
												source_list = source_list,
												text_input = text_input_rsf,
												line_list = line_list,
												which = "rsf":
												self.update_data(line_list, data_dict, source_list, figure, radio, text_input, new, which))


			text_input_sputter.on_change("value", lambda attr, old, new, 
													radio = radio_group, 
													data_dict = data_dict,
													figure = figure_obj,
													source_list = source_list, 
													text_input = text_input_sputter,
													which = "sputter":
													self.update_data(data_dict, source_list, figure, radio, text_input, new, which))

			text_input_crater_depth.on_change("value", lambda attr, old, new, 
														radio = radio_group, 
														data_dict = data_dict,
														source_list = source_list,
														figure = figure_obj,
														text_input = text_input_crater_depth, 
														which = "crater_depth":
														self.update_data(data_dict, source_list, figure, radio, text_input, new, which))


			#Initialization of actual plotting. 
			tab_plots.append(Panel(child = hplot(figure_obj, 
										   vform(
										   vform(radio_group, save_flexDPE_button, save_all_flexDPE_button, save_textfile_button, matplot_button), 
										   vform(text_input_rsf, smoothing_button, text_input_sputter, text_input_crater_depth)
										   ),
										   vform(text_input_xval_integral, text_input_dose, do_integral_button)),
										   title = attr_id))



		"""
		Check to see if one or more element exists in the samples and creat a comparison plot for each 
		of those elements.
		"""
		
		for element in self.all_elements:
			checkers = list(self.all_elements)
			checkers.remove(element)
			if element in checkers and not element in self.elements_comparison:
				self.elements_comparison.append(element)

		"""create plots for each element that is to be compared """
	
		for comparison_element in self.elements_comparison: 

			figure_obj = figure(plot_width = 1000, plot_height = 800, y_axis_type = "log", title = comparison_element, tools = TOOLS)
			#figure_obj.xaxis.major_label_text_font_size("12pt")
			#figure_obj.yaxis.major_label_text_font_size("12pt")
			
			y_axis_units = []
			x_axis_units = []

			comparison_datasets = []

			for data_dict_iter in self.column(self.figure_data, 1):

				for dataset in data_dict_iter["data"]:

					if dataset["sample_element"] == comparison_element:
						comparison_datasets.append(dataset)
						y_axis_units.append(dataset["y_unit"])
						x_axis_units.append(dataset["x_unit"])

			figure_obj.xaxis.axis_label = comparison_datasets[-1]["x_unit"]
			figure_obj.yaxis.axis_label = comparison_datasets[-1]["y_unit"]

			if not all(x == y_axis_units[-1] for x in y_axis_units):
				for unit, data in zip(y_axis_units, comparison_datasets): 
					if not unit == y_axis_units[-1]:
						figure_obj.extra_y_ranges =  {"foo": Range1d(start = np.amin(data["y"]),
						end = np.amax(data["y"]))}
						figure_obj.add_layout(LogAxis(y_range_name = "foo", axis_label = unit), "right")
						break

			if not all(x == x_axis_units[-1] for x in x_axis_units):
				for unit, data in zip(x_axis_units, comparison_datasets): 
					if not unit == x_axis_units[-1]:
						figure_obj.extra_x_ranges =  {"bar": Range1d(start = np.amin(data["x"]),
						end = np.amax(data["x"]))}
						figure_obj.add_layout(LinearAxis(x_range_name = "bar", axis_label = unit), "above")
						break

			active_sources = []
			for data_dict, source_line_nested, attr_id, color_index  in zip(self.column(self.figure_data, 1), self.source_line,  self.attribute_ids,  colour_indices):

				for dataset, source_lis_coup, in zip(data_dict["data"], source_line_nested[0]):
					
					source_local = source_lis_coup[0]
					active_sources.append(source_local)

					self.source_test(source_local)
					self.source_dataset_test(source_local, dataset)

					if dataset["sample_element"] == comparison_element:
						color = colour_list[color_index]

						"""
						Logic that ensures that plots get put with correspoinding axes. 
						"""
						if dataset["x_unit"] != x_axis_units[-1] or dataset["y_unit"] != y_axis_units[-1]:

							if dataset["x_unit"] != x_axis_units[-1] and dataset["y_unit"] != y_axis_units[-1]:
								name_check = data_dict["gen_info"]["DATA FILES"]
								attr_id = name_check[1][4][:-3] + "_" + name_check[2][2]

								figure_obj.line("x", "y", source = source_local,
								line_width = 2, 
								line_color = color, 
								legend = attr_id,
								x_range_name = "bar", 
								y_range_name = "foo")

							elif dataset["x_unit"] != x_axis_units[-1]:

								figure_obj.line("x", "y", source = source_local,
								line_width = 2, 
								line_color = color, 
								legend = attr_id, 
								x_range_name = "bar")

							else: 

								figure_obj.line("x", "y", source = source_local,
								line_width = 2, 
								line_color = color, 
								legend = attr_id, 
								y_range_name = "foo")

						else: 
							figure_obj.line("x", "y", source = source_local,
							line_width = 2, 
							line_color = color, 
							legend = attr_id)


			matplot_button = Button(label = "Create matplotlib fig")
			save_all_flexDPE_button = Button(label = "Save all elements for FlexPDE")

			matplot_button.on_click(lambda source_list = active_sources:
							self.matplotlib_export(source_list))	

			save_all_flexDPE_button.on_click(lambda 
									source_list = active_sources, 
									attrname = comparison_element:
									self.write_all_to_flexPDE(source_list, attrname))


			tab_plots.append(Panel(child = hplot(figure_obj, vform(save_all_flexDPE_button, matplot_button)), 
				title = comparison_element))	


		tabs = Tabs(tabs = tab_plots)
		#curdoc().add_root(tabs)
		session = push_session(curdoc())
		session.show()
		session.loop_until_closed()
Exemplo n.º 31
0
    def create(self):
        manufacturers = sorted(mpg["manufacturer"].unique())
        models = sorted(mpg["model"].unique())
        transmissions = sorted(mpg["trans"].unique())
        drives = sorted(mpg["drv"].unique())
        classes = sorted(mpg["class"].unique())

        manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers)
        manufacturer_select.on_change('value', self.on_manufacturer_change)
        model_select = Select(title="Model:", value="All", options=["All"] + models)
        model_select.on_change('value', self.on_model_change)
        transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions)
        transmission_select.on_change('value', self.on_transmission_change)
        drive_select = Select(title="Drive:", value="All", options=["All"] + drives)
        drive_select.on_change('value', self.on_drive_change)
        class_select = Select(title="Class:", value="All", options=["All"] + classes)
        class_select.on_change('value', self.on_class_change)

        columns = [
            TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")),
            TableColumn(field="model",        title="Model",        editor=StringEditor(completions=models)),
            TableColumn(field="displ",        title="Displacement", editor=NumberEditor(step=0.1),              formatter=NumberFormatter(format="0.0")),
            TableColumn(field="year",         title="Year",         editor=IntEditor()),
            TableColumn(field="cyl",          title="Cylinders",    editor=IntEditor()),
            TableColumn(field="trans",        title="Transmission", editor=SelectEditor(options=transmissions)),
            TableColumn(field="drv",          title="Drive",        editor=SelectEditor(options=drives)),
            TableColumn(field="class",        title="Class",        editor=SelectEditor(options=classes)),
            TableColumn(field="cty",          title="City MPG",     editor=IntEditor()),
            TableColumn(field="hwy",          title="Highway MPG",  editor=IntEditor()),
        ]
        data_table = DataTable(source=self.source, columns=columns, editable=True)

        plot = Plot(title=None, x_range= DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300)

        # Set up x & y axis
        plot.add_layout(LinearAxis(), 'below')
        yaxis = LinearAxis()
        plot.add_layout(yaxis, 'left')
        plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

        # Add Glyphs
        cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5)
        hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5)
        cty = plot.add_glyph(self.source, cty_glyph)
        hwy = plot.add_glyph(self.source, hwy_glyph)

        # Add the tools
        tooltips = [
            ("Manufacturer", "@manufacturer"),
            ("Model", "@model"),
            ("Displacement", "@displ"),
            ("Year", "@year"),
            ("Cylinders", "@cyl"),
            ("Transmission", "@trans"),
            ("Drive", "@drv"),
            ("Class", "@class"),
        ]
        cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")])
        hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")])
        select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions=['width'])
        plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool)


        controls = vplot(manufacturer_select, model_select, transmission_select, drive_select, class_select)
        top_panel = hplot(controls, plot)
        layout = vplot(top_panel, data_table)

        return layout
Exemplo n.º 32
0
from bokeh.io import hplot, output_file, show
from bokeh.plotting import figure

output_file("layout.html")

x = list(range(11))
y0 = x
y1 = [10 - i for i in x]
y2 = [abs(i - 5) for i in x]

# create a new plot
s1 = figure(width=250, plot_height=250, title=None)
s1.circle(x, y0, size=10, color="navy", alpha=0.5)

# create another one
s2 = figure(width=250, height=250, title=None)
s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)

# create and another
s3 = figure(width=250, height=250, title=None)
s3.square(x, y2, size=10, color="olive", alpha=0.5)

# put all the plots in an HBox
p = hplot(s1, s2, s3)

# show the results
show(p)
Exemplo n.º 33
0
def nb_view_patches(Yr,
                    A,
                    C,
                    b,
                    f,
                    d1,
                    d2,
                    image_neurons=None,
                    thr=0.99,
                    denoised_color=None):
    '''
    Interactive plotting utility for ipython notbook

    Parameters
    -----------
    Yr: np.ndarray
        movie
    A,C,b,f: np.ndarrays
        outputs of matrix factorization algorithm

    d1,d2: floats
        dimensions of movie (x and y)

    image_neurons: np.ndarray
        image to be overlaid to neurons (for instance the average)

    thr: double
        threshold regulating the extent of the displayed patches

    denoised_color: string or None
        color name (e.g. 'red') or hex color code (e.g. '#F0027F')

    '''
    colormap = cm.get_cmap("jet")  # choose any matplotlib colormap here
    grayp = [mpl.colors.rgb2hex(m) for m in colormap(np.arange(colormap.N))]
    nr, T = C.shape
    nA2 = np.sum(np.array(A)**2, axis=0)
    b = np.squeeze(b)
    f = np.squeeze(f)
    #Y_r = np.array(spdiags(1/nA2,0,nr,nr)*(A.T*np.matrix(Yr-b[:,np.newaxis]*f[np.newaxis] - A.dot(C))) + C)
    Y_r = np.array(
        spdiags(old_div(1, nA2), 0, nr, nr) *
        (A.T * np.matrix(Yr) -
         (A.T * np.matrix(b[:, np.newaxis])) * np.matrix(f[np.newaxis]) -
         A.T.dot(A) * np.matrix(C)) + C)

    bpl.output_notebook()
    x = np.arange(T)
    z = old_div(np.squeeze(np.array(Y_r[:, :].T)), 100)
    k = np.reshape(np.array(A), (d1, d2, A.shape[1]), order='F')
    if image_neurons is None:
        image_neurons = np.nanmean(k, axis=2)

    fig = pl.figure()
    coors = plot_contours(coo_matrix(A), image_neurons, thr=thr)
    pl.close()
    #    cc=coors[0]['coordinates'];
    cc1 = [cor['coordinates'][:, 0] for cor in coors]
    cc2 = [cor['coordinates'][:, 1] for cor in coors]
    c1 = cc1[0]
    c2 = cc2[0]
    npoints = list(range(len(c1)))

    source = ColumnDataSource(data=dict(
        x=x, y=z[:, 0], y2=old_div(C[0], 100), z=z, z2=old_div(C.T, 100)))
    source2 = ColumnDataSource(
        data=dict(x=npoints, c1=c1, c2=c2, cc1=cc1, cc2=cc2))

    plot = bpl.figure(plot_width=600, plot_height=300)
    plot.line('x', 'y', source=source, line_width=1, line_alpha=0.6)
    if denoised_color is not None:
        plot.line('x',
                  'y2',
                  source=source,
                  line_width=1,
                  line_alpha=0.6,
                  color=denoised_color)

    callback = CustomJS(args=dict(source=source, source2=source2),
                        code="""
            var data = source.get('data');
            var f = cb_obj.get('value')-1
            x = data['x']
            y = data['y']
            y2 = data['y2']

            for (i = 0; i < x.length; i++) {
                y[i] = data['z'][i][f]
                y2[i] = data['z2'][i][f]
            }

            var data2 = source2.get('data');
            c1 = data2['c1'];
            c2 = data2['c2'];
            cc1 = data2['cc1'];
            cc2 = data2['cc2'];

            for (i = 0; i < c1.length; i++) {
                   c1[i] = cc1[f][i]
                   c2[i] = cc2[f][i]
            }
            source2.trigger('change');
            source.trigger('change');

        """)

    slider = bokeh.models.Slider(start=1,
                                 end=Y_r.shape[0],
                                 value=1,
                                 step=1,
                                 title="Neuron Number",
                                 callback=callback)
    xr = Range1d(start=0, end=image_neurons.shape[1])
    yr = Range1d(start=image_neurons.shape[0], end=0)
    plot1 = bpl.figure(x_range=xr, y_range=yr, plot_width=300, plot_height=300)

    plot1.image(image=[image_neurons[::-1, :]],
                x=0,
                y=image_neurons.shape[0],
                dw=d2,
                dh=d1,
                palette=grayp)
    plot1.patch('c1',
                'c2',
                alpha=0.6,
                color='purple',
                line_width=2,
                source=source2)

    layout = vform(slider, hplot(plot1, plot))

    bpl.show(layout)

    return Y_r
Exemplo n.º 34
0
from bokeh.io import hplot
from bokeh.plotting import figure

x = list(range(11))
y0 = x
y1 = [10 - i for i in x]
y2 = [abs(i - 5) for i in x]

# create a new plot
s1 = figure(width=250, plot_height=250, title=None)
s1.circle(x, y0, size=10, color="navy", alpha=0.5)

# create another one
s2 = figure(width=250, height=250, title=None)
s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)

# create and another
s3 = figure(width=250, height=250, title=None)
s3.square(x, y2, size=10, color="olive", alpha=0.5)

# put all the plots in a HBox
p = hplot(s1, s2, s3)

# show the results
# script, div = components(p)
Exemplo n.º 35
0
p21.xgrid.grid_line_color = None
p21.ygrid.grid_line_color = None

menu = [("U", "item_1"), ("V", "item_2"), ("B", "item_3"), ("R", "item_4")]
dropdown = Dropdown(label="U", menu=menu)
select = Select(value="U - U",
                options=[
                    "U - U", "U - B", "U - V", "U - R", "B - U", "B - B",
                    "B - V", "B - R", "V - U", "V - B", "V - V", "V - R",
                    "R - U", "R - B", "R - V", "R - R"
                ])

layout_p2 = vform(slider, p2)
layout_p22 = vform(select, p21)
layout1 = hplot(layout_p2, layout_p22)

tab2 = Panel(child=layout1, title="filters")

tab3 = Panel(child=p3, title="Detailed Plot")

#.........................................Transmission passbands........................
#ux_pass = np.arange(300,425,5)
#uy_pass = [0.00,0.016,0.068,0.167,0.287,0.423,0.560,0.673,0.772,0.841,0.905,0.943,0.981,0.993,1.000,0.989,0.916,0.804,0.625,0.423,0.238,0.114,0.051,0.019,0.000]

#bx_pass = np.arange(360,570,10)
#by_pass = [0.0,0.030,0.134,0.567,0.920,0.978,1.000,0.978,0.935,0.853,0.740,0.640,0.536,0.424,0.325,0.235,0.150,0.095,0.043,0.009,0.0]

#vx_pass = np.arange(470,710,10)
#vy_pass = [0.000,0.030,0.163,0.458,0.780,0.967,1.000,0.973,0.898,0.792,0.684,0.574,0.461,0.359,0.270,0.197,0.135,0.081,0.045,0.025,0.017,0.013,0.009,0.000]
Exemplo n.º 36
0
 def get_plot(self):
     return hplot(self.plot)
Exemplo n.º 37
0
def update():
    global layout
    global energy_per_capita

    new_df = data_changed(energy_per_capita)
    if new_df is not None:
        energy_per_capita = new_df
        layout.children[0] = create_line(energy_per_capita)
        layout.children[1] = create_bar(energy_per_capita)


line = create_line(energy_per_capita)
bar = create_bar(energy_per_capita)
desc1 = Paragraph(text="""
This example shows live integration between bokeh server and Excel using
XLWings.""")
desc2 = Paragraph(text="""
*** YOU MUST HAVE EXCEL and XLWINGS INSTALLED ON YOUR MACHINE FOR IT TO WORK ***
""")
desc3 = Paragraph(text="""
It opens this plots window and an excel spreadsheet instance with the
values being plotted. When user changes the values on the excel spreadsheet
the plots will be updated accordingly. It's not required to save the spreadsheet for the plots to update.
""")
layout = vplot(desc1, desc2, desc3, hplot(line, bar))
curdoc().add_root(layout)
curdoc().add_periodic_callback(update, 500)

session.show()  # open the document in a browser
session.loop_until_closed()  # run forever
Exemplo n.º 38
0
                  end=date(2004, 12, 31),
                  bounds=(date(2001, 1, 1), date(2006, 12, 31)))
y_range = Range1d(start=00, end=40, bounds=(10, 60))
y_range_extra = Range1d(start=300, end=700, bounds=(200, 1000))
###### -- end -- ########

plot_extra = figure(
    x_axis_type="datetime",
    x_range=x_range,
    y_range=y_range,
    title=
    "Multiple ranges x:(2001/1/1, 2006/12/31), y1:(10, 60), y2:(200, 1000)")
plot_extra.line(x, apple_y, color='lightblue')
plot_extra.extra_y_ranges = {'goog': y_range_extra}
plot_extra.line(x, google_y, color='pink', y_range_name='goog')
plot_extra.add_layout(
    LinearAxis(y_range_name="goog", major_label_text_color='pink'), 'left')

# Tweak the formats to make it all readable
plots = [
    plot_datarange, plot_range, plot_range_un, plot_range_rev,
    plot_cat_autobounded, plot_cat_unbounded, plot_cat_bounded, plot_extra
]
for plot in plots:
    plot.title_text_font_size = '12pt'

show(
    vplot(plot_datarange, hplot(plot_range, plot_range_un, plot_range_rev),
          hplot(plot_cat_autobounded, plot_cat_unbounded, plot_cat_bounded),
          plot_extra))
Exemplo n.º 39
0
    # r2.glyph.line_alpha = 1 - 0.8 * abs(step)
    global y1, y2, y3, y4, y5
    y1 = np.delete(y1, 0)
    y2 = np.delete(y2, 0)
    y3 = np.delete(y3, 0)
    y4 = np.delete(y4, 0)
    y5 = np.delete(y5, 0)

    read = pd.read_pickle('./feature_vector')
    y1 = np.append(y1, read.ent_ip_src)
    y2 = np.append(y2, read.ent_tp_src)
    y3 = np.append(y3, read.ent_tp_dst)
    y4 = np.append(y4, read.ent_packet_type)
    y5 = np.append(y5, read.total_packets)

    r1.data_source.data["y"] = y1
    r2.data_source.data["y"] = y2
    r3.data_source.data["y"] = y3
    r4.data_source.data["y"] = y4
    r5.data_source.data["y"] = y5
    # print "y1=",y1


curdoc().add_periodic_callback(update, 5000)  #millisecs
# grid = vplot([[p1, p2, p3], [p4, p5, None]])
# vertical = vplot(p1,p2,p3,p4,p5)
vertical = hplot(p, p5)
session.show()  # open the document in a browser

session.loop_until_closed()  # run forever
Exemplo n.º 40
0
    def initialize_plot(self, ranges=None):
        ranges = self.compute_ranges(self.layout, self.keys[-1], None)
        plots = [[] for i in range(self.rows)]
        passed_plots = []
        tab_titles = {}
        insert_rows, insert_cols = [], []
        adjoined = False
        for r, c in self.coords:
            subplot = self.subplots.get((r, c), None)
            if subplot is not None:
                shared_plots = passed_plots if self.shared_axes else None
                subplots = subplot.initialize_plot(ranges=ranges,
                                                   plots=shared_plots)

                # Computes plotting offsets depending on
                # number of adjoined plots
                offset = sum(r >= ir for ir in insert_rows)
                if len(subplots) > 2:
                    adjoined = True
                    # Add pad column in this position
                    insert_cols.append(c)
                    if r not in insert_rows:
                        # Insert and pad marginal row if none exists
                        plots.insert(r + offset,
                                     [None for _ in range(len(plots[r]))])
                        # Pad previous rows
                        for ir in range(r):
                            plots[ir].insert(c + 1, None)
                        # Add to row offset
                        insert_rows.append(r)
                        offset += 1
                    # Add top marginal
                    plots[r + offset - 1] += [subplots.pop(-1), None]
                elif len(subplots) > 1:
                    adjoined = True
                    # Add pad column in this position
                    insert_cols.append(c)
                    # Pad previous rows
                    for ir in range(r):
                        plots[r].insert(c + 1, None)
                    # Pad top marginal if one exists
                    if r in insert_rows:
                        plots[r + offset - 1] += 2 * [None]
                else:
                    # Pad top marginal if one exists
                    if r in insert_rows:
                        plots[r + offset - 1] += [None] * (1 +
                                                           (c in insert_cols))
                plots[r + offset] += subplots
                if len(subplots) == 1 and c in insert_cols:
                    plots[r + offset].append(None)
                passed_plots.append(subplots[0])

            if self.tabs:
                if isinstance(self.layout, Layout):
                    tab_titles[r, c] = ' '.join(self.paths[r, c])
                else:
                    dim_vals = zip(self.layout.kdims, self.paths[r, c])
                    tab_titles[r, c] = ', '.join(
                        [d.pprint_value_string(k) for d, k in dim_vals])

        # Replace None types with empty plots
        # to avoid bokeh bug
        if adjoined:
            plots = layout_padding(plots)

        # Determine the most appropriate composite plot type
        # If the object cannot be displayed in a single layout
        # it will be split into Tabs, for 1-row or 1-column
        # Layouts we use the vplot and hplots.
        # If there is a table and multiple rows and columns
        # everything will be forced to a vertical layout
        if self.tabs:
            panels = [
                Panel(child=child, title=tab_titles.get(r, c))
                for r, row in enumerate(plots) for c, child in enumerate(row)
                if child is not None
            ]
            layout_plot = Tabs(tabs=panels)
        elif len(plots) == 1 and not adjoined:
            layout_plot = vplot(hplot(*plots[0]))
        elif len(plots[0]) == 1:
            layout_plot = vplot(*[p[0] for p in plots])
        else:
            layout_plot = gridplot(plots)

        self.handles['plot'] = layout_plot
        self.handles['plots'] = plots
        self.drawn = True

        return self.handles['plot']
Exemplo n.º 41
0
    #for mytool in Tools:
    #	mytool.plot = figure_obj

    #figure_obj.tools = Tools

    figure_obj.line("x",
                    "y",
                    source=two[0],
                    line_width=2,
                    line_color=colour_list[3])
    figure_obj.line("x",
                    "y",
                    source=two[1],
                    line_width=2,
                    line_color=colour_list[1])

    text = TextInput(title="title", value='my sine wave')
    radio = RadioGroup(labels=["0", "1"], active=0)

    text.on_change('value',
                   lambda attr, old, new, radio=radio, sources=two:
                   update_title(new, radio, sources))

    tabs.append(
        Panel(child=hplot(figure_obj, vform(text, radio)), title="two by two"))

tabs = Tabs(tabs=tabs)
session = push_session(curdoc())
session.show()
session.loop_until_closed()
Exemplo n.º 42
0
 def getFigure(self):
     return hplot(self.figure, self.gaugefigure)
s3.hbar(y = [1,2,3], height=0.5, left = 0, right = stats_deaths, color="#CAB2D6")"""
#vertical_plot = vplot(p,s3)
s3.xaxis.axis_label = 'Estimated Number of Cases (1000)'
#s3.yaxis.axis_label = 'Cancer Type'
s3.title.text_font_size = "25px"

label_opts = dict(
    x=230, y=0,
        x_units='screen', y_units='screen'
        )

msg1 = '(Based on Developed and under developed Region)'                                                   #Subtitle addition hack as it is not supported adding through label for plot: mortality and new cases for breast cancer plot.        
caption1 = Label(text =msg1, **label_opts)
s3.add_layout(caption1, "above")

p = hplot(s1,vplot(s2,s3))

"""p.legend.label_text_font = "times"
p.legend.label_text_font_style = "italic"
p.legend.label_text_color = "navy"""
#show(vertical_plot)
show(p)



#plots = {'Average': s1, "Stages": s2}

#script, div = components(plots)

#print script
#print div
Exemplo n.º 44
0
def update():
    global layout
    global energy_per_capita

    new_df = data_changed(energy_per_capita)
    if new_df is not None:
        energy_per_capita = new_df
        plots_box.children[0] = create_line(energy_per_capita)
        plots_box.children[1] = create_bar(energy_per_capita)

line = create_line(energy_per_capita)
bar = create_bar(energy_per_capita)
desc1 = Paragraph(text="""
This example shows live integration between bokeh server and Excel using
XLWings.""")
desc2 = Paragraph(text="""
*** YOU MUST HAVE EXCEL and XLWINGS INSTALLED ON YOUR MACHINE FOR IT TO WORK ***
""")
desc3 = Paragraph(text="""
It opens this plots window and an excel spreadsheet instance with the
values being plotted. When user changes the values on the excel spreadsheet
the plots will be updated accordingly. It's not required to save the spreadsheet for the plots to update.
""")
plots_box = hplot(line, bar)
layout = vplot(desc1, desc2, desc3, plots_box)
curdoc().add_root(layout)
curdoc().add_periodic_callback(update, 500)

session.show() # open the document in a browser
session.loop_until_closed() # run forever
Exemplo n.º 45
0
def plot():
    name = request.args.get('name')
    items = request.args.get('items')
    #print items
    # get webpage:
    web = 'https://www.quandl.com/api/v3/datatables/WIKI/PRICES.json?ticker=' + name + '&qopts.columns=date' + items + '&api_key=vE8zyFxDsKyf5NnGyDdC'
    #print web

    # get data
    r = requests.get(web)
    jdata = simplejson.dumps(r.json())
    datadict = simplejson.loads(jdata)['datatable']

    #get column names
    names = []
    for i in range(len(datadict['columns'])):
        names.append(datadict['columns'][i]['name'])

    # convert to dataframe
    df = pd.DataFrame(datadict['data'], columns=names)

    #print df['close']
    #print df['adj_close']

    #print df['close']
    # check if the post request has the file part
    #name = request.args.get('name')
    #df = request.files['file']
    #df = pd.DataFrame(df)
    #print list(df)
    #print df['date']

    def datetime(x):
        return np.array(x, dtype=np.datetime64)

    #p1 = figure(x_axis_type="datetime", title="")
    #p1.grid.grid_line_alpha=0.3
    #p1.xaxis.axis_label = 'Date'
    #p1.yaxis.axis_label = 'Price'

    colors = ['#A6CEE3', '#B2DF8A', '#33A02C', '#FB9A99']

    plots = [None] * (len(list(df)) - 1)

    for i in range(1, len(list(df))):
        plots[i - 1] = figure(x_axis_type="datetime", title=list(df)[i])

        plots[i - 1].grid.grid_line_alpha = 0.1
        plots[i - 1].xaxis.axis_label = 'Date'
        plots[i - 1].yaxis.axis_label = 'Price'

        y = df[list(df)[i]]
        #print y
        x = df['date']
        #print df['date']

        plots[i - 1].line(datetime(x),
                          y,
                          color=colors[i - 1],
                          legend=list(df)[i])

    p = hplot(*plots)

    #p1.line(datetime(df['date']), df['close'])

    #p1.legend.location = "top_left"

    #window_size = 30

    script, div = components(p)

    return encode_utf8(
        render_template("plot.html", name=name, script=script, div=div))
Exemplo n.º 46
0
    data1 = source1.get('data')
    f = cb_obj.get('value')
    date = sorted(data1.keys())[f-1]
    r = data1[date]
    data1['radius'] = r
    source1.trigger('change')
    data2 = source2.get('data')
    r = data2[date]
    data2['radius'] = r
    source2.trigger('change')

slider = Slider(start=1, end=len(sorted(source1.data.keys())[:-4]), value=1, step=1, title="hour",
                callback=CustomJS.from_py_func(callback),
                orientation='horizontal')

layout = hplot(plot1, plot2)
layout = vform(layout, slider)

show(layout)
save(layout, 'HourlyTripsOneDay.html')

df_StartCount = df.loc[:, ['start station id', 'starttime']]
df_StartCount['started trips'] = 1

df_StartCount = df_StartCount.groupby([pd.Grouper(freq='D', key='starttime'), 'start station id']).sum()
df_StartCount = df_StartCount.unstack(level=0)['started trips'].reset_index()
df_StartCount = pd.merge(lut_Start.reset_index(), df_StartCount.fillna(0))
df_StartCount['radius'] = df_StartCount.loc[:, pd.to_datetime(df_StartCount.columns[6])]
df_StartCount.columns = df_StartCount.columns.format()

radius_factor = 3
Exemplo n.º 47
0
# source = ColumnDataSource(row)
# columns = [
        # TableColumn(field="date", title="Dates", formatter=DateFormatter()),
        # TableColumn(field="cpm", title="CPM", formatter=NumberFormatter(format="$0.00")),
        # TableColumn(field="impressions", title="Impressions",formatter=NumberFormatter()),
        # TableColumn(field="sales_channel", title="Sales_channel"),
        # TableColumn(field="bins_cpm", title="bins_cpm")
        # ]
# data_table = DataTable(source=source, columns=columns, width=800, height=810)
# multi_select = MultiSelect(title="Option:", value=["foo", "quux"], options=["foo", "bar", "baz", "quux"])       
#dateRange = Instance(DateRangeSlider)
#dateRange = DateRangeSlider(title="Period:", name="period", value=(26-08-2015,18-09-2015), bounds=(26-08-2015,18-09-2015), range=(dict(days=1), None))
#slider = Slider(start=0, end=10, value=1, step=.1, title="eCPM_bins", orientation = "vertical")

curdoc().add_periodic_callback(update, 30)
session.show() # open the document in a browser
session.loop_until_closed() # run forever


output_file("figures.html")

s = vplot(hplot(p,slider),multi_select,data_table)
show(s)

# renderer = p.select(dict(name='bar'))
# ds = renderer[0].data_source

# while True:
	# slider(ds.data["cpm"])
	# #cursession().store_objects(ds)

## Plot with multiple ranges that are bounded
x = np.array(AAPL['date'], dtype=np.datetime64)
x = x[0:1000]
apple_y = AAPL['adj_close'][0:1000]
google_y = GOOG['adj_close'][0:1000]

###### -- ranges set here -- ########
x_range = Range1d(
    start=date(2000, 1, 1), end=date(2004, 12, 31),
    bounds=(date(2000, 1, 1), date(2006, 12, 31)),
    min_interval=timedelta(100),
)
y_range = Range1d(start=0, end=40, bounds=(0, 60))
y_range_extra = Range1d(start=300, end=700, bounds=(200, 1000))
###### -- end -- ########

plot_extra = figure(x_axis_type="datetime", x_range=x_range, y_range=y_range, title="Multiple ranges x:(2000/1/1, 2006/12/31), y1:(10, 60), y2:(200, 1000)")
plot_extra.line(x, apple_y, color='lightblue')
plot_extra.extra_y_ranges = {'goog': y_range_extra}
plot_extra.line(x, google_y, color='pink', y_range_name='goog')
plot_extra.add_layout(LinearAxis(y_range_name="goog", major_label_text_color='pink'), 'left')

# Tweak the formats to make it all readable
plots = [plot_default, plot_range, plot_range_un, plot_range_rev, plot_cat_autobounded, plot_cat_unbounded, plot_cat_bounded, plot_extra]
for plot in plots:
    plot.title_text_font_size = '12pt'

show(vplot(plot_default, hplot(plot_range, plot_range_un, plot_range_rev), hplot(plot_cat_unbounded, plot_cat_autobounded, plot_cat_bounded), plot_extra))
Exemplo n.º 49
0
 temp_bar_2 = temp_graph[['third_less_adv', 'abs_third_less_adv_simple', 'abs_third_less_adv']].mean()
 temp_bar_2 = temp_bar_2.reset_index()
 temp_bar_2 = temp_bar_2.rename(columns = {0:'values'})
 p2_2 = figure(width=500, height=800, x_range=['Third less adv', 'Abs third less adv', 'Agg abs third less adv'], title= "Third less advanced")
 p2_2.quad(top=temp_bar_2['values'], bottom=0, left=['Third less adv', 'Abs third less adv', 'Agg abs third less adv'], right=['Third less adv', 'Abs third less adv', 'Agg abs third less adv'], line_width=100, color=["red","yellow","magenta"]) 
 #p2.text([.5, 2.5], [.5, .5], text=['Yes', 'No'], text_font_size="20pt", text_align='center')
 
 #p2.xgrid.grid_line_color = None
 #p2.ygrid.grid_line_color = None
 p2_2.yaxis.minor_tick_line_color = None
 p2_2.xaxis.minor_tick_line_color = None
 #added these two lines
 p2_2.y_range.start = 0
 p2_2.y_range.end = temp_bar['values'].max()*1.1
 
 p2 = hplot(p2_1, p2_2)    
 
 
 
 ''' temp_bar = temp_graph[['third_less_adv', 'abs_third_less_adv_simple', 'abs_third_less_adv']].mean()
 temp_bar = temp_bar.reset_index()
 temp_bar = temp_bar.rename(columns = {0:'values'})
 p2 = figure(width=800, height=800, x_range=['Third less adv', 'Absolute third less adv', 'Agg absolute third less adv'], title= "Different estimates of " + temp_graph['category'].iloc[0])
 p2.quad(top=temp_bar['values'], bottom=0, left=['Third less adv', 'Absolute(third less adv)', 'Agg: absolute(third less adv)'], right=['Third less adv', 'Absolute(third less adv)', 'Agg: absolute(third less adv)'], line_width=100, color=["blue","green","red"]) 
 #p2.text([.5, 2.5], [.5, .5], text=['Yes', 'No'], text_font_size="20pt", text_align='center')
 
 #p2.xgrid.grid_line_color = None
 #p2.ygrid.grid_line_color = None
 p2.yaxis.minor_tick_line_color = None
 p2.xaxis.minor_tick_line_color = None
 #added these two lines