def interact_with_mesh_physical_model(): """ build an interactive bar for users to zoom in and out the mesh physical model. """ from IPython.html.widgets import interact interact(show_mesh_physical_model, bound=(1, 10), tube_radius=(1, 10))
def examine_cutouts(catalog, cluster_directory='./', invert_color=False): # some generic things you can configure: # what columns we want to plot columns = ['ZooID', 'object_id', 'stage', 'field_flavor', 'object_flavor', 'status', 'markers_in_object', 'markers_in_field', 'people_marking_objects', 'people_marking_field', 'people_looking_at_field', 'object_size', 'mean_probability', 'x', 'y'] def examine_entry(i): entry = catalog.iloc[i] ZooID = entry['ZooID'] display(entry[columns]) cluster_path = cluster_directory + entry['object_name'] cluster = imread(cluster_path) * 1. / 255. if invert_color: cluster = np.abs(cluster - cluster.max()) fig, axs = plt.subplots(nrows=1, ncols=1, figsize=(5, 5)) cluster = imread(cluster_path) axs.imshow(cluster) interact(examine_entry, i=(0, len(catalog)-1), show_field=False)
def select_CPDFS(self): def f(**kwargs): if kwargs['pdfset']=='cteq6': self.CPDF=Cteq6PDF(self.root) if kwargs['pdfset']=='fake': self.CPDF=FakePDF() interact(f,pdfset={'cteq6':'cteq6','fake':'fake'})
def interactA(): widH = widgets.IntSliderWidget(min=0,max=1000,step=1,value=100) widZ = widgets.IntSliderWidget(min=0,max=1000,step=1,value=1) wida = widgets.FloatSliderWidget(min=0.01,max=1,step=0.01,value=0.05) widb = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.3) widz = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.2) interact(graficaSolucionA,humanos=widH, zombies=widZ, muertos=fixed(0), a=wida, b=(0.1,1,0.05), z=(0.01,0.5,0.01));
def examine_catalog(catalog): def examine_cat(groupby_str): groupby_list = eval(groupby_str) print(catalog.groupby(groupby_list).apply(len)) interact(examine_cat, groupby_str="['stage', 'field_flavor', 'object_flavor']")
def myshow(img, title=None, margin=0.05, dpi=80 ): nda = sitk.GetArrayFromImage(img) spacing = img.GetSpacing() slicer = False if nda.ndim == 3: # fastest dim, either component or x c = nda.shape[-1] # the the number of components is 3 or 4 consider it an RGB image if not c in (3,4): slicer = True elif nda.ndim == 4: c = nda.shape[-1] if not c in (3,4): raise Runtime("Unable to show 3D-vector Image") # take a z-slice slicer = True if (slicer): ysize = nda.shape[1] xsize = nda.shape[2] else: ysize = nda.shape[0] xsize = nda.shape[1] # Make a figure big enough to accomodate an axis of xpixels by ypixels # as well as the ticklabels, etc... figsize = (1 + margin) * ysize / dpi, (1 + margin) * xsize / dpi def callback(z=None): extent = (0, xsize*spacing[1], ysize*spacing[0], 0) fig = plt.figure(figsize=figsize, dpi=dpi) # Make the axis the right size... ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin]) plt.set_cmap("gray") if z is None: ax.imshow(nda,extent=extent,interpolation=None) else: ax.imshow(nda[z,...],extent=extent,interpolation=None) if title: plt.title(title) plt.show() if slicer: interact(callback, z=(0,nda.shape[0]-1)) else: callback()
def _repr_html_(self): def _data_frame(solution): notice("%s: %f" % self.solutions.axes[0][solution - 1][0]) notice("%s: %f" % self.solutions.axes[0][solution - 1][1]) display(self.solutions.iloc[solution - 1]) interact(_data_frame, solution=[1, len(self.solutions)]) return ""
def interactB(): widH = widgets.IntSliderWidget(min=0,max=1000,step=1,value=100) widZ = widgets.IntSliderWidget(min=0,max=1000,step=1,value=1) widI = widgets.IntSliderWidget(min=0,max=10,step=1,value=0) wida = widgets.FloatSliderWidget(min=0.01,max=1,step=0.01,value=0.05) widb = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.6) widz = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.2) widr = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.9) interact(solucionB,humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), a=wida, b=widb, z=widz, r=widr);
def iview(self, width = 400): f = lambda rows_start, rows_end,cols: display(self[list(cols)].iloc[rows_start:rows_end]) rs = IntSlider(min=0, max=self.shape[0], width=width) re = IntSlider(min=0, max=self.shape[0], width= width) link((re, 'min'), (rs, 'value')) interact(f, cols=SelectMultiple(options=self.columns.tolist()), rows_start=rs, rows_end=re, width=width)
def ksplot(func,mu_lims,sig_lims,t_series,p_series,bar_num,*func_auxargs): """Compare traced data to a normal distribution with a KS test. Returns output of a KS test: + The KS statistic + The corrisponding p-value Returns two plots: + A trace of the give data and time series + A histogram of the trace's scaled fds and a fit gaussian. Sliders are used to vary the parameters 'a' and 'b' in func. Arguments --------- func = use etrace or atrace to act on p_series and t_series mu_lims = slider limits for the paramter 'a' in func sig_lims = slider limits for the paramter 'b' in func t_series = the time series corrisponding to p_series p_series = the data set which will be traced bar_num = number of bars in the histogramed plot func_auxargs = auxilary arguments for func """ def makeplots(a,b): dat = func('price',t_series,p_series,a,b,*func_auxargs) fig, ax = plt.subplots(figsize=(10,2)) ax.set_title('Data After Trace') ax.set_ylabel('wiener',fontsize=13) ax.set_xlabel('time',fontsize=13) ax.set_xlim(min(t_series),max(t_series)) ax.plot(t_series,dat) dat_fds = np.array(ufuncs.get_fds(dat)) dat_cnt,dat_mkr = np.histogram(dat_fds,bar_num) norm_hist = np.histogram(dat_fds,bar_num)[0] cnt_norm = normpdf(dat_mkr,0,np.std(dat_fds)) cnt_norm = cnt_norm*max(dat_cnt)/max(cnt_norm) ksstat,pval = ks_2samp(cnt_norm, dat_cnt) print 'KS test using scaled fds of traced dat and a fit gaussian:' print 'Statistic value =',ksstat print 'Two sided p-value =',pval fig,ax1 = plt.subplots(figsize=(10,4)) ax1.set_title('Finite Difference Series Comparison') ax1.set_ylabel('count',fontsize=13) ax1.set_xlabel('difference',fontsize=13) wdth = float(max(dat_mkr)-min(dat_mkr))/bar_num plt.bar(dat_mkr[:-1],dat_cnt,label='traced fds (scaled by dt)',width = wdth,align='center') plt.plot(dat_mkr,cnt_norm,label='fit gaussian',color='m') ax1.set_xlim(min(dat_mkr)-wdth,max(dat_mkr)+wdth) plt.legend(loc='best') plt.show() interact(makeplots,a=mu_lims,b=sig_lims)
def plot_interaktiv_kNN(x, naboer=(1,17)): def f(k, metode): xd, yd = ukendte_data() fit = fit_kNN(xd, yd, k, metode) plot_kNN(x, fit, data=(xd,yd)) widgets.interact(f, k=widgets.IntSliderWidget(min=naboer[0], max=naboer[1], step=1, value=naboer[0]), metode=("uniform", "distance"))
def plot_interaktivt_polynomium(x, ordener=(0,20), figsize=(10,6)): def f(orden): xd, yd = ukendte_data() fit = fit_polynomium(xd, yd, orden) plot_polynomium(x, fit, data=(xd,yd), ordener=ordener, figsize=figsize) widgets.interact(f, orden=widgets.IntSliderWidget(min=ordener[0], max=ordener[1], step=1, value=ordener[0]))
def confusion_matrix(truths, predictions, sampling_rate=1): from IPython.html.widgets import interact, fixed assert len(truths) == len(predictions) if sampling_rate < 1: n = len(truths) indices = random.sample(range(n), int(n * sampling_rate)) truths = [truths[i] for i in indices] predictions = [predictions[i] for i in indices] interact(_show_confusion_matrix, threshold=(0.0, 1.0, 0.01), truths=fixed(truths), predictions=fixed(predictions))
def interactive_plot(self): """Create an interative plot using Ipython widgets """ basedict = self.__class__.__base_traits__ inputs = dict([(c, (getattr(basedict[c], 'low'), getattr(basedict[c], 'high'))) for c in list_ios(self, 'in')]) def f(**kwargs): my_call(self, **kwargs) display(self.plot()) interact(f, **inputs)
def plot_pca_interactive(data, n_components=6): from sklearn.decomposition import PCA from IPython.html.widgets import interact pca = PCA(n_components=n_components) Xproj = pca.fit_transform(data) def show_decomp(i=0): plot_image_components(data[i], Xproj[i], pca.mean_, pca.components_) interact(show_decomp, i=(0, data.shape[0] - 1));
def interactC(): widH = widgets.IntSliderWidget(min=0,max=1000,step=1,value=100) widZ = widgets.IntSliderWidget(min=0,max=1000,step=1,value=1) widI = widgets.IntSliderWidget(min=0,max=10,step=1,value=0) wida = widgets.FloatSliderWidget(min=0.01,max=1,step=0.01,value=0.05) widb = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.85) widz = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.09) widr = widgets.FloatSliderWidget(min=0.1,max=1,step=0.05,value=0.8) widk = widgets.FloatSliderWidget(min=0.1,max=1,step=0.1,value=0.3) wids = widgets.FloatSliderWidget(min=0.01,max=0.5,step=0.01,value=0.01) widg = widgets.FloatSliderWidget(min=0.1,max=1,step=0.1,value=0.6) interact(solucionC,humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), cuarentena=fixed(0), a=wida, b=widb, z=widz, r=widr, k=widk, s=wids, g=widg);
def simulate(transitions, input='10101', unary=False, input_unary=12, pause=0.05, step_from=0, step_to=100, step_slack=100): """loads widget to simulate a given TM""" # widgets to specify the range of steps to simulate from_w = widgets.IntText(value=step_from, description="simulate from step") to_w = widgets.IntText(value=step_to, description="simulate to step") pause_w = widgets.FloatText(value=pause, description="pause between steps"); # widget to indicate current step steps_w = widgets.IntSlider(min=0, max=step_to + step_slack, value=0, description="current step") # subroutine to animate the simulation def animate(x): steps_w.max = to_w.value + step_slack for steps in range(from_w.value, to_w.value+1): steps_w.value = steps sleep(pause_w.value) # button to start animated simulation simulate_w = widgets.Button(description='simulate') simulate_w.on_click(animate) input_w = widgets.Text(value=input, description="input") unary_w = widgets.Checkbox(value=unary, description='unary?') input_unary_w = widgets.IntText(value=input_unary, description='input number') def update(): if unary_w.value: input_w.disabled = True input_unary_w.visible = True input_w.value = '1' * input_unary_w.value else: input_w.disabled = False input_unary_w.visible = False update() unary_w.on_trait_change(update) input_unary_w.on_trait_change(update) # display control widgets box = widgets.VBox(children=[simulate_w, from_w, to_w, pause_w, unary_w, input_unary_w]) display(box) # widgets to display simulation interact(display_wrap(run), transitions=fixed(transitions), input=input_w, steps=steps_w)
def _repr_html_(self): def _data_frame(solution): df = self.nth_panel(solution - 1) notice("biomass: {0:g}".format(df['biomass'].iat[0])) notice("production: {0:g}".format(df['production'].iat[0])) df = df.loc[abs(df['normalized_gaps']) >= non_zero_flux_threshold] df.sort_values('normalized_gaps', inplace=True) display(df) num = len(self.solutions.groupby(['biomass', 'production'], as_index=False, sort=False)) interact(_data_frame, solution=(1, num)) return ''
def createPlots(filter1, filter2, filter3, type, filename=None): if type == 'Ia': lightcurvesPlotsFunc = lightcurvesPlots.plot_Ia elif type == 'Ibc': lightcurvesPlotsFunc = lightcurvesPlots.plot_Ibc elif type == 'II': lightcurvesPlotsFunc = lightcurvesPlots.plot_II if filename is not None: p = paramsFromFile(filter1, filter2, filter3, filename) else: p = paramsFromHand(filter1, filter2, filter3) interact(lightcurvesPlotsFunc, **p)
def __init__(self, r, paramIds=None, minFactor=0, maxFactor=2, sliderStepFactor=10, selection=None, simulateAndPlot=simulateAndPlot ): if paramIds is None: paramIds = r.model.getGlobalParameterIds() paramMap = {} def runSim(start=0, stop=100, steps=100, **paramMap): r.reset() for k, v in paramMap.items(): try: key = k.encode('ascii', 'ignore') r[key] = v except: # error in setting model variable e = sys.exc_info() print e try: simulateAndPlot(r, start, stop, steps, selection) except: # error in simulation e = sys.exc_info() print e for i, id in enumerate(paramIds): val = r[id] try: r[id] = val paramMap[id] = widgets.FloatSliderWidget( min=minFactor*val, max=maxFactor*val, step=val/sliderStepFactor, value=val) except: e = sys.exc_info() print e interact(runSim, start=widgets.FloatTextWidget(min=0, value=0), stop=widgets.FloatTextWidget(min=0, value=100), steps=widgets.IntTextWidget(min=0, value=100), **paramMap )
def interactive_reset_outliers(self): """User selects from columns that start with 'outlier_' to merge multiple outlier classifications""" outlier_columns = dict() for column in self.metadata.data.columns: if column.startswith("outlier_"): outlier_columns[column] = False def do_interact(**columns): if len(columns.keys()) == 0: print "You have not specified any 'outlier_' columns in " "study.metadata.data... \n" "This function will do nothing to your data." else: self.metadata.set_outliers_by_merging_columns([k for (k, v) in columns.items() if v]) interact(do_interact, **outlier_columns)
def openDB(DBchoice = 0): global dbname global lists dbname = lists[DBchoice] print 'dbname',dbname con = sqlite3.connect(dbname) query = "SELECT * FROM sqlite_master WHERE type='table'" print query global df df = pd.io.sql.read_frame(query,con) # print df.tail() global tablelen tablelen = len(df['name'])/3 if not tablelen == 1: tablelen = tablelen -1 print 'tablelen',tablelen global i2 if not i2 == 0: i2.widget.close() # i2.visible = False i2 = interact(show_tables,Tablechoice=(0,tablelen)) con.close()
def show_args(**kwargs): for k,v in kwargs.items(): global dbname global lists dbname = lists[v] print 'dbname',dbname con = sqlite3.connect(dbname) query = "SELECT * FROM sqlite_master WHERE type='table'" print query global df df = pd.io.sql.read_frame(query,con) # print df.tail() # df = dftemp.sort(ascending=True,columns=['name']) global tablelen tablelen = len(df['name']) if not tablelen == 1: tablelen = tablelen -1 print 'tablelen',tablelen global i2 if not i2 == 0: i2.widget.close() # i2.visible = False i2 = interact(show_tables,Table=(0,tablelen),Name=u'Type here')
def interactive_classifier(self, data_types=('expression', 'splicing'), sample_subsets=None, feature_subsets=None, categorical_variables=None, predictor_types=None, score_coefficient=(0.1, 20), draw_labels=False, savefile='data/last.clf.pdf'): def do_interact(data_type, sample_subset, feature_subset, predictor_type=default_classifier, categorical_variable='outlier', score_coefficient=2, savefile='data/last.clf.pdf'): for k, v in locals().iteritems(): if k == 'self': continue sys.stdout.write('{} : {}\n'.format(k, v)) self.plot_classifier(trait=categorical_variable, feature_subset=feature_subset, sample_subset=sample_subset, predictor_name=predictor_type, score_coefficient=score_coefficient, data_type=data_type) if savefile is not '': self.maybe_make_directory(savefile) plt.gcf().savefig(savefile) if feature_subsets is None: feature_subsets = Interactive.get_feature_subsets(self, data_types) feature_subsets.insert(0, 'variant') if sample_subsets is None: sample_subsets = self.default_sample_subsets if categorical_variables is None: categorical_variables = [ i for i in self.default_sample_subsets if not i.startswith("~") and i != 'all_samples' ] if predictor_types is None: predictor_types = self.predictor_config_manager.predictor_configs.keys( ) # self.plot_study_sample_legend() return interact(do_interact, data_type=data_types, sample_subset=sample_subsets, feature_subset=feature_subsets, categorical_variable=categorical_variables, score_coefficient=score_coefficient, draw_labels=draw_labels, predictor_type=predictor_types, savefile=savefile)
def _repr_html_(self): def _data_frame(solution): notice("%s: %f" % self.solutions.axes[0][solution - 1][0]) notice("%s: %f" % self.solutions.axes[0][solution - 1][1]) display(self.solutions.iloc[solution - 1]) return interact(_data_frame, solution=[1, len(self.solutions)])
def iplot(N_points=100, n_clusters=2): X, y = make_blobs(n_samples=N_points, centers=n_clusters, random_state=0, cluster_std=0.60) def _kmeans_step(k=n_clusters, frame=0): rng = np.random.RandomState(2) labels = np.zeros(X.shape[0]) centers = X[rng.randint(N_points, size=k),:] nsteps = frame // 3 for i in range(nsteps + 1): old_centers = centers if i < nsteps or frame % 3 > 0: dist = euclidean_distances(X, centers) labels = dist.argmin(1) if i < nsteps or frame % 3 > 1: centers = np.array([X[labels == j].mean(0) for j in range(k)]) nans = np.isnan(centers) centers[nans] = old_centers[nans] # plot the cluster centers fig = plt.figure(figsize=(8,6)) plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='rainbow'); plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='s', c="white", s=200) plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='s', c=np.arange(k), s=50, cmap='rainbow') # plot new centers if third frame if frame % 3 == 2: for i in range(k): plt.annotate('', centers[i], old_centers[i], arrowprops=dict(arrowstyle='->', linewidth=1)) plt.scatter(centers[:, 0], centers[:, 1], marker='s', c="white", s=200, cmap='rainbow') plt.scatter(centers[:, 0], centers[:, 1], marker='s', c=np.arange(k), s=50, cmap='rainbow') plt.xlim(-4, 4) plt.ylim(-2, 10) if frame % 3 == 1: plt.text(3.8, 9.5, "1. Reasignacion de etiquetas", ha='right', va='top', size=14) elif frame % 3 == 2: plt.text(3.8, 9.5, "2. Calculo de centroides", ha='right', va='top', size=14) frame_range = [0,20] k_range = [2, n_clusters+2] return interact(_kmeans_step, k=k_range, frame=frame_range)
def interactB(): widH = widgets.IntSliderWidget(min=0, max=1000, step=1, value=100) widZ = widgets.IntSliderWidget(min=0, max=1000, step=1, value=1) widI = widgets.IntSliderWidget(min=0, max=10, step=1, value=0) wida = widgets.FloatSliderWidget(min=0.01, max=1, step=0.01, value=0.05) widb = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.6) widz = widgets.FloatSliderWidget(min=0.01, max=0.5, step=0.01, value=0.2) widr = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.9) interact(solucionB, humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), a=wida, b=widb, z=widz, r=widr)
def plot_kmeans_interactive(): from IPython.html.widgets import interact from sklearn.metrics.pairwise import euclidean_distances from sklearn.datasets.samples_generator import make_blobs X, y = make_blobs(n_samples=300, centers=4, random_state=0, cluster_std=0.60) def _kmeans_step(frame, n_clusters): rng = np.random.RandomState(2) labels = np.zeros(X.shape[0]) centers = rng.randn(n_clusters, 2) nsteps = frame // 3 for i in range(nsteps + 1): old_centers = centers if i < nsteps or frame % 3 > 0: dist = euclidean_distances(X, centers) labels = dist.argmin(1) if i < nsteps or frame % 3 > 1: centers = np.array([X[labels == j].mean(0) for j in range(n_clusters)]) nans = np.isnan(centers) centers[nans] = old_centers[nans] # plot the cluster centers plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='rainbow'); plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='o', c=np.arange(n_clusters), s=200, cmap='rainbow') plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='o', c='black', s=50) # plot new centers if third frame if frame % 3 == 2: for i in range(n_clusters): plt.annotate('', centers[i], old_centers[i], arrowprops=dict(arrowstyle='->', linewidth=1)) plt.scatter(centers[:, 0], centers[:, 1], marker='o', c=np.arange(n_clusters), s=200, cmap='rainbow') plt.scatter(centers[:, 0], centers[:, 1], marker='o', c='black', s=50) plt.xlim(-4, 4) plt.ylim(-2, 10) if frame % 3 == 1: plt.text(3.8, 9.5, "1. Reassign points to nearest centroid", ha='right', va='top', size=14) elif frame % 3 == 2: plt.text(3.8, 9.5, "2. Update centroids to cluster means", ha='right', va='top', size=14) return interact(_kmeans_step, frame=[0, 50], n_clusters=[3, 5])
def interactive_classifier(self, data_types=('expression', 'splicing'), sample_subsets=None, feature_subsets=None, categorical_variables=None, predictor_types=None, score_coefficient=(0.1, 20), draw_labels=False, savefile='data/last.clf.pdf'): def do_interact(data_type, sample_subset, feature_subset, predictor_type=default_classifier, categorical_variable='outlier', score_coefficient=2, savefile='data/last.clf.pdf'): for k, v in locals().iteritems(): if k == 'self': continue sys.stdout.write('{} : {}\n'.format(k, v)) self.plot_classifier(trait=categorical_variable, feature_subset=feature_subset, sample_subset=sample_subset, predictor_name=predictor_type, score_coefficient=score_coefficient, data_type=data_type) if savefile is not '': self.maybe_make_directory(savefile) plt.gcf().savefig(savefile) if feature_subsets is None: feature_subsets = Interactive.get_feature_subsets(self, data_types) feature_subsets.insert(0, 'variant') if sample_subsets is None: sample_subsets = self.default_sample_subsets if categorical_variables is None: categorical_variables = [i for i in self.default_sample_subsets if not i.startswith( "~") and i != 'all_samples'] if predictor_types is None: predictor_types = self.predictor_config_manager.predictor_configs.keys() # self.plot_study_sample_legend() return interact(do_interact, data_type=data_types, sample_subset=sample_subsets, feature_subset=feature_subsets, categorical_variable=categorical_variables, score_coefficient=score_coefficient, draw_labels=draw_labels, predictor_type=predictor_types, savefile=savefile)
def interactive_lavalamp_pooled_inconsistent( self, sample_subsets=None, feature_subsets=None, difference_threshold=(0.001, 1.00), colors=["red", "green", "blue", "purple", "yellow"], savefile="", ): from IPython.html.widgets import interact savefile = "figures/last.lavalamp_pooled_inconsistent.pdf" def do_interact( sample_subset=self.default_sample_subsets, feature_subset=self.default_feature_subsets, difference_threshold=0.1, color=red, savefile=savefile, ): for k, v in locals().iteritems(): if k == "self": continue sys.stdout.write("{} : {}\n".format(k, v)) assert feature_subset in self.splicing.feature_subsets.keys() feature_ids = self.splicing.feature_subsets[feature_subset] sample_ids = self.sample_subset_to_sample_ids(sample_subset) color = str_to_color[color] self.splicing.plot_lavalamp_pooled_inconsistent(sample_ids, feature_ids, difference_threshold, color=color) plt.tight_layout() if feature_subsets is None: feature_subsets = Interactive.get_feature_subsets(self, ["splicing", "expression"]) if sample_subsets is None: sample_subsets = self.default_sample_subsets gui = interact( do_interact, sample_subset=sample_subsets, feature_subset=feature_subsets, difference_threshold=difference_threshold, color=colors, savefile="", ) def save(w): filename, extension = os.path.splitext(savefile.value) self.maybe_make_directory(savefile.value) gui.widget.result.savefig(savefile.value, format=extension.lstrip(".")) savefile = TextWidget(description="savefile", value="figures/clustermap.pdf") save_widget = ButtonWidget(description="save") gui.widget.children = list(gui.widget.children) + [savefile, save_widget] save_widget.on_click(save)
def test_call_interact_kwargs(): def foo(a="default"): pass with tt.monkeypatch(interaction, "display", record_display): ifoo = interact(foo, a=10) nt.assert_equal(len(displayed), 1) w = displayed[0].children[0] check_widget(w, cls=widgets.IntSlider, value=10)
def show_images(button): """ Do a quick and dirty plot of an image. Parameters ---------- button : `IPython.html.widgets.ButtonWidget` Button whose click generated this call. """ images = button.parent.image_list num = len(images) def view_image(i): plt.imshow(images[i]) plt.title("Image {0}".format(i)) plt.show() widgets.interact(view_image, i=(0, num - 1))
def plot_tree_interactive(X, y): from sklearn.tree import DecisionTreeClassifier def interactive_tree(depth=1): clf = DecisionTreeClassifier(max_depth=depth, random_state=0) visualize_tree(clf, X, y) from IPython.html.widgets import interact return interact(interactive_tree, depth=[1, 5])
def test_call_interact_kwargs(): def foo(a='default'): pass with tt.monkeypatch(interaction, 'display', record_display): ifoo = interact(foo, a=10) nt.assert_equal(len(displayed), 1) w = displayed[0].children[0] check_widget(w, cls=widgets.IntSlider, value=10, )
def DC2DPseudoWidget(): # print xzlocs Q = interact(DC2DPseudoWidgetWrapper, rhohalf=FloatSlider(min=10, max=1000, step=1, value=1000), rhosph=FloatSlider(min=10, max=1000, step=1, value=50), xc=FloatSlider(min=-40, max=40, step=1, value=0), zc=FloatSlider(min=-20, max=0, step=1, value=-10), r=FloatSlider(min=0, max=15, step=0.5, value=5), surveyType=ToggleButtons( options=['DipoleDipole', 'PoleDipole', 'DipolePole'])) return Q
def interactive_graph(self): """Create an interative graph using Ipython widgets """ basedict = self.__class__.__base_traits__ inputs = dict([(c, (getattr(basedict[c], 'low'), getattr(basedict[c], 'high'))) for c in list_ios(self, 'in')]) def f(**kwargs): my_call(self, **kwargs) display(self.draw_graph(value=True)) return interact(f, **inputs)
def test_call_interact(): def foo(a='default'): pass with tt.monkeypatch(interaction, 'display', record_display): ifoo = interact(foo) nt.assert_equal(len(displayed), 1) w = displayed[0].children[0] check_widget( w, cls=widgets.TextWidget, value='default', )
def InteractSeismogram(): return interact(plotSeismogramInteract, d2=(0., 150., 1), d3=(0., 200., 1), rho1=(2000., 5000., 50.), rho2=(2000., 5000., 50.), rho3=(2000., 5000., 50.), v1=(100., 4000., 5.), v2=(100., 4000., 5.), v3=(300., 4000., 50.), wavf=(5., 100., 2.5), wavA=FloatSlider(min=-0.5, max=1., step=0.25, value=1.), addNoise=False, usingT=True)
def test_interact_instancemethod(): class Foo(object): def show(self, x): print(x) f = Foo() with tt.monkeypatch(interaction, 'display', record_display): g = interact(f.show, x=(1,10)) nt.assert_equal(len(displayed), 1) w = displayed[0].children[0] check_widget(w, cls=widgets.IntSlider, value=5, )
def setup_likelihood_sampler(kernel): # Pre-compute some stuff. x0 = np.linspace(-5, 5, 300) r = x0[:, None] - x0[None, :] # This function samples from the likelihood distribution. def sample_likelihood(amp, ell): np.random.seed(123) K = kernel([amp, ell], r) y0 = np.random.multivariate_normal(np.zeros_like(x0), K, 6) pl.plot(x0, y0.T, "k", alpha=0.5) pl.ylim(-1.5, 1.5) pl.xlim(-5, 5) return interact(sample_likelihood, amp=(1.0e-4, 1.0), ell=(0.01, 3.0))
def interactC(): widH = widgets.IntSliderWidget(min=0, max=1000, step=1, value=100) widZ = widgets.IntSliderWidget(min=0, max=1000, step=1, value=1) widI = widgets.IntSliderWidget(min=0, max=10, step=1, value=0) wida = widgets.FloatSliderWidget(min=0.01, max=1, step=0.01, value=0.05) widb = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.85) widz = widgets.FloatSliderWidget(min=0.01, max=0.5, step=0.01, value=0.09) widr = widgets.FloatSliderWidget(min=0.1, max=1, step=0.05, value=0.8) widk = widgets.FloatSliderWidget(min=0.1, max=1, step=0.1, value=0.3) wids = widgets.FloatSliderWidget(min=0.01, max=0.5, step=0.01, value=0.01) widg = widgets.FloatSliderWidget(min=0.1, max=1, step=0.1, value=0.6) interact(solucionC, humanos=widH, infectados=widI, zombies=widZ, muertos=fixed(0), cuarentena=fixed(0), a=wida, b=widb, z=widz, r=widr, k=widk, s=wids, g=widg)
def interactive_lavalamp_pooled_inconsistent( self, sample_subsets=None, feature_subsets=None, difference_threshold=(0.001, 1.00), colors=['red', 'green', 'blue', 'purple', 'yellow'], savefile=''): from IPython.html.widgets import interact # not sure why nested fxns are required for this, but they are... i # think... def do_interact(sample_subset=self.default_sample_subsets, feature_subset=self.default_feature_subsets, difference_threshold=0.1, color=red, savefile='data/last.lavalamp_pooled_inconsistent.pdf'): for k, v in locals().iteritems(): if k == 'self': continue sys.stdout.write('{} : {}\n'.format(k, v)) assert (feature_subset in self.splicing.feature_subsets.keys()) feature_ids = self.splicing.feature_subsets[feature_subset] sample_ids = self.sample_subset_to_sample_ids(sample_subset) color = str_to_color[color] self.splicing.plot_lavalamp_pooled_inconsistent( sample_ids, feature_ids, difference_threshold, color=color) plt.tight_layout() if savefile is not '': self.maybe_make_directory(savefile) plt.gcf().savefig(savefile) if feature_subsets is None: feature_subsets = Interactive.get_feature_subsets( self, ['splicing', 'expression']) if sample_subsets is None: sample_subsets = self.default_sample_subsets return interact(do_interact, sample_subset=sample_subsets, feature_subset=feature_subsets, difference_threshold=difference_threshold, color=colors, savefile='')
def __init__(self): dfiles = glob.glob('DATA' + os.path.sep + '*.SPUV') dfiles.sort() self.slopes = zeros(6) # calibration constants self.spa = [ 0.0, 2.412917, 1.0417198 / 1.4, 2.60924 / 2.5, 0.92835 / 0.85, 1.32079 / 0.85, 9.28147 ] self.spb = [ 0.0, 0.001200, -0.0009700, -0.00040, 0.00050, -0.00197, 0.00030 ] self.spc = 1000.0 self.spd = 0.0 self.w1 = interact(self.file_select, filename=dfiles)
def interactive_localZ(self): from IPython.html.widgets import interact def do_interact(data_type='expression', sample1='', sample2='', pCut='0.01'): for k, v in locals().iteritems(): if k == 'self': continue sys.stdout.write('{} : {}'.format(k, v)) pCut = float(pCut) assert pCut > 0 if data_type == 'expression': data_obj = self.expression if data_type == 'splicing': data_obj = self.splicing try: assert sample1 in data_obj.df.index except: sys.stdout.write("sample: {}, is not in {} DataFrame, " "try a different sample ID".format( sample1, data_type)) return try: assert sample2 in data_obj.df.index except: sys.stdout.write("sample: {}, is not in {} DataFrame, " "try a different sample ID".format( sample2, data_type)) return self.localZ_result = data_obj.plot_twoway(sample1, sample2, pCut=pCut).result_ sys.stdout.write("local_z finished, find the result in " "<this_object>.localZ_result_") return interact(do_interact, data_type=('expression', 'splicing'), sample1='replaceme', sample2='replaceme', pCut='0.01')
def PseudoSectionWidget(survey, flag): dx = 5 xr = np.arange(-40, 41, dx) if flag == "PoleDipole": ntx, nmax = xr.size - 2, 8 dxr = np.diff(xr) elif flag == "DipolePole": ntx, nmax = xr.size - 1, 7 dxr = xr elif flag == "DipoleDipole": ntx, nmax = xr.size - 3, 8 dxr = np.diff(xr) xzlocs = getPseudoLocs(dxr, ntx, nmax, flag) PseudoSectionPlot = lambda i, j: PseudoSectionPlotfnc(i, j, survey, flag) return interact(PseudoSectionPlot, i=IntSlider(min=0, max=ntx - 1, step=1, value=0), j=IntSlider(min=0, max=nmax - 1, step=1, value=0))
def interact_with_plot_all_outputs(sa_dict, demo=False, manual=True): """ This function adds the ability to interactively adjust all of the plotting.make_plot() arguments. Parameters ---------- sa_dict : dict a dictionary with all the sensitivity analysis results. demo : bool, optional plot only few outcomes for demo purpose. Returns ------- Interactive widgets to control plot """ min_val_box = BoundedFloatText(value=0.01, min=0, max=1, description='Min value:') top_box = IntText(value=20, description='Show top:') stacks = Checkbox( description='Show stacked plots:', value=True, ) error_bars = Checkbox(description='Show error bars:', value=True) log_axis = Checkbox(description='Use log axis:', value=True) # get a list of all the parameter options key = sa_dict.keys()[0] param_options = list(sa_dict[key][0].Parameter.values) highlighted = SelectMultiple(description="Choose parameters to highlight", options=param_options, value=[]) return interact(plot_all_outputs, sa_dict=fixed(sa_dict), demo=fixed(demo), min_val=min_val_box, top=top_box, stacked=stacks, error_bars=error_bars, log_axis=log_axis, highlighted_parameters=highlighted, __manual=manual)
def fig(self, ix, raw=False, alt_df=None): """Generate interactive plot of a specified target. alt_df: df to use for fig; None if using self.pbb ix: index of the dataframe to plot raw: slider for raw image """ if alt_df is None: df = self.pbbs else: df = alt_df row = df.loc[ix] print row pid, z, y, x, d = row['pid'], row['z'],\ row['y'],row['x'],row['d'] import IPython.html.widgets as w if not raw: img = np.load(os.path.join(self.PREP, pid + '_clean.npy')) else: img, origin, spacing = utils.load_itk_image(os.path.join(self.RAW,pid + '.mhd')) # convert z,y,x,d to raw voxel coordinates v = np.array([z,y,x]) ebox_origin = np.load(os.path.join(self.PREP,pid+'_ebox_origin.npy')) v = v + ebox_origin prep_spacing = np.load(os.path.join(self.PREP,pid+'_spacing.npy')) v = utils.voxelToWorldCoord(v, origin, prep_spacing) v = utils.worldToVoxelCoord(v, origin, spacing) z, y, x = v[0], v[1], v[2] d = d * prep_spacing[1] / spacing[1] # convert title row = row.copy() row['z'] = z row['y'] = y row['x'] = x row['d'] = d def fz(k): utils.showTargetImgComp(img, [k,y,x], plt, d=d, t=str(row)) def fy(k): utils.showTargetImgComp(np.swapaxes(img,0,1), [k,z,x], plt, d=d, t=str(row)) def fx(k): utils.showTargetImgComp(np.swapaxes(img,0,2), [k,y,z], plt, d=d, t=str(row)) w.interact(fz, k=w.IntSlider(min=0,max=img.shape[0]-1,step=1,value=z)) w.interact(fy, k=w.IntSlider(min=0,max=img.shape[1]-1,step=1,value=y)) w.interact(fx, k=w.IntSlider(min=0,max=img.shape[2]-1,step=1,value=x))
def file_select(self, filename=''): f = open(filename, 'r') self.title = filename lines = f.readlines() spuv = [] for line in lines[18:]: spuv.append([float(val) for val in line.split()[0:]]) f.close() self.spuv = array(spuv) self.cspuv = copy.deepcopy(self.spuv) for i in range(0, 6): self.cspuv[:, i + 3] = (self.spuv[:, i + 3] - (self.spb[i + 1] * self.spc - self.spd)) / ( self.spa[i + 1] * self.spc) self.cspuv = where(self.cspuv < 0, 1e-10, self.cspuv) self.costheta = self.spuv[:, 2] self.costheta = where(self.costheta < 0, 1e-10, self.costheta) self.m = 1. / self.costheta self.xtime = self.spuv[:, 1] self.sza = arccos(self.costheta) * 180 / pi # remove possible existing widget before starting a new one try: self.w2.widget.close() except: None # setup widget: roptions = ['slopes', 'Langley slopes'] self.w2 = interact(self.langley, representation=roptions, wl_368nm=True, wl_501nm=True, wl_670nm=True, wl_780nm=True, wl_870nm=True, wl_940nm=True, dayfraction=['morning', 'afternoon'], mmin=(1, 10, 0.1), mmax=(1, 10, 0.1))
def InteractSeismogramTBL(v1=125, v2=125, v3=125): return interact(plotSeismogramInteractTBL, d2=FloatSlider(min=1., max=100., step=0.1, value=9.), d3=FloatSlider(min=2., max=100., step=0.1, value=9.5), rho1=FloatSlider(min=2000., max=5000., step=50., value=2300.), rho2=FloatSlider(min=2000., max=5000., step=50., value=2300.), rho3=FloatSlider(min=2000., max=5000., step=50., value=2300.), v1=FloatSlider(min=100., max=1200., step=5., value=v1), v2=FloatSlider(min=100., max=1200., step=5., value=v2), v3=FloatSlider(min=100., max=1200., step=5., value=v3), wavf=FloatSlider(min=5., max=100., step=1, value=67), wavA=FloatSlider(min=-0.5, max=1., step=0.25, value=1.), addNoise=False, usingT=True)
def file_select(self, filename=''): f = open(filename, 'r') self.title = filename lines = f.readlines() spuv = [] for line in lines[18:]: spuv.append([float(val) for val in line.split()[0:]]) f.close() self.spuv = array(spuv) self.cspuv = copy.deepcopy(self.spuv) for i in range(0, 6): self.cspuv[:, i + 3] = (self.spuv[:, i + 3] - (self.spb[i + 1] * self.spc - self.spd)) / ( self.spa[i + 1] * self.spc) self.cspuv = where(self.cspuv < 0, 1e-10, self.cspuv) self.costheta = self.spuv[:, 2] self.costheta = where(self.costheta < 0, 1e-10, self.costheta) self.m = 1. / self.costheta self.xtime = self.spuv[:, 1] self.sza = arccos(self.costheta) * 180 / pi # remove possible existing widget before starting a new one try: self.w2.widget.close() except: None # setup widget: roptions = ['raw counts', 'calibrated radiances', 'airmass'] self.w2 = interact(self.aerosol, representation=roptions, wl_368nm=True, wl_501nm=False, wl_670nm=False, wl_780nm=False, wl_870nm=False, wl_940nm=False)
y = y[:N] clf = SVC(kernel='linear') clf.fit(X, y) plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='RdYlGn') plt.xlim(-50, 300) plt.ylim(0, 350) plot_svc_decision_function(clf, plt.gca()) plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=200, facecolors='none') plt.xlabel(u'freies mtl. Einkommen [EUR]') plt.ylabel(u'angefragte mtl. Kreditrate [EUR]') interact(plot_svm, N=[5, 500], kernel='poly') # # Unsupervised Learning: Clustering # # [KMeans](http://scikit-learn.org/stable/modules/clustering.html#k-means) findet Cluster selbst, man muss nur sagen, wieviel unterschiedliche man haben möchte. # In[24]: from sklearn.cluster import KMeans # In[25]: cluster = KMeans(n_clusters=2) # In[26]:
require(["leaflet"], function(leaflet) { var map = window._my_maps['i3c9fe247-096f-4df2-b6d7-291bb6d3b0e1'] console.log(map.getCenter()); }); # <codecell> from IPython.html import widgets from IPython.html.widgets import interact, fixed zoom_widget = widgets.IntSliderWidget(min=1, max=18, step=1) zoom_widget.value = 12 interact (leaflet, leaflet_api_key=fixed(LEAFLET_KEY), lat=fixed(37.8717), long=fixed(-122.2728),height=fixed(500), zoom=zoom_widget) # <headingcell level=1> # Doing more with a map # <codecell> %%javascript console.log(IPython.notebook.get_cells()); # <codecell> %%javascript require(["leaflet"], function(leaflet) {
def secondorder(K_in, tau_in, zeta_in): values = {K: K_in, tau: tau_in, zeta: zeta_in} AA = A.subs(values) stepresponse = sympy.re( (x0.subs(values) - sympy.exp(AA * t) * x0.subs(values))[0, 0]) evalf = sympy.lambdify((t, ), stepresponse, modules='numpy') plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title('Step response') tau_height = evalf(tau_in) plt.plot(ts, evalf(ts)) plt.axhline(K_in) plt.plot([0, tau_in, tau_in], [tau_height] * 2 + [0], alpha=0.4) plt.text(0, K_in, '$K=${}'.format(K_in)) plt.text(0, tau_height, '{:.3}$K$'.format(tau_height)) plt.text(tau_in, 0, r'$\tau={:.3}$'.format(tau_in)) plt.ylim(0, 10) plt.subplot(1, 2, 2) plt.title('Poles plot') realpart = [sympy.re(r.subs(values)) for r in roots] imagpart = [sympy.im(r.subs(values)) for r in roots] plt.scatter(realpart, imagpart, marker='x', s=30) plt.axhline(0, color='black') plt.axvline(0, color='black') plt.axis([-2, 2, -2, 2]) # In[22]: interact(secondorder, K_in=(0.1, 10.), tau_in=(0., 10.), zeta_in=(0., 2))
plt.plot(x,data[:]) plt.xlabel("y") plt.ylabel("w") plt.figure() scalex = np.sqrt(np.abs(data[1]/x[1]) * p['viscosity']) / p['viscosity'] scaley = 1./np.sqrt(np.abs(data[1]/x[1]) * p['viscosity']) plt.plot(scalex*x[:50],scaley*data[:50], 'x-') plt.grid(True) plt.xlabel("y+") plt.ylabel("w+") plt.figure() scalex = np.sqrt(np.abs(data[-1]/(x[-1]-1)) * p['viscosity']) / p['viscosity'] scaley = 1./np.sqrt(np.abs(data[-1]/(x[-1]-1)) * p['viscosity']) plt.plot(scalex*(x[-50:]-1),scaley*data[-50:], 'x-') plt.grid(True) plt.xlabel("y+") plt.ylabel("w+") interact(plot_profile, frame=(0,64), index=IntSlider(min=0,max=sc[0.0,'w_xy'].shape[0]-1,step=8,value=int(sc[0.0,'w_xy'].shape[0]*7/9)) ) # In[8]: get_ipython().magic('install_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py') get_ipython().magic('load_ext version_information') get_ipython().magic('version_information numpy, matplotlib, slict, chest, glopen, globussh')
def mean_filter_interactive_demo(image): from IPython.html import widgets mean_filter_step = mean_filter_demo(image) step_slider = widgets.IntSliderWidget(min=0, max=image.size - 1, value=0) widgets.interact(mean_filter_step, i_step=step_slider)
def simulate(transitions, input='10101', unary=False, input_unary=12, pause=0.05, step_from=0, step_to=100, step_slack=100): """loads widget to simulate a given TM""" # widgets to specify the range of steps to simulate from_w = widgets.IntText(value=step_from, description="simulate from step") to_w = widgets.IntText(value=step_to, description="simulate to step") pause_w = widgets.FloatText(value=pause, description="pause between steps") # widget to indicate current step steps_w = widgets.IntSlider(min=0, max=step_to + step_slack, value=0, description="current step") # subroutine to animate the simulation def animate(x): steps_w.max = to_w.value + step_slack for steps in range(from_w.value, to_w.value + 1): steps_w.value = steps sleep(pause_w.value) # button to start animated simulation simulate_w = widgets.Button(description='simulate') simulate_w.on_click(animate) input_w = widgets.Text(value=input, description="input") unary_w = widgets.Checkbox(value=unary, description='unary?') input_unary_w = widgets.IntText(value=input_unary, description='input number') def update(): if unary_w.value: input_w.disabled = True input_unary_w.visible = True input_w.value = '1' * input_unary_w.value else: input_w.disabled = False input_unary_w.visible = False update() unary_w.on_trait_change(update) input_unary_w.on_trait_change(update) # display control widgets box = widgets.VBox( children=[simulate_w, from_w, to_w, pause_w, unary_w, input_unary_w]) display(box) # widgets to display simulation interact(display_wrap(run), transitions=fixed(transitions), input=input_w, steps=steps_w)
def plot_line(ax, intercept): plt.figure(figsize=(12, 12)) ax = plt.gca() ax.set_xlim([0.0, 1.0]) ax.set_ylim([0.0, 1.0]) make_roc("gnb", clfgnb, ytest, Xtest, ax, labe=60) make_roc("dt", clfdt, ytest, Xtest, ax, labe=1) ax.plot(z1, slope * z1 + intercept, 'k-') # In[48]: from IPython.html.widgets import interact, fixed interact(plot_line, ax=fixed(ax), intercept=(0.0, 1.0, 0.02)) # In[50]: def percentage(tpr, fpr, priorp, priorn): perc = tpr * priorp + fpr * priorn return perc def av_cost2(tpr, fpr, cost, priorp, priorn): profit = priorp * (cost[1][1] * tpr + cost[1][0] * (1. - tpr)) + priorn * (cost[0][0] * (1. - fpr) + cost[0][1] * fpr) return profit
def show(self): plt.close(self.plots[self.i - 1]) interact(self.showFigure, i=[1, self.i, 1])