'pop' : (gapminder.loc[yr].population / 20000000) + 2, 'gdp' : gapminder.loc[date_start].gdp, 'child mortality' : gapminder.loc[date_start].child_mortality, 'region' : gapminder.loc[yr].region, } source.data = new_data plot.x_range.start = min(gapminder[x]) plot.x_range.end = max(gapminder[x]) plot.y_range.start = min(gapminder[y]) plot.y_range.end = max(gapminder[y]) plot.title.text = '%s VS. %s in %d' % (y,x,yr) #setting up the slider slider = Slider(start=date_start,end=date_end,step=1,value=date_start,title='Year') #making thing interactive using the update function slider.on_change('value',update_value) x_value.on_change('value', update_value) y_value.on_change('value', update_value) plot.add_tools(hover) layout = row(widgetbox(x_value,y_value,slider), plot) curdoc().add_root(layout) curdoc().title = "Gapminder"
def get(self, request): s1 = ColumnDataSource(data=test_data) TOOLTIPS = [ ("index", "$index"), ("(x,y)", "($x, $y)"), ("patient id", "@patient_id"), ] p1 = figure( # plot_width=400, # plot_height=400, tools=tools, title="Select Here", tooltips=TOOLTIPS, ) p1.circle('x', 'y', source=s1, alpha=0.6, size=15) s2 = ColumnDataSource(data=dict(x=[], y=[])) p2 = figure(plot_width=400, plot_height=400, x_range=(0, 100), y_range=(0, 100), tools="", title="Watch Here") p2.circle('x', 'y', source=s2, alpha=0.6) s1.selected.js_on_change( 'indices', CustomJS(args=dict(s1=s1, s2=s2), code=""" var tbody = $('#tbl_selected_items').children('tbody'); var table = tbody.length ? tbody : $('#tbl_selected_items'); var row = '<tr>'+ '<td>%%seq%%</td>'+ '<td>%%patient_id%%</td>'+ '<td>%%x%%</td>'+ '<td>%%y%%</td>' '</tr>'; $('#tbl_selected_items tbody').empty(); var inds = cb_obj.indices; var d1 = s1.data; var d2 = s2.data; d2['x'] = [] d2['y'] = [] var row_no = 0; for (var i = 0; i < inds.length; i++) { var x = d1['x'][inds[i]]; var y = d1['y'][inds[i]]; var patient_id = d1['patient_id'][inds[i]]; d2['x'].push(x); d2['y'].push(y); //row_no += 1; table.append(row.compose({ 'seq': (i+1), 'patient_id': patient_id, 'x': x, 'y': y})); } s2.change.emit(); """)) dx_min = test_data['x'].min() dx_max = test_data['x'].max() def callback_range_slider(source=test_data, window=None): print("call================", source) range_slider = RangeSlider( title="Filter range X", value=[dx_min, dx_max], start=dx_min, end=dx_max, step=1, callback=CustomJS.from_py_func(callback_range_slider)) # callback_range_slider = CustomJS(args=dict(data=test_data), code=""" # var d = data; # var range_data = cb_obj.value; # range_data_min = range_data[0]; # range_data_max = range_data[1]; # console.log(range_data[0]); # console.log(range_data[1]); # """) # # range_slider.js_on_change('value', callback_range_slider) # range_slider.on_change('value', callback_range_slider) callback_button = CustomJS(args=dict(data=test_data), code=""" var a = cb_obj.value; console.log(a[0]); console.log(a[1]); """) button_search = Button(label="Filter", width=100, disabled=False, callback=callback_button) slider = Slider(start=0, end=100, value=1, step=1, title="Range x") select = Select(title="Gender:", value="all", options=["all", "male", "female"]) row_criteria = row(range_slider, slider, select) layout = column(row_criteria, button_search, row(p1, p2)) script, div = components(layout) return render(request, 'report_radiomic_brain.html', { 'script': script, 'div': div })
from bokeh.io import curdoc from bokeh.plotting import Figure, output_file, show, ColumnDataSource from bokeh.models import HBox from bokeh.models.widgets import Slider, Select # from bokeh.sampledata.autompg import autompg as am cir_x = [10] cir_y = [10] cir_size = [10] cir_source = ColumnDataSource(data=dict(x1=cir_x, y1=cir_y, sz=cir_size)) p1 = Figure(plot_width=300, plot_height=300) p1.circle('x1', 'y1', size='sz', color='red', source=cir_source) my_slider = Slider(start=0, end=100, step=1, value=50, title="Circle Radius") def update_size(attrname, old, new): new_sz = [my_slider.value] cir_source.data = dict(x1=cir_x, y1=cir_y, sz=new_sz) for w in [my_slider]: w.on_change('value', update_size) hlayout = HBox(my_slider, p1) output_file('circle1.html') curdoc().add_root(hlayout) #show(hlayout)
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") multi_select = MultiSelect(title="Features to drop:", value=[],options=[('a','avg_dist'),('b','avg_rating_by_driver'),('c','avg_rating_of_driver'),('d','avg_surge'),('e','surge_pct'),('f','trips_in_first_30_days'),('g','luxury_car_user'),('h','weekday_pct'),('i','city_Astapor'),('k','city_Winterfell'),('l','phone_Android'),('m','phone_iPhone'),('n','phone_no_phone')]) p.add_tools(HoverTool(tooltips = [ ("Count", "@counts"), ])) def update_points(): E = ent.value N = int(input.value) T = float(tsize.value) ms= multi_select.value print(ms) ms = [str(i) for i in ms]
def create_slider(time_unit="hour"): start, end, value, step, title = _get_slider_params(time_unit) return Slider(start=start, end=end, value=value, step=step, title=title)
def attention_tab(beers): # Dataset for density plot based on Genres and range of ratings # and bandwidth for density estimation def make_dataset( genre_list, range_start, range_end, bandwidth ): xs = [] ys = [] colors = [] labels = [] for i, genre in enumerate(genre_list): subset = beers[beers['style_genre'] == genre] subset = subset[subset['ratings'].between(range_start, range_end)] kde = gaussian_kde(subset['ratings'], bw_method=bandwidth) # Evenly space x values x = np.linspace(range_start, range_end, 6500) # Evaluate pdf at every value of x y = kde.pdf(x) # Append the values to plot xs.append(list(x)) ys.append(list(y)) # Append the colors and label colors.append(genre_colors[i]) labels.append(genre) new_src = ColumnDataSource(data={'x': xs, 'y': ys, 'color': colors, 'label': labels}) return new_src def make_plot(src): p = figure(plot_width = 700, plot_height = 650, title = 'Distribution of Beer Genre Attention', x_axis_label = 'Attention of Genre (Number of Ratings of Beer)', y_axis_label = 'Density') p.multi_line('x', 'y', color = 'color', legend = 'label', line_width = 3, source = src) # Hover tool with next line policy hover = HoverTool(tooltips=[('Genre', '@label'), ('Ratings', '$x'), ('Density', '$y')], line_policy = 'next') # Add the hover tool and styling p.add_tools(hover) p = p_style(p) return p def update(attr, old, new): # List of genres to plot genres_to_plot = [genre_selection.labels[i] for i in genre_selection.active] # If no bandwidth is selected, use the default value if bandwidth_choose.active == []: bandwidth = None # If the bandwidth select is activated, use the specified bandwith else: bandwidth = bandwidth_select.value new_src = make_dataset(genres_to_plot, range_start = range_select.value[0], range_end = range_select.value[1], bandwidth = bandwidth) src.data.update(new_src.data) def p_style(p): # Title p.title.align = 'center' p.title.text_font_size = '20pt' p.title.text_font = 'serif' # Axis titles p.xaxis.axis_label_text_font_size = '14pt' p.xaxis.axis_label_text_font_style = 'bold' p.yaxis.axis_label_text_font_size = '14pt' p.yaxis.axis_label_text_font_style = 'bold' # Tick labels p.xaxis.major_label_text_font_size = '12pt' p.yaxis.major_label_text_font_size = '12pt' return p # genres and colors available_genres = list(set(beers['style_genre'])) available_genres.sort() genre_colors = Category20_16 genre_colors.sort() # Genres to plot genre_selection = CheckboxGroup(labels=available_genres, active = [0, 1]) genre_selection.on_change('active', update) range_select = RangeSlider(start = 0, end = 500, value = (0, 200), step = 50, title = 'Range of Attention (Number of Ratings)') range_select.on_change('value', update) # intial genres and data source initial_genres = [genre_selection.labels[i] for i in genre_selection.active] # Bandwidth of kernel bandwidth_select = Slider(start = 0.1, end = 5, step = 0.1, value = 2, title = 'Bandwidth for Density Plot') bandwidth_select.on_change('value', update) # Whether to set the bandwidth or have it done automatically bandwidth_choose = CheckboxButtonGroup( labels=['Choose Bandwidth (Else Auto)'], active = []) bandwidth_choose.on_change('active', update) # Make the density data source src = make_dataset(initial_genres, range_start = range_select.value[0], range_end = range_select.value[1], bandwidth = bandwidth_select.value) sidetext = Div( text="""Please use the filters below to adjust the <b>Attention Density Plot</b> as needed.""", width=250, height=50) # Make the density plot p = make_plot(src) # Add style to the plot p = p_style(p) # Put controls in a single element controls = WidgetBox(sidetext, genre_selection, range_select, bandwidth_select, bandwidth_choose) # Create a row layout layout = row(controls, p) # Make a tab with the layout tab = Panel(child=layout, title = 'Distribution of Beer Genre Attention') return tab
id2word = {v: k for k, v in word2id.items()} embeddings = np.vstack(vectors) return embeddings, id2word, word2id nmax = 50000 # maximum number of word embeddings to load src_path = 'results/eng_titles.vec' tgt_path = 'results/fr_titles.vec' #ar_titles.vec for arabic src_embeddings, src_id2word, src_word2id = load_vec(src_path, nmax) tgt_embeddings, tgt_id2word, tgt_word2id = load_vec(tgt_path, nmax) #User interface and visualization (using Bokeh) user_query = TextInput(value='medicine', title="Search for an article: ") no_of_articles = Slider(title="Number of articles", start=1, end=50, value=5, step=1) source = ColumnDataSource( data=dict(x=[], y=[], names=[], size=[], word_labels_display=[], rank=[])) columns = [ TableColumn(field="rank", title="No.", width=2), TableColumn( field="names", title="Articles", formatter=HTMLTemplateFormatter( template= '<a href="https://fr.wikipedia.org/wiki/<%= names %>" target="_blank"><%= value %></a>' )), ] data_table = DataTable(source=source,
p3.ygrid.visible = False p3.yaxis.visible = False p3.xaxis.major_tick_line_color = None # turn off y-axis major ticks p3.xaxis.minor_tick_line_color = None # turn off y-axis minor ticks p3.xaxis.major_label_text_font_size = '0pt' # turn off y-axis tick labels p3.xgrid.visible = False p3.xaxis.visible = False plot.background_fill_color = '#2F2F2F' plot.border_fill_color = '#2F2F2F' # Set up widgets electricfield = Slider(title="Initial electric field", value=1.0, start=0.0, end=5.0, step=0.1) wavelength = Slider(title="Wavelength (nm)", value=400, start=400, end=700, step=5.0) distance = Slider(title="Distance Between Slits (nm)", value=500, start=500, end=5000, step=50) length = Slider(title="Distance between slits and screen", value=1.0, start=0.0,
gateways.append((None, "--- Choose a Gateway ---")) for d in cursor: gateways.append((d["id"], d["name"])) redisconn.set("gateways", json.dumps(gateways)) except errors.ServerSelectionTimeoutError as e: print("MongoDB Server timed out: %s" % e) notificationDiv.text = "MongoDB Server timed out: %s" % e sys.exit(-1) gatewayControl = Select(title="Choose a Gateway", options=gateways) deviceControl = Select(title="Choose a Device") indicatorControl = Select(title="Choose an indicator") submitButton = Button(label="Submit", button_type="primary") timemachine = Slider(title="How many minutes back would you like to travel", start=1, end=30, value=1, step=1, callback_policy="mouseup") controls = [ gatewayControl, deviceControl, indicatorControl, timemachine, submitButton, notificationDiv ] statsDiv = Div(width=1100, text="") def getStats(): gatewayCount = db.gateways.count() deviceCount = db.devices.count() datasetCount = db.datasets.count() dataitemCount = db.dataitems.count()
<p> Prepared by <b>Rajat Kabra</b>.<br/> Presented to <b>Prof. Kevin Smith</b>.<br/> Under <b>Assignment 4 of CS 235</b>. </p> <br/>""") 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) tsize = Slider(title="Period", start=1, end=7, value=7, step=1) button = Button(label="Filter Hover View", button_type="success") radio_group = RadioGroup( labels=["Name", "Atomic Number", "Atomic Mass", "Metal", "CPK Color"], active=0) periods = ["I", "II", "III", "IV", "V", "VI", "VII"] groups = [str(x) for x in range(1, 19)] df = elements.copy() df["atomic mass"] = df["atomic mass"].astype(str) df["group"] = df["group"].astype(str) df["period"] = [periods[x - 1] for x in df.period] df = df[df.group != "-"] df = df[df.symbol != "Lr"] df = df[df.symbol != "Lu"]
p.xaxis.formatter=DatetimeTickFormatter( hourmin = ['%H:%M'] ) #flights = psql.read_sql("SELECT * FROM Arr_Delays_vs_time_h", conn) flights = psql.read_sql("SELECT * FROM Arr_Delays_vs_time_h24102007", conn) flights["time_str"] = "0000" + flights["time"].astype(str) flights["time_str"] = flights.time_str.str[-4:] flights["time_str"] = flights.time_str.str[0:2] + ":" + flights.time_str.str[2:4] flights["time"] = pd.to_datetime(flights.time_str, format='%H:%M').dt.time # Create Input controls carrier = Select(title="Carrier", value="CO",options=open(str(dirname(abspath(__file__))) + "/carriers.txt").read().split()) box_size = Slider(title="Box size", start=3, end=100, value=15, step=1) # Create Column Data Source that will be used by the plot source = ColumnDataSource(data=dict(dep=[], delay_smooth=[], delay=[], name=[], time_str=[], num_of_flights=[], num_of_flights_smooth=[])) p.scatter(x="dep", y="delay", line_width=2, source = source, legend="Raw Data") g1 = p.line(x="dep", y="delay_smooth", line_width=2, line_color="red", source = source, legend="Smooth") tooltips = OrderedDict([ ('Dep.: ', '@time_str'), ('Est. Arr. Delay: ', '@delay_smooth'), ]) p.add_tools( HoverTool(tooltips=tooltips, renderers=[g1])) p.title.text = 'Predicted Delays' p.legend.location = "top_left"
x = list(range(start, start + len(data['circle_radius']))) source = ColumnDataSource( data=dict(image=[data['image'][0]], circle_radius=[data['circle_radius'][0]], major_radius=[data['major_radius'][0]], minor_radius=[data['minor_radius'][0]], frame_num=[x[0]], circle_radius_text=["{:.2f}".format(data['circle_radius'][0])], major_radius_text=["{:.2f}".format(data['major_radius'][0])], minor_radius_text=["{:.2f}".format(data['minor_radius'][0])])) slider = Slider(start=start, end=(start + len(x) - 1), value=start, step=1, title="Frame") # circle fit plot plot_line_circle = figure(width=800, height=300) plot_line_circle.line(x=x, y=data['circle_radius']) plot_line_circle.circle(x='frame_num', y='circle_radius', size=20, fill_color="firebrick", fill_alpha=0.5, line_color=None, source=source) labels_circle = LabelSet(x='frame_num', y='circle_radius',
session.store_objects(mdssource) def on_btn_clear(): current_topic = None mdssource.selected = [] session.store_objects(mdssource) btn_prev.on_click(on_btn_prev) btn_next.on_click(on_btn_next) btn_clear.on_click(on_btn_clear) slider = Slider(title="Slide to adjust relevance metric", value=0.25, start=0.0, end=1.0, step=0.01) topics = HBox(height=50, children=[btn_prev, btn_next, btn_clear]) metric = HBox(height=50, children=[slider]) left_panel = VBox(children=[topics, intertopic_distance_map]) right_panel = VBox(children=[metric, top_R_terms]) layout = HBox(children=[left_panel, right_panel]) document.add(layout) session.store_document(document) if __name__ == "__main__":
title="Titre", formatter=HTMLTemplateFormatter( template='<div><%= title %></div>')), TableColumn(field="body", title="Corps", formatter=HTMLTemplateFormatter( template='<div><%= body %></div>')), ] p2 = DataTable(source=s2, columns=columns, width=1200) # p2= DataTable(source=s2, columns=columns, width=wi, height=400) end_slider = max(df.n_vote) nvote_slider = Slider(start=0, end=end_slider, value=0, step=10, title="Nombre de votes minimum", callback=filtervote) filtervote.args["nvote"] = nvote_slider vote_slider = Slider(start=50, end=100, value=50, title="Approbation/rejet(%)", callback=filtervote) filtervote.args["vote"] = vote_slider toggle = Toggle(label="Cacher points non significatifs", callback=filtervote, width=50) toggle_expl = Div( text=
x_axis_label='freq(Hz)', y_axis_label='strain', plot_width=500, plot_height=400) pn23.line(x='freq', y='amp', source=sourcep2, color='green', line_width=3) pn23.toolbar.logo = None pn24 = figure(title='Phase', x_axis_label='freq(Hz)', y_axis_label='rad', plot_width=500, plot_height=400) pn24.line(x='freq', y='phase', source=sourcep2, color='red', line_width=3) pn24.toolbar.logo = None q_sliderFD = Slider(start=1, end=10, value=1, step=.5, title="Mass ratio (q)") e_sliderFD = Slider(start=0., end=0.9, value=0, step=.05, title="Eccentricity (e)") model_selectFD = Select(title="FD Models", options=fd_approximants()) def update_slider(attrname, old, new): # Get the current slider values q = q_sliderFD.value e = e_sliderFD.value approximant = model_selectFD.value freq, hp_real, hc_real, hp_imag, hc_imag, amp, phase = generate_analytic_waveform( mass_rat=q, eccentricity=e, approximant=approximant)
### Download data ## TODO: Implementar! download_button = Button(label="Download data", button_type="success") download_button.callback = CustomJS(code=open( os.path.join(os.path.dirname(__file__), 'download_events.js')).read()) download_button_wo = Button(label="Download data (without images)", button_type="success") download_button_wo.callback = CustomJS(code=open( os.path.join(os.path.dirname(__file__), 'download_wo_events.js')).read()) ######################### ## MEASURE TAB ### ######################### button_begin_measure = RadioButtonGroup(labels=["STOP", "BEGIN"], active=0) slider_gain = Slider(start=1, end=1023, value=1, step=1, title="Gain") slider_evsize = Slider(start=1, end=100, value=2, step=1, title="Minimum size") slider_trigger = RangeSlider(start=0, end=1023, value=(150, 200), step=1, title="Detection threshold/trigger") def run(cmd, filename, endbutton): try: logfile = open(os.path.join(os.path.dirname(__file__), filename), "w") p = subprocess.Popen(cmd.split(), universal_newlines=True, stdout=logfile) ret_code = p.poll()
p.xaxis.formatter = DatetimeTickFormatter(hourmin=['%H:%M']) #flights = psql.read_sql("SELECT * FROM Arr_Delays_vs_time_h", conn) flights = psql.read_sql("SELECT * FROM Arr_Delays_vs_time_h24102007", conn) flights["time"] = "0000" + flights["time"].astype(str) flights["time"] = flights.time.str[-4:] flights["time"] = flights.time.str[0:2] + ":" + flights.time.str[2:4] flights["time"] = pd.to_datetime(flights.time, format='%H:%M').dt.time # Create Input controls genre = Select( title="Airport", value="CO", options=open('/home/pkosewski/python/pd4/carriers.txt').read().split()) box_size = Slider(title="Box size", start=3, end=100, value=15, step=1) # Create Column Data Source that will be used by the plot source = ColumnDataSource( data=dict(dep=[], delay_smooth=[], delay=[], name=[])) #ML = Line(x="dep", y="delay", line_color="color", line_width=2) ML = Line(x="dep", y="delay", line_width=2) Smooth = Line(x="dep", y="delay_smooth", line_width=2, line_color="red") g1 = p.add_glyph(source, ML) g2 = p.add_glyph(source, Smooth) legend = Legend(legends=[("curve1", [g1]), ("curve2", [g2])]) p.legend.location = "top_left"
def interactive_county_map(dfm, key='GPCD', slider_key='Year', initial_query='Year == 2014', title='California GPCD', tools="pan,wheel_zoom,box_zoom,reset,hover,save", width=600, height=600, zscale='linear'): """ Plots interactive map given dataframe with COunty boundary fields as wall as key value and slider_key present in columns""" palette = Viridis256 palette = palette[::-1] if zscale == 'log': color_mapper = LogColorMapper(palette=palette, low=dfm[key].min(), high=dfm[key].max()) else: color_mapper = LinearColorMapper(palette=palette, low=dfm[key].min(), high=dfm[key].max()) source = ColumnDataSource(dfm.dropna(), id='src') source_flt = ColumnDataSource(dfm.query(initial_query).fillna(-1), id='src_flt') p = figure(title=title, tools=tools, x_axis_location=None, y_axis_location=None, width=width, height=height) p.grid.grid_line_color = None p.patches('x', 'y', source=source_flt, fill_color={ 'field': key, 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) hover = p.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = [ ("County", "@County"), ("{}".format(key), "@{}".format(key)), ] callback_js_code = """ var orig_data = s1.data; var filtered_data = s2.data; var selected = cb_obj["value"]; for (var key in orig_data) {{ filtered_data[key] = []; for (var i = 0; i < orig_data['County'].length; ++i) {{ if (orig_data['{VARNAME}'][i] === selected) {{ filtered_data[key].push(orig_data[key][i]); }} }} }} s2.trigger("change"); """.format(VARNAME=slider_key) callback = CustomJS(args=dict(s1=source, s2=source_flt), code=callback_js_code) slider = Slider(start=dfm[slider_key].min(), end=dfm[slider_key].max(), value=dfm[slider_key].min(), step=1, title="Select {}".format(slider_key), width=width, callback=callback) color_bar = ColorBar(color_mapper=color_mapper, location=(0, 0), orientation='vertical') p.add_layout(color_bar, 'right') p.toolbar_location = 'left' return column(slider, p)
# Set up plot """Deifnes default player plot that will be shown when the page is rendered for the first time""" player = map_classes.Player('Kevin Durant') p1 = player.hex_accuracy('2017-18') # Set up widgets """Creates the objects from bokeh.widgets that will be used to interact with the plot""" search_bar = TextInput(title="Search (eg. Kevin Durant or GSW)", value='Kevin Durant') search = Button(label="Go", button_type="success") slider = Slider(start=2007, end=2017, value=2017, step=1, title="Season", name="slider", callback_policy="mouseup") button_group1 = RadioButtonGroup(labels=["Player", "Team"], active=0) button_group2 = RadioButtonGroup(labels=["Accuracy", "Frequency"], active=0) # Set up layouts and add to document """Sets up the widgets and plot in an html document that will be pushed to the website""" inputs = widgetbox(button_group1, search_bar, search, button_group2, slider, name='Widgets')
order by 1 """ #------------ETL process------------------------------------------------- #df =pd.read_sql(template, conn) df = pd.read_csv('tests/error.csv') df['time'] =pd.to_datetime(df.time, format="%Y-%m-%d %H:%M:%S") df =df.set_index('time') output_file("anomaly.html") #-----------------------Load the data into the model---------------------------------- window = Slider(start=0, end=24, value=6,title="window", step=6) scale = Slider(start=0, end=3, value=1.96,title="scale factor", step=0.03) #-------------------Rolling mean---------------------------- anomaly = AnomalyTimeSeries(window=window.value, scale=scale.value) model, series, lower_band, upper_band, anomalies = anomaly.rolling_mean_model(df, '../config/config.ini', 'email') #model, series, lower_band, upper_band, anomalies = anomaly.rolling_mean_model(df, 'email') #---------------Start dashboarding---------------------------------------- select_widget = Select(options=["Moving Average","Holt Winter", "Linear Regression", "Ridge Cv", "Lasso Cv", "XGBoost"],
executor = SQLExecutor(server, username, password, database) executor.connect() data_date = [d[:10] for d in executor.fetch(timeIntervalOnly=True)] date_form = lambda d: date(*map(int, d.split('-'))) # Widgets show_btnGroup = RadioButtonGroup(name="Loading", labels=["show", "hide"], active=1) mb_btnGroup = RadioButtonGroup(name="mb_btngroup", labels=["less than", "disable", "greater than"], active=1, margin=(0, 0, 20, 0)) mb_slider = Slider(title="Marginal Balance Change Ratio (%)", start=-100, end=100, value=0, step=10) cp_btnGroup = RadioButtonGroup(name="cp_btngroup", labels=["less than", "disable", "greater than"], active=1, margin=(0, 0, 20, 0)) cp_slider = Slider( title="Closing Price Change Ratio (%)", start=-100, end=100, value=0, step=10, ) date_range_slider = DateRangeSlider(title="Date range", value=(date_form(data_date[20]),
y = np.sin(x) source = ColumnDataSource(data=dict(x=x, y=y)) # Set up plot plot = figure(plot_height=400, plot_width=400, title="my sine wave #1", tools="crosshair,pan,reset,save,wheel_zoom", x_range=[0, 4 * np.pi], y_range=[-2.5, 2.5]) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) # Set up widgets text = TextInput(title="this is sliders widget #1", value='my sine wave #1') offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1) amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0, step=0.1) phase = Slider(title="phase", value=0.0, start=0.0, end=2 * np.pi) freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1) # Set up callbacks def update_title(attrname, old, new): plot.title.text = text.value text.on_change('value', update_title) def update_data(attrname, old, new): # Get the current slider values
def apply_all(our, add_before=None, add_after=None): before = add_before if (add_before != None) else tuple() heights = tuple(our.height[i] for i in range(0, len(our.height))) radii = tuple(our.radius[i] for i in range(0, len(our.radius))) after = add_after if (add_after != None) else tuple() inputs1 = widgetbox(*(heights + before)) inputs2 = widgetbox(*(radii + after)) curdoc().add_root(row(inputs1, inputs2, p, width=1400)) sliders = MySliders() p_input = tuple(TextInput(title="Power", value=str(power)) for power in P) s_platform_z = Slider(title="Water Z", value=wz, start=-3, end=12) s_magnet_M = Slider(title="Magnet M", value=Ms, start=0, end=1, step=0.01) def update_plot_data(attr_name, old, new): # Get ready to modify data by first loading the data: state = program.optimize.last_result.x hs = program.optimize.get_hs(state) rs = program.optimize.get_rs(state) da = program.optimize.get_da(state) # Modify the data using values from all the sliders: for i in range(0, min(len(sliders.height), len(sliders.radius))): s_h = sliders.height[i] s_r = sliders.radius[i] hs[i] = from_slider(s_h.value) rs[i] = s_r.value
# Carriers to plot carrier_selection = CheckboxGroup(labels=available_carriers, active=[0, 1]) carrier_selection.on_change('active', update) range_select = RangeSlider(start=-60, end=180, value=(-60, 120), step=5, title='Range of Delays (min)') range_select.on_change('value', update) # Initial carriers and data source initial_carriers = [carrier_selection.labels[i] for i in carrier_selection.active] # Bandwidth of kernel bandwidth_select = Slider(start=0.1, end=5, step=0.1, value=0.5, title='Bandwidth for Density Plot') bandwidth_select.on_change('value', update) # Whether to set the bandwidth or have it done automatically bandwidth_choose = CheckboxButtonGroup( labels=['Choose Bandwidth (Else Auto)'], active=[]) bandwidth_choose.on_change('active', update) # FUNDS_EARMARKED_FOR_GOAL fund_input = TextInput(value="100000", title="Funds for Goal:") contribution_input = TextInput(value="1000", title="Contribution Amount:")
def t_value_change(attrname, old, new): update_point() # initialize data source source_curve = ColumnDataSource(data=dict(x=[], y=[])) source_point = ColumnDataSource(data=dict(x=[], y=[])) source_sector = ColumnDataSource(data=dict(x=[], y=[])) source_lines = ColumnDataSource(data=dict(x_start=[], y_start=[], x_end=[], y_end=[])) source_text = ColumnDataSource(data=dict(area=[])) # initialize controls # slider controlling the current parameter t t_value_input = Slider(title="parameter t", name='parameter t', value=leibnitz_settings.t_value_init, start=leibnitz_settings.t_value_min, end=leibnitz_settings.t_value_max, step=leibnitz_settings.t_value_step) t_value_input.on_change('value', t_value_change) # text input for the x component of the curve x_component_input = TextInput(value=leibnitz_settings.x_component_input_msg, title="curve x") x_component_input.on_change('value', curve_change) # text input for the y component of the curve y_component_input = TextInput(value=leibnitz_settings.y_component_input_msg, title="curve y") y_component_input.on_change('value', curve_change) # dropdown menu for selecting one of the sample curves sample_curve_input = Dropdown(label="choose a sample function pair or enter one below", menu=leibnitz_settings.sample_curve_names) sample_curve_input.on_change('value', sample_curve_change) # initialize plot toolset = "crosshair,pan,reset,save,wheel_zoom"
line_color='white', fill_color=factor_cmap( 'plot_x', palette=Spectral6, factors=plot_x, )) exit_population_plot.legend.location = "top_left" exit_population_plot.legend.orientation = "horizontal" exit_population_plot.xaxis.axis_label = "Rounds" exit_population_plot.yaxis.axis_label = "Number of startups (Mass)" # Set up widgets text = TextInput(title="title", value='Probes and Population') # cycle = Slider(title="Cycle", value=0, start=0, end=2, step=1) cycle = Slider(title="Year", bar_color="green", value=min_row, start=min_row, end=max_row, step=1) # Set up widgets growth_rate_A = Slider(title="Growth Rate A", value=1.5, start=-5.0, end=5.0, step=0.1) growth_rate_B = Slider(title="Growth Rate A", value=1.0, start=-5.0, end=5.0, step=0.1) growth_rate_C = Slider(title="Growth Rate A",
def integration_with_sliders(rsys, tend, c0, parameters, fig_kwargs=None, slider_kwargs=None, conc_bounds=None, x_axis_type="linear", y_axis_type="linear", integrate_kwargs=None, odesys_extra=None, get_odesys_kw=None, integrate=None): """ Parameters ---------- rsys : ReactionSystem tend : float like c0 : dict Initial concentrations. parameters : dict Parameter values. fig_kwargs : dict Keyword-arguments passed to bokeh's ``Figure``. slider_kwargs : dict Keyword-arguments passed to bokeh's ``Slider``. conc_bounds : dict of dicts Mapping substance key to dict of bounds ('start', 'end', 'step'). x_axis_type : str y_axis_type : str integrate_kwargs : dict Keyword-arguments passed to integrate. odesys_extra : tuple If odesys & extra have already been generated (avoids call to ``get_odesys``). get_odesys_kw : dict Keyword-arguments passed to ``get_odesys``. integrate : callback Defaults to ``odesys.integrate``. """ import numpy as np from bokeh.plotting import Figure from bokeh.models import ColumnDataSource, Column, Row from bokeh.models.widgets import Slider if slider_kwargs is None: slider_kwargs = {} if get_odesys_kw is None: get_odesys_kw = {} if odesys_extra is None: odesys, extra = get_odesys(rsys, **get_odesys_kw) else: odesys, extra = odesys_extra if integrate is None: integrate = odesys.integrate state_keys, rarg_keys, p_units = [ extra[k] for k in ('param_keys', 'unique', 'p_units') ] output_conc_unit = get_odesys_kw.get('output_conc_unit', None) output_time_unit = get_odesys_kw.get('output_time_unit', None) unit_registry = get_odesys_kw.get('unit_registry', None) if output_conc_unit is None: if unit_registry is not None: raise ValueError( "if unit_registry is given, output_conc_unit must also be given" ) output_conc_unit = 1 if output_time_unit is None: if unit_registry is not None: raise ValueError( "if unit_registry is given, output_time_unit must also be given" ) output_conc_unit = 1 param_keys = list(chain(state_keys, rarg_keys)) if x_axis_type == 'linear': tout = linspace(tend * 0, tend) elif x_axis_type == 'log': tout = logspace_from_lin(tend * 1e-9, tend) else: raise NotImplementedError("Unknown x_axis_type: %s" % x_axis_type) result = integrate(tout, c0, parameters, **(integrate_kwargs or {})) sources = [ ColumnDataSource( data={ 'tout': to_unitless(result.xout, output_time_unit), k: to_unitless(result.yout[:, idx], output_conc_unit) }) for idx, k in enumerate(rsys.substances) ] if fig_kwargs is None: Cmax = np.max(result.yout) x_range = list( to_unitless([result.xout[0], result.xout[-1]], output_time_unit)) y_range = list(to_unitless([Cmax * 0, Cmax * 1.1], output_conc_unit)) fig_kwargs = dict(plot_height=400, plot_width=400, title="C vs t", tools="crosshair,pan,reset,save,wheel_zoom", x_range=x_range, y_range=y_range, x_axis_type=x_axis_type, y_axis_type=y_axis_type) plot = Figure(**fig_kwargs) colors = 'red green blue black cyan magenta'.split() for idx, k in enumerate(rsys.substances): plot.line('tout', k, source=sources[idx], line_width=3, line_alpha=0.6, color=colors[idx % len(colors)]) def _C(k): return to_unitless(c0[k], output_conc_unit) if p_units is None: p_units = [None] * len(param_keys) p_ul = [ to_unitless(parameters[k], _u) for k, _u in zip(param_keys, p_units) ] def _dict_to_unitless(d, u): return {k: to_unitless(v, u) for k, v in d.items()} c0_widgets = OrderedDict() for k in rsys.substances: if conc_bounds is not None and k in conc_bounds: if k in slider_kwargs: raise ValueError( "Key '%s' both in slider_kwargs and conc_bounds" % k) slider_defaults = _dict_to_unitless(conc_bounds[k], output_conc_unit) else: ck = _C(k) if ck == 0: max_ = max(*[_C(k) for k in rsys.substances]) slider_defaults = dict(start=0, end=max_, step=max_ / 100) else: slider_defaults = dict(start=_C(k) / 2, end=_C(k) * 2, step=_C(k) / 10) c0_widgets[k] = Slider(title=k if output_conc_unit is 1 else k + ' / ' + output_conc_unit.dimensionality.unicode, value=_C(k), **slider_kwargs.get(k, slider_defaults)) param_widgets = OrderedDict([ (k, Slider(title=k if u is None else k + ' / ' + u.dimensionality.unicode, value=v, **_dict_to_unitless( slider_kwargs.get( k, dict(start=v / 10, end=v * 10, step=v / 10)), u))) for k, v, u in zip(param_keys, p_ul, p_units) ]) all_widgets = list(chain(param_widgets.values(), c0_widgets.values())) def update_data(attrname, old, new): _c0 = defaultdict(lambda: 0 * output_conc_unit) for k, w in c0_widgets.items(): _c0[k] = w.value * output_conc_unit _params = {} for (k, w), u in zip(param_widgets.items(), p_units): _params[k] = w.value if u is None else w.value * u _result = integrate(tout, _c0, _params) for idx, k in enumerate(rsys.substances): sources[idx].data = { 'tout': to_unitless(_result.xout, output_time_unit), k: to_unitless(_result.yout[:, idx], output_conc_unit) } for w in all_widgets: w.on_change('value', update_data) inputs = Column(children=all_widgets) return Row(children=[inputs, plot], width=800)
checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1]) radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0) text_input = TextInput(placeholder="Enter value ...") completions = ["aaa", "aab", "aac", "baa", "caa"] autocomplete_input = AutocompleteInput(placeholder="Enter value (auto-complete) ...", completions=completions) select = Select(options=["Option 1", "Option 2", "Option 3"]) multi_select = MultiSelect(options=["Option %d" % (i+1) for i in range(16)], size=6) slider = Slider(value=10, start=0, end=100, step=0.5) range_slider = RangeSlider(value=[10, 90], start=0, end=100, step=0.5) date_slider = DateSlider(value=date(2016, 1, 1), start=date(2015, 1, 1), end=date(2017, 12, 31)) date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31)), start=date(2015, 1, 1), end=date(2017, 12, 31)) spinner = Spinner(value=100) color_picker = ColorPicker(color="red", title="Choose color:") date_picker = DatePicker(value=date(2017, 8, 1)) paragraph = Paragraph(text="some text")
def player_marking(doc, df, headers, id_def, id_att, slider_steps, x_range, y_range, image_url, sport='football', anim_speed=50, attack=True): """ Parameters --------------------------- :param doc: Plots the graph :param df: Gets the user defined dataframe :param headers: Give the headers to the dataframe - Headers should be ["x", "y", "team_id", "player_id","time"] {x, y - int/float - Player location coordinates x and y team_id - int/string - Team Id for both attacking and defending teams player_id - int/string - Player Id for both attacking and defending team. Id for ball is optional time - int/float - Game time in seconds or any units.} :param id_def: Provide id of defending team :param id_att: Provide id of attacking team :param x_range: Provide x range of the pitch coordinates :param y_range: Provide y range of the pitch coordinates :param image_url: Provide the location of the background image of the pitch :param slider_steps: Provide the slider steps :param sport: (football/basketball) - Provide the sport details to change slider function - Default is football(⚽️) Football allows slider timer to move from low to max (0-90 minutes), while sports that have decreasing timer (12 to 0 minutes) should use "basketball". :param attack:(True/False) - If 'True', then the attacking team is considered players marking and defending team is considered as players being marked. If 'false' then logic is reversed. :return: Returns the animation plot """ """ Value Errors --------------------------- """ if not isinstance(df, pd.DataFrame): raise ValueError( "The expected data type of input data is a dataframe but a {} was provided." .format(type(df))) accept_dtypes_id = [int, float, str, tuple] if type(id_def) not in accept_dtypes_id: raise ValueError( "The expected data type for defending team-id is either integer, float " "or a string but {} was provided.".format(type(id_def))) if type(id_att) not in accept_dtypes_id: raise ValueError( "The expected data type for defending team-id is either integer, float " "or a string but {} was provided.".format(type(id_att))) if not isinstance(x_range, (list, tuple)): raise ValueError( "The expected data type for x-range is a list but a {} was provided." .format(type(x_range))) if not isinstance(y_range, (list, tuple)): raise ValueError( "The expected data type for y-range is a list but a {} was provided." .format(type(y_range))) if len(x_range) != 2: raise ValueError( "Length of x range of coordinates is {} but expected length is 2.". format(len(x_range))) if len(y_range) != 2: raise ValueError( "Length of y range of coordinates is {} but expected length is 2.". format(len(x_range))) if sport not in ['football', 'basketball']: raise ValueError( "Only football/basketball in accepted as input for sport type, but {} was provided." .format(sport)) if not isinstance(image_url, list): image_url = [image_url] all_team = pd.DataFrame(df, columns=headers) all_team['x'] = pd.to_numeric(all_team['x']) all_team['y'] = pd.to_numeric(all_team['y']) all_team['time'] = pd.to_numeric(all_team['time']) all_team['player_id'] = all_team['player_id'].apply(str) all_team['team_id'] = np.where( ((all_team['team_id'] != id_att) & (all_team['team_id'] != id_def)), -99, all_team['team_id']) all_team['player_id'] = np.where( ((all_team['team_id'] != id_att) & (all_team['team_id'] != id_def)), " ", all_team['player_id']) if sport == 'basketball': all_team['time'] = -all_team['time'] all_team = all_team.sort_values(['time', 'team_id', 'player_id'], ascending=[False, False, True ]).reset_index(drop=True) else: all_team['time'] = all_team['time'] all_team = all_team.sort_values(['time', 'team_id', 'player_id'], ascending=[True, False, True ]).reset_index(drop=True) team_def = all_team[all_team.team_id == id_def] team_att = all_team[all_team.team_id == id_att] if team_def.empty: raise ValueError( "Defending team ID is not valid. Please enter a valid team ID") elif team_att.empty: raise ValueError( "Attacking team ID is not valid. Please enter a valid team ID") current_time = all_team['time'].min() coord_x = all_team[all_team.time == current_time]['x'] coord_y = all_team[all_team.time == current_time]['y'] team_def_xy = team_def[team_def.time == current_time] team_att_xy = team_att[team_att.time == current_time] player_id = all_team[all_team['time'] == current_time]['player_id'] c = (['dodgerblue'] * len(team_def['player_id'].unique()) + ['green'] * len(team_att['player_id'].unique()) + ['gold']) """ For each frame, calculate the nearest player for each given player using cdist """ def get_distances(team_def_xy, team_att_xy, attack): if attack: columns = team_def_xy['player_id'].values.tolist() index = team_att_xy['player_id'].values.tolist() dist_mat = cdist(team_att_xy[['x', 'y']].values, team_def_xy[['x', 'y']].values) source_x, source_y = team_att_xy['x'].values, team_att_xy[ 'y'].values merge_df = team_def_xy[['player_id', 'x', 'y']] else: columns = team_att_xy['player_id'].values.tolist() index = team_def_xy['player_id'].values.tolist() dist_mat = cdist(team_def_xy[['x', 'y']].values, team_att_xy[['x', 'y']].values) source_x, source_y = team_def_xy['x'].values, team_def_xy[ 'y'].values merge_df = team_att_xy[['player_id', 'x', 'y']] dist_df = pd.DataFrame(dist_mat) dist_df.columns = columns dist_df.index = index nearest_player = dist_df.idxmin(axis=1) dist_df['closest_player'] = nearest_player dist_df['source_player'] = index dist_df['source_x'] = source_x dist_df['source_y'] = source_y lines_x = pd.merge(dist_df, merge_df, left_on='closest_player',right_on='player_id', sort=False)\ .rename(columns = {'x':'target_x','y':'target_y'}) x_lines = list(zip(lines_x['source_x'], lines_x['target_x'])) y_lines = list(zip(lines_x['source_y'], lines_x['target_y'])) return x_lines, y_lines x_lines, y_lines = get_distances(team_def_xy, team_att_xy, attack) source_coord = ColumnDataSource( data=dict(x=coord_x, y=coord_y, player_id=player_id, color=c)) source_lines = ColumnDataSource(data=dict(xs=x_lines, ys=y_lines)) """ Remove plot background and alter other styles """ def plot_clean(plot): plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None plot.axis.major_label_text_font_size = "10pt" plot.axis.major_label_standoff = 0 plot.border_fill_color = "white" plot.title.text_font = "times" plot.title.text_font_size = '10pt' plot.background_fill_color = "white" plot.title.align = 'center' return plot plot = figure(name='base', plot_height=860, plot_width=1889, title="Player Marking Animation", tools="reset,save,wheel_zoom,pan", x_range=x_range, y_range=y_range, toolbar_location="below") image_min_x, image_min_y, image_max_x, image_max_y = min(x_range), min(y_range), \ (abs(x_range[0]) + abs(x_range[1])), \ (abs(y_range[0]) + abs(y_range[1])) plot.image_url(url=image_url, x=image_min_x, y=image_min_y, w=image_max_x, h=image_max_y, anchor="bottom_left") plot.multi_line('xs', 'ys', source=source_lines, color='green', line_width=3, line_alpha=.7, line_cap='round', line_dash="dashed") plot.scatter('x', 'y', source=source_coord, size=20, fill_color='color') labels = LabelSet(x='x', y='y', text='player_id', source=source_coord, y_offset=-8, render_mode='canvas', text_color='black', text_font_size="8pt", text_align='center') plot.add_layout(labels) plot.axis.visible = False plot = plot_clean(plot) slider_start = all_team.time.unique().min() slider_end = all_team.time.unique().max() game_time = Slider(title="Game Time (seconds)", value=slider_start, start=slider_start, end=slider_end, step=slider_steps) """ Update the figure every time slider is updated. """ def update_data(attrname, old, new): slider_value = np.round(game_time.value, 2) coord_x = all_team[all_team.time == slider_value]['x'] coord_y = all_team[all_team.time == slider_value]['y'] team_def_xy = team_def[team_def.time == slider_value] team_att_xy = team_att[team_att.time == slider_value] x_lines, y_lines = get_distances(team_def_xy, team_att_xy, attack) source_coord.data = dict(x=coord_x, y=coord_y, player_id=player_id, color=c) source_lines.data = dict(xs=x_lines, ys=y_lines) for w in [game_time]: w.on_change('value', update_data) """ Animation """ def animate_update(): time = game_time.value + slider_steps if time > all_team.time.max(): time = all_team.time.min() game_time.value = time callback_id = None def animate(): global callback_id if button.label == '► Play': button.label = '❚❚ Pause' callback_id = curdoc().add_periodic_callback( animate_update, anim_speed) else: button.label = '► Play' curdoc().remove_periodic_callback(callback_id) button = Button(label='► Play', width=60) button.on_click(animate) inputs = widgetbox(row(column(game_time, button))) layout = column(row(column(plot, inputs))) doc.add_root(layout) doc.title = "Game Animation" return doc
def plot(numFrac, numPF, args): W = weightsFromFraction(np.linspace(0, 1, numFrac)) p1 = figure(height=200, width=200, toolbar_location=None, title='Weights') l = p1.line(np.linspace(0, 1, numFrac), W[1], legend_label="w1", color='navy') l = p1.line(np.linspace(0, 1, numFrac), W[1], legend_label="w2", color='chocolate') B0 = 3 # Tesla mapper = LinearColorMapper(palette='Spectral11', low=0, high=1) colorBar = ColorBar(color_mapper=mapper, location=(0, 0)) acquistionTimes = np.arange(start=float(args.tmin), stop=float(args.tmax), step=float(args.dt)) numTa = len(acquistionTimes) partialFourierFactors = np.linspace(start=0.5, stop=1, num=numPF) dephasingTimes = np.empty(shape=(numPF, numFrac, numTa, 2), dtype=np.float32) firstEchoFractions = np.linspace(start=0, stop=1, num=numFrac) NSA = np.empty(shape=(numPF, numFrac, numTa, 2), dtype=np.float32) # NSA_ss [weighted, unweighted] for nt, ta in enumerate(acquistionTimes): for nPF, PF in enumerate(partialFourierFactors): for nf, f in enumerate(firstEchoFractions): dephasingTimes[nPF, nf, nt, :] = getDephasingTimes(ta / 1.0e3, PF, f) weights = weightsFromFraction(f) NSA[nPF, nf, nt, 0] = np.mean( np.reciprocal( weightedCrbTwoEchoes(B0, dephasingTimes[nPF, nf, nt, :], weights))) # Weighted NSA_ss NSA[nPF, nf, nt, 1] = np.mean( np.reciprocal( weightedCrbTwoEchoes( B0, dephasingTimes[nPF, nf, nt, :], weightsFromFraction(.5)))) # Unweighted NSA_ss print(100. * (nt + 1) / numTa) pWeighted = figure(height=350, width=350, toolbar_location=None, title='Weighted NSA_ss (3T)') pUnWeighted = figure(height=350, width=350, toolbar_location=None, title='Unweighted NSA_ss (3T)') pUnWeighted.add_layout(colorBar, 'right') CDSimages = [ ColumnDataSource({'imageData': [NSA[:, :, -1, 0]]}), ColumnDataSource({'imageData': [NSA[:, :, -1, 1]]}) ] pWeighted.image(image='imageData', x=0, y=0, dw=numFrac, dh=numPF, color_mapper=mapper, source=CDSimages[0]) pUnWeighted.image(image='imageData', x=0, y=0, dw=numFrac, dh=numPF, color_mapper=mapper, source=CDSimages[1]) for p in [pWeighted, pUnWeighted]: p.xaxis.ticker = [ 0, (numFrac - 1) / 4, (numFrac - 1) / 2, 3 * (numFrac - 1) / 4, numFrac - 1 ] p.xaxis.major_label_overrides = { 0: '0', (numFrac - 1) / 4: '.25', (numFrac - 1) / 2: '.5', 3 * (numFrac - 1) / 4: '.75', numFrac - 1: '1' } p.yaxis.ticker = [0, (numPF - 1) / 2, numPF - 1] p.yaxis.major_label_overrides = { 0: '0.5', (numPF - 1) / 2: '.75', numPF - 1: '1.0' } pWeighted.x_range.range_padding = pWeighted.y_range.range_padding = 0 pUnWeighted.x_range.range_padding = pUnWeighted.y_range.range_padding = 0 spans = [ Span(location=-1, dimension='height', line_color='navy', line_dash='dashed'), Span(location=-1, dimension='height', line_color='chocolate', line_dash='dashed') ] pGrad = figure(height=350, width=350, toolbar_location=None, title='Gradients') pGrad.add_layout(spans[0]) pGrad.add_layout(spans[1]) CDSFirst = ColumnDataSource({'t': [0, 0, .5, .5], 'amp': [0, 1, 1, 0]}) CDSSecond = ColumnDataSource({'t': [.5, .5, 1, 1], 'amp': [0, -1, -1, 0]}) pGrad.line(x='t', y='amp', color='navy', line_width=2, source=CDSFirst) pGrad.line(x='t', y='amp', color='chocolate', line_width=2, source=CDSSecond) pCompass = figure(height=350, width=350, toolbar_location=None, title='Fat vectors', x_range=(-1.1, 1.1), y_range=(-1.1, 1.1)) pCompass.circle(0, 0, radius=1, fill_color=None, line_color='black') CDSArrow = [ ColumnDataSource({ 'x': [0, 0], 'y': [0, 0] }), ColumnDataSource({ 'x': [0, 0], 'y': [0, 0] }) ] pCompass.line(x='x', y='y', color='navy', line_width=2, source=CDSArrow[0]) pCompass.line(x='x', y='y', color='chocolate', line_width=2, source=CDSArrow[1]) slider = Slider(start=np.min(acquistionTimes), end=np.max(acquistionTimes), value=np.max(acquistionTimes), step=acquistionTimes[1] - acquistionTimes[0], title="Available acquisition time [ms]") hoverCallback = CustomJS(args={ 'dephasingTimes': dephasingTimes, 'firstEchoFractions': firstEchoFractions, 'partialFourierFactors': partialFourierFactors, 'spans': spans, 'arrows': CDSArrow, 'first': CDSFirst, 'slider': slider, 'second': CDSSecond, }, code=""" if ( isFinite(cb_data['geometry']['x']) && isFinite(cb_data['geometry']['y']) ) { let ta = slider.value / 1000.0 if (typeof window.taIdx == 'undefined') { window.taIdx = dephasingTimes[0][0].length - 1; } let fIdx = Math.floor(cb_data["geometry"]['x']) % firstEchoFractions.length; let pfIdx = Math.floor(cb_data["geometry"]['y']); first.data.t[2] = first.data.t[3] = ta*firstEchoFractions[fIdx]; second.data.t[0] = second.data.t[1] = ta*firstEchoFractions[fIdx]; second.data.t[2] = second.data.t[3] = ta; first.data.amp[1] = first.data.amp[2] = partialFourierFactors[pfIdx] / firstEchoFractions[fIdx]; second.data.amp[1] = second.data.amp[2] = - partialFourierFactors[pfIdx] / (1 - firstEchoFractions[fIdx]); spans[0].location = ta/2.0 + dephasingTimes[pfIdx][fIdx][window.taIdx][0]; spans[1].location = ta/2.0 + dephasingTimes[pfIdx][fIdx][window.taIdx][1]; spans[0].change.emit(); spans[1].change.emit(); first.change.emit(); second.change.emit(); let omega = 2*Math.PI*42.58*3*3.4 for (let i = 0; i < 2; i++) { arrows[i].data.x[1] = Math.cos(omega*dephasingTimes[pfIdx][fIdx][window.taIdx][i]); arrows[i].data.y[1] = Math.sin(omega*dephasingTimes[pfIdx][fIdx][window.taIdx][i]); arrows[i].change.emit(); } window.fIdx = fIdx; window.pfIdx = pfIdx; } """) pWeighted.add_tools( HoverTool(tooltips=None, callback=hoverCallback, mode='mouse')) pUnWeighted.add_tools( HoverTool(tooltips=None, callback=hoverCallback, mode='mouse')) sliderCallback = CustomJS(args={ 'acquistionTimes': acquistionTimes, 'images': CDSimages, 'NSA': NSA }, code=""" window.taIdx = Math.floor((cb_obj.value - cb_obj.start ) / cb_obj.step) console.log(window.taIdx) images[0].data.imageData = [NSA.map(PF => PF.map(f => f[window.taIdx][0])).flat()] images[1].data.imageData = [NSA.map(PF => PF.map(f => f[window.taIdx][1])).flat()] images[0].change.emit(); images[1].change.emit(); """) slider.js_on_change('value', sliderCallback) output_file(args.filename) combinedPlot = column(row(pWeighted, pUnWeighted), row(pGrad, pCompass), slider) save(combinedPlot, filename=args.filename, title=args.title)