def hpd(): hpdf = pd.read_csv('hpd.csv') print(hpdf.head()) print(len(hpdf)) #print(hpdf.long.tolist()) map_options = GMapOptions(lat=40.80, lng=-73.94, map_type="roadmap", zoom=13, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """) #do NOT change zoom to 12, map won't load! plot = GMapPlot( x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, plot_width=600, plot_height=750, api_key=API_KEY #, tools=TOOLS #title=title, tools=[hover] ) source = ColumnDataSource(data=dict(x=[], y=[])) source.data = dict( x = hpdf.long.tolist(), y = hpdf.lat.tolist() ) circle = Circle(x='x', y='y', size=5, fill_color="orange", fill_alpha=0.2, line_color=None) plot.add_glyph(source, circle) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())#, hover) script, div = components(plot) return render_template('hpd.html', script=script, div=div)
def get_thiel_analysis_plots(simname, realname): global datalog, original_data, datasource, layout, ts1, chart, annotation_counter additional_links = "<b><a href='/browse?search=sim'>Load Simulation Log</a> <p> <a href='/browse?search=real'>Load Real Log</a></b>" save_settings(config) datalog = get_data(simname, realname, sim_metric, real_metric, read_file) original_data = copy.deepcopy(datalog) for i in range(10): if keys[i][0] == 'x': found_x = i datatype = Select(value='x', options=keys[found_x]) datatype.on_change('value', sim_change) intro_text = Div(text="""<H2>Sim/Real Thiel Coefficient Calculator</H2> \ <p> Load two PX4 datalogs, one a real flight and the other a simulation of that flight, \ and see how well they compare. We use the well-known <a href="https://www.vosesoftware.com/riskwiki/Thielinequalitycoefficient.php">Thiel Coefficient</a> and <a href="https://drive.google.com/file/d/1XY8aZz89emFt-LAuUZ2pjC1GHwRARr9f/view">Song variation</a> of that to generate correspondence scores. Our Jupyter Notebook that demonstrates and explains the Song methodology is <a href="https://github.com/zlite/PX4_flight_review/blob/master/thiel_app/clean_replication.ipynb">here</a>""", width=800, height=120, align="center") choose_field_text = Paragraph(text="Choose a data field to compare:", width=500, height=15) links_text = Div(text="<table width='100%'><tr><td><h3>" + "</h3></td><td align='left'>" + additional_links + "</td></tr></table>") datasource = ColumnDataSource( data=dict(time=[], sim=[], real=[], trend=[], position=[])) datasource.data = datalog tools = 'xpan,wheel_zoom,reset' ts1 = figure(plot_width=tplot_width, plot_height=tplot_height, tools=tools, x_axis_type='linear') # ts1.add_layout(Legend(), 'right') # if you want the legend outside of the plot print("real description", realdescription) ts1.line('time', 'sim', source=datasource, line_width=3, color="orange", legend_label="Simulated data: " + simdescription) ts1.line('time', 'real', source=datasource, line_width=3, color="blue", legend_label="Real data: " + realdescription) ts1.line('time', 'trend', source=datasource, line_width=1, color="green", legend_label="Difference in trend (scaled)") ts1.line('time', 'position', source=datasource, line_width=1, color="red", line_dash='solid', legend_label="Difference in position (scaled)") ts1.legend.background_fill_alpha = 0.7 # make the background of the legend more transparent ts1.add_layout(Title(text="Time (seconds)", align="center"), "below") # annotation_counter = annotation_counter + 1 # increment the list of annotations # x_range_offset = (datalog.last_timestamp - datalog.start_timestamp) * 0.05 # x_range = Range1d(datalog.start_timestamp - x_range_offset, datalog.last_timestamp + x_range_offset) plot_flight_modes(sim_flight_mode_changes, 'sim') plot_flight_modes(real_flight_mode_changes, 'real') # set up layout widgets = column(datatype, stats, stats2) mission_button = column(mission_mode_button) normalize_button = column(normalize_mode_button) sim_button = column(sim_reverse_button) real_button = column(real_reverse_button) sswap_button = column(sim_swap_button) rswap_button = column(real_swap_button) rule = column(explainer) space = column(spacer) main_row = row(widgets) chart = column(ts1) buttons = column(mission_button, normalize_button, space, sim_button, sswap_button, rule, real_button, rswap_button) layout = column(main_row, chart, buttons) # initialize update() curdoc().add_root(intro_text) curdoc().add_root(links_text) curdoc().add_root(choose_field_text) curdoc().add_root(layout) curdoc().title = "Flight data"
x_train_original,x_test_original,y_train_original,y_test_original=train_test_split(x,y,test_size=0.25) #For standardizing data clf = SVC() #rfe = RFE(clf, 5) clf.fit(x_train_original,y_train_original) predictions=clf.predict(x_test_original) print("Accuracy =", accuracy_score(y_test_original,predictions)) print(np.unique(predictions)) tn, fp, fn, tp = confusion_matrix(y_test_original,predictions).ravel() fruits = ['True Positive', 'False Positive', 'False Negative', 'True Negative'] source = ColumnDataSource(data=dict(bins=fruits, counts=[1, 10, 20, 30])) #fruits = [tp, fp, tn, fn] # counts = [tp, fp, tn, fn] source.data = dict(fruits=fruits, counts=[tp, fp, fn, tn]) p = figure(tools='crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,lasso_select',x_range=fruits, plot_height=450, title="Counts") p.vbar(x='fruits', top='counts', width=0.9, source=source, legend="fruits", line_color='white',fill_color=factor_cmap('fruits', palette=Spectral6, factors=fruits)) labels = LabelSet(x='fruits', y='counts', text='counts', level='glyph', x_offset=-15, y_offset=0, source=source, render_mode='canvas') p.add_layout(labels) p.title.text = "Model Accuracy %f" % accuracy_score(y_test_original,predictions) tsize = Slider(title="Test Size", start=0.05, end=0.50, value=0.2, step=0.05) input = Slider(title="Degree", start=1, end=10, value=3, step=1) ent = Select(title="Kernel", options=sorted(axis_map.keys()), value="rbf") button = Button(label="Submit Parameters", button_type="success") button2 = Button(label="Play_Depth", button_type="success")
ticker1 = Select(value='IDM', options=DATA_TICKERS, width=400,height=80,default_size= 30, title='data set',background='lightblue') # set up plots source = ColumnDataSource(data=dict(x=[], y=[])) source_static = ColumnDataSource(data=dict(x=[], y=[])) def update_stats(data, t1): # stats.text = str(data[[t1]].describe()) stats.text = str(data[["ene1","sigma","dll"]].describe()) # initialization t1 = ticker1.value data = get_data(t1) #source.data = source.from_df(data[['centerx', 'centery','ene1','sigma','figure']]) source.data = source.from_df(data[['centerx', 'centery','ene1','sigma','datetime','EXTID']]) source_static.data = source.data update_stats(data, t1) #tools = 'pan,wheel_zoom,xbox_select,reset,lasso_select,box_zoom' tools = 'pan,wheel_zoom,box_select,reset,lasso_select,box_zoom,save' # TOOLTIPS = """ # <div> # <div> # <img # src="@figure" height="400" alt="@figure" width="600" # style="float: left; margin: 0px 15px 15px 0px;" # border="2" # ></img> # </div>
from bokeh.io import curdoc from bokeh.layouts import column from bokeh.models import ColumnDataSource from bokeh.plotting import figure # initialize from data_source import get_data data = get_data() source = ColumnDataSource(data=dict(date=[], t1=[], t2=[])) source.data = source.from_df(data[['x', 'y']]) # set up plots corr = figure(plot_width=350, plot_height=350, tools='box_select,reset') corr.circle('x', 'y', size=2, source=source, selection_color="orange", alpha=0.6, nonselection_alpha=0.1, selection_alpha=0.4) def selection_change(attrname, old, new): selected = source.selected.indices if selected: xs = source.data['x'][selected] ys = source.data['y'][selected] xy = [(x, y) for x, y in zip(xs, ys)]
def update(attrname, old, new): PFA = float(pfa.value) N = slider1.value Yb = gamma.ppf(1 - PFA, N) if case.value == "Case 1": K = 1 elif case.value == "Case 2": K = N elif case.value == "Case 3": K = 2 elif case.value == "Case 4": K = 2 * N else: K = 1000 newPDseries = vprobdet(N, Yb, K, xdBseries) newdata = dict(snr=xdBseries, pd=newPDseries) source.data = newdata controls = [slider1, case, pfa] for control in controls: control.on_change('value', update) layout = column(pfa, case, slider1, space, plot) curdoc().add_root(layout)
tools="") #################################### palette = Spectral4 + Spectral6 palette += palette clrs = [] for i in range(len(cities)): factor = 1 clrs.extend([palette[i]] * factor) source_new = ColumnDataSource( data=dict(x=x, counts=counts, colors=palette[0:len(cities)] * int(len(counts) / len(cities)), cities=cities * int(len(counts) / len(cities)))) source.data = source_new.data p.vbar(x=source.data['x'], top=source.data['counts'], width=0.9, line_color="black", fill_color=clrs) p.x_range.factors = source.data['x'] p.xgrid.grid_line_color = None ######################################## p.xaxis.major_label_orientation = "vertical" city_selection.on_change('active', update_plot) checkbox_cities_column = column(city_selection)
latest_data_date = max(init_data['date']) with gzip.GzipFile( ext_datafiles['path'] + ext_datafiles['location_to_filename'][init_location] + '_map.json.gz', 'r') as fin: init_mapfile = json.loads(fin.read().decode('utf-8')) init_map = init_mapfile['data'] # Create source data structure and initialize state map source_state_data = ColumnDataSource(init_data) source_county_data = ColumnDataSource(init_data) source_state_map = ColumnDataSource(init_map) source_county_map = ColumnDataSource(init_map) # Erase the underlying data to reduce the html filesize (will be loaded upon user tap feedback) source_state_data.data = {k: [] for k in source_state_data.data} source_county_data.data = {k: [] for k in source_county_data.data} source_county_map.data = {k: [] for k in source_county_map.data} """ # %% Make State graph for COVID data ________________________________________________________________________________ """ # Set Axis limits ax_limits = { 'x': (pd.Timestamp.now() - pd.DateOffset(months=4), pd.Timestamp.now()), 'yl': ( 0, max_pos #1e6*5/100 ), 'yr': (-100, 500)
from bokeh.sampledata.autompg import autompg from bokeh.plotting import figure from bokeh.models import ColumnDataSource, LinearColorMapper, ColorBar from bokeh.palettes import Viridis256 from bokeh.io import curdoc from bokeh.layouts import column from bokeh.models.widgets import Dropdown # data autompg['brand'] = autompg.name.apply(lambda n: n.split(' ')[0]) source = ColumnDataSource(autompg) # setup data brand = 'ford' source = ColumnDataSource(autompg.loc[autompg.brand == brand]) source.data = ColumnDataSource.from_df(autompg.loc[autompg.brand == brand]) # tooltips tooltips = [('index', '@index'), ('Name', '@name'), ('Weight', '@weight'), ('Horsepower', '@hp'), ('Acceleration', '@accel')] # figure p = figure(plot_width=800, plot_height=500, tooltips=tooltips, title='car acceleration (in seconds)') # color mapper mapper = LinearColorMapper(palette=Viridis256, low=autompg.accel.min(), high=autompg.accel.max())
) # Outbreak Graph ob_cases_ds = ColumnDataSource(data=dict(date=[], cases=[])) outbreak = figure(title='Outbreak', x_axis_type='datetime', plot_height=plot_height, plot_width=plot_width, y_axis_label='# Cases', y_range=(0, 100)) ob1 = outbreak.line(x='date', y='cases', source=ob_cases_ds, legend_label='ob1', line_width=2, line_color='blue') outbreak.add_tools(outbreak_hover) outbreak.xaxis.major_label_orientation = 3.14 / 4 # Add second graph to fig sp500_cs = ColumnDataSource(data=dict(date=[], close=[])) sp500_cs.data = dict( date=sp['date'], close=sp['close'] ) outbreak.extra_y_ranges = {'SP500': Range1d(start=sp.close.min(), end=sp.close.max())} outbreak.add_layout(LinearAxis(y_range_name='SP500', axis_label='S&P Index'), 'right') sp5 = outbreak.line(x='date', y='close', source=sp500_cs, line_color='black', y_range_name='SP500', legend_label='S&P500') legend = Legend(items=[ ('Cases', [ob1]), ('S&P500', [sp5]) ]) # Measure dict for stylistic purposes measure_dict = { 'New Cases': 'cases', 'New Deaths': 'deaths',
oldest_date_date = pd.to_datetime('20191101', format='%Y%m%d') #min(init_data['date']) init_location = 'Earth' # get location with gzip.GzipFile( ext_datafiles['path'] + ext_datafiles['location_to_filename'][init_location] + '_map.json.gz', 'r') as fin: init_mapfile = json.loads(fin.read().decode('utf-8')) init_map = init_mapfile['data'] # Create source data structure and initialize state map source_graph = ColumnDataSource(init_data) source_map = ColumnDataSource(init_map) # Erase the underlying data to reduce the html filesize (will be loaded upon user tap feedback) source_graph.data = {k: source_graph.data[k][-2:-1] for k in source_graph.data} """ # %% Make State graph for COVID data ________________________________________________________________________________ """ # Set Soft Axis limits ax_limits = { 'x': (pd.Timestamp.now() - pd.DateOffset(months=4), pd.Timestamp.now()), } # Create figure p_graph = figure( x_axis_type='datetime', y_axis_type="linear", title= '(Tap a state on the map above to show the corresponding COVID data here)', # plot_width=800, plot_height=600,
from os.path import dirname, join import pandas as pd import collections from bokeh.io import curdoc from bokeh.layouts import column, row, layout from bokeh.models import (Button, ColumnDataSource, CustomJS, DataTable, NumberFormatter, TableColumn, Div, Panel) df = pd.read_csv(join(dirname(__file__), '../data/Netflix.csv')) #to keep dict order source = ColumnDataSource(data=collections.OrderedDict()) source.data = { 'Region': df['Area'], 'QTR-YR': df['Years'], 'Revenue': df[' Revenue '].str.replace(',', '').astype(float), 'Subscribers': df[' Subscribers '].str.replace(',', '').astype(float) } columns = [ TableColumn(field='Region', title='Region'), TableColumn(field='QTR-YR', title='QTR-YR'), TableColumn(field='Subscribers', title='Subscribers', formatter=NumberFormatter(format='0,0')), TableColumn(field='Revenue', title='Revenue', formatter=NumberFormatter(format='$0,0')), ] columnNames = [x.field for x in columns]
title='Latest Release Year') gross_slider = Slider(start=0, end=films_df['gross'].max(), value=0, step=10, title="Minimum Gross") rating_slider = Slider(start=0, end=100, value=0, step=1, title='Minimum Metascore') source.data = dict(title=films_df['title'], year=films_df['year'], genre=films_df['genre'], imdb_rating=films_df['imdb_rating'], metascore=films_df['metascore'], director=films_df['director'], stars=films_df['stars'], gross=films_df['gross']) #Create a histogram of the actors appearing most frequently actors_data = list(zip(*get_actors(source.data).most_common(10))) actors_source = ColumnDataSource( data=dict(actors=actors_data[0], number=actors_data[1])) top_actors = figure( x_range=actors_data[0], plot_height=350, plot_width=500, title="Most Common Actors", sizing_mode='scale_both',
def modify_doc(): # collect all the names of .npz files in the folder lfpca_all_names = glob.glob("*.npz") lfpca_all_names.sort() # loading the npz files lfpca_all = {} for ind, lf in enumerate(lfpca_all_names): lfpca_all[lf[:-4]] = lfpca.lfpca_load_spec(lf) # initialize with the first lfpca object lf = lfpca_all[lfpca_all_names[0][:-4]] # grabbing channel count from psd chan_count, freq = lf.psd.shape # mapping all the channels DEFAULT_TICKERS = list(map(str, range(chan_count))) LF_TICKERS = [key for key in lfpca_all.keys()] # initializing values for frequency, psd, scv, histogram plot chan = 0 select_freq = 10 select_bin = 20 freq_vals = lf.f_axis[1:] psd_vals = lf.psd[chan].T[1:] scv_vals = lf.scv[chan].T[1:] # creating a selector and slider lf_ticker = Select(value=lfpca_all_names[0][:-4], title='lf_condition', options=LF_TICKERS) ticker = Select(value=str(chan), title='channel', options=DEFAULT_TICKERS) freq_slider = Slider(start=1, end=199, value=select_freq, step=1, title="Frequency", callback_policy="mouseup") bin_slider = Slider(start=10, end=55, value=select_bin, step=5, title="Number of bins", callback_policy="mouseup") # create data and selection tools source = ColumnDataSource( data=dict(freq_vals=freq_vals, psd_vals=psd_vals, scv_vals=scv_vals)) TOOLS = "help" #tapTool work in progress # setting up plots psd_plot = figure(tools=TOOLS, title='PSD', x_axis_type='log', y_axis_type='log') psd_plot.legend.location = 'top_left' psd_plot.xaxis.axis_label = 'Frequency (Hz)' psd_plot.yaxis.axis_label = 'Power/Frequency (dB/Hz)' psd_plot.grid.grid_line_alpha = 0.3 scv_plot = figure(tools=TOOLS, title='SCV', x_axis_type='log', y_axis_type='log') scv_plot.legend.location = 'top_left' scv_plot.xaxis.axis_label = 'Frequency (Hz)' scv_plot.yaxis.axis_label = '(Unitless)' scv_plot.grid.grid_line_alpha = 0.3 # create histogram frame hist_source = ColumnDataSource({'top': [], 'left': [], 'right': []}) fit_hist_source = ColumnDataSource({'x': [], 'y': []}) hist, edges = np.histogram(lf.spg[chan, select_freq, :], bins=select_bin, density=True) hist_source.data = {'top': hist, 'left': edges[:-1], 'right': edges[1:]} # create fit line for the histogram rv = expon(scale=sp.stats.expon.fit(lf.spg[chan, select_freq, :], floc=0)[1]) hist_source.data = {'top': hist, 'left': edges[:-1], 'right': edges[1:]} fit_hist_source.data = {'x': edges, 'y': rv.pdf(edges)} hist_fig = figure(x_axis_label='Power', y_axis_label='Probability', background_fill_color="#E8DDCB") hist_fig.axis.visible = False hist_fig.title.text = 'Freq = %.1fHz, p-value = %.4f' % ( select_freq, lf.ks_pvals[chan, select_freq]) # customize plot to psd def create_psd_plot(psd_plot, source): psd_plot.line('freq_vals', 'psd_vals', source=source, color='navy') psd_plot.circle( 'freq_vals', 'psd_vals', source=source, size=5, color='darkgrey', alpha=0.2, # set visual properties for selected glyphs selection_color="firebrick", # set visual properties for non-selected glyphs nonselection_fill_alpha=0.2, nonselection_fill_color="darkgrey", name='psd_circ') # customize plot to psd def create_scv_plot(scv_plot, source): scv_plot.line('freq_vals', 'scv_vals', source=source, color='navy') scv_plot.circle( 'freq_vals', 'scv_vals', source=source, size=5, color='darkgrey', alpha=0.2, # set visual properties for selected glyphs selection_color="firebrick", # set visual properties for non-selected glyphs nonselection_fill_alpha=0.2, nonselection_fill_color="darkgrey", name='scv_circ') # customize histogram def create_hist(hist_fig, hist_source): hist_fig.quad(top='top', bottom=0, left='left', right='right', fill_color="#036564", line_color="#033649", source=hist_source) # initializing plots create_psd_plot(psd_plot, source) create_scv_plot(scv_plot, source) vline_psd = Span(location=select_freq, dimension='height', line_color='red', line_dash='dashed', line_width=3) vline_scv = Span(location=select_freq, dimension='height', line_color='red', line_dash='dashed', line_width=3) psd_plot.add_layout(vline_psd) scv_plot.add_layout(vline_scv) create_hist(hist_fig, hist_source) fit_line = bokeh.models.glyphs.Line(x='x', y='y', line_width=8, line_alpha=0.7, line_color="#D95B43") hist_fig.add_glyph(fit_hist_source, fit_line) all_plots = gridplot([[psd_plot, scv_plot, hist_fig]], plot_width=300, plot_height=300) # set up connector spans freq_slider.callback = CustomJS(args=dict(span1=vline_psd, span2=vline_scv, slider=freq_slider), code="""span1.location = slider.value; span2.location = slider.value""" ) def update(attrname, old, new): # get current slider values chan = int(ticker.value) lf = lfpca_all[lf_ticker.value] select_freq = freq_slider.value select_bin = bin_slider.value # update data psd_vals = lf.psd[chan].T[1:] scv_vals = lf.scv[chan].T[1:] data = dict(freq_vals=freq_vals, psd_vals=psd_vals, scv_vals=scv_vals) # create a column data source for the plots to share source.data = data # update histogram and fit line hist, edges = np.histogram(lf.spg[chan, select_freq, :], bins=select_bin, density=True) rv = expon( scale=sp.stats.expon.fit(lf.spg[chan, select_freq, :], floc=0)[1]) hist_source.data = { 'top': hist, 'left': edges[:-1], 'right': edges[1:] } fit_hist_source.data = {'x': edges, 'y': rv.pdf(edges)} create_psd_plot(psd_plot=psd_plot, source=source) create_scv_plot(scv_plot=scv_plot, source=source) hist_fig.title.text = 'Freq = %.1fHz, p-value = %.4f' % ( select_freq, lf.ks_pvals[chan, select_freq]) create_hist(hist_fig=hist_fig, hist_source=hist_source) fit_line = bokeh.models.glyphs.Line(x='x', y='y', line_width=8, line_alpha=0.7, line_color="#D95B43") hist_fig.add_glyph(fit_hist_source, fit_line) # whenever a widget changes, the changes are tracked and histogram always updated for widget in [lf_ticker, ticker, bin_slider, freq_slider]: widget.on_change('value', update) # when selected value changes, take the following methods of actions # lf_ticker.on_change('value', lf_selection_change) # ticker.on_change('value', selection_change) # what to do when freq slider value changes def freq_change(attr, old, new): select_freq = source.selected.indices[0] # update histogram and fit line hist, edges = np.histogram(lf.spg[chan, select_freq, :], bins=select_bin, density=True) rv = expon( scale=sp.stats.expon.fit(lf.spg[chan, select_freq, :], floc=0)[1]) hist_source.data = { 'top': hist, 'left': edges[:-1], 'right': edges[1:] } fit_hist_source.data = {'x': edges, 'y': rv.pdf(edges)} hist_fig.title.text = 'Freq = %.1fHz, p-value = %.4f' % ( select_freq, lf.ks_pvals[chan, select_freq]) create_hist(hist_fig=hist_fig, hist_source=hist_source) fit_line = bokeh.models.glyphs.Line(x='x', y='y', line_width=8, line_alpha=0.7, line_color="#D95B43") hist_fig.add_glyph(fit_hist_source, fit_line) # organize layout widgets = row(lf_ticker, ticker) sliders = row(freq_slider, bin_slider) layout = column(widgets, sliders, all_plots) # doc.add_root(layout) return layout # In the notebook, just pass the function that defines the app to show # show(modify_doc, notebook_handle=True) # curdoc().add_root(layout) - for .py file # curdoc().add_root(layout) # h = show(layout, notebook_handle=True) # In the notebook, just pass the function that defines the app to show # show(modify_doc) # curdoc().add_root(layout) # for .py file
dict = {} for attr in attributes[1:]: dict["timestamp_"+attr] = [] dict[attr] = [] # The data sources for the main plot and the task boxes source = ColumnDataSource(dict) task_source = ColumnDataSource({"tasks" : [], "time" : []}) # The data source for the plo displaying the active tasks over time session_source = ColumnDataSource({"xss": [], "yss": [], "colors": [], "tasktype": [], "running_tasks": []}) source.data, task_source.data, session_source.data = query_events(current_run) # a dropdown menu to select a run for which data shall be visualized run_menu = [(run_format(k, v['numLogEntries'], v['tstart']), add_prefix(k)) for k, v in run_map.iteritems() if v['tstart'] is not None] # use None for separator dropdown = Dropdown(label="run", button_type="warning", menu=run_menu) dropdown.on_click(lambda newValue: select_run(rem_prefix(newValue))) manualLegendBox = Div(text=legendFormat(task_types), width=PLOT_WIDTH, height=80) # info boxes to display the number of log messages in this run and the elapsed wall clock time numMessages = Div(text=infoBoxFormat("Messages", 0), width=200, height=100) runID = Div(text=infoBoxFormat("run", str(current_run)), width=400, height=100) startTime = Div(text=infoBoxFormat("start time [ms]", str(general_info["start_time"])), width=200, height=100) # Set the properties of the first plot p = figure(plot_height=PLOT_HEIGHT, plot_width=PLOT_WIDTH,
def index(): transactioncity_list = ['All', 'CINCINNATI', 'CLEARWATER', 'WAXHAW', 'SIDNEY', 'Richmond', 'PARKERSBURG', 'ELGIN', 'ROUND LAKE', 'EAST PEORIA', 'BARTONVILLE', 'MOORESVILLE', 'TROUTMAN', 'ERLANGER', 'LOUISVILLE', 'ELKHART', 'MERRILLVILLE', 'EVANSVILLE', 'MOORESVILLE', 'ROCKY RIVER', 'WAPAKONETA', 'Columbus', 'LEXINGTON'] controls = { "transactionamount": Slider(title="Min # transaction amount", value=10, start=10, end=200000, step=10), "min_year": Slider(title="Start Year", start=1970, end=2021, value=1970, step=1), "max_year": Slider(title="End Year", start=1970, end=2021, value=2021, step=1), "transactioncity": Select(title="transaction city", value="All", options=transactioncity_list) } controls_array = controls.values() def selectedData(): res = get("pKlngQAWSGXeC43W", offset, limit) return res source = ColumnDataSource() callback = CustomJS(args=dict(source=source, controls=controls), code=""" if (!window.full_data_save) { window.full_data_save = JSON.parse(JSON.stringify(source.data)); } var full_data = window.full_data_save; var full_data_length = full_data.x.length; var new_data = { x: [], y: [], color: [], title: [], released: [], imdbvotes: [] } for (var i = 1; i < full_data_length; i++) { if (full_data.imdbvotes[i] === null || full_data.released[i] === null || full_data.transactioncity[i] === null) continue; if ( full_data.imdbvotes[i] > controls.transactionamount.value && Number(full_data.released[i].slice(-4)) >= controls.min_year.value && Number(full_data.released[i].slice(-4)) <= controls.max_year.value && (controls.transactioncity.value === 'All' || full_data.transactioncity[i].split(",").some(ele => ele.trim() === controls.transactioncity.value)) ) { Object.keys(new_data).forEach(key => new_data[key].push(full_data[key][i])); } } source.data = new_data; source.change.emit(); """) fig = figure(plot_height=600, plot_width=720, tooltips=[("transaction date", "@transactiondate"), ("transaction type", "@transactiontype"), ("merchant city", "@merchantcity")]) fig.circle(x="x", y="y", source=source, size=5, color="color", line_color=None) fig.xaxis.axis_label = "User Identifiers" fig.yaxis.axis_label = "User transaction amounts" transactions = selectedData() # print(transactions) source.data = dict( x = [d['hshdnum'] for d in transactions], y = [d['transactionamount'] for d in transactions], color = ["#FF9900" for d in transactions], date = [d['transactiondate'] for d in transactions], type = [d['transactiontype'] for d in transactions], # imdbvotes = [d['imdbvotes'] for d in transactions], transactioncity = [d['merchantcity'] for d in transactions] ) for single_control in controls_array: single_control.js_on_change('value', callback) inputs_column = column(*controls_array, width=320, height=1000) layout_row = row([ inputs_column, fig ]) script, div = components(layout_row) return render_template( 'index.html', plot_script=script, plot_div=div, js_resources=INLINE.render_js(), css_resources=INLINE.render_css(), )
def ajax_getplot(x, y, y_bottom, ref_value): #fi,ff,y_bottom,ref_value,x,y): # En la ventana del plot graf = figure(tools="save", x_axis_label="Frequency [Hz]", y_axis_label='Power [dBm]', width=700, height=400, sizing_mode='stretch_width', x_range=(x[0], x[-1]), y_range=(float(y_bottom), float(ref_value))) graf.toolbar.logo = None graf.toolbar.active_drag = None graf.toolbar.active_scroll = None graf.yaxis.major_label_text_font_style = 'bold' graf.xaxis.major_label_text_font_style = 'bold' graf.xaxis.axis_label_text_font_style = 'bold' graf.yaxis.axis_label_text_font_style = 'bold' graf.xaxis[0].formatter.use_scientific = True graf.xaxis[0].ticker.desired_num_ticks = 15 graf.yaxis[0].ticker.desired_num_ticks = 10 graf.ygrid.grid_line_alpha = 0.4 graf.ygrid.grid_line_dash = [6, 4] graf.xgrid.grid_line_alpha = 0.4 graf.xgrid.grid_line_dash = [6, 4] # graf.ygrid.minor_grid_line_alpha = 0.1 # graf.ygrid.minor_grid_line_color = 'navy' # graf.xgrid.minor_grid_line_alpha = 0.1 graf.background_fill_color = "black" graf.border_fill_color = "black" graf.border_fill_alpha = 0 graf.xaxis.axis_line_color = "white" graf.yaxis.axis_line_color = "white" props = dict(line_width=4, line_alpha=0.7) # source for (marker_abs, markers [CANT_MARKERS]) source_markers = ColumnDataSource(data={}) # source for table of graf's markers source_table = ColumnDataSource() # strings for table of graf's markers source_table_share = ColumnDataSource( ) # only for share strings of table's rows between graf_adapter.js, checkbox_callback.js ################################################################################################################################################################# # # -------------------------------------------------------------------------------------- # button_height = 30 # button_width = 70 #SLIDER_WIDTH = 500 # px CHECKBOX_WIDTH = 100 # -------------------------------------------------------------------------------------- if x != 0 and y != 0: max_abs_y = max(y) max_abs_x = argmax(y) #x_npa=asarray(x) y_npa = asarray(y) x_axis = linspace(x[0], x[-1], len(x)) else: y_bottom = -100 ref_value = -60 y_npa = asarray([0, 0]) x_axis = [0, 0] max_abs_y = 0 max_abs_x = 0 ################################################################################################################################################################# # Sliders de marcadores # solicitar frecuencias al analizador sliders = [] if x[0] != x[-1]: step = (x[-1] - x[0]) / len(x) if step <= 0: step = 1 init = (max_abs_x * step) + x[0] for i in range(0, CANT_MARKERS): sliders.append( Slider(start=x[0], end=x[-1], value=init, step=step, title="MARKER " + str(i + 1))) else: for i in range(0, CANT_MARKERS): sliders.append( Slider(start=0, end=1, value=0, step=1, title="MARKER " + str(i + 1))) ################################################################################################################################################################# # Tablas de configuracion (las de solo lectura) source_set_an = ColumnDataSource() source_set_gen = ColumnDataSource() source_set_powm = ColumnDataSource() ################################################################################################################################################################# # preparo el marcador movil # ve posibilidad de agregar PointDrawTool de hovertools # http://docs.bokeh.org/en/1.0.0/docs/user_guide/tools.html#click-tap-tools graf.add_tools( HoverTool( tooltips=[ ('frec', '@x{0,0} Hz'), ('amp', '@y dBm'), # use @{ } for field names with spaces ], point_policy='follow_mouse', mode='vline')) with open("static/js/graf_adapter.js", "r") as f: code = f.read() adapter = CustomJS(args=dict(graf=graf, sliders=sliders, source_markers=source_markers, source_table=source_table, source_table_share=source_table_share, source_set_an=source_set_an, source_set_gen=source_set_gen, source_set_powm=source_set_powm), code=code) source = AjaxDataSource(data_url=request.url_root + 'data/', polling_interval=1000, mode='replace', adapter=adapter) source.data = dict(x=[], y=[], y_bottom=[], ref_value=[], start_freq=[], stop_freq=[]) #, power = [] ) # span = [], center_freq = [], demod_time = [], ref_level = [], # ANALIZADOR # lf_freq = [], lf_level = [], rf_freq = [], rf_level = [], fm_mod_freq = [], am_mod_freq = [],am_mod_index= [],fm_mod_index= [],pm_mod_index= [], power = []) # GENERADOR graf.line('x', 'y', source=source, line_color="cyan") ############################################################################### # maximos relativos max_rel_x = argrelextrema(y_npa, greater) #dato pasado a numpy array ############################################################################### # datos para la tabla de datos info = [] value = [] # tabla de datos source_table.data = dict(x_data=info, y_data=value) source_table_share.data = dict(x_data=info, y_data=value) #source_table = source columns = [ TableColumn(field="x_data", title="Information"), TableColumn(field="y_data", title="Value") ] data_table = DataTable(source=source_table, columns=columns, height=200, width=400) ############################################################################### set_div = Div(text="<b>Current Settings</b>") # tabla de valores seteados actualmente del analizador source_set_an.data = dict( configuration=[ "X scale", "Y scale", "Start freq", "Stop freq", "Span", "Center freq", "Ref level", "Demod time", "Demod type", "Input att", "Resolution BW", "Scale div", "Avg state", "Avg times" ], value=[ "LIN", "LOG", "0.0", "1.0", "1.0", "1.0", "0.0", "0.0", "FM", "10", "100000", "10.0", "WRITe", "1" ], ) columns_set_an = [ TableColumn(field="configuration", title="Analizer"), TableColumn(field="value", title="value"), ] info_table_an = DataTable(source=source_set_an, columns=columns_set_an, width=220, height=180) # tabla de valuees seteados actualmente en el generador source_set_gen.data = dict( configuration=[ "LF state", "LF freq", "LF level", "LF waveform", "RF state", "RF freq", "RF level", "AM state", "AM source", "AM mod freq", "AM mod index", "AM waveform", "Modulation type", "Modulation state", "FM mod freq", "FM mod index", "FM waveform", "PM mod freq", "PM mod index", "PM waveform" ], value=[ "OFF", "0.0", "0.0", "SINE", "0.0", "0.0", "0.0", "OFF", "INT", "0.0", "0.0", "SINE", "FM", "OFF", "0.0", "0.0", "SINE", "0.0", "0.0", "0.0" ], ) columns_set_gen = [ TableColumn(field="configuration", title="Generator"), TableColumn(field="value", title="value"), ] info_table_gen = DataTable(source=source_set_gen, columns=columns_set_gen, width=220, height=180) # tabla de valuees seteados actualmente en el generador source_set_powm.data = dict( configuration=["Duty cycle", "Average"], value=["50", "1"], ) columns_set_powm = [ TableColumn(field="configuration", title="Power meter"), TableColumn(field="value", title="value"), ] info_table_powm = DataTable(source=source_set_powm, columns=columns_set_powm, width=200, height=180) #source_table = source ############################################################################### ## cosas a graficar # source5 = ColumnDataSource(data=dict(x5=[x_axis[max_abs_x]], y5=[max_abs_y])) # source4 = ColumnDataSource(data=dict(x4=[x_axis[max_abs_x]], y4=[max_abs_y])) # source3 = ColumnDataSource(data=dict(x3=[x_axis[max_abs_x]], y3=[max_abs_y])) # source2 = ColumnDataSource(data=dict(x2=[x_axis[max_abs_x]], y2=[max_abs_y])) # source5 = ColumnDataSource(data=dict(x5=[], y5=[])) # source4 = ColumnDataSource(data=dict(x4=[], y4=[])) # source3 = ColumnDataSource(data=dict(x3=[], y3=[])) # source2 = ColumnDataSource(data=dict(x2=[], y2=[])) # marcadores moviles que arrancan en el absolute maximum # l5=graf.circle('x5', 'y5', source=source5, color="lawngreen", line_width=8, line_alpha=0.7 ) # l4=graf.circle('x4', 'y4', source=source4, color="lime", line_width=8, line_alpha=0.7) # l3=graf.circle('x3', 'y3', source=source3, color="yellow", line_width=8, line_alpha=0.7) # l2=graf.circle('x2', 'y2', source=source2, color="blue", line_width=8, line_alpha=0.7) # custom markers #markers_rel_dict = {} markers = [] colors = ["yellow", "red", "pink", "lime"] for i in range(0, CANT_MARKERS): x_label = 'x_mark_' + str(i + 1) y_label = 'y_mark_' + str(i + 1) source_markers.data[x_label] = [x_axis[max_abs_x]] source_markers.data[y_label] = [max_abs_y] markers.append( graf.circle(x_label, y_label, source=source_markers, color=colors[i], line_width=8, line_alpha=0.7)) #l1=graf.circle(x_axis[max_rel_x[0]] , y_npa[max_rel_x[0]], color="yellowgreen", **props) # max abs marker source_markers.data['x_abs'] = [x_axis[max_abs_x]] source_markers.data['y_abs'] = [max_abs_y] marker_abs = graf.circle(x='x_abs', y='y_abs', source=source_markers, color="red", line_width=8, line_alpha=0.7) #marker_abs=graf.circle(x_axis[max_abs_x],max_abs_y, color="green", **props) ############################################################################### # presentacion del maximo #maximo=str('%.2f' % max_abs_y)+"V @ "+str('%.2f' % x_axis[max_abs_x]+" rad") # presentacion de maximos relativos max_rel = ["a" for i in range(len(max_rel_x[0]))] for i in range(len((max_rel_x[0]))): max_rel[i] = (str('%.2f' % y_npa[max_rel_x[0][i]]) + "V @ " + str('%.2f' % x_axis[max_rel_x[0][i]] + " rad")) ############################################################################### # Sliders de marcadores #callback unico para todos los sliders with open("static/js/callback_sm.js", "r") as f: callback_sm_code = f.read() callback_sm = CustomJS(args=dict(source_table=source_table, source=source, source_markers=source_markers, sliders=sliders, markers=markers, graf=graf, props=props), code=callback_sm_code) for i in range(0, CANT_MARKERS): sliders[i].js_on_change('value', callback_sm) ############################################################################### # Acciones relativas a los checkbox checkbox_labels = ["Max. Abs"] # checkbox_labels = ["Max. Abs", "Max. Rel"] checkbox_preset = CheckboxGroup(labels=checkbox_labels, active=[], width=CHECKBOX_WIDTH) checkbox_mark = CheckboxGroup( labels=["Mark 1", "Mark 2", "Mark 3", "Mark 4"], active=[], width=CHECKBOX_WIDTH) #checkbox.active=[] <- indica los índices de los elementos "activados" (para activar el 1: [1], para activar el 0 y el 3: [0 3]) #checkbox.active=[] #checkbox.active[0]=False marker_abs.visible = False #checkbox.active[1]=False for i in range(0, CANT_MARKERS): markers[i].visible = False pass #checkbox_mark.active=[] #checkbox_mark.active[0]=False # marker[i].visible=False #checkbox_mark.active[1]=False # marker[i].visible=False #checkbox_mark.active[2]=False # marker[i].visible=False #checkbox_mark.active[3]=False # marker[i].visible=False ##---------------------------------------------------------------------------## with open("static/js/checkbox_callback.js", "r") as f: checkbox_code = f.read() cjs = CustomJS(args=dict(marker_abs=marker_abs, markers=markers, checkbox_preset=checkbox_preset, checkbox_mark=checkbox_mark, source_table=source_table, source=source, source_markers=source_markers, source_table_share=source_table_share, sliders=sliders), code=checkbox_code) checkbox_preset.js_on_click(cjs) checkbox_mark.js_on_click(cjs) ##---------------------------------------------------------------------------## sliders_col = column(sliders) # Ploteos layout_graf = gridplot([[graf]], sizing_mode='scale_width', toolbar_location="right") layout_widgets = widgetbox(row(checkbox_preset, checkbox_mark, sliders_col, data_table), sizing_mode='scale_width') layout_seteos = widgetbox(row(info_table_an, info_table_gen, info_table_powm), sizing_mode='scale_width') analyzer_layout = layout( [layout_graf, layout_widgets, set_div, layout_seteos], sizing_mode='scale_width') return components(analyzer_layout)
T4 = -((q * (1 / (h1 * A_chamber))) - Tc) T3 = -((q * (L1 / (cond * A_innerbrick))) - T4) T2 = -((q * (L2 / (k_ws * A_sand))) - T3) T1 = [] for i in time_range: abc = (((L3 * h2 * T_bulk[i]) / k_brick) + T2) / (1 + (L3 * h2) / k_brick) T1.append(abc) #print(T1) return T1 Costa_T1 = T1_calc(initial_dims, yearly_temps_df.iloc[2], 18, "Brick", range(0, 12)) sourceDP.data = dict(time=time_range1, temps=yearly_temps_df.iloc[2], dp=dp_Costa, T1=Costa_T1) gl3 = g4.line('time', 'T1', source=sourceDP, legend_label="Outer Wall Temperature", line_width=2, line_dash=[8, 2], color='purple') #Adding display of value for when each line is hovered over at specific point h1 = HoverTool(tooltips=[("Temp", "@temps")], renderers=[gl1]) h2 = HoverTool(tooltips=[("Temp", "@dp")], renderers=[gl2]) h3 = HoverTool(tooltips=[("Temp", "@T1")], renderers=[gl3]) g4.add_tools(h1, h2, h3)
checkbox_scales = CheckboxGroup(labels=scales, active=[0]) range_slider = RangeSlider(start=0, end=10, value=(1, 9), step=.1, title="Stuff") # # #plot_title = TextInput(title="Title :", value='') source = ColumnDataSource(data=dict(x=[], y=[])) source.data = dict(y=df[df['ID'] == "BE156915425"].ix[:, 'CH4'].tolist(), x=range(len(y))) #hover = HoverTool(tooltips=[ # ("Customer", "@customer"), # ("Area", "@area"), # ("Equipment", "@equipment"), # ("POM", "@POM"), # ("x","@x"), # ("y","@y") #]) # p = figure(plot_width=page_width, plot_height=page_width / 2, title="", toolbar_location="right", tools=[
rk_data['color'] = rk_data['Type'].map(mapper) # Column with colors my_num_axes = [ 'Distance (km)', 'Average Speed (km/h)', 'Climb (m)', 'Average Heart Rate (bpm)' ] for_totals = ['Distance (km)', 'Climb (m)'] default_y_axis = 'Distance (km)' src_nm = ColumnDataSource() src_nm.data = { 'x_ax': rk_data.index, 'y_ax': rk_data[default_y_axis], 'average_speed': rk_data['Average Speed (km/h)'], 'duration': rk_data['Duration'], 'average_pace': rk_data['Average Pace'], 'distance': rk_data['Distance (km)'], 'climb': rk_data['Climb (m)'], 'ahr': rk_data['Average Heart Rate (bpm)'], 'type': rk_data['Type'], 'col': rk_data['color'], } hvr = HoverTool() tooltip_main = [('Activity', '@type'), ('Date', '@x_ax{%a %b %d %Y}'), ('Distance', '@distance{0.00} km'), ('Duration', '@duration{%H:%M:%S}'), ('Average Pace', '@average_pace{%M:%S}')] current_tooltip = [('Average Speed', '@average_speed{0.00} km/h')] hvr.tooltips = tooltip_main + current_tooltip hvr.formatters = {
t1_sm_TF=[], t1_s_rms=[], t1_s_rms_=[], t1_sr_TF=[])) ts1 = figure(title="Energy Change", plot_width=500, plot_height=500, tools=tools, active_drag="xbox_select") t1 = "r1" data_1 = get_data(t1) source_1.data = source_1.from_df(data_1[[ 't1', 't1_e', 't1_e_', 't1_e_TF', 't1_c_max', 't1_c_max_', 't1_gm_TF', 't1_c_rms', 't1_c_rms_', 't1_gr_TF', 't1_s_max', 't1_s_max_', 't1_sm_TF', 't1_s_rms', 't1_s_rms_', 't1_sr_TF' ]]) source_1_static.data = source_1.data steps = [int(i) for i in source_1_static.data["step"]] t1s = [i for i in source_1_static.data["t1"]] ts1.line(steps, t1s, color='grey', legend='r1') t1 = "r2" data_1 = get_data(t1) source_1.data = source_1.from_df(data_1[[ 't1', 't1_e', 't1_e_', 't1_e_TF', 't1_c_max', 't1_c_max_', 't1_gm_TF', 't1_c_rms', 't1_c_rms_', 't1_gr_TF', 't1_s_max', 't1_s_max_', 't1_sm_TF', 't1_s_rms', 't1_s_rms_', 't1_sr_TF' ]]) source_1_static.data = source_1.data
df["Edited"] = np.zeros(len(df), dtype=bool) if "include" in df.columns: pass else: df["include"] = df.apply(lambda _: "yes", axis=1) # df["color"] = df.Edited.apply(lambda x: 'red' if x else 'black') # color clusters df["color"] = df.apply(lambda x: Category20[20][int(x.CLUSTID) % 20] if x.MEMCNT > 1 else "black", axis=1) # make datasource source = ColumnDataSource(data=dict()) source.data = {col: df[col] for col in df.columns} # read dims from config config_path = Path("peakipy.config") if config_path.exists(): config = json.load(open(config_path)) print(f"Using config file with --dims={config.get('--dims')}") dims = config.get("--dims", [0, 1, 2]) _dims = ",".join(str(i) for i in dims) else: # get dim numbers from commandline _dims = args.get("--dims") dims = [int(i) for i in _dims.split(",")] # read pipe data
elif (not Active and mass_pos[0] <= 8): g1coriolisforce = curdoc().add_periodic_callback(move, 100) glob_callback.data = dict(cid=[g1coriolisforce]) glob_active.data = dict(Active=[True]) glob_AtStart.data = dict(aS=[True]) # /output def chooseRef(attrname, old, new): glob_OnTable.data = dict(oT=[new == 1]) # /output # initialise the start position of the ball # (these lines are not in initialise() as it is unnecessary to call "circ_to_cart" at every "stop" or "reset") [mass_pos] = glob_mass_pos.data["pos"] # input/ [X, Y] = circ_to_cart([mass_pos[0]], [mass_pos[1]]) glob_startPos.data = dict(sP=[[X[0], Y[0]]]) # /output # initialise object positions initialise() ## Create slider to rotate plate Omega_input = Slider(title=u"\u03C9", value=2.0, start=0.0, end=10.0, step=0.1) Omega_input.on_change('value', rotation_speed) ## Create slider to select v0-x v0_input_x = Slider(title=u"v\u2092-x", value=2.0, start=-5.0, end=5.0, step=0.5) v0_input_x.on_change('value', particle_speed_x)
def index(): def selecteddata(): con = psycopg2.connect(database=DATABASE, user=USER, password=PASSWD, host=HOST, port=PORT) # print("Database opened successfully") cur = con.cursor() statement = """ select classnrshots, xagg, nr_player_shots, yagg, pcttotal, pctplayer, season, pctdiff, playername, playerid, team from shots_agg """ cur.execute(statement) rows = cur.fetchall() res = [] for row in rows: record_dict = { "classnrshots" : row[0], "xagg" : row[1], "nr_player_shots" : row[2], "yagg" : row[3], "pcttotal" : row[4], "pctplayer" : row[5], "season" : row[6], "pctdiff" : row[7], "playername" : str(row[8]), "playerid" : str(row[9]), "team" : str(row[10]) } res.append(record_dict) print("Data loaded") con.close() return res src = selecteddata() seasons_list = sorted(list(set([str(item['season']) for item in src]))) players_list = sorted(list(set([item['playername'] for item in src]))) controls = { "playername": Select(title="Player", value="ALL", options=players_list), "season": Select(title="Season", value="2017", options=seasons_list) } controls_array = controls.values() source = ColumnDataSource() callback = CustomJS(args=dict(source=source, controls=controls), code=""" if (!window.full_data_save) { window.full_data_save = JSON.parse(JSON.stringify(source.data)); } var full_data = window.full_data_save; var full_data_length = full_data.x.length; var new_data = { x: [], y: [], color : [], size : [], nr_player_shots : [], pctplayer : [], playername : []} for (var i = 0; i < full_data_length; i++) { if (full_data.x[i] === null || full_data.y[i] === null || full_data.playername[i] === null) continue; if ( ( full_data['playername'][i] == controls.playername.value) && ( full_data['season'][i] == controls.season.value) ) { Object.keys(new_data).forEach(key => new_data[key].push(full_data[key][i])); } } source.data = new_data; source.change.emit(); """) color_mapper = LinearColorMapper(palette=Turbo256,low=min([float(d['pctdiff']) for d in src]),high=max([float(d['pctdiff']) for d in src])) c = Court(tooltips=[("Nr FG", "@nr_player_shots"), ("Pct", "@pctplayer")]) fig = c.draw_court() fig.circle(x="x", y="y", source=source, size="size", line_color=None, color={'field': 'color', 'transform': color_mapper}) color_bar = ColorBar(color_mapper=color_mapper, label_standoff=12) fig.add_layout(color_bar, 'right') source.data = dict( x = [float(d['xagg']) for d in src], y = [float(d['yagg']) for d in src], color = [float(d['pctdiff']) for d in src], size = [int(d['classnrshots'])*3 for d in src], nr_player_shots = [float(d['nr_player_shots']) for d in src], pctplayer = [float(d['pctplayer'])*100.0 for d in src], playername = [d['playername'] for d in src], season = [int(d['season']) for d in src] ) for single_control in controls_array: single_control.js_on_change('value', callback) inputs_column = column(*controls_array, width=220, height=300) layout_row = column ([ inputs_column, fig ]) script, div = components(layout_row) return render_template( 'index.html', plot_script=script, plot_div=div, js_resources=INLINE.render_js(), css_resources=INLINE.render_css(), )
# imports from bokeh.io import curdoc from bokeh.plotting import figure from bokeh.models import ColumnDataSource from bokeh.layouts import column from bokeh.models.widgets import Dropdown from bokeh.sampledata.iris import flowers # load data # setup data species = 'setosa' source = ColumnDataSource(flowers.loc[flowers.species == species]) source.data = ColumnDataSource.from_df(flowers.loc[flowers.species == species]) # setup tooltips tooltips = [('index', '@index'), ('Sepal Length', '@sepal_length'), ('Sepal Width', '@sepal_width'), ('Species', '@species')] # setup plot p = figure(plot_width=400, plot_height=400, tooltips=tooltips) p.circle('sepal_length', 'sepal_width', size=10, color='blue', alpha=0.5, source=source) # setup widget menu = [(s.capitalize(), s) for s in flowers.species.unique()] dropdown = Dropdown(label='Species', menu=menu)
} return collect #print(collect) #dataSource.stream(collect, 60) def __call__(self): dataSource.stream(self.update(), 60) mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001) stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01) #trackerThread = classtracker.ClassTracker().start_periodic_snapshots() interfaceContainer = InterfaceContainer() dataDict = interfaceContainer.update() dataSource.data = dataDict palette = viridis(len(dataDict)) for i, (key, value) in enumerate(dataDict.items()): if key != 'time': p.line(x='time', y=key, source=dataSource, color=palette[i]) print(key) #p.legend.location= "bottom_center" #p.legend.click_policy = "mute" #p.legend.orientation="horizontal" interfaceSelection = CheckboxGroup( labels=interfaceContainer.getInterfaces(), active=[i for i in range(len(interfaceContainer.getInterfaces()))]) statSelection = CheckboxGroup( labels=list(interfaceContainer.stats.keys()), active=[i for i in range(len(interfaceContainer.getInterfaces()))])
def get_data_country(data_c): source = ColumnDataSource(data=dict(date=[], price=[], date_formatted=[], hour_formatted=[])) source.data = source.from_df(data_c[['date','price','date_formatted','hour_formatted']]) return source
data = source_data_from_df(df) layout.set_select(selector=dict(name="ChosenSource"), updates=dict(data=data)) old_table = layout.select_one(dict(name='ChosenTable')) tcols = table_columns_from_source(old_source) layout.set_select(selector=dict(name="ChosenTable"), updates=dict(columns=tcols, fit_columns=True, width=900)) return servers_source = ColumnDataSource() servers_source.name = 'server' servers_source.data = source_data_from_list(lst=Servers, key='Name',) servers_table = data_table(source=servers_source, titlemap={"Name":"Server"}, width=200) init_dbs = databases_on_server(server=Servers[0]) server_dbs_source = ColumnDataSource() server_dbs_source.name = 'db' server_dbs_source.data = source_data_from_list(lst=init_dbs, key='Name',) server_dbs_table = data_table(source=server_dbs_source, titlemap={"Name":"Db"}, width=200) server_dbs_source.on_change("selected", update_tbl_source)
p.x_range.end = 180 sourcefk = ColumnDataSource(data=dict(x=[1, 2, 3], y=[1, 2, 3])) data_raw = np.loadtxt(curves[i["a"]]) xdata = np.empty(0) ydata = np.empty(0) ydata1 = np.empty(0) xdata = np.append(xdata, data_raw[:, 0] * 1e9) ydata = np.append(ydata, data_raw[:, 2] * 1e12) ydata1 = np.append(ydata1, data_raw[:, 1] * 1e12) data = dict(x=xdata, y=ydata) sourcefk.data = data p.line('x', 'y', source=sourcefk) p.xaxis.axis_label = "Extension [nm]" p.xaxis.axis_label_text_font_size = "20pt" p.xaxis.axis_label_text_font_style = 'bold' p.yaxis.axis_label = "Force [pN]" p.yaxis.axis_label_text_font_size = "20pt" p.yaxis.axis_label_text_font_style = 'bold' print "ssss", source.data['x'] print "ssss", source.data['y'] def next():
columns = [ TableColumn(field="name", title="Name", width=120), TableColumn(field="phone_number", title="Phone", width=100), TableColumn(field="tenure", title="Tenure", width=60, formatter=StringFormatter()), TableColumn(field="email", title="Email", width=150) # TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="0.000%")), ] customer_directory_table = DataTable(source=customer_directory_source, columns=columns, row_headers=False, editable=True, width=280, height=300, fit_columns=False) customer_directory_source.on_change('selected', lambda attr, old, new: selection_update(new)) customer_directory_source.data = { 'name': customer_directory_df.name, 'phone_number': customer_directory_df.phone_number, 'tenure': ((customer_directory_df.tenure / 365).astype(int)).astype(str) + 'yr', 'email': customer_directory_df.email } churn_table_columns = [ TableColumn(field="Characteristic", title="Characteristic"), TableColumn(field="Prediction", title="Prediction") # TableColumn(field="Prediction", title="Probability", formatter=NumberFormatter(format="0.000%")) ] machine_learning_table = ColumnDataSource(data=dict()) ML_table = DataTable(source=machine_learning_table, columns=churn_table_columns, row_headers=False, editable=True, width=280, height=160) ##############################################################################
port='5432') return conn except: print('Can not connect to database') print('###################################################') df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) print('df:\n', df) print('source:\n', source) data = df.rolling('{0}D'.format(5)).mean() print('data:\n', data) source.data = ColumnDataSource(data=data).data print('source.data:\n', source.data) # ------------------------------------------- conn = connect_to_db() # QUERY: TIME SERIES OF H500, ERC AT ONE LOCATION # Reading data into a list object 'results' directly from postgres fire_weather_db: cur = conn.cursor() sql = 'select id, lat, lon, date, h500, h500_grad_x, erc from narr_erc \ where lat = 39.2549 and lon = 236.314 \ order by id' df = pd.read_sql(sql, conn) cur.close() conn.close()
state_widget.on_change('value', update) product_widget.on_change('value', update) issue_widget.on_change('value', update) min_complaints_widget.on_change('value', update) ### Step 3: Build the charts # Build state bar chart state_bar_chart = Bar(build_state_data(), label="state", values='complaint_count', toolbar_location=None, title="Complaints by State", width=1300, height=200, ylabel="", xlabel="", color="#2cb34a") # Build zip code scatter plot zip_data = build_zip_data() zip_source.data = dict(x = zip_data["median_income"], y = zip_data["complaint_count"]) zip_scatter_plot = Figure(plot_height=500, plot_width=1000, title="Complaints by Median Income", title_text_font_size='14pt', x_range=Range1d(0,100000)) zip_scatter_plot.circle(x="x", y="y", source=zip_source, size=4, color="#addc91", line_color=None, fill_alpha="0.95") zip_xaxis = zip_scatter_plot.select(dict(type=Axis, layout="below"))[0] zip_xaxis.formatter.use_scientific = False # Build the data table columns = [ TableColumn(field="labels", title="Label"), TableColumn(field="data", title="Data") ] data_table = DataTable(source=table_source, columns=columns,
# Create widgets select_symbol = Select(options=symbols, title='Select a symbol', value='NIFTY') button = Button(label='Refresh', button_type="success") # Create plots p = figure(title='Open interest chart for NIFTY futures', x_axis_type='datetime', tooltips=[('date', '@date'), ('combined OI', '@combined_oi{0 a}'), ('expiry_at', '$name q:@$name{0.0 a}')], background_fill_color='beige', background_fill_alpha=0.4) cols, data = get_open_interest(df, 'NIFTY') data['date'] = data.timestamp.dt.date colors = Dark2[6][:len(cols)] source.data = source.from_df(data) p.yaxis[0].formatter = NumeralTickFormatter(format='0.00 a') p.vbar_stack(cols, width=3.6e7, x='date', color=colors, source=source, fill_alpha=0.7) price_data = get_price_oi(df, 'NIFTY') prices.data = prices.from_df(price_data) h0 = price_data['close'].max() l0 = price_data['close'].min() h1 = price_data['open_int'].max() l1 = price_data['open_int'].min()