Пример #1
0
def make_sidebar():
    global sidebar, master_selector
    master_selector = Select(title="MASTOR SELECTOR:", value="test", options=["test", 'sandbox', 'template', "timeseries", "mdr_history"])
    def selector_func(attrname, old, new):
        new_master_plot( master_selector.value )
    master_selector.on_change('value', selector_func )
    sidebar = vform(master_selector)
def empty_plot():
    p = figure(
        tools="hover,wheel_zoom,reset",
        width=FIGURE_WIDTH,
        responsive=True,
        tags=["clusterPlot"],
    )

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(LassoSelectTool(select_every_mousemove=False))

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    but_relevant = Button(label="Relevant", type="success")
    but_irrelevant = Button(label="Irrelevant", type="success")
    but_neutral = Button(label="Neutral", type="success")
    custom_tag_input = TextInput(value="Add custom tag...")
    custom_tag_select = Select(value="Custom tags", options=["Custom tags"])
    but_backward_crawl = Button(label="Backlinks", type="success")
    but_forward_crawl = Button(label="Forwardlinks", type="success")
    
    tags = hplot(custom_tag_input, custom_tag_select, but_relevant, but_irrelevant, but_neutral)
    tags_crawl = hplot(but_backward_crawl, but_forward_crawl)
    layout = vform(p, tags, tags_crawl)

    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
Пример #3
0
 def start(self):
     c = self.last_report()
     b = [i for sub in c for i in sub]
     graph = vform(*b)
     s = '../Report' + '/' + 'report_%s.html' % self.build[0].replace('.', '_')
     output_file(s, title=self.build[0] + '-' + self.devicename[0] + 'Report')
     return show(graph)
Пример #4
0
def timeplot(data):
    #input data is a DataFrame
    time = pd.DatetimeIndex(data['ltime'])
    #String list to store column names from the third column of the dataframe
    columns = []
    for x in data.columns[1:]:
        columns.append(x)
    #change string to float in the data
    for x in columns[0:(len(columns) - 2)]:
        if (type(data[x][0]) is str):
            for i in range(len(data[x])):
                data[x][i] = float(data[x][i].replace(',', ''))
    output_notebook()
    y = data[columns[1]]
    x = time
    p = Figure(x_axis_type='datetime', title="TimeSeries Plotting")

    source = ColumnDataSource(data=dict(x=x, y=y, d=data))
    #create a new columndatasoure to pass column name to CustomJS
    source2 = ColumnDataSource(data=dict(columns=columns))

    p.line('x', 'y', source=source)
    p.xaxis.axis_label = "Time"
    p.yaxis.axis_label = "Selected Y"
    callback = CustomJS(args=dict(source=source, columns=source2),
                        code="""
				var data = source.get('data');
				var columns = columns.get('data')['columns'];
				var f = cb_obj.get('value');
				y = data['y'];
				console.log('y');
				console.log(y);
				var d = data['d'];
				//get the index of the chosen column from the widget

				for(i = 0; i<columns.length;i++){
					if(f[0]==columns[i]){
					index = i;
					}
				}
				//make the column transpose since the CustomJS
				//takes dataframe as an array of arrays which is 
				//a row of the DataFrame
				for (i = 0; i < d.length; i++) {
					y[i] = d[i][index+1];
				}
				console.log('y');
				console.log(y.length);
				source.trigger('change');
				""")

    select = MultiSelect(title="Y_Option:",
                         value=[columns[0]],
                         options=columns,
                         callback=callback)
    layout = vform(select, p)
    show(layout)
Пример #5
0
 def start(self):
     c = self.last_report()
     b = [i for sub in c for i in sub]
     graph = vform(*b)
     s = '../Report' + '/' + 'report_%s.html' % self.build[0].replace(
         '.', '_')
     output_file(s,
                 title=self.build[0] + '-' + self.devicename[0] + 'Report')
     return show(graph)
Пример #6
0
def plotDayOfWeekTimeline(fileName, initData, bokehPlaceholderId='bokehContent'):    

    source = ColumnDataSource(data=initData)
    selectDOW = Select(title="Days:", value="Monday", options=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
    selectUT = Select(title="User Type:", value="All", options=["All", "Subscriber", "Customer"])
    model = dict(source=source, select_dow = selectDOW, select_ut = selectUT)
    plot = Figure(plot_width=1200, plot_height=400, x_axis_type="datetime")
    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
    
    callback = CustomJS(args=model, code="""
          var dayOfWeek = select_dow.get('value')
            var userType = select_ut.get('value')
            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['x'] = temp;
                        data['y'] = result.y;
                        source.trigger('change');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {dow:dayOfWeek, ut:userType};
        url = "/select?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)
        
    selectDOW.callback = callback
    selectUT.callback = callback
    layout = vform(selectDOW, selectUT, plot)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
    
    
Пример #7
0
def timeplot(data):
	#input data is a DataFrame
	time = pd.DatetimeIndex(data['ltime'])
	#String list to store column names from the third column of the dataframe
	columns = []
	for x in data.columns[1:]:
		columns.append(x)
	#change string to float in the data 
	for x in columns[0:(len(columns)-2)]:
		if (type(data[x][0]) is str):
			for i in range(len(data[x])):
				data[x][i] = float(data[x][i].replace(',',''))
	output_notebook()
	y = data[columns[1]]
	x = time
	p = Figure(x_axis_type = 'datetime', title = "TimeSeries Plotting")
	
	source = ColumnDataSource(data=dict(x=x, y=y, d=data))
	#create a new columndatasoure to pass column name to CustomJS
	source2 = ColumnDataSource(data = dict(columns = columns))

	p.line('x', 'y', source = source)
	p.xaxis.axis_label = "Time"
	p.yaxis.axis_label = "Selected Y"
	callback = CustomJS(args = dict(source = source, columns=source2), code="""
				var data = source.get('data');
				var columns = columns.get('data')['columns'];
				var f = cb_obj.get('value');
				y = data['y'];
				console.log('y');
				console.log(y);
				var d = data['d'];
				//get the index of the chosen column from the widget

				for(i = 0; i<columns.length;i++){
					if(f[0]==columns[i]){
					index = i;
					}
				}
				//make the column transpose since the CustomJS
				//takes dataframe as an array of arrays which is 
				//a row of the DataFrame
				for (i = 0; i < d.length; i++) {
					y[i] = d[i][index+1];
				}
				console.log('y');
				console.log(y.length);
				source.trigger('change');
				""")
	
	select = MultiSelect(title="Y_Option:", value=[columns[0]],
							options=columns, callback=callback)
	layout = vform(select, p)
	show(layout)
Пример #8
0
Файл: gui.py Проект: YDnepr/asda
def plotPairs(fileName, bokehPlaceholderId='bokehContent'):    

    source = ColumnDataSource(data={'count':[], 'index':[]})
    minCount = TextInput(value="20", title="Minimum number of trips per pair:")
    checkbox_group = CheckboxGroup(labels=["Include trips from a station to itself."])
    ShowButton = Toggle(label="Show", type="success")
    model = dict(source=source, checkbox = checkbox_group, minCount = minCount)
    plot = Figure(title="Accumulative Number Of Trips Over Top Station Pairs", x_axis_label='Top Station Pairs in Decreasing Order', y_axis_label='Accumulative Number of Trips', plot_width=1200, plot_height=400)
    plot.ray(x = [0], y=[90], line_color='red', angle=0.0, name='90%', length = 0, line_width=2)
    plot.ray(x = [0], y=[90], line_color='red', angle=180.0, angle_units = 'deg', length = 0, line_width=2)
    plot.line(x = 'index', y ='count', source=source, line_width=2, line_alpha=0.6)
    
    callback = CustomJS(args=model, code="""
            var selectSelf = checkbox.get('active').length;
            var minCountVal = minCount.get('value');
            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);
                        
                        data['count'] = result.count;
                        data['index'] = result.index;
                        source.trigger('change');
                        alert('triggered');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {self:selectSelf, min:minCountVal};
        url = "/pairsdist?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)
        
    ShowButton.callback = callback
    layout = vform(checkbox_group, minCount, ShowButton, plot)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
Пример #9
0
	def __init__(self, local_ip='n/a', public_ip='n/a', arp = []):

		# Set palette of colors for n vlans 
		palette = [
		"#004529", "#006837", "#238443", "#41ab5d", "#78c679", "#addd8e", 
		"#d9f0a3", "#f7fcb9", "#ffffe5","#084081", "#0868ac", "#2b8cbe", "#4eb3d3", "#7bccc4", 
		"#a8ddb5", "#ccebc5", "#e0f3db", "#f7fcf0","#4d004b", "#810f7c", "#88419d", "#8c6bb1",
		"#EFEFEF","#CFCFCF","#5F5F5F","#000000", "#8c96c6", "#9ebcda", "#bfd3e6", "#e0ecf4", 
		"#f7fcfd","#fff7fb", "#ece2f0", "#d0d1e6", "#a6bddb", "#67a9cf", "#3690c0", "#02818a", 
		"#016c59", "#014636","#67001f", "#980043", "#ce1256","#e7298a", "#df65b0", "#c994c7", 
		"#d4b9da", "#e7e1ef", "#f7f4f9", "#fff7ec", "#fee8c8", "#fdd49e", "#fdbb84", "#fc8d59", 
		"#ef6548", "#d7301f", "#b30000", "#7f0000"
		]
		try:
		    import pandas as pd
		except ImportError as e:
		    raise RuntimeError("Data requires pandas (http://pandas.pydata.org) to be installed")

		data = pd.read_csv(join(dirname(__file__), "vlan.csv"))
		# pandas magic
		df = data[data.columns[:-1]]
		df2 = df.set_index(df[df.columns[0]].astype(str))
		df2.drop(df.columns[0], axis=1, inplace=True)
		df3 = df2.transpose()
		output_file("output/switch.html", title = 'vlan map')
		# text_input = TextInput(value="VLAN NAME", title="Make Vlan:", callback= )

		# Make Heapmap
		hm = HeatMap(df3, title="VLANs", width=950, palette=palette)

		# Make Ip/Arp Table		
		x = [ 'Local', 'Public']
		y = [ local_ip,public_ip]
		for i in arp:
			valueX = i[1].strip().strip("()")
			valueY = i[0].strip().strip("()")			
			x.append(valueX)
			y.append(valueY)
		data = dict(
		    sourceCol=x,
		    ipCol=y,
		)
		source = ColumnDataSource(data)
		columns = [
		    TableColumn(field="sourceCol", title="Source"),
		    TableColumn(field="ipCol", title="IP Address"),
		]

		data_table = DataTable(source=source, columns=columns, width=650, height=450)
		p = vform(hm,data_table)
		show(p)
Пример #10
0
def my_link(s1):
    ex = db.get_data(fname=s1)[0]
    # patterns = []
    # for foot in range(2):
    #     for st in ex.steps_annotation[foot]:
    #           if st[1]-st[0] < 30:
    #               continue
    #     patterns += [Pattern(dict(coord='RY', l_pat=st[1]-st[0],
    #                                       foot='right' if foot else 'left'),
    #                                  ex.data_sensor[6*foot+4, st[0]:st[1]])]
    #     patterns += [Pattern(dict(coord='AZ', l_pat=st[1]-st[0],
    #                                       foot='right' if foot else 'left'),
    #                                  ex.data_sensor[6*foot+2, st[0]:st[1]])]
    #     patterns += [Pattern(dict(coord='AV', l_pat=st[1]-st[0],
    #                                       foot='right' if foot else 'left'),
    #                                  ex.data_earth[6*foot+2, st[0]:st[1]])]
    # stepDet = StepDetection(patterns=patterns, lmbd=.8, mu=.1)
    # steps, steps_label = stepDet.compute_steps(ex)
    # print('steps: ',steps)


    seg = ex.seg_annotation
    print('segm: ',seg)
    print(ex.DAZ[0][seg[1]:seg[2]].T)

    T = len(ex.DAZ[0][seg[0]:seg[1]])
    t = np.arange(T)/100
    plot = figure(width=350, plot_height=250, title="Aller")
    plot.line(t,ex.DAZ[0][seg[0]:seg[1]])

    T = len(ex.DAZ[0][seg[1]:seg[2]])
    t = np.arange(T)/100
    plot1 = figure(width=350, plot_height=250, title="u-Turn")
    plot1.line(t,ex.DAZ[0][seg[1]:seg[2]])

    T = len(ex.DAZ[0][seg[2]:seg[3]])
    t = np.arange(T)/100
    plot2 = figure(width=350, plot_height=250, title="Return")
    plot2.line(t,ex.DAZ[0][seg[2]:seg[3]])

    p = hplot(plot, plot1, plot2)

    tab1 = Panel(child=p, title="Segmentation")

    tabs = Tabs(tabs=[tab1])
    text_input = TextInput(value=ex.fname, title="Enregistrement: ")
    layout = vform(text_input, tabs)
    html = file_html(layout, CDN, "home2")
    return html
Пример #11
0
def empty_plot():
    p = figure(
        tools="hover,wheel_zoom,reset",
        width=FIGURE_WIDTH,
        height=FIGURE_HEIGHT,
        responsive=True,
        tags=["clusterPlot"],
        min_border_bottom=MIN_BORDER_BOTTOM,
        min_border_top=MIN_BORDER_TOP,
        min_border_left=MIN_BORDER_LEFT,
        min_border_right=MIN_BORDER_RIGHT,
    )

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(LassoSelectTool(select_every_mousemove=False))

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    but_relevant = Button(label="Relevant", type="success")
    but_irrelevant = Button(label="Irrelevant", type="success")
    but_neutral = Button(label="Neutral", type="success")
    custom_tag_input = TextInput(value="Add custom tag...")
    custom_tag_select = Select(value="Custom tags", options=["Custom tags"])
    but_backward_crawl = Button(label="Backlinks", type="success")
    but_forward_crawl = Button(label="Forwardlinks", type="success")

    tags = hplot(but_relevant,
                 but_irrelevant,
                 but_neutral,
                 custom_tag_input,
                 custom_tag_select,
                 height=40)
    tags_crawl = hplot(but_backward_crawl, but_forward_crawl)
    layout = vform(p, tags, tags_crawl)

    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
    def _table(self, source):
        """The table of replacement dates and segment positions.

        Params:
        -------
        source : pandas.DataFrame
            Data source.

        Returns:
        --------
        bokeh.plotting.Figure
            Table of replacement dates and segment positions.
        """
        columns = [
            TableColumn(field='ReplacementDate', title='Installation Date', formatter=DateFormatter(format='d M yy')),
            TableColumn(field='SegmentPosition', title='Segment'),
            TableColumn(field='DaysSinceReplacement', title='Days Since Installation')
        ]

        return vform(DataTable(source=source, columns=columns, row_headers=False, width=400, height=1000))
Пример #13
0
def empty_plot():
    p = figure(tools="hover", height=FIGURE_HEIGHT,
            toolbar_location=None, responsive=True)

    # Ensure that the lasso only selects with mouseup, not mousemove.
    p.add_tools(LassoSelectTool(select_every_mousemove=False))

    # These turn off the x/y axis ticks
    p.axis.visible = None

    # These turn the major grid off
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Plot non-selected circles with a particular style using CIRCLE_SIZE and
    # 'color' list
    button1 = Button(label="Relevant", type="success")
    button2 = Button(label="Irrelevant", type="success")
    button3 = Button(label="Neutral", type="success")
    layout = vform(p, button1, button2, button3)

    # Combine script and div into a single string.
    plot_code = components(layout)
    return plot_code[0] + plot_code[1]
Пример #14
0
                       y='y',
                       width=1,
                       height=10,
                       color='crcolor',
                       source=crsource)

# set up hover tool to show color hex code and sample swatch
p2.select_one(HoverTool).tooltips = [('color',
                                      '$color[hex, rgb, swatch]:crcolor'),
                                     ('RGB levels', '@RGBs')]

# theme everything for a cleaner look
curdoc().theme = Theme(json=yaml.load("""
attrs:
    Plot:
        toolbar_location: null
    Grid:
        grid_line_color: null
    Axis:
        axis_line_color: null
        major_label_text_color: null
        major_tick_line_color: null
        minor_tick_line_color: null
"""))

layout = hplot(vform(red_slider, green_slider, blue_slider), vform(p1, p2))

output_file("color_sliders.html")

show(layout)
    var area = b*b*slope/2-a*a*slope/2;
    area = ['Area is: ' + area.toFixed(3)];
    data['area'] = area;
    
    source.trigger('change');
"""    )

slidera = Slider(start=-10, end=1, value=-5, step=.1,
                title="a", callback=callbacka)
sliderb = Slider(start=1, end=10, value=5, step=.1,
                title="b", callback=callbackb)

slider = Slider(start=-5, end=5, value=1, step=.1,
                title="Slope", callback=callback)

layout = vform(slidera,sliderb,slider,plot)
save(layout)

script, div = components(layout, CDN)

with open('lineplotab.js','w') as f:
    f.write(script)

#now fix for what we want

with open('lineplotab.js','r') as f:
    in_data = f.readlines()

with open('lineplotab.js','w') as f:
    for i in in_data[1:-1]:
        f.write(i)
x = np.linspace(-20,20,100)
y = myfunc(x)

plot = figure(y_range=(-5, 5),title = 'sin(x) + x/8', x_range=(-1,10), plot_width=750, plot_height=400)

plot.toolbar_location = None


plot.line(x, y, line_width=3, line_alpha=1,color = 'orange')
plot.xaxis.axis_label = 'x'
plot.yaxis.axis_label = 'f(x)'




layout = vform(plot)
save(layout)

script, div = components(layout, CDN)

with open('sinplot.js','w') as f:
    f.write(script)

#now fix for what we want

with open('sinplot.js','r') as f:
    in_data = f.readlines()

with open('sinplot.js','w') as f:
    for i in in_data[1:-1]:
        f.write(i)
Пример #17
0
freq_slider = Slider(start=0.1,
                     end=10,
                     value=1,
                     step=.1,
                     title="Frequency",
                     callback=callback)
callback.args["freq"] = freq_slider

phase_slider = Slider(start=0,
                      end=6.4,
                      value=0,
                      step=.1,
                      title="Phase",
                      callback=callback)
callback.args["phase"] = phase_slider

offset_slider = Slider(start=-5,
                       end=5,
                       value=0,
                       step=.1,
                       title="Offset",
                       callback=callback)
callback.args["offset"] = offset_slider

layout = hplot(vform(amp_slider, freq_slider, phase_slider, offset_slider),
               plot)

output_file("slider.html")

show(layout)
Пример #18
0
def mann_only_interactive(data,
                          cut1,
                          cut2,
                          chrs_plot=None,
                          ms=6,
                          color_sequence=['#7fc97f', "#beaed4", '#fdc086']):
    '''
    Generate interactive dots.
    :param data:
    :param cut1:
    :param cut2:
    :param ms: Marker size. Default 6.
    :return:
    '''

    # Defining DataFrame for bokeh
    ts = DataFrame({
        'snp': data['snp'],
        'pos': data['pos'],
        'chr': data['chr'],
        'color': np.zeros(len(data), dtype='S20'),
        'abspos': data['pos'],
        'pval1': -np.log10(data['pval1']),
        'pval1_q': -np.log10(data['pval1_q']),
        'pval2': -np.log10(data['pval2']),
        'pval2_q': -np.log10(data['pval2_q'])
    })

    # Calculating proper positions

    if chrs_plot is None:
        chrs = np.unique(ts['chr'])
        if type(chrs[0]) == str:
            chrs = sorted_nicely(chrs)
        else:
            chrs.sort()
    else:
        chrs = chrs_plot

    print(chrs)

    temp_pos = 0
    xtixks_pos = np.zeros(len(chrs) + 1)
    print(chrs)
    for i in range(len(chrs)):
        # Can be optimized here
        temp = ts['abspos'][ts['chr'] == chrs[i]]
        if len(temp) > 0:
            temp = np.max(temp)
        else:
            temp = 1000
        print(temp)
        xtixks_pos[i + 1] = temp
        # temp_pos += temp
        # xtixks_pos[i+1] = temp_pos
        # ts['abspos'][ts['chr'] == chrs[i+1]] += temp_pos

    print(xtixks_pos)
    xtixks_pos = np.cumsum(xtixks_pos)
    print(xtixks_pos)

    for i in range(len(chrs)):
        ts['abspos'][ts['chr'] == chrs[i]] += xtixks_pos[i]

    print(xtixks_pos)
    xtixks_pos = (xtixks_pos[1:] + xtixks_pos[:-1]) / 2.0
    print(xtixks_pos)
    print(chrs)

    # Old color selection
    # for i in range(len(chrs)):
    #     if i % 2 == 0:
    #         ts['color'][ts['chr'] == chrs[i]] = '#FA8072'
    #     else:
    #         ts['color'][ts['chr'] == chrs[i]] = '#00BFFF'

    for i in range(len(chrs)):
        ts['color'][ts['chr'] == chrs[i]] = color_sequence[i %
                                                           len(color_sequence)]

    # Defining hover tools
    hover1 = HoverTool(tooltips=[
        ("chr", "@chr"),
        ("snp", "@snp"),
        ("pos", "@pos"),
        ("-log10(pval1,pval2)", "(@pval1, @pval2)"),
    ])
    hover2 = HoverTool(tooltips=[
        ("chr", "@chr"),
        ("snp", "@snp"),
        ("pos", "@pos"),
        ("-log10(pval1,pval2)", "(@pval1, @pval2)"),
    ])
    hoverq = HoverTool(tooltips=[
        ("chr", "@chr"),
        ("snp", "@snp"),
        ("pos", "@pos"),
        ("-log10(pval1,pval2)", "(@pval1, @pval2)"),
    ])
    tools1 = ['reset', 'xwheel_zoom', 'xpan', 'box_select', hover1]
    tools2 = ['reset', 'xwheel_zoom', 'xpan', 'box_select', hover2]
    toolsq = ['reset', 'wheel_zoom', 'pan', 'box_select', hoverq]

    source = ColumnDataSource(data=ts)
    #     original_source = ColumnDataSource(data=ts)

    source_filt = ColumnDataSource(
        data=dict(snp=[], pos=[], pval1=[], pval2=[]))

    source.callback = CustomJS(args=dict(source_filt=source_filt),
                               code="""
        var inds = cb_obj.get('selected')['1d'].indices;
        var d1 = cb_obj.get('data');
        var d2 = source_filt.get('data');
        d2['snp'] = []
        d2['pos'] = []
        d2['chr'] = []
        d2['pval1'] = []
        d2['pval2'] = []
        for (i = 0; i < inds.length; i++) {
            d2['snp'].push(d1['snp'][inds[i]])
            d2['pos'].push(d1['pos'][inds[i]])
            d2['chr'].push(d1['chr'][inds[i]])
            d2['pval1'].push(d1['pval1'][inds[i]])
            d2['pval2'].push(d1['pval2'][inds[i]])
        }
        source_filt.trigger('change');
       // data_table_filt.trigger('change');
        """)

    selection_glyph = Circle(fill_color='firebrick', line_color=None, size=ms)
    nonselection_glyph = Circle(fill_color='gray',
                                fill_alpha=0.1,
                                line_color=None,
                                size=ms)
    selection_glyph_2 = Square(fill_color='firebrick',
                               line_color=None,
                               size=ms)
    nonselection_glyph_2 = Square(fill_color='gray',
                                  fill_alpha=0.1,
                                  line_color=None,
                                  size=ms)

    upper_bound = np.ceil(
        np.max([np.max(ts['pval1']), np.max(ts['pval2'])]) + .51)

    p1 = figure(responsive=True,
                plot_width=900,
                plot_height=300,
                tools=tools1,
                x_range=[0, np.max(ts['abspos'])],
                y_range=[-0.12 * upper_bound, upper_bound],
                webgl=True)
    r1 = p1.circle('abspos',
                   'pval1',
                   source=source,
                   line_color=None,
                   color='color',
                   size=ms)
    r1.selection_glyph = selection_glyph
    r1.nonselection_glyph = nonselection_glyph
    p1.patch([0, np.max(ts['abspos']),
              np.max(ts['abspos']), 0],
             [0, 0, -np.log10(cut1), -np.log10(cut1)],
             alpha=0.5,
             line_color=None,
             fill_color='gray',
             line_width=2)

    p2 = figure(responsive=True,
                plot_width=900,
                plot_height=300,
                tools=tools2,
                x_range=p1.x_range,
                y_range=p1.y_range,
                webgl=True)
    r2 = p2.square('abspos',
                   'pval2',
                   source=source,
                   line_color=None,
                   color='color',
                   size=ms)
    r2.selection_glyph = selection_glyph_2
    r2.nonselection_glyph = nonselection_glyph_2
    p2.patch([0, np.max(ts['abspos']),
              np.max(ts['abspos']), 0],
             [0, 0, -np.log10(cut1), -np.log10(cut1)],
             alpha=0.5,
             line_color=None,
             fill_color='gray',
             line_width=2)

    pq1 = figure(responsive=True,
                 plot_width=400,
                 plot_height=400,
                 tools=toolsq,
                 webgl=True)
    pq1.line([0, 7], [0, 7],
             line_width=3,
             color="black",
             alpha=0.5,
             line_dash=[4, 4])
    rq1 = pq1.circle('pval1_q',
                     'pval1',
                     source=source,
                     line_color=None,
                     size=ms)
    #     err_x = -np.log10(np.concatenate([data['pval1_q'][:100], data['pval1_q'][100::-1]]))
    #     err_y = -np.log10(np.concatenate([data['pval1_q_top'][:100], data['pval1_q_bot'][100::-1]]))
    #     er1 = pq1.patch(err_x, err_y, alpha=0.2, color='blue')
    rq2 = pq1.square('pval2_q',
                     'pval2',
                     source=source,
                     line_color=None,
                     size=ms,
                     color="red")
    #     err_x = -np.log10(np.concatenate([data['pval2_q'][:100], data['pval2_q'][100::-1]]))
    #     err_y = -np.log10(np.concatenate([data['pval2_q_top'][:100], data['pval2_q_bot'][100::-1]]))
    #     er2 = pq1.patch(err_x, err_y, alpha=0.2, color='olive')
    rq1.selection_glyph = selection_glyph
    rq1.nonselection_glyph = nonselection_glyph
    rq2.selection_glyph = selection_glyph_2
    rq2.nonselection_glyph = nonselection_glyph_2

    # Labels for axes
    pq1.yaxis.axis_label = "Experimental quantiles, -log10(p)"
    pq1.xaxis.axis_label = "Theoretical quantiles, -log10(p)"
    p1.yaxis.axis_label = "-log10(p)"
    p1.xaxis.axis_label = "Chromosomes"
    p2.yaxis.axis_label = "-log10(p)"
    p2.xaxis.axis_label = "Chromosomes"
    p1.xgrid.grid_line_color = None
    p2.xgrid.grid_line_color = None

    # print(xtixks_pos)
    p1.xaxis[0].ticker = FixedTicker(ticks=[])
    p2.xaxis[0].ticker = FixedTicker(ticks=[])
    p1.text(xtixks_pos,
            xtixks_pos * 0 - 0.12 * upper_bound,
            [str(chrs[i]) for i in range(len(chrs))],
            text_align='center')
    p2.text(xtixks_pos,
            xtixks_pos * 0 - 0.12 * upper_bound,
            [str(chrs[i]) for i in range(len(chrs))],
            text_align='center')
    # p1.xaxis[0].ti

    columns = [
        TableColumn(field="chr", title="chr"),
        TableColumn(field="snp", title="snp"),
        TableColumn(field="pos", title="pos"),
        TableColumn(field="pval1", title="pval1"),
        TableColumn(field="pval2", title="pval2"),
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           width=300,
                           height=280)
    p3 = vform(data_table)

    data_table_filt = DataTable(source=source_filt,
                                columns=columns,
                                width=500,
                                height=500)
    p4 = vform(data_table_filt)

    return p1, p2, p3, p4, pq1
Пример #19
0
from bokeh.models.widgets import Div
from bokeh.io import output_file, show, vform

output_file("div.html")

div = Div(text="""Your <a href="https://en.wikipedia.org/wiki/HTML">HTML</a>-supported text is initialized with the <b>text</b> argument.  The
remaining div arguments are <b>width</b> and <b>height</b>. For this example, those values
are <i>200</i> and <i>100</i> respectively.""",
width=200, height=100)

show(vform(div))
Пример #20
0
def individual_stock(request, stock_id):

    stock1 = get_object_or_404(Stock, pk=stock_id)

    # Stock Information per Stock
    stock1.lastprice = ystockquote.get_price(stock1)
    stock1.volume = ystockquote.get_volume(stock1)
    price_change = ystockquote.get_change(stock1)
    market_cap = ystockquote.get_market_cap(stock1)
    get_high = ystockquote.get_52_week_high(stock1)
    get_low = ystockquote.get_52_week_low(stock1)
    pb_ratio = ystockquote.get_price_book_ratio(stock1)
    ebitda = ystockquote.get_ebitda(stock1)
    dividend = ystockquote.get_dividend_yield(stock1)

    # Graph

    # Last known weekday
    current_day = weekday().isoformat()

    # Retrieve live data YYYY-MM-DD
    historical_price = ystockquote.get_historical_prices(
        stock1, '2010-01-24', current_day)
    correct_order = sorted(historical_price)
    stock_prices = []
    dates = []
    for values in correct_order:
        stock_prices.append(historical_price[values]['Adj Close'])
        dates.append(values)

    # Convert to Float
    for p in range(len(stock_prices)):
        stock_prices[p] = float(stock_prices[p])

    # Convert to Datetime Format
    dates_objects = []
    for d in dates:
        dates_objects.append(datetime.strptime(d, '%Y-%m-%d'))

    source = ColumnDataSource(
        data=dict(x=dates_objects, y=stock_prices, time=dates))

    # Tools
    hover = HoverTool(tooltips=[
        ('Stock Price', '@y'),
        ('time', '@time'),
    ],
                      mode='vline')
    crosshair = CrosshairTool(dimensions=['height'])

    TOOLS = [hover, crosshair]

    plot = figure(x_axis_type="datetime",
                  responsive=True,
                  plot_height=250,
                  tools=TOOLS,
                  toolbar_location=None)
    plot.line('x', 'y', source=source)

    first_date = dates[0]
    last_date = dates[-1]

    callback = CustomJS(args=dict(x_range=plot.x_range),
                        code="""
                var start = cb_obj.get("value");
                x_range.set("start", start);
                x_range.set("end", start+2);
                """)

    slider = vform(
        Slider(start=0, end=100, title="Start Date", callback=callback))

    widget_script, widget_div = components(slider)
    script, div = components(plot)

    stock1.save()
    context = {
        'stock': stock1,
        'hprice': stock_prices,
        'widget_script': widget_script,
        'widget_div': widget_div,
        'the_script': script,
        'the_div': div,
        'thedate': dates_objects,
        'dates': dates
    }

    return render(request, 'stocktracker/individual.html', context)
Пример #21
0
    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }

    para.set('text', "Slider Values\\n\\n  Slider 1: {0}\\n  Slider 2: {1}\\n  Slider 3: {2}".format(s1, s2, s3))
""")

para = PreText(text = "Slider Values:\n\n  Slider 1: 0\n  Slider 2: 0\n  Slider 3: 0", width = 200, height = 150)

s1 = Slider(title="Slider 1 (Continuous)", start=0, end=1000, value=0, step=1, callback=callback, callback_policy="continuous")
s2 = Slider(title="Slider 2 (Throttle)", start=0, end=1000, value=0, step=1, callback=callback, callback_policy="throttle", callback_throttle=2000)
s3 = Slider(title="Slider 3 (Mouse Up)", start=0, end=1000, value=0, step=1, callback=callback, callback_policy="mouseup")

callback.args['para'] = para
callback.args['slider1'] = s1
callback.args['slider2'] = s2
callback.args['slider3'] = s3

output_file('slider_callback_policy.html')

show(vform(s1, s2, s3, para))
Пример #22
0
from bokeh.io import vform
from bokeh.models import CustomJS, ColumnDataSource, Slider
from bokeh.plotting import Figure, output_file, show

output_file("callback.html")

x = [x*0.005 for x in range(0, 200)]
y = x

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

plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

def callback(source=source):
    data = source.get('data')
    f = cb_obj.get('value')
    x, y = data['x'], data['y']
    for i in range(len(x)):
        y[i] = Math.pow(x[i], f)
    source.trigger('change')

slider = Slider(start=0.1, end=4, value=1, step=.1, title="power",
                callback=CustomJS.from_py_func(callback))

layout = vform(slider, plot)

show(layout)
Пример #23
0
    tau_re_s.value = opt_tau.real / (2 * pi * fmax)
    tau_im_s.value = opt_tau.imag / (2 * pi * fmax)


for w in [tau_re_s, tau_im_s]:
    w.on_change('value', update_data1)
eps_s.on_change('value', update_data2)
frange_s.on_change('range', update_data2)
reset.on_click(click)

# Set up layouts and add to document
inputs_1 = widgetbox(tau_re_s, tau_im_s)
#inputs_2 = widgetbox(Nom_text, fmin_s, fmax_s, eps_s)
inputs_2 = widgetbox(frange_s, eps_s)
inputs_2 = widgetbox(frange_s, eps_s)
inputs_3 = vform(reset)
spacer_1 = Spacer(width=20, height=40)
spacer_2 = Spacer(width=20, height=40)
spacer_3 = Spacer(width=20, height=130)

div1 = Div(
    text=
    """<font size="4"><b>Seed parameter tau</b></font> <br> (relative w.r.t. f_max)""",
    width=300,
    height=30)
text1 = widgetbox(div1)

div2 = Div(text="""<font size="4"><b>Frequency range & damping</b></font>""",
           width=300,
           height=20)
text2 = widgetbox(div2)
Пример #24
0
from bokeh.models.widgets import Div
from bokeh.io import output_file, show, vform

output_file("div.html")

div = Div(
    text=
    """Your <a href="https://en.wikipedia.org/wiki/HTML">HTML</a>-supported text is initialized with the <b>text</b> argument.  The
remaining div arguments are <b>width</b> and <b>height</b>. For this example, those values
are <i>200</i> and <i>100</i> respectively.""",
    width=200,
    height=100)

show(vform(div))
Пример #25
0
from bokeh.models.widgets import RadioGroup
from bokeh.io import output_file, show, vform

output_file("radio_group.html")

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)

show(vform(radio_group))
Пример #26
0
  def create_html(self):
    self.reduce()
    temp = datetime.now()
    filename = temp.strftime("%y_%m_%d__%H_%M_%S_") + "{:0>6}".format(temp.microsecond) + ".html"
    output_file(self.directory_to_save + filename)
 
    current_position = ColumnDataSource(data={'num':[0]})
    flags = ColumnDataSource(data={'flag':[{'is_playing': False}]})
    text = ColumnDataSource(data=dict(score=['Score ' + self.all_bodies['score'][0]]))
    current_polyg = ColumnDataSource(data=self.all_bodies['rects_timesteps'][0])
    all_polyg = ColumnDataSource(data=self.all_bodies)
 
    current_circles = ColumnDataSource(data=self.all_bodies['circles_timesteps'][0])
    slider_callback = Callback(
        args=dict(
          current=current_polyg,
          current_circles=current_circles, 
          all_polyg=all_polyg,
          text=text,
          flags=flags,
          current_position=current_position
          ), 
        code="""
var num = cb_obj.get('value');
current_position.get('data')['num'][0] = num;
var flags_data = flags.get('data');
flags_data['flag']['is_playing'] = false;
flags.trigger('change');
current_position.trigger('change');
""" + self.js_code)
 
    slider = Slider(start=0, end=len(self.all_bodies['rects_timesteps']) - 1,
        value=0, step=1,
        title="Iteration number", callback=slider_callback)
    slider_id = '' + str(slider.vm_serialize()['id'])
 
    p = figure(
        plot_width=int(self.width), plot_height=int(self.height),
        x_range=(0, int(self.model_size['x'])), y_range=(0, int(self.model_size['y'])),
        title="Watch Here"
        )
 
    button_callback = Callback(
        args=dict(
          current=current_polyg,
          current_circles=current_circles, 
          all_polyg=all_polyg,
          text=text,
          flags=flags,
          current_position=current_position
          ), 
        code="""
console.log("Start");
var flags_data = flags.get('data');
var num = current_position.get('data')['num'][0]
var slider_id = '""" + slider_id + """'
var amount_of_iterations = """ + str(len(self.all_bodies['rects_timesteps'])) + """; 
if (!flags_data['flag']['is_playing']) {
  flags_data['flag']['is_playing'] = true
  intervalID = setInterval(function () {
  var flags_data = flags.get('data');
  is_playing = flags_data['flag']['is_playing']
    if (is_playing) {
      """ + self.js_code + """
      Bokeh.$('div #' + slider_id).val(Math.floor(num));
      Bokeh.$('div #' + slider_id + ' :first-child').css('left', num / (amount_of_iterations - 1) * 100 + '%')
      num += 1
    }
   
    if (num > (amount_of_iterations - 1) || !is_playing) {
      current_position.get('data')['num'][0] = num
      current_position.trigger('change')
      flags_data['flag']['is_playing'] = is_playing = false
      window.clearInterval(intervalID);
      console.log("Finally")
  }
  }, Math.floor(1000.0 / """ + str(self.start_settings.model_settings.hz / 10.0) + """ / """ + str((float(self.max_iteration) / self.len_before_redunction)) + """));
} else {
  flags_data['flag']['is_playing'] = false
}
flags.trigger('change')
return false;
""")
    button = Button(label="Play", type="success", callback=button_callback)
    ground = points_to_dictionary(self.start_settings.ground_settings.points,
        self.local_zero_point)
    p.line(ground['x'], ground['y'])
    p.patches('xs', 'ys', color='color', source=current_polyg)
    p.circle('x', 'y', radius='radius', color='color', source=current_circles)
    p.text(1, int(self.model_size['y']) - 3, text='score', alpha=5,
        text_font_size="15pt", text_baseline="middle", text_align="left",
        source=text)

    self.layout = vform(button, slider, p)
Пример #27
0
from bokeh.models.widgets import Paragraph
from bokeh.io import output_file, show, vform

output_file("div.html")

p = Paragraph(text="""Your text is initialized with the 'text' argument.  The
remaining Paragraph arguments are 'width' and 'height'. For this example, those values
are 200 and 100 respectively.""",
              width=200,
              height=100)

show(vform(p))
Пример #28
0
from bokeh.models.widgets import MultiSelect
from bokeh.io import output_file, show, vform

output_file("multi_select.html")

multi_select = MultiSelect(title="Option:",
                           value=["foo", "quux"],
                           options=["foo", "bar", "baz", "quux"])

show(vform(multi_select))
Пример #29
0
from bokeh.models.widgets import Toggle
from bokeh.io import output_file, show, vform

output_file("toggle.html")

toggle = Toggle(label="Foo", type="success")

show(vform(toggle))
Пример #30
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()
Пример #31
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
Пример #32
0
from bokeh.models.widgets import TextInput
from bokeh.io import output_file, show, vform

output_file("text_input.html")

text_input = TextInput(value="default", title="Label:")

show(vform(text_input))
Пример #33
0
    x = data['x']
    y = data['y']

    nickname = new Array();
    datetime = new Array();
    fgames = new Array();
    for (i = 0; i < data['dates'][f].length; i++) {
            nickname.push(data['dframe'][f])
            datetime.push(new Date(data['dates'][f][i]))
            fgames.push(data['first_games'][f])
        }
    data['nick'] = nickname
    data['x'] = data['dates'][f]
    data['y'] = data['players'][f]
    data['desc'] = data['list_uniq_heroes'][f]
    var date = new Date(data['dates'][f][0]);
    data['time'] = datetime
    data['since'] = fgames
    source.trigger('change');
""")

select = Select(title="Player:", value="None", options=[str(x)+ '\t' + dframe[0].unique()[x]
                                                        for x in range(0, len(players))], callback=select_callback)

# Задаём выходной файл:
output_file("dropdown.html", title="Зависимость числа героев от месяца")

layout = vform(select,  plot1)
show(layout)

Пример #34
0
              width=800)

    output_file('Respiration_DataQuality_of_' + str(ids[i]) + ".html",
                title="RIP_BAR_Plot")

    source = ColumnDataSource(data)

    columns = [
        TableColumn(field="Date", title="Date"),
        TableColumn(field="ACCEPTABLE", title="ACCEPTABLE(Hours)"),
        TableColumn(field="UNACCEPTABLE", title="UNACCEPTABLE(Hours)"),
        TableColumn(field="Total", title="Total(Hours)")
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           width=500,
                           height=400)

    show(hplot(bar, vform(data_table)))
    dataf['ACCEPTABLE'] = dataf['ACCEPTABLE'] + data['ACCEPTABLE']
    dataf['UNACCEPTABLE'] = dataf['UNACCEPTABLE'] + data['UNACCEPTABLE']
    dataf['Date'] = dataf['Date'] + data['Date']
    dataf['Total'] = dataf['Total'] + data['Total']
    dataf['ParticipantID'] = dataf['ParticipantID'] + [
        ids[i] for f in range(len(data['Total']))
    ]

df = pd.DataFrame(dataf)

df.to_csv('rip.csv', sep=',')
Пример #35
0
p.background_fill_color = 'black'
p.outline_line_color = None
p.grid.grid_line_color = None

# add a text renderer to out plot (no data yet)
r = p.text(x=[],
           y=[],
           text=[],
           text_color=[],
           text_font_size="20pt",
           text_baseline="middle",
           text_align="center")

session = push_session(curdoc())

data = dict(
    dates=[date(2014, 3, i + 1) for i in range(10)],
    downloads=[randint(0, 100) for i in range(10)],
)
source = ColumnDataSource(data)

columns = [
    TableColumn(field="dates", title="Date", formatter=DateFormatter()),
    TableColumn(field="downloads", title="Downloads"),
]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

curdoc().add_root(vform(data_table))

session.show()
Пример #36
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()
Пример #37
0
def individual_stock(request, stock_id):

    stock1 = get_object_or_404(Stock, pk=stock_id)

    # Stock Information per Stock
    #update(stock1)

    # Graph

    # Last known weekday
    current_day = weekday().isoformat()

    # Retrieve live data YYYY-MM-DD
    historical_price = ystockquote.get_historical_prices(stock1, '2010-01-24', current_day)
    correct_order = sorted(historical_price)
    stock_prices = []
    dates = []
    for values in correct_order:
        stock_prices.append(historical_price[values]['Adj Close'])
        dates.append(values)

    # Convert to Float
    for p in range(len(stock_prices)):
        stock_prices[p] = float(stock_prices[p])

    # Convert to Datetime Format
    dates_objects = []
    for d in dates:
        dates_objects.append(datetime.strptime(d,'%Y-%m-%d'))

    source = ColumnDataSource(data=dict(x=dates_objects,y=stock_prices, time=dates))

    # Tools
    hover = HoverTool(tooltips=[('Stock Price','@y'),('Date','@time'),], mode='vline')
    crosshair = CrosshairTool(dimensions=['height'])

    TOOLS = [BoxZoomTool(),hover, crosshair, PreviewSaveTool(), ResetTool()]

    plot = figure(x_axis_type="datetime", responsive = True ,plot_height=250, tools = TOOLS)
    plot.line('x','y',source=source)
    plot.border_fill = "whitesmoke"

    plot.grid.grid_line_alpha = 0.3
    plot.xaxis.axis_label = 'Date'
    plot.yaxis.axis_label = 'Price'

    #widget
    first_date = dates[0]
    last_date = dates[-1]

    callback = CustomJS(args=dict(x_range=plot.x_range), code="""
                var start = cb_obj.get("value");
                x_range.set("start", start);
                x_range.set("end", start+2);
                """)

    slider = vform(Slider(start=0, end=100, title="Start Date", callback=callback))

    #widget_script, widget_div = components(slider)
    script, div = components(plot)

    stock1.save()
    context = {'stock':stock1,
               'hprice': stock_prices,
               #'widget_script': widget_script,
               #'widget_div': widget_div,
               'the_script': script,
               'the_div':div,
               'thedate': dates_objects,
               'dates':dates
               }

    return render(request, 'stocktracker/individual.html', context)
Пример #38
0
from datetime import date
from random import randint

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

output_file("data_table.html")

data = dict(
    dates=[date(2014, 3, i + 1) for i in range(10)],
    downloads=[randint(0, 100) for i in range(10)],
)
source = ColumnDataSource(data)

columns = [
    TableColumn(field="dates", title="Date", formatter=DateFormatter()),
    TableColumn(field="downloads", title="Downloads"),
]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

show(vform(data_table))
from bokeh.models.widgets import CheckboxButtonGroup
from bokeh.io import output_file, show, vform

output_file("checkbox_button_group.html")

checkbox_button_group = CheckboxButtonGroup(
        labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])

show(vform(checkbox_button_group))
#    var d2 = s2.get('data');
#    d2['Time'] = [];
#    d2['operating'] = [];
#    d2['maintenance'] = [];
#    d2['repair'] = [];
#    d2['total'] = [];
#    for (i = 0; i < inds.length; i++) {
#        d2['Time'].push(d1['Time'][inds[i]]);
#        d2['operating'].push(d1['operating'][inds[i]]);
#        d2['maintenance'].push(d1['maintenance'][inds[i]]);
#        d2['repair'].push(d1['repair'][inds[i]]);
#        d2['total'].push(d1['total'][inds[i]]);
#    }
#    s2.trigger('change');
#""")

#display N table
columns = [
	TableColumn(field='Time', title='Time: click to update table'),
	TableColumn(field='operating', title='operating'),
	TableColumn(field='maintenance', title='maintenance'),
	TableColumn(field='repair', title='repair'),
	TableColumn(field='total', title='total'),
]
N_table = DataTable(source=s2, columns=columns, width=1000, height=300)

#export plot to html and return
plot_grid = vplot(dec_fig, earn_fig, rev_fig, motor_fig, vform(N_table))
show(plot_grid, browser=None)

Пример #41
0
from bokeh.models import Button
from bokeh.plotting import figure, gridplot
from bokeh.io import vform, output_file, show

output_file("3943.html")

w = 300
h = 150

fig1 = figure(width=w, height=h, tools=[])
fig1.circle(x=[0, 1, 3, 4], y=[10, 4, 1, 5])

fig2 = figure(width=w, height=h, tools=[])
fig2.circle(x=[0, 1, 3, 4], y=[10, 4, 1, 5])

fig3 = figure(width=w, height=h, tools=[])
fig3.circle(x=[0, 1, 3, 4], y=[10, 4, 1, 5])

fig4 = figure(width=w, height=h, tools=[])
fig4.circle(x=[0, 1, 3, 4], y=[10, 4, 1, 5])

grid = gridplot([[fig1, fig2], [fig3, fig4]])
button = Button(label="Click")

v = vform(button, grid)
show(v)
Пример #42
0
def individual_stock(request, stock_id):

    stock1 = get_object_or_404(Stock, pk=stock_id)

    # Stock Information per Stock
    stock1.lastprice = ystockquote.get_price(stock1)
    stock1.volume = ystockquote.get_volume(stock1)
    price_change = ystockquote.get_change(stock1)
    market_cap = ystockquote.get_market_cap(stock1)
    get_high = ystockquote.get_52_week_high(stock1)
    get_low = ystockquote.get_52_week_low(stock1)
    pb_ratio = ystockquote.get_price_book_ratio(stock1)
    ebitda = ystockquote.get_ebitda(stock1)
    dividend = ystockquote.get_dividend_yield(stock1)

    # Graph

    # Last known weekday
    current_day = weekday().isoformat()

    # Retrieve live data YYYY-MM-DD
    historical_price = ystockquote.get_historical_prices(stock1, '2010-01-24', current_day)
    correct_order = sorted(historical_price)
    stock_prices = []
    dates = []
    for values in correct_order:
        stock_prices.append(historical_price[values]['Adj Close'])
        dates.append(values)

    # Convert to Float
    for p in range(len(stock_prices)):
        stock_prices[p] = float(stock_prices[p])

    # Convert to Datetime Format
    dates_objects = []
    for d in dates:
        dates_objects.append(datetime.strptime(d,'%Y-%m-%d'))

    source = ColumnDataSource(data=dict(x=dates_objects,y=stock_prices, time=dates))

    # Tools
    hover = HoverTool(tooltips=[('Stock Price','@y'),('time','@time'),], mode='vline')
    crosshair = CrosshairTool(dimensions=['height'])

    TOOLS = [hover, crosshair]

    plot = figure(x_axis_type="datetime", responsive = True ,plot_height=250, tools = TOOLS, toolbar_location=None)
    plot.line('x','y',source=source)

    first_date = dates[0]
    last_date = dates[-1]

    callback = CustomJS(args=dict(x_range=plot.x_range), code="""
                var start = cb_obj.get("value");
                x_range.set("start", start);
                x_range.set("end", start+2);
                """)

    slider = vform(Slider(start=0, end=100, title="Start Date", callback=callback))

    widget_script, widget_div = components(slider)
    script, div = components(plot)

    stock1.save()
    context = {'stock':stock1,
               'hprice': stock_prices,
               'widget_script': widget_script,
               'widget_div': widget_div,
               'the_script': script,
               'the_div':div,
               'thedate': dates_objects,
               'dates':dates
               }

    return render(request, 'stocktracker/individual.html', context)
        data['leftR'].push(end - dx);
        data['topR'].push(myfunc(end));
        data['rightR'].push(end);
        end = end - dx;
        }
    
    
    source.trigger('change');
"""    )

slider = Slider(start=1, end=80, value=val, step=2,
                title="n", callback=callback)
 
grid = gridplot([[plotL,plotR],[plot,plotSum]])
grid.toolbar_location = None
layout = vform(slider,grid)

save(layout)

script, div = components(layout, CDN)

jsname = 'Riemann.js'
with open(jsname ,'w') as f:
    f.write(script)
    

#now fix for what we want

with open(jsname ,'r') as f:
    in_data = f.readlines()
Пример #44
0
            song_alpha[i] = f;
            voc_alpha[i]=f;
        }
        source_song.trigger('change');
        source_voc.trigger('change');
    """)
callback_size = CustomJS(args=dict(source_song=source_song,source_voc=source_voc), code="""
        var song_data = source_song.get('data');
        var voc_data = source_voc.get('data');
        var f = cb_obj.get('value');
        song_size = song_data['size'];
        sorv_song = song_data['SorV'];
        voc_size = voc_data['size'];
        sorv_voc = voc_data['SorV'];
        for (i=0;i<voc_size.length;i++){
            if(sorv_song[i]==1){
                song_size[i] = f;
            }
            if(sorv_voc[i]==1){
                voc_size[i] = f;
            }
        }
        source_song.trigger('change');
        source_voc.trigger('change');
    """)
##########################################################
slider_alpha = Slider(start=0.1, end=1, value=0.3, step=.1, title="fill_alpha", callback=callback_alpha)
slider_size = Slider(start=1, end=10, value=5, step=1, title="size", callback=callback_size)

show(vform(vform(slider_alpha,slider_size),hplot(p_song,p_voc)))
Пример #45
0
from bokeh.models.widgets import Slider
from bokeh.io import output_file, show, vform

output_file("slider.html")

slider = Slider(start=0, end=10, value=1, step=.1, title="Stuff")

show(vform(slider))
Пример #46
0
def plotDayOfWeekTimeline(fileName,
                          initData,
                          bokehPlaceholderId='bokehContent'):

    source = ColumnDataSource(data=initData)
    selectDOW = Select(title="Days:",
                       value="Monday",
                       options=[
                           "Sunday", "Monday", "Tuesday", "Wednesday",
                           "Thursday", "Friday", "Saturday"
                       ])
    selectUT = Select(title="User Type:",
                      value="All",
                      options=["All", "Subscriber", "Customer"])
    model = dict(source=source, select_dow=selectDOW, select_ut=selectUT)
    plot = Figure(plot_width=1200, plot_height=400, x_axis_type="datetime")
    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

    callback = CustomJS(args=model,
                        code="""
          var dayOfWeek = select_dow.get('value')
            var userType = select_ut.get('value')
            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['x'] = temp;
                        data['y'] = result.y;
                        source.trigger('change');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {dow:dayOfWeek, ut:userType};
        url = "/select?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)

    selectDOW.callback = callback
    selectUT.callback = callback
    layout = vform(selectDOW, selectUT, plot)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
Пример #47
0
    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
Пример #48
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
Пример #49
0
    for (i = 0; i < x.length; i++) {
        y[i] = B + A*Math.sin(k*x[i]+phi);
    }
    source.trigger('change');
""")

amp_slider = Slider(start=0.1, end=10, value=1, step=.1,
                    title="Amplitude", callback=callback)
callback.args["amp"] = amp_slider

freq_slider = Slider(start=0.1, end=10, value=1, step=.1,
                     title="Frequency", callback=callback)
callback.args["freq"] = freq_slider

phase_slider = Slider(start=0, end=6.4, value=0, step=.1,
                      title="Phase", callback=callback)
callback.args["phase"] = phase_slider

offset_slider = Slider(start=-5, end=5, value=0, step=.1,
                       title="Offset", callback=callback)
callback.args["offset"] = offset_slider

layout = hplot(
    plot,
    vform(amp_slider, freq_slider, phase_slider, offset_slider),
)

output_file("slider.html", title="slider.py example")

show(layout)
Пример #50
0
def get_spectral_network_bokeh_plot(
    spectral_network_data,
    plot_range=None,
    plot_joints=False,
    plot_data_points=False,
    plot_on_cylinder=False,
    plot_two_way_streets=False,
    soliton_trees=None,
    no_unstable_streets=False,
    soliton_tree_data=None,
    plot_width=800,
    plot_height=800,
    notebook=False,
    slide=False,
    logger_name=None,
    marked_points=[],
    without_errors=False,
    download=False,
    #downsample=True,
    downsample=False,
    downsample_ratio=None,
):
    logger = logging.getLogger(logger_name)

    # Determine if the data set corresponds to a multi-parameter
    # configuration.
    if type(spectral_network_data.sw_data) is list:
        multi_parameter = True
    else:
        multi_parameter = False

    if without_errors is True:
        spectral_networks = [
            sn for sn in spectral_network_data.spectral_networks
            if len(sn.errors) == 0
        ]
    else:
        spectral_networks = spectral_network_data.spectral_networks

    if soliton_trees is None:
        soliton_trees = spectral_network_data.soliton_trees

    if (len(spectral_networks) == 0
            and (soliton_trees is None or len(soliton_trees) == 0)):
        raise RuntimeError('get_spectral_network_bokeh_plot(): '
                           'No spectral network to plot.')

    sw_data = spectral_network_data.sw_data

    plot_x_range, plot_y_range = plot_range
    y_min, y_max = plot_y_range

    # Setup tools.
    hover = HoverTool(tooltips=[
        ('name', '@label'),
        ('root', '@root'),
    ])

    # Prepare a bokeh Figure.
    bokeh_figure = figure(
        tools='reset,box_zoom,pan,wheel_zoom,save,tap',
        plot_width=plot_width,
        plot_height=plot_height,
        title=None,
        x_range=plot_x_range,
        y_range=plot_y_range,
    )
    bokeh_figure.add_tools(hover)
    bokeh_figure.grid.grid_line_color = None

    # Data source for marked points, which are drawn for an illustration.
    mpds = ColumnDataSource({
        'x': [],
        'y': [],
        'color': [],
        'label': [],
        'root': []
    })
    for mp in marked_points:
        z, color = mp
        mpds.data['x'].append(z.real)
        mpds.data['y'].append(z.imag)
        mpds.data['color'].append(color)
        mpds.data['label'].append('')
        mpds.data['root'].append('')
    bokeh_figure.circle(
        x='x',
        y='y',
        size=5,
        color='color',
        source=mpds,
    )

    # Data source for punctures.
    if multi_parameter is False:
        puncts = sw_data.regular_punctures + sw_data.irregular_punctures
    else:
        puncts = sw_data[0].regular_punctures + sw_data[0].irregular_punctures
    ppds = ColumnDataSource({'x': [], 'y': [], 'label': [], 'root': []})
    for pp in puncts:
        if pp.z == oo:
            continue
        ppds.data['x'].append(pp.z.real)
        ppds.data['y'].append(pp.z.imag)
        ppds.data['label'].append(str(pp.label))
        ppds.data['root'].append('')
    bokeh_figure.circle(
        'x',
        'y',
        size=10,
        color="#e6550D",
        fill_color=None,
        line_width=3,
        source=ppds,
    )

    # Data source for branch points & cuts.
    if multi_parameter is False:
        bpds = ColumnDataSource({'x': [], 'y': [], 'label': [], 'root': []})
        for bp in sw_data.branch_points:
            if bp.z == oo:
                continue
            bpds.data['x'].append(bp.z.real)
            bpds.data['y'].append(bp.z.imag)
            bpds.data['label'].append(str(bp.label))
            positive_roots = bp.positive_roots
            if len(positive_roots) > 0:
                root_label = ''
                for root in positive_roots:
                    root_label += str(root.tolist()) + ', '
                bpds.data['root'].append(root_label[:-2])
            else:
                bpds.data['root'].append('')
        bokeh_figure.x(
            'x',
            'y',
            size=10,
            color="#e6550D",
            line_width=3,
            source=bpds,
        )

        bcds = ColumnDataSource({'xs': [], 'ys': []})
        try:
            branch_cut_rotation = sw_data.branch_cut_rotation
        except AttributeError:
            branch_cut_rotation = None
        if branch_cut_rotation is not None:
            for bl in sw_data.branch_points + sw_data.irregular_singularities:
                y_r = (2j * y_max) * complex(sw_data.branch_cut_rotation)
                bcds.data['xs'].append([bl.z.real, bl.z.real + y_r.real])
                bcds.data['ys'].append([bl.z.imag, bl.z.imag + y_r.imag])

            bokeh_figure.multi_line(
                xs='xs',
                ys='ys',
                line_width=2,
                color='gray',
                line_dash='dashed',
                source=bcds,
            )

    # XXX: Need to clean up copy-and-pasted codes.
    else:
        bpds = []
        bcds = []
        for swd in sw_data:
            bpds_i = ColumnDataSource({
                'x': [],
                'y': [],
                'label': [],
                'root': []
            })
            for bp in swd.branch_points:
                if bp.z == oo:
                    continue
                bpds_i.data['x'].append(bp.z.real)
                bpds_i.data['y'].append(bp.z.imag)
                bpds_i.data['label'].append(str(bp.label))
                root_label = ''
                for root in bp.positive_roots:
                    root_label += str(root.tolist()) + ', '
                bpds_i.data['root'].append(root_label[:-2])
            bpds.append(bpds_i)

            bcds_i = ColumnDataSource({'xs': [], 'ys': []})
            for bl in swd.branch_points + swd.irregular_singularities:
                y_r = (2j * y_max) * complex(swd.branch_cut_rotation)
                bcds_i.data['xs'].append([bl.z.real, bl.z.real + y_r.real])
                bcds_i.data['ys'].append([bl.z.imag, bl.z.imag + y_r.imag])
            bcds.append(bcds_i)

        # In this case the branch points and cuts will be
        # drawn differently for each spectral network.
        # Each call of the slider will deal with them.

    # Data source for the current plot
    cds = ColumnDataSource({
        'xs': [],
        'ys': [],
        'ranges': [],
        'color': [],
        'alpha': [],
        'arrow_x': [],
        'arrow_y': [],
        'arrow_angle': [],
        'label': [],
        'root': [],
    })

    # Data source for plotting data points
    dpds = ColumnDataSource({
        'x': [],
        'y': [],
    })

    # Data source for phases
    pds = ColumnDataSource({
        'phase': [],
    })
    #    for sn in spectral_networks:
    #        # sn_phase = '{:.3f}'.format(sn.phase / pi)
    #        sn_phase = '{:.3f}'.format(sn.phase)
    #        pds.data['phase'].append(sn_phase)

    # Data source containing all the spectral networks
    snds = ColumnDataSource({
        'spectral_networks': [],
    })

    if soliton_trees is not None and len(soliton_trees) > 0:
        # snds['spectral_networks'] is a 1-dim array,
        # of soliton trees.
        for tree in soliton_trees:
            if no_unstable_streets and tree.stability != 1:
                continue
            elif tree.stability == 1 or tree.stability is None:
                s_wall_color = '#0000FF'
            elif tree.stability == 0:
                s_wall_color = '#00FF00'
            elif tree.stability > 1:
                s_wall_color = '#FF0000'
            tree_data = get_s_wall_plot_data(
                tree.streets,
                sw_data,
                logger_name,
                tree.phase,
                s_wall_color=s_wall_color,
                downsample=downsample,
                downsample_ratio=downsample_ratio,
            )
            snds.data['spectral_networks'].append(tree_data)
            pds.data['phase'].append('{:.3f}'.format(tree.phase))
        init_data = snds.data['spectral_networks'][0]

    elif plot_two_way_streets:
        if soliton_tree_data is not None:
            # snds['spectral_networks'] is a 2-dim array,
            # where the first index chooses a spectral network
            # and the second index chooses a soliton tree
            # of the two-way streets of the spectral network.
            for i, soliton_trees in enumerate(soliton_tree_data):
                data_entry = []
                theta_i = spectral_networks[i].phase
                if len(soliton_trees) == 0:
                    # Fill with empty data.
                    empty_data = get_s_wall_plot_data(
                        [],
                        sw_data,
                        logger_name,
                        theta_i,
                        downsample=downsample,
                        downsample_ratio=downsample_ratio,
                    )
                    data_entry.append(empty_data)
                else:
                    for tree in soliton_trees:
                        tree_data = get_s_wall_plot_data(
                            tree.streets,
                            sw_data,
                            logger_name,
                            theta_i,
                            downsample=downsample,
                            downsample_ratio=downsample_ratio,
                        )
                        # The first data contains all the soliton trees
                        # of the two-way streets in a spectral network.
                        if len(data_entry) == 0:
                            data_entry.append(deepcopy(tree_data))
                        else:
                            for key in tree_data.keys():
                                data_entry[0][key] += tree_data[key]
                        data_entry.append(tree_data)

                snds.data['spectral_networks'].append(data_entry)
                pds.data['phase'].append('{:.3f}'.format(theta_i))

            init_data = snds.data['spectral_networks'][0][0]
        else:
            logger.warning('No data to plot.')
    else:
        # snds['spectral_networks'] is a 1-dim array,
        # of spectral network data.
        for sn in spectral_networks:
            skip_plotting = False
            for error in sn.errors:
                error_type, error_msg = error
                if error_type == 'Unknown':
                    skip_plotting = True
            if skip_plotting is True:
                continue

            sn_data = get_s_wall_plot_data(
                sn.s_walls,
                sw_data,
                logger_name,
                sn.phase,
                downsample=downsample,
                downsample_ratio=downsample_ratio,
            )
            snds.data['spectral_networks'].append(sn_data)
            pds.data['phase'].append('{:.3f}'.format(sn.phase))

        init_data = snds.data['spectral_networks'][0]

    # Initialization of the current plot data source.
    for key in cds.data.keys():
        cds.data[key] = init_data[key]

    bokeh_figure.scatter(
        x='x',
        y='y',
        alpha=0.5,
        source=dpds,
    )

    bokeh_figure.multi_line(
        xs='xs',
        ys='ys',
        color='color',
        alpha='alpha',
        line_width=1.5,
        source=cds,
    )

    bokeh_figure.triangle(
        x='arrow_x',
        y='arrow_y',
        angle='arrow_angle',
        color='color',
        alpha='alpha',
        size=8,
        source=cds,
    )

    bokeh_obj = {}
    notebook_vform_elements = []

    # XXX: Where is a good place to put the following?
    custom_js_code = ''
    if notebook is True or slide is True:
        with open('static/bokeh_callbacks.js', 'r') as fp:
            custom_js_code += fp.read()
            custom_js_code += '\n'

    # Data source for plot ranges
    if download is False and notebook is False and slide is False:
        range_callback = CustomJS(
            args={
                'x_range': bokeh_figure.x_range,
                'y_range': bokeh_figure.y_range
            },
            code=(custom_js_code + 'update_plot_range(x_range, y_range);'),
        )
        bokeh_figure.x_range.callback = range_callback
        bokeh_figure.y_range.callback = range_callback

    # 'Redraw arrows' button.
    redraw_arrows_button = Button(
        label='Redraw arrows',
        callback=CustomJS(
            args={
                'cds': cds,
                'x_range': bokeh_figure.x_range,
                'y_range': bokeh_figure.y_range
            },
            code=(custom_js_code + 'redraw_arrows(cds, x_range, y_range);'),
        ),
    )
    bokeh_obj['redraw_arrows_button'] = redraw_arrows_button
    notebook_vform_elements.append(redraw_arrows_button)

    # 'Show data points' button
    show_data_points_button = Button(label='Show data points', )
    show_data_points_button.callback = CustomJS(
        args={
            'cds': cds,
            'dpds': dpds,
            'hover': hover
        },
        code=(custom_js_code + 'show_data_points(cds, dpds, hover);'),
    )
    bokeh_obj['show_data_points_button'] = show_data_points_button
    notebook_vform_elements.append(show_data_points_button)

    # 'Hide data points' button
    hide_data_points_button = Button(label='Hide data points', )
    hide_data_points_button.callback = CustomJS(
        args={
            'cds': cds,
            'dpds': dpds,
            'hover': hover
        },
        code=(custom_js_code + 'hide_data_points(cds, dpds, hover);'),
    )
    bokeh_obj['hide_data_points_button'] = hide_data_points_button
    notebook_vform_elements.append(hide_data_points_button)

    # Prev/Next soliton tree button
    tree_idx_ds = ColumnDataSource({'j': ['0']})
    sn_idx_ds = ColumnDataSource({'i': ['0']})
    plot_options_ds = ColumnDataSource({
        'notebook': [notebook],
        'show_trees': [plot_two_way_streets]
    })

    if plot_two_way_streets and soliton_tree_data is not None:
        prev_soliton_tree_button = Button(label='<', )
        prev_soliton_tree_button.callback = CustomJS(
            args={
                'cds': cds,
                'snds': snds,
                'sn_idx_ds': sn_idx_ds,
                'tree_idx_ds': tree_idx_ds,
                'plot_options_ds': plot_options_ds,
            },
            code=(custom_js_code +
                  'show_prev_soliton_tree(cds, snds, sn_idx_ds, tree_idx_ds, '
                  'plot_options_ds);'),
        )
        bokeh_obj['prev_soliton_tree_button'] = prev_soliton_tree_button
        notebook_vform_elements.append(prev_soliton_tree_button)

        next_soliton_tree_button = Button(label='>', )
        next_soliton_tree_button.callback = CustomJS(
            args={
                'cds': cds,
                'snds': snds,
                'sn_idx_ds': sn_idx_ds,
                'tree_idx_ds': tree_idx_ds,
                'plot_options_ds': plot_options_ds,
            },
            code=(custom_js_code +
                  'show_next_soliton_tree(cds, snds, sn_idx_ds, tree_idx_ds, '
                  'plot_options_ds);'),
        )
        bokeh_obj['next_soliton_tree_button'] = next_soliton_tree_button
        notebook_vform_elements.append(next_soliton_tree_button)

    # Slider
    if (plot_two_way_streets and soliton_trees is not None
            and len(soliton_trees) > 0):
        slider_title = 'soliton tree #'
    else:
        slider_title = 'spectral network #'
    num_of_plots = len(snds.data['spectral_networks'])
    if num_of_plots > 1:
        if multi_parameter is False:
            sn_slider = Slider(
                start=0,
                end=num_of_plots - 1,
                value=0,
                step=1,
                title=slider_title,
            )

            sn_slider.callback = CustomJS(
                args={
                    'cds': cds,
                    'snds': snds,
                    'sn_idx_ds': sn_idx_ds,
                    'dpds': dpds,
                    'pds': pds,
                    'hover': hover,
                    'plot_options': plot_options_ds,
                    'tree_idx_ds': tree_idx_ds
                },
                code=(custom_js_code +
                      'sn_slider(cb_obj, cds, snds, sn_idx_ds, dpds, pds, '
                      'hover, plot_options, tree_idx_ds);'),
            )
            plot = vform(
                bokeh_figure,
                sn_slider,
                width=plot_width,
            )
            notebook_vform_elements = ([bokeh_figure, sn_slider] +
                                       notebook_vform_elements)

        else:
            # TODO: implement new js routine for sn_slider when
            # there are multiple parameters.
            # Need to draw branch points and cuts for each value of the
            # parameters.
            sn_slider = Slider(start=0,
                               end=num_of_plots - 1,
                               value=0,
                               step=1,
                               title="spectral network #")

            sn_slider.callback = CustomJS(
                args={
                    'cds': cds,
                    'snds': snds,
                    'sn_idx_ds': sn_idx_ds,
                    'dpds': dpds,
                    'pds': pds,
                    'hover': hover,
                    'plot_options': plot_options_ds,
                    'tree_idx_ds': tree_idx_ds
                },
                code=(custom_js_code +
                      'sn_slider(cb_obj, cds, snds, sn_idx_ds, dpds, pds, '
                      'hover, plot_options, tree_idx_ds);'),
            )
            plot = vform(
                bokeh_figure,
                sn_slider,
                width=plot_width,
            )
            notebook_vform_elements = ([bokeh_figure, sn_slider] +
                                       notebook_vform_elements)

    else:
        plot = bokeh_figure
        notebook_vform_elements = ([bokeh_figure] + notebook_vform_elements)

    bokeh_obj['plot'] = plot

    if notebook is True:
        # TODO: Include phase text input
        return vform(*notebook_vform_elements, width=plot_width)
    elif slide is True:
        return plot
    else:
        return bokeh.embed.components(bokeh_obj)
Пример #51
0
from bokeh.models.widgets import Select
from bokeh.io import output_file, show, vform

output_file("select.html")

select = Select(title="Option:", value="foo", options=["foo", "bar", "baz", "quux"])

show(vform(select))
Пример #52
0
from bokeh.models.widgets import Button
from bokeh.io import output_file, show, vform

output_file("button.html")

button = Button(label="Foo", type="success")

show(vform(button))
Пример #53
0
p4.xaxis.minor_tick_line_color = None
p4.line(temp_graph['date_t'], temp_graph['adv_less_current'], color='red', line_width=3, legend="Advance less current")

p4.legend.location = "bottom_left"

# put all the plots in a grid layout
p = gridplot([[p1, p2], [p3, p4]])

# show the results
#show(p)


########## BUILD FIGURES ################

source = ColumnDataSource(temp_graph)
columns = [
        TableColumn(field='code', title = "BEA - Code", width = temp_graph['code'].map(len).max()),
        TableColumn(field='description', title = "Description", width = temp_graph['description'].map(len).max()),
        TableColumn(field='ADVANCE', title = "Advanced Est", width = 5),
        TableColumn(field='SECOND', title = "Second Est", width = 5),
        TableColumn(field='THIRD', title = "Third Est", width = 5),
        TableColumn(field='adv_less_third', title = "Revision (advance est less third est)", width = 10),
        TableColumn(field='abs_two_year', title = "Revision (absolute avg(2-year))", width = 10)
    ]
data_table = DataTable(source=source, columns=columns, width=1000, height=1000)


layout = vform(p, data_table)

#show(layout)
save(layout)
Пример #54
0
color_range1 = p2.rect(x='x', y='y', width=1, height=10, color='crcolor', source=crsource)
# set up hover tool to show color hex code and sample swatch
hover = p2.select(dict(type=HoverTool))
hover.tooltips = [
				   ('color', '$color[hex, rgb, swatch]:crcolor'),
				   ('RGB levels', '@RGBs')
				 ]

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

p2.ygrid.grid_line_color = None
p2.xgrid.grid_line_color = None
p2.axis.axis_line_color  = None
p2.axis.major_label_text_color = None
p2.axis.major_tick_line_color = None
p2.axis.minor_tick_line_color = None

layout = bkplt.hplot(
	vform(red_slider, green_slider, blue_slider),
	vform(p1, p2)
)

bkplt.output_file("colorSliders.html")
bkplt.show(layout)