def display_plots(filebase, directory=None, width=700, height=500, **kwargs): """Display a series of plots controlled by sliders. The function relies on Python string format functionality to index through a series of plots.""" def show_figure(filebase, directory, **kwargs): """Helper function to load in the relevant plot for display.""" filename = filebase.format(**kwargs) if directory is not None: filename = directory + '/' + filename display(HTML("<img src='{filename}'>".format(filename=filename))) interact(show_figure, filebase=fixed(filebase), directory=fixed(directory), **kwargs)
def setFloat(self, label, default=0, min=-20, max=20, description='Set Float', format='text'): """ Set float in a notebook pipeline (via interaction or with nbconvert) """ obj = self.load(label) if obj == None: obj=default self.save(obj, label) # initialize with default floatw = FloatSlider(value=obj, min=min, max=max, description=description) hndl = interact(self.save, obj=floatw, label=fixed(label), format=fixed(format))
def setText(self, label, default='', description='Set Text', format='text'): """ Set text in a notebook pipeline (via interaction or with nbconvert) """ obj = self.load(label) if obj == None: obj=default self.save(obj, label) # initialize with default textw = Text(value=obj, description=description) hndl = interact(self.save, obj=textw, label=fixed(label), format=fixed(format))
def setDropdown(self, label, default=None, options=[], description='Set Dropdown', format='text'): """ Set float in a notebook pipeline (via interaction or with nbconvert) """ obj = self.load(label) if obj == None: obj=default self.save(obj, label) # initialize with default dropdownw = Dropdown(value=obj, options=options, description=description) hndl = interact(self.save, obj=dropdownw, label=fixed(label), format=fixed(format))
def layer_select(m, design): layers_to_plot = m features_to_plot = {'features':[],'layer':[]} if len(layers_to_plot)>0: features_to_plot['features'] = [x for x in design.features if design.features[x].layer in layers_to_plot] features_to_plot['layers'] = [layers_to_plot.index(design.features[x].layer) for x in design.features if design.features[x].layer in layers_to_plot] if len(features_to_plot['features'])>0: #chk = [Checkbox(description=a) for a in features_to_plot] #interact(updatePlot, **{c.description: c.value for c in chk}) sel_mult2 = SelectMultiple(options = features_to_plot['features']) interactive_plot2 = interactive(updatePlot, n=sel_mult2, design = fixed(design), all_features = fixed(features_to_plot)) display(interactive_plot2)
def im(self, z=None, zmin=None, zmax=None, cmap='jet'): if z is None: if self._interactive: name_options = list() for dim_names, var_names in self._inspector.dim_names_to_var_names.items(): no_zero_dim = all([self._inspector.dim_name_to_size[dim] > 0 for dim in dim_names]) if no_zero_dim and len(dim_names) == 2: name_options.extend(var_names) name_options = sorted(name_options) # TODO (forman, 20160709): add sliders for zmin, zmax interact(self._plot_im, z_name=name_options, zmin=fixed(zmax), zmax=fixed(zmax), cmap=fixed(cmap)) else: raise ValueError('name must be given') else: self._plot_im(z_name=z, zmin=zmin, zmax=zmax, cmap=cmap)
def myinteract(img): min_ = round(np.nanmin(img), 4) max_ = round(np.nanmax(img), 4) p30, p70 = np.percentile(img[~np.isnan(img)], (30, 70)) delta = round((p30-min_)/50, 5) interact(myimshow, img=fixed(img), vmin=(min_, p30, delta), vmax=(p70, max_, delta), i=(0, len(interpolators)-1))
def plot_expm(r:(0,4,0.1)=1.1, n0=fixed(100)): nt = [r**t * n0 for t in range(10)] plt.figure(figsize=[9,4]) plt.plot(nt, lw=2) plt.xlabel('generation number') plt.ylabel('population size') plt.ylim(0, max(nt)*1.1) plt.show()
def test_fixed(): c = interactive(f, a=widgets.fixed(5), b='text') nt.assert_equal(len(c.children), 2) w = c.children[0] check_widget(w, cls=widgets.Text, value='text', description='b', )
def plot_mc_sol(s1:(0,1,0.1)=1,p:(0,1,0.1)=0.9,q:(0,1,0.1)=0.9, tmax=fixed(20)): s1,s2 = list(zip(*[mc_sol(s1,p,q,t) for t in range(tmax+1)])) plt.figure(figsize=[9,4]) plt.plot(s1, label='S_1, off') plt.plot(s2, label='S_2, on') plt.xlabel('time') plt.ylabel('proportion of channels') plt.ylim(-0.01,1.01) plt.legend() plt.show()
def display_widget(f, title_to_filename, select_widget, checkbox_list): ''' this function creates the interactive window for the user to explore the data ''' i = widgets.interactive(f, movie_title = select_widget, title_to_filename = fixed(title_to_filename), anger=checkbox_list[0], anticipation=checkbox_list[1], disgust=checkbox_list[2], fear=checkbox_list[3], joy=checkbox_list[4], negative=checkbox_list[5], positive=checkbox_list[6], sadness=checkbox_list[7], surprise=checkbox_list[8], trust=checkbox_list[9], visulalize_emotions=fixed(True), hierarchy_emotions=widgets.ToggleButton(value=False, description='See emotion importance for\ the whole script'), hierarchy_emotions_subplot=widgets.ToggleButton(value=False, description='See emotion importance for\ the beginning, middle and end of the script')) hbox1 = widgets.HBox([i.children[0]]) #select movie to explore hbox2 = widgets.HBox(i.children[6:8]) #positive and negative sentiment analysis hbox3 = widgets.HBox(i.children[1:6]+i.children[8:11]) #emotions hbox4 = widgets.HBox(i.children[11:12]) hbox5 = widgets.HBox(i.children[12:]) display( hbox1 ) display( hbox2 ) display( hbox3 ) display( hbox4 ) display( hbox5 )
def plot_mc_sol2(p:(0,1,0.1)=0.9,q:(0,1,0.1)=0.9, \ tmax=fixed(20), log_n:(0,10,1)=0): s1,s2 = list(zip(*[mc_sol(1,p,q,t) for t in range(tmax+1)])) n = int(np.exp(log_n)) sim = [list(mc(p,q,tmax)) for _ in range(n)] sim_av = [np.mean(s) for s in list(zip(*sim))] print("n = %d" % n) plt.figure(figsize=[9,4]) plt.plot(s2) plt.plot(sim_av) plt.xlabel('time') plt.ylabel('proportion of channels on') plt.ylim(-0.01,1.01) plt.show()
def plot_riemann_SW(h_l,h_r,u_l,u_r,g=1.,force_waves=None,extra_lines=None, tracer=False): stripes = not tracer plot_function_stripes, plot_function_xt_phase = \ make_plot_functions(h_l,h_r,u_l,u_r,g, force_waves,extra_lines,stripes=stripes) interact(plot_function_stripes, t=widgets.FloatSlider(value=0.,min=0,max=.9), fig=fixed(0)) if tracer: interact(plot_function_xt_phase, plot_1_chars=Checkbox(description='1-characteristics', value=False), plot_2_chars=Checkbox(description='2-characteristics'), plot_tracer_chars=Checkbox(description='Tracer characteristics')) else: interact(plot_function_xt_phase, plot_1_chars=Checkbox(description='1-characteristics', value=False), plot_2_chars=Checkbox(description='2-characteristics'))
def plot_1(thedata): widgets.interact(_plot_1, thedata = widgets.fixed(thedata), Country1 = widgets.Dropdown( description = 'OECD Country (No data for % AVG Wage for Turkey)', options = thedata['Country'].unique().tolist(), value = 'Australia', disabled = False), Country2 = widgets.Dropdown( description = 'OECD Country (No data for % AVG Wage for Turkey)', options = thedata['Country'].unique().tolist(), value = 'Australia', disabled = False), Variable1 = widgets.Dropdown( description = 'Variable1', options = ['Total Unemployment (%)','Inflation Rate (%)','Average Wage Growth (%)','GDP Growth (%)'], value = 'Total Unemployment (%)'), )
def show_results(results, header, prefix): """!@brief Display results A function to display all the accepted candidates using a dropdown list. @param results (np.ndarray) numpy array of results sorted by total energy @param header (str) A comma separated string of the output properties of the conformer @param prefix (dict) A dictionary of the prefix of the run and the associated helical configuration @returns None @sa run @sa single_result """ # Set a list of conformer names and their indices in the results options = [(str(int(conformer[0])) + '_' + str(int(conformer[1])) + '.pdb', i) for i, conformer in enumerate(results)] # Show a dropdown widget of all the accepted conformers dropdown = widgets.Dropdown(value=options[0][1], options=options, style={'description_width': 'initial'}, description='Conformer') w = widgets.interactive(single_result, result=dropdown, header=widgets.fixed(header), results=widgets.fixed(results), prefix=widgets.fixed(prefix)) display(w)
def confined_aquifer(analysis=False): approx = Checkbox(value=True, description='approx.') semilog = Checkbox(value=False, description='SemiLog') Q = FloatSlider(value=1000, description=r'$Q$ [m$^3$/day]', min=500, max=1500, step=500, continuous_update=False) t = FloatLogSlider(value=1.0, description=r'$t$ [day]', base=10, min=-1, max=2, step=0.2, continuous_update=False) r = FloatSlider(value=200, description=r'$r$ [m]', min=100, max=500, step=100, continuous_update=False) T = FloatSlider(value=300, description=r'$T$ [m$^2$/day]', min=100, max=500, step=100, continuous_update=False) io = interactive_output( show_theis, { 'Q': Q, 't': t, 'r': r, 'T': T, 'approx': approx, 'semilog': semilog, 'analysis': fixed(analysis) }) return VBox([HBox([Q, t, approx]), HBox([T, r, semilog]), io])
def bases(param): """!@brief Bases widget for use in Jupyter notebook This function displays information on the available nucleobases that are defined in the program. The bases are defined in "data/bases_library.yaml" @returns None @sa display_options_widgets """ display(widgets.HTML(value='<H3>Bases</H3>')) display(widgets.HTML(value=('These bases are already defined:' + '<br> Adenine (A), Guanine (G), Cytosine (C), Uracil (U), Thymine (T), ' + 'Cyanuric Acid (I), and aminopyrimidine (E)'))) num_defined_bases = len([k for k in param if 'Base' in k]) - 1 # Subtract the item from the main options w = widgets.interactive(add_base, param=widgets.fixed(param), number_of_bases=widgets.BoundedIntText(value=num_defined_bases, min=0, description="Number of additional bases", style={'description_width': 'initial'})) help_box = widgets.Button(description='?', tooltip=('The number of additional bases to define'), layout=widgets.Layout(width='4%')) display(widgets.HBox([help_box, w]))
def interactive_indifference_curves(preferences="cobb_douglas", **kwargs): interactive_utility_settings(preferences, kwargs) widgets.interact( _interactive_indifference_curves, alpha=widgets.FloatSlider( description="$\\alpha$", min=kwargs["alpha_min"], max=kwargs["alpha_max"], step=kwargs["alpha_step"], value=kwargs["alpha"], ), beta=widgets.FloatSlider( description="$\\beta$", min=kwargs["beta_min"], max=kwargs["beta_max"], step=kwargs["beta_step"], value=kwargs["beta"], ), par=widgets.fixed(kwargs), )
def create_wordcloud(frame = fixed(text) , community = [0, 1, 2, 3], maximum = [50,100,300] , atitle = fixed('')): if community == 0: mk = imageio.imread('./data/club.jpg') if community == 1: mk = imageio.imread('./data/diamond.png') if community == 2: mk = imageio.imread('./data/spade.jpg') if community == 3: mk = imageio.imread('./data/heart.jpg') wordcloud = WordCloud(max_font_size = 70, max_words = maximum, background_color = 'white', collocations = False, mask = mk).generate(text[community]) image_colors = ImageColorGenerator(mk) plt.style.use('seaborn') plt.figure(figsize=[15, 15]) plt.title('community '+str(community), fontsize = 20) plt.imshow(wordcloud.recolor(color_func = image_colors), interpolation = 'bilinear') plt.axis('off')
def nifti_plotter(self, plotting_func=None, colormap=None, figsize=(15, 5), **kwargs): """ Plot volumetric data. Args ---- plotting_func : function A plotting function for .nii files, most likely mask_background : bool Whether the background should be masked (set to NA). This parameter only works in conjunction with the default plotting function (`plotting_func=None`). It finds clusters of values that round to zero and somewhere touch the edges of the image. These are set to NA. If you think you are missing data in your image, set this False. colormap : str | list The matplotlib colormap that should be applied to the data. By default, the widget will allow you to pick from all that are available, but you can pass a string to fix the colormap or a list of strings to offer the user a few options. figsize : tup The figure height and width for matplotlib, in inches. If you are providing a custom plot function, any kwargs you provide to nifti_plotter will be passed to that function. """ kwargs['colormap'] = get_cmap_dropdown(colormap) kwargs['figsize'] = fixed(figsize) if plotting_func is None: self._default_plotter(**kwargs) else: self._custom_plotter(plotting_func, **kwargs)
def interact(): from ipywidgets import interactive, fixed, widgets, interact_manual from IPython.display import display from ipywidgets import AppLayout, Button, Layout target_values_options = list(df["{}"].unique()) features_options = list(df.columns.values) features_options.remove("{}") w1 = widgets.SelectMultiple( options=target_values_options, value=target_values_options, rows=len(target_values_options), description="Target Values (column: {})", style={{ "description_width": "initial" }}, disabled=False, ) w2 = widgets.SelectMultiple( options=features_options, value=features_options[0:min(len(features_options), 2)], rows=len(features_options), description="Features", disabled=False, ) ui = widgets.HBox([w1, w2]) out = widgets.interactive_output( pairwise_scatter_plots, {{ "df": fixed(df), "target_values": w1, "features": w2 }}, ) display(ui, out)
def display_lineplot_widget(cls, df, include_all=False): options = df.StationCode.unique().tolist() stations_dropdown = cls.create_stations_dropdown(options, include_all) validation_dropdown = cls.create_validation_dropdown() options = df.select_dtypes("float").columns.tolist() param_dropdown = cls.create_param_dropdown(options) options = df.DateTimeStamp.dt.year.unique().tolist() year_dropdown = cls.create_year_dropdown(options) def on_dropdown_update(df, station_code, validation_code, param_code, year_code): df = filter_by_station_code(df, station_code) df = filter_by_year_code(df, year_code) df = filter_by_validation_code(df, validation_code) if not df.empty: msg = f"Generating lineplot for {station_code}: {validation_code}" display(widgets.HTML(msg)) lineplot_options = dict( x="DateTimeStamp", y=param_code, hue="StationCode", ci=None ) cls.create_lineplot(df, **lineplot_options) else: msg = "No data was found with the selected filters." msg += "Unable to generate report." display(widgets.HTML(msg)) widgets.interact( on_dropdown_update, df=widgets.fixed(df), station_code=stations_dropdown, validation_code=validation_dropdown, param_code=param_dropdown, year_code=year_dropdown )
def observation_error(): #out = Output() seed = 13 rolldice = Button(description='ROLL THE DICE', tooltip='randomise the random number generator') Nsldr = IntSlider(value=5, description='$N_{obs}$', min=2, max=10, step=1, continuous_update=False) trueModel = Checkbox(value=False, description='True Process') bestModel = Checkbox(value=False, description='Best (LSQ) Model') varsldr = FloatLogSlider(value=0.1, base=10, description='$\sigma_i^2$', min=-2, max=0, step=1, continuous_update=False) sdf = fixed(seed) np.random.seed(13) def on_button_clicked(b): sdf.value = int(time.time()) rolldice.on_click(on_button_clicked) io = interactive_output( plot_observations, { 'N_obs': Nsldr, 'trueModel': trueModel, 'bestModel': bestModel, 'var': varsldr, 'seed': sdf }) return VBox([HBox([Nsldr, bestModel, trueModel, rolldice, varsldr]), io])
def plot_measures(data_path): dd_style = {'description_width': 'initial'} w = ipywidgets.Dropdown(options=[ 'dikeraising_evr_smooth', 'dikeraising_lrg_smooth', 'groynelowering_evr_smooth', 'groynelowering_lrg_smooth', 'lowering_evr_natural', 'lowering_evr_smooth', 'lowering_lrg_natural', 'lowering_lrg_smooth', 'minemblowering_evr_smooth', 'minemblowering_lrg_smooth', 'sidechannel_evr_natural', 'sidechannel_evr_smooth', 'sidechannel_lrg_natural', 'sidechannel_lrg_smooth', 'smoothing_evr_natural', 'smoothing_evr_smooth', 'smoothing_lrg_natural', 'smoothing_lrg_smooth' ], value='lowering_evr_smooth', description='Select measure:', style=dd_style) res = interactive(_plot_datasets, data_path=fixed(data_path), measure_dir=w) display(res)
def im_line(self, z=None, zmin=None, zmax=None, xind=None, yind=None, cmap='jet'): if self._interactive: has_xind = xind is not None has_yind = yind is not None if not z or not has_xind or not has_yind: if xind is None: widget_xind = widgets.IntSlider(min=0, max=10, step=1, description='X:') else: widget_xind = fixed(xind) if yind is None: widget_yind = widgets.IntSlider(min=0, max=10, step=1, description='Y:') else: widget_yind = fixed(yind) if not z: valid_var_names = list() for dim_names, var_names in self._inspector.dim_names_to_var_names.items(): no_zero_dim = all([self._inspector.dim_name_to_size[dim] > 0 for dim in dim_names]) if no_zero_dim and len(dim_names) == 2: valid_var_names.extend(var_names) valid_var_names = sorted(valid_var_names) value = z if z and z in valid_var_names else valid_var_names[0] widget_var = widgets.Dropdown(options=valid_var_names, value=value, description='Var:') # noinspection PyUnusedLocal def on_widget_var_change(change): variable = self._inspector.dataset[widget_var.value] if xind is None: widget_xind.max = variable.shape[1] - 1 if yind is None: widget_yind.max = variable.shape[0] - 1 widget_var.observe(on_widget_var_change, names='value') else: widget_var = fixed(z) # TODO (forman, 20160709): add sliders for zmin, zmax interact(self._plot_im_line, z_name=widget_var, xind=widget_xind, yind=widget_yind, zmin=fixed(zmax), zmax=fixed(zmax), cmap=fixed(cmap)) else: if not z: raise ValueError('z_name must be given') self._plot_im_line(z, zmin=zmin, zmax=zmin, xind=xind, yind=yind, cmap=cmap)
def visualise(self, sample): encoder_ids = sample['encoder_input_ids'].flatten() decoder_ids = sample['decoder_input_ids'] all_ids = encoder_ids.tolist() + decoder_ids.tolist() encoder_tokens = self.tokenizer.batch_decode(encoder_ids.view(-1, 1)) decoder_tokens = self.tokenizer.batch_decode(decoder_ids.view(-1, 1)) all_tokens = encoder_tokens + decoder_tokens all_token_and_ids = [ f"{idx}->{tok}" for idx, tok in zip(all_ids, all_tokens) ] ipyw.interact(self.visualise_for_token, sample=ipyw.fixed(sample), target_id=ipyw.SelectionSlider( options=all_token_and_ids, value=all_token_and_ids[0], description='Selected token:', disabled=False, continuous_update=False, orientation='horizontal', readout=True))
def prediction(var): mtrue, ctrue = [2, 3] cmin, c0, cmax = [2.55, 3.05, 3.55] mmin, m0, mmax = [1.3, 2.1, 2.9] cmin, c0, cmax = [1.55, 3.05, 4.55] mmin, m0, mmax = [0.3, 2.1, 4.9] p = Posterior(cmin=cmin, cmax=cmax, Nc=101, mmin=mmin, mmax=mmax, Nm=101, ctrue=ctrue, mtrue=mtrue, var=var) zoom = Checkbox(value=False, description='zoom') Nsamples = FloatLogSlider(value=16, base=4, description='samples', min=0, max=5, step=1, continuous_update=False) xf = FloatSlider(value=3, description=r'$x_f$', min=2, max=5, step=0.5, continuous_update=False) io = interactive_output(plot_predictions, { 'zoom': zoom, 'N': Nsamples, 'xf': xf, 'p': fixed(p) }) return VBox([HBox([zoom, Nsamples, xf]), io])
def paginate_df(df, nb_items=10): def show_df(df, page): display(df.head(page * nb_items).tail(nb_items)) def show_next(change): pagination_slider.value += change def get_pagination_buttons(): next_button = widgets.Button(layout=widgets.Layout(width='30px'), icon='chevron-right') next_button.on_click(lambda _: show_next(1)) prev_button = widgets.Button(layout=widgets.Layout(width='30px'), icon='chevron-left') prev_button.on_click(lambda _: show_next(-1)) return [prev_button, next_button] nb_rows = widgets.Label(value='{} rows'.format(len(df))) if len(df) > nb_items: nb_pages = int(np.ceil(len(df) / nb_items)) pagination_slider = widgets.IntSlider(value=1, min=1, max=nb_pages, layout=Layout(width='60%')) pagination_slider_label = widgets.Label( value='of {} pages with '.format(nb_pages)) pagination_controls = widgets.HBox([ pagination_slider, pagination_slider_label, nb_rows, *get_pagination_buttons() ]) paginated_table = interactive_output( show_df, dict(df=fixed(df), page=pagination_slider)) display(pagination_controls, paginated_table) else: display(nb_rows, df)
def manual_ps(data, notebook=False): """ Manual Phase correction using matplotlib A matplotlib widget is used to manually correct the phase of a Fourier transformed dataset. If the dataset has more than 1 dimensions, the first trace will be picked up for phase correction. Clicking the 'Set Phase' button will print the current linear phase parameters to the console. A ipywidget is provided for use with Jupyter Notebook to avoid changing backends. This can be accessed with notebook=True option in this function .. note:: Needs matplotlib with an interactive backend. Parameters ---------- data : ndarray Array of NMR data. notebook : Bool True for plotting interactively in Jupyter Notebook Uses ipywidgets instead of matplotlib widgets Returns ------- p0, p1 : float Linear phase correction parameters. Zero and first order phase corrections in degrees calculated from pc0, pc1 and pivot displayed in the interactive window. Examples -------- >>> import nmrglue as ng >>> p0, p1 = ng.process.proc_autophase.manual_ps(data) >>> # do manual phase correction and close window >>> phased_data = ng.proc_base.ps(data, p0=p0, p1=p1) In [1] # if you are using the Jupyter Notebook In [2] ng.process.proc_autophase.manual_ps(data) Out [2] # do manual phase correction. p0 and p1 values will be updated # continuously as you do so and are printed below the plot In [3] phased_data = ng.proc_base.ps(data, p0=p0, p1=p1) """ if len(data.shape) == 2: data = data[0, ...] elif len(data.shape) == 3: data = data[0, 0, ...] elif len(data.shape) == 4: data = data[0, 0, 0, ...] if notebook: from ipywidgets import interact, fixed import matplotlib.pyplot as plt def phasecorr(dataset, phcorr0, phcorr1, pivot): fig, ax = plt.subplots(figsize=(10, 7)) phaseddata = dataset * np.exp( 1j * (phcorr0 + phcorr1 * ( np.arange(-pivot, -pivot+dataset.size)/dataset.size))) ax.plot(np.real(phaseddata)) ax.set(ylim=(np.min(np.real(data))*2, np.max(np.real(data))*2)) ax.axvline(pivot, color='r', alpha=0.5) plt.show() p0 = np.round( (phcorr0 - phcorr1 * pivot/dataset.size) * 360 / 2 / np.pi, 3) p1 = np.round(phcorr1*360/2/np.pi, 3) print('p0 =', p0, 'p1 =', p1) interact( phasecorr, dataset=fixed(data), phcorr0=(-np.pi, np.pi, 0.01), phcorr1=(-10*np.pi, 10*np.pi, 0.01), pivot=(0, data.size, 1)) else: from matplotlib.widgets import Slider, Button import matplotlib.pyplot as plt plt.subplots_adjust(left=0.25, bottom=0.35) interactive, = plt.plot(data.real, lw=1, color='black') axcolor = 'white' axpc0 = plt.axes([0.25, 0.10, 0.65, 0.03], facecolor=axcolor) axpc1 = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor) axpiv = plt.axes([0.25, 0.20, 0.65, 0.03], facecolor=axcolor) axpst = plt.axes([0.25, 0.25, 0.15, 0.04], facecolor=axcolor) spc0 = Slider(axpc0, 'p0', -360, 360, valinit=0) spc1 = Slider(axpc1, 'p1', -360, 360, valinit=0) spiv = Slider(axpiv, 'pivot', 0, data.size, valinit=0) axps = Button(axpst, 'Set Phase', color=axcolor) def update(val): pc0 = spc0.val * np.pi / 180 pc1 = spc1.val * np.pi / 180 pivot = spiv.val interactive.set_ydata((data * np.exp( 1.0j * (pc0 + (pc1 * np.arange(-pivot, -pivot + data.size) / data.size))).astype(data.dtype)).real) plt.draw() def setphase(val): p0 = spc0.val-spc1.val*spiv.val/data.size p1 = spc1.val print(p0, p1) spc0.on_changed(update) spc1.on_changed(update) spiv.on_changed(update) axps.on_clicked(setphase) plt.show(block=True) p0 = spc0.val-spc1.val*spiv.val/data.size p1 = spc1.val return p0, p1
def dynamic_lisa_composite_explore(rose, gdf, pattern='', p=0.05, figsize=(13, 10)): """ Interactive exploration of dynamic LISA values for different dates in a dataframe. Note: only possible in jupyter notebooks Parameters ---------- rose : giddy.directional.Rose instance A ``Rose`` object, which contains (among other attributes) weights to calculate `esda.moran.Moran_local` values gdf : geopandas dataframe instance The Dataframe containing information and polygons to plot. pattern : str, optional Option to extract all columns ending with a specific pattern. Only extracted columns will be used for comparison. p : float, optional The p-value threshold for significance. Default =0.05 figsize: tuple, optional W, h of figure. Default =(13,10) Returns ------- None Examples -------- **Note**: this function creates Jupyter notebook widgets, so is meant only to run in a notebook. >>> import geopandas as gpd >>> import pandas as pd >>> from pysal.lib.weights.contiguity import Queen >>> from pysal.lib import examples >>> import numpy as np >>> import matplotlib.pyplot as plt If you want to see figures embedded inline in a Jupyter notebook, add a line ``%matplotlib inline`` at the top of your notebook. >>> from pysal.explore.giddy.directional import Rose >>> from pysal.viz.splot.giddy import dynamic_lisa_composite_explore get csv and shp files >>> shp_link = examples.get_path('us48.shp') >>> df = gpd.read_file(shp_link) >>> income_table = pd.read_csv(examples.get_path("usjoin.csv")) calculate relative values >>> for year in range(1969, 2010): ... income_table[str(year) + '_rel'] = ( ... income_table[str(year)] / income_table[str(year)].mean()) merge to one gdf >>> gdf = df.merge(income_table,left_on='STATE_NAME',right_on='Name') retrieve spatial weights and data for two points in time >>> w = Queen.from_dataframe(gdf) >>> w.transform = 'r' >>> y1 = gdf['1969_rel'].values >>> y2 = gdf['2000_rel'].values calculate rose Object >>> Y = np.array([y1, y2]).T >>> rose = Rose(Y, w, k=5) plot >>> fig = dynamic_lisa_composite_explore(rose, gdf, pattern='rel') >>> # plt.show() """ coldict = {col: col for col in gdf.columns if col.endswith(pattern)} interact(_dynamic_lisa_widget_update, start_time=coldict, end_time=coldict, rose=fixed(rose), gdf=fixed(gdf), p=fixed(p), figsize=fixed(figsize))
def waveform_line(self, ind=None, ref_ind=None): """ Draw waveform 2D line plot. :param ind: Time index :param ref_ind: Reference time index """ if ind is None and self._interactive: interact(self._plot_waveform_line, ind=(0, self._inspector.num_times - 1), ref_ind=fixed(ref_ind)) else: self._plot_waveform_line(ind=ind if ind else 0, ref_ind=ref_ind)
def _default_plotter(self, mask_background=False, **kwargs): """Plot three orthogonal views. This is called by nifti_plotter, you shouldn't call it directly. """ plt.gcf().clear() plt.ioff() # disable interactive mode data_array = self.data.get_data() if not ((data_array.ndim == 3) or (data_array.ndim == 4)): raise ValueError('Input image should be 3D or 4D') # mask the background if mask_background: # TODO: add the ability to pass 'mne' to use a default brain mask # TODO: split this out into a different function if data_array.ndim == 3: labels, n_labels = scipy.ndimage.measurements.label( (np.round(data_array) == 0)) else: # 4D labels, n_labels = scipy.ndimage.measurements.label( (np.round(data_array).max(axis=3) == 0)) mask_labels = [ lab for lab in range(1, n_labels + 1) if (np.any(labels[[0, -1], :, :] == lab) | np.any(labels[:, [0, -1], :] == lab) | np.any(labels[:, :, [0, -1]] == lab)) ] if data_array.ndim == 3: data_array = np.ma.masked_where(np.isin(labels, mask_labels), data_array) else: data_array = np.ma.masked_where( np.broadcast_to( np.isin(labels, mask_labels)[:, :, :, np.newaxis], data_array.shape), data_array) # init sliders for the various dimensions for dim, label in enumerate(['x', 'y', 'z']): if label not in kwargs.keys(): kwargs[label] = IntSlider(value=(data_array.shape[dim] - 1) / 2, min=0, max=data_array.shape[dim] - 1, continuous_update=False) if (data_array.ndim == 3) or (data_array.shape[3] == 1): kwargs['t'] = fixed(None) # time is fixed else: kwargs['t'] = IntSlider(value=0, min=0, max=data_array.shape[3] - 1, continuous_update=False) widgets.interact(self._plot_slices, data=fixed(data_array), **kwargs) plt.close() # clear plot plt.ion() # return to interactive state
merged.set_index(['continent','year'],inplace=True) merged = merged.join(merged_grouped_last) merged.reset_index(inplace=True) merged['g_total'] = merged['last']/merged['first']*100 # Dropdown widget on pop and gdp_cap development: def plot(dataframe, continent): I = dataframe['continent'] == continent ax_gdp = dataframe.loc[I,:].plot(x='year', y = 'gdp', style = '-o', legend = 'False') ax_pop = dataframe.loc[I,:].plot(x='year', y = 'pop', style = '-o', legend = 'False') widgets.interact(plot, dataframe = widgets.fixed(merged), continent = widgets.Dropdown(description='continent', options=merged.continent.unique(), value='Europe & Central Asia') ); # Creating 5-year growth rates in GDP per cap in the continents: merged_5 = merged[merged['year'].isin(['1970','1975','1980','1985','1990','1995','2000','2005','2010','2015'])] merged_5.set_index(['continent','year'],inplace=True) merged_5_grouped = merged_5.groupby('continent') merged_5_change = merged_5_grouped.gdp_cap.pct_change() merged_5_change.name = 'growth_5' merged_5 = merged_5.join(merged_5_change) merged_5.reset_index(inplace=True) # Bar plot with dropdown widget:
def cr72_manipulate(pA=None, r20a=None, r20b=None, kex=None, dw_h=None, dw_n=None, num=None): """ My attempt at using interact in a function. INPUTS: r20a, r20b: intrinsic r2 rates for states a and b, respectively, usually the same. pA: population of the major state. kex: k1 + k2, the sum of the forward and reverse rates of exchange. dw_h, dw_n: differences in chem. shift between the two states in ppm for 1H and 15N, respectively TO DO: Add in the ability to import parameter values from the `relax` analysis for a particular residue and set the values and ranges in the interact call automatically. Make another function to plot RD data for a given residue and then a third function that calls both the data and simulation functions. I MAY HAVE THE FIRST FUNCTION HERE IN MY RD PLOTTING FROM BEFORE. Add in functionality to calculate whether a residue is in slow, fast, or intermediate exchange. That could be a function itself. """ import sys sys.path.append('/usr/local/relax-4.0.2/lib') sys.path.append('/usr/local/relax-4.0.2') import relax import nmr from dispersion.cr72 import r2eff_CR72 from ipywidgets import interact, interactive, fixed import ipywidgets as widgets import matplotlib.pyplot as plt import numpy as np # The number of steps for each slider if num == None: num = 15 # Choosing the major population slider if pA == None: lower, upper = .5, 1. step, val = (upper - lower) / num, 0.9 pA_slider = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) else: lower, upper = .5, 1. step, val = (upper - lower) / num, pA pA_slider = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) # Setting the intrinsic r2 value, held constant if r20a == None or r20b == None: r2int = fixed(20) elif r20b == None: r2int = fixed(r20a) else: r2int = fixed(r20b) # Setting kex if kex == None: lower, upper, step, val = 100., 600., (600. - 100.) / num, 500. kex_slider = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) else: lower, upper = .1 * kex, 1.5 * kex step, val = (upper - lower) / num, kex kex_slider = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) # Setting dw_h & dw_n if dw_h == None or dw_n == None: lower, upper = .1, 4. step, val = (upper - lower) / num, 1. dw_n_slid = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) lower, upper = .01, 1 step, val = (upper - lower) / num, .1 dw_h_slid = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) else: lower, upper = dw_h * .1, dw_h * 1.5 step, val = (upper - lower) / num, dw_h dw_h_slid = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) lower, upper = dw_n * .1, dw_n * 1.5 step, val = (upper - lower) / num, dw_n dw_n_slid = widgets.FloatSlider(min=lower, max=upper, step=step, value=val) interact(cr72_simulate, pA=pA_slider, r20a=r2int, r20b=r2int, kex=kex_slider, dw_h=dw_h_slid, dw_n=dw_n_slid) return
def qonduit_visualization_metrics_plot_histogram(data): return interactive(lambda data: display(plot_state_histogram(data)), data=fixed(data))
min=0.01, max=0.1, step=0.01, value=.05, continuous_update=True, readout_format='.3f', description='Init. capital ratio', style = {'description_width': 'initial'}) # %% tags=[] # Make the widget interact(plot1, Epsilon = Epsilon_widget1, DiscFac = DiscFac_widget1, PopGrowth = PopGrowth_widget1, YearsPerGeneration = fixed(years_per_gen), Initialk = Initialk_widget1); # %% [markdown] # ### Gross and Net Per Capita Output as a Function of k # %% # Define a function that plots something given some inputs def plot2(Epsilon, PopGrowth, YearsPerGeneration): '''Inputs: Epsilon: Elasticity of output with respect to capital/labour ratio DiscFac: One period discount factor YearPerGeneration: No. of years per generation PopGrowth: Gross growth rate of population in one period'''
def interactive_rad(temp_pd, stations): """Interactive plotting of elevation-azimuth plots for a set of satellites and a set of stations Parameters ---------- temp_pd : Pandas dataframe Output of aiub.import_RM_file function stations: pandas dataframe station dataframe as output of aiub.import_stations() Returns ------- """ all_dates = temp_pd.time_stamp.unique( ) #temp_pd.datetime.apply(lambda x: x.timestamp()).unique() #all_dates_read = temp_pd.datetime.unique() time_list = list( map(lambda x: datetime.datetime.fromtimestamp(x), temp_pd.time_stamp.unique())) all_dates_read = [ str(tl.year) + '-' + str(tl.month) + '-' + str(tl.day) + ' ' + str(tl.hour) + ':' + str(tl.minute) for tl in time_list ] colors = ['red', 'blue', 'green', 'cyan', 'orange'] items = [ widgets.ColorPicker(description=temp_pd.satellite.unique()[i], value=colors[i]) for i in range(len(temp_pd.satellite.unique())) ] if len(items) < 5: items = items + [ widgets.ColorPicker(description='None', value=colors[i]) for i in range(5 - len(items)) ] colwidget = widgets.VBox(items) #min_date_widget = widgets.IntSlider(min=0, max=len(all_dates)-1, step=1, value = 0, continuous_update = False) #max_date_widget = widgets.IntSlider(min=0, max=len(all_dates)-1, step=1, value = 0, continuous_update = False) style = {'description_width': '20%', 'readout_width': '20%'} min_date_widget = widgets.SelectionSlider(options=all_dates_read, style=style, description='Min Time', layout={'width': '400px'}) max_date_widget = widgets.SelectionSlider(options=all_dates_read, style=style, description='Max Time', layout={'width': '400px'}) sat_type = widgets.SelectMultiple(options=temp_pd.satellite.unique(), description='Select satellite types', value=[temp_pd.satellite.unique()[0]], disabled=False) station_widget = widgets.Dropdown(options=stations.statname.unique(), value=stations.iloc[0].statname, description='Select observation station', style={'description_width': '50%'}, layout={'width': '400px'}) d = { 'data': widgets.fixed(temp_pd), 'all_dates': widgets.fixed(all_dates), 'all_dates_read': widgets.fixed(all_dates_read), 'sat_type': sat_type, 'date_min': min_date_widget, 'date_max': max_date_widget, 'stations': widgets.fixed(stations), 'station_sel': station_widget } d2 = {'col' + str(ind): value for (ind, value) in enumerate(items)} d.update(d2) title_w = widgets.HTML( "<span style='float:left;font-size:2em;font-weight:bold'>Radial plot of satellite observation</span>" ) time_title_w = widgets.HTML( "<span style='float:left;font-size:1em;font-weight:bold'>Pick time range for observations</span>" ) w1 = widgets.HBox([sat_type, colwidget]) w2 = widgets.HBox([station_widget]) w3 = widgets.HBox([min_date_widget, max_date_widget]) ui = widgets.VBox([title_w, w1, w2, time_title_w, w3], layout=Layout(align_items='stretch')) out = widgets.interactive_output(plot_radial, d) display(ui, out)
#Interact functionality with GUIs #Works only on jupiter notebook from ipywidgets import interact, interactive, fixed import ipywidgets as widgets def func(x): return x interact(func, x='Hello') @interact(x=True, y=fixed(1.0)) def g(x, y): return (x, y) interact(func, x=widgets.IntSlider(min=-100, max=100, step=1, value=0)) interact(func, x=(-10, 10, .1)) @interact(x=(0.0, 20.0, 0.5)) def h(x=5.0): return x interact(func, x=['Hello', 'option 2', 'option 3']) interact(func, x={'one': 10, 'two:': 20})
def _default_plotter(self, **kwargs): """ Basic plot function to be used if no custom function is specified. This is called by plot, you shouldn't call it directly. """ self.lengths = np.array([length(x) for x in self.lines2use_]) if not ("grayscale" in kwargs and kwargs["grayscale"]): self.colors = np.array([color(x) for x in self.lines2use_]) else: self.colors = np.zeros((len(self.lines2use_), 3), dtype=np.float16) self.colors[:] = [0.5, 0.5, 0.5] self.state = {"threshold": 0, "indices": []} width = 600 height = 600 perc = 80 if "width" in kwargs: width = kwargs["width"] if "height" in kwargs: height = kwargs["height"] if "percentile" in kwargs: perc = kwargs["percentile"] ipv.clear() fig = ipv.figure(width=width, height=height) self.state["fig"] = fig with fig.hold_sync(): x, y, z, indices, colors, self.line_pointers = self._create_mesh() limits = np.array( [ min([x.min(), y.min(), z.min()]), max([x.max(), y.max(), z.max()]), ] ) mesh = ipv.Mesh(x=x, y=y, z=z, lines=indices, color=colors) fig.meshes = [mesh] if "style" not in kwargs: fig.style = { "axes": { "color": "black", "label": {"color": "black"}, "ticklabel": {"color": "black"}, "visible": False, }, "background-color": "white", "box": {"visible": False}, } else: fig.style = kwargs["style"] ipv.pylab._grow_limits(limits, limits, limits) fig.camera_fov = 1 ipv.show() interact( self._plot_lines, state=fixed(self.state), threshold=widgets.FloatSlider( value=np.percentile(self.lengths, perc), min=self.lengths.min() - 1, max=self.lengths.max() - 1, continuous_update=False, ), )
def display_prediction(basis, num_basis=4, wlim=(-1.,1.), fig=None, ax=None, xlim=None, ylim=None, num_points=1000, offset=0.0, **kwargs): """Interactive widget for displaying a prediction function based on summing separate basis functions. :param basis: a function handle that calls the basis functions. :type basis: function handle. :param xlim: limits of the x axis to use. :param ylim: limits of the y axis to use. :param wlim: limits for the basis function weights.""" import numpy as np import pylab as plt if fig is not None: if ax is None: ax = fig.gca() if xlim is None: if ax is not None: xlim = ax.get_xlim() else: xlim = (-2., 2.) if ylim is None: if ax is not None: ylim = ax.get_ylim() else: ylim = (-1., 1.) # initialise X and set up W arguments. x = np.zeros((num_points, 1)) x[:, 0] = np.linspace(xlim[0], xlim[1], num_points) param_args = {} for i in range(num_basis): lim = list(wlim) if i ==0: lim[0] += offset lim[1] += offset param_args['w_' + str(i)] = lim # helper function for making basis prediction. def predict_basis(w, basis, x, num_basis, **kwargs): Phi = basis(x, num_basis, **kwargs) f = np.dot(Phi, w) return f, Phi if type(basis) is dict: use_basis = basis[list(basis.keys())[0]] else: use_basis = basis f, Phi = predict_basis(np.zeros((num_basis, 1)), use_basis, x, num_basis, **kwargs) if fig is None: fig, ax=plt.subplots(figsize=(12,4)) ax.set_ylim(ylim) ax.set_xlim(xlim) predline = ax.plot(x, f, linewidth=2)[0] basislines = [] for i in range(num_basis): basislines.append(ax.plot(x, Phi[:, i], 'r')[0]) ax.set_ylim(ylim) ax.set_xlim(xlim) def generate_function(basis, num_basis, predline, basislines, basis_args, display_basis, offset, **kwargs): w = np.zeros((num_basis, 1)) for i in range(num_basis): w[i] = kwargs['w_'+ str(i)] f, Phi = predict_basis(w, basis, x, num_basis, **basis_args) predline.set_xdata(x[:, 0]) predline.set_ydata(f) for i in range(num_basis): basislines[i].set_xdata(x[:, 0]) basislines[i].set_ydata(Phi[:, i]) if display_basis: for i in range(num_basis): basislines[i].set_alpha(1) # make visible else: for i in range(num_basis): basislines[i].set_alpha(0) display(fig) if type(basis) is not dict: basis = fixed(basis) plt.close(fig) interact(generate_function, basis=basis, num_basis=fixed(num_basis), predline=fixed(predline), basislines=fixed(basislines), basis_args=fixed(kwargs), offset = fixed(offset), display_basis = False, **param_args)
def single_run(data_dir="", id=""): if not os.path.exists(data_dir): raise FileNotFoundError("No directory found named: "+ data_dir) run_summary = RunSummary(data_dir=data_dir, id=id) sedov_solution = SedovSolution(E_0, run_summary.overview.background_density, run_summary.overview.metallicity) #### PASS TO PLOTTER #### num_checkpoints = len(run_summary.filenames) # log_R_max = round(np.log10(run_summary.df["Radius"].max()), 2) # log_R_min = max(log_R_max-4, # round(np.log10(run_summary.df["Radius"].min()), 2)+1) R_min = run_summary.df["Radius"].min() R_min = 0 R_max = run_summary.df["Radius"].max() if type(single_run.previous_widget) is widgets.Box: single_run.previous_widget.close() w = interactive(plotter, run_summary = fixed(run_summary), sedov_solution = fixed(sedov_solution), xlim = FloatRangeSlider(min=R_min, max=R_max, step=0.01 * (R_max-R_min), value=(R_min, R_max), ), checkpoint_index = IntSlider(min=0, max=num_checkpoints-1, step=0, value=num_checkpoints-1), y_axis_variable = Dropdown(options=cols_plot, value="Density"), x_axis_variable = RadioButtons(options=["Radius", "M_int", "zones"]), label = fixed("numeric"), density_in_mH_cm3 = fixed(False), verbose = fixed(True), ) w1 = widgets.Button(description=u"\u23EA") def show_first(b): checkpoint_slider = w.children[5] checkpoint_slider.value = checkpoint_slider.min w1.on_click(show_first) wl = widgets.Button(description=u"\u276E") def show_prev(b): checkpoint_slider = w.children[5] if checkpoint_slider.value > checkpoint_slider.min: checkpoint_slider.value -= 1 wl.on_click(show_prev) w2 = widgets.Button(description=u"\u25BA") # w2.stop = False def play(b): checkpoint_slider = w.children[5] for i in range(checkpoint_slider.value+1, checkpoint_slider.max+1): plt.gcf() checkpoint_slider.value=i # plt.show() # time.sleep(.1) # if b.stop: # break w2.on_click(play) # wp = widgets.Button(description=u"p") # def pause(b): # w2.stop=True # wp.on_click(pause) wr = widgets.Button(description=u"\u276F") def show_next(b): checkpoint_slider = w.children[5] if checkpoint_slider.value < checkpoint_slider.max: checkpoint_slider.value += 1 wr.on_click(show_next) w3 = widgets.Button(description=u"\u23E9") def show_last(b): checkpoint_slider = w.children[5] checkpoint_slider.value = checkpoint_slider.max w3.on_click(show_last) w_buttons = widgets.HBox(children=[w1, wl, w2, wr, w3]) w.children = tuple([_w for _w in w.children ] + [w_buttons]) single_run.previous_widget = w display(w) # display(w_buttons) return run_summary
def display_registration_results(fixed_image, moving_image, tx): moving_resampled = sitk.Resample(moving_image, fixed_image, tx, sitk.sitkLinear, 0.0, moving_image.GetPixelIDValue()) interact(display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]-1), alpha=(0.0,1.0,0.05), image1 = fixed(fixed_image), image2=fixed(moving_resampled));
def display_gui(wti_index, print_args=False): def lw(width='180px', left='0'): return widgets.Layout(width=width) def parties_options(): return ['ALL'] + sorted([ x for x in wti_index.get_countries_list() if x not in ['ALL', 'ALL OTHER']]) period_group_index_widget = widgets_config.period_group_widget(index_as_value=True) topic_group_name_widget = widgets_config.topic_groups_widget(layout=lw()) parties_widget = widgets_config.parties_widget(options=parties_options(), value=['ALL'], rows=10) recode_7corr_widget = widgets_config.toggle('Recode 7CULT', True, tooltip='Recode all treaties with cultural=yes as 7CORR', layout=lw(width='110px')) use_lemma_widget = widgets_config.toggle('Use LEMMA', False, tooltip='Use WordNet lemma', layout=lw(width='110px')) remove_stopwords_widget = widgets_config.toggle('Remove STOP', True, tooltip='Do not include stopwords', layout=lw(width='110px')) compute_co_occurance_widget = widgets_config.toggle('Cooccurrence', True, tooltip='Compute Cooccurrence', layout=lw(width='110px')) extra_groupbys_widget = widgets_config.dropdown('Groupbys', EXTRA_GROUPBY_OPTIONS, None, layout=lw()) min_word_size_widget = widgets_config.itext(0, 5, 2, description='Min word', layout=lw()) # plot_style_widget = widgets_config.plot_style_widget(layout=lw()) n_top_widget = widgets_config.slider('Top/grp #', 2, 100, 25, step=10, layout=lw(width='200px')) n_min_count_widget = widgets_config.slider('Min count', 1, 10, 5, step=1, tooltip='Filter out words with count less than specified value', layout=lw(width='200px')) treaty_filter_widget = widgets_config.dropdown('Filter', config.TREATY_FILTER_OPTIONS, 'is_cultural', layout=lw()) output_format_widget = widgets_config.dropdown('Output', OUTPUT_OPTIONS, 'plot_stacked_bar', layout=lw()) progress_widget = widgets_config.progress(0, 8, 1, 0, layout=lw(width='95%')) def progress(x=None): progress_widget.value = progress_widget.value + 1 if x is None else x iw = widgets.interactive( display_headnote_toplist, period_group_index=period_group_index_widget, topic_group_name=topic_group_name_widget, recode_7corr=recode_7corr_widget, treaty_filter=treaty_filter_widget, parties=parties_widget, extra_groupbys=extra_groupbys_widget, n_min_count=n_min_count_widget, n_top=n_top_widget, min_word_size=min_word_size_widget, use_lemma=use_lemma_widget, compute_co_occurance=compute_co_occurance_widget, remove_stopwords=remove_stopwords_widget, output_format=output_format_widget, progress=widgets.fixed(progress), wti_index=widgets.fixed(wti_index), print_args=widgets.fixed(print_args) # plot_style=plot_style ) boxes = widgets.HBox( [ widgets.VBox([ period_group_index_widget, parties_widget ]), widgets.VBox([ topic_group_name_widget, extra_groupbys_widget, n_top_widget, min_word_size_widget, n_min_count_widget]), widgets.VBox([ recode_7corr_widget, use_lemma_widget, remove_stopwords_widget, compute_co_occurance_widget ]), widgets.VBox([ treaty_filter_widget, output_format_widget, progress_widget]), ] ) display(widgets.VBox([boxes, iw.children[-1]])) iw.update()
disabled=False) # Define a check box for whether to show the target annotation show_targ_widget = widgets.Checkbox(value=True, description='Show target $(m,c)$', disabled=False) # Make an interactive plot of the tractable buffer stock solution # To make some of the widgets not appear, replace X_widget with fixed(desired_fixed_value) in the arguments below. interact( makeTBSplot, DiscFac=DiscFac_widget, CRRA=CRRA_widget, # We can fix a parameter using the fixed() operator Rfree=fixed(TBS_dictionary['Rfree']), # Rfree = Rfree_widget, # This is the line which, when uncommented, would make Rfree a slider PermGroFac=PermGroFac_widget, UnempPrb=UnempPrb_widget, mMin=mMin_widget, mMax=mMax_widget, cMin=cMin_widget, cMax=cMax_widget, show_targ=show_targ_widget, plot_emp=plot_emp_widget, plot_ret=plot_ret_widget, plot_mSS=plot_mSS_widget, ) # %%
def NM_fast(L_dev, Y_dev, k=2, sig=0.01, policy='new', verbose=False, return_more_info=False): # create pd dataframe Complete_dev = np.concatenate((np.array([Y_dev]).T, L_dev), axis=1) df = pd.DataFrame(data=Complete_dev, columns=["GT"] + ["LF_" + str(i) for i in range(L_dev.shape[1])]) no_other_LFs = L_dev.shape[1] - 2 def create_CT_tables(df, L_dev, k): """create all combinations of contingency table's of {LF_i, LF_j, [LF_all others]}""" CT_list = [] for i in range(L_dev.shape[1]): for j in [k for k in range(i, L_dev.shape[1]) if k != i]: other_LFs_list = [ df['LF_' + str(m)] for m in range(L_dev.shape[1]) if (m != i and m != j) ] CT = pd.crosstab([df['GT']] + other_LFs_list + [df['LF_' + str(i)]], df['LF_' + str(j)], margins=False) #k_list = [i-1 for i in range(k+1)]; GT_indices = [i for i in range(k)] #CT = CT.reindex(index=list(itertools.product(GT_indices, *[tuple(k_list)] * (no_other_LFs+1))), columns=k_list, fill_value=0) # prep to reindex only the LF column closest to values (this is new in the fast version) indices_other_LFs = [ ] # first get current indices of other LF columns for itera in range(len(CT.index)): indices_other_LFs.append(CT.index[itera][:-1]) indices_other_LFs = list( set(indices_other_LFs)) # get unique values only indices_closest_LF = [(i - 1, ) for i in range(k + 1)] all_indices = [ ind1 + ind2 for ind1 in indices_other_LFs for ind2 in indices_closest_LF ] k_list = [i - 1 for i in range(k + 1)] # reindex only the LF column closest to values CT = CT.reindex(index=all_indices, columns=k_list, fill_value=0) CT_list.append(CT) return CT_list def show_CT(q, CT_list): """function to return qth CT at index q-1 of CT_list""" return CT_list[q - 1] # create and show all CT's (if verbose) with slider applet CT_list = create_CT_tables( df, L_dev, k) # create all combinations of Contingency Tables if verbose: print("No of tables = Choosing 2 from " + str(L_dev.shape[1]) + " LFs = " + str(L_dev.shape[1]) + "C2 = " + str(len(CT_list))) #print("Note: Showing subtables where CI is not clearly evident") interact(show_CT, q=IntSlider(min=1, max=len(CT_list), value=0, step=1), CT_list=fixed(CT_list)) def get_conditional_deps(CT_list, sig, k, delta=0): """peform 3-way table chi-square independence test and obtain test statistic chi_square (or corresponding p-value) for each CT table where each CT-table is a ({k+1}^{no of other LFs})x(k+1)x(k+1) matrix https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html""" CD_edges = [] CD_nodes = [] CD_edges_p_vals = [] p_vals_sum_dict = {} CT_reduced_list = [] count = 0 #n_bad = 0 for CT in CT_list: count += 1 Z = int(len(CT.values) / 3) # no of rows/3 (this is new in the fast version) CT_reshaped = np.reshape(CT.values, (Z, k + 1, k + 1)) if policy == 'old': p_val_tot, CT_reduced = get_p_total_old_policy( CT_reshaped, k, Z, delta, sig, count, verbose, return_more_info ) # Older policy of one round of 0 row/col reduction and then adding delta else: p_val_tot, CT_reduced = get_p_total_new_policy( CT_reshaped, k, Z, sig, count, verbose, return_more_info) # newer policy of complete reduction CT_reduced_list.append(CT_reduced) # checking if total p_value is lesser than chosen sig if p_val_tot < sig: digits_LF1 = CT.index.names[1 + no_other_LFs][ 3:] # add 1 for the GT column digits_LF2 = CT.columns.name[ 3:] # 3rd index onwards to remove LF_ (3 characters) CD_edges.append((int(digits_LF1), int(digits_LF2))) CD_edges_p_vals.append(p_val_tot) #printing info edges_info_dict = {} edges_info_dict['CD_edges'] = CD_edges edges_info_dict['CD_edges_p_vals'] = CD_edges_p_vals if verbose: edges_df = pd.DataFrame(edges_info_dict) print(edges_df) return edges_info_dict, CT_reduced_list # retrieve modified CTs & tuples of LFs that are conditionally independent edges_info_dict, CT_reduced_list = get_conditional_deps(CT_list, sig=sig, k=k, delta=1) # display reduced contingency tables' submatrices whose all elements = delta is not true if verbose: non_delta_tuple_indices = [] for q in range(len(CT_reduced_list)): for r in range(len(CT_reduced_list[q])): delta = 1 if ~(CT_reduced_list[q][r] == delta).all(): non_delta_tuple_indices.append( ((q, r), (q, r)) ) # apending a tuple of tuples because first part of outer tuple is key and second is value passed gy slider to fn def show_CT_sub_matrices(t, CT_reduced_list): """function to return qth CT at index q-1 of CT_list""" return CT_reduced_list[t[0]][t[1]] print( "The reduced and modified contingency tables with non-delta values are given below" ) interact( show_CT_sub_matrices, t=Dropdown( description='index tuples (table number, submatrix number)', options=non_delta_tuple_indices), CT_reduced_list=fixed(CT_reduced_list)) if return_more_info: return edges_info_dict else: return edges_info_dict['CD_edges']
def show_masked_images_sagittal(image, mask): interact(display_images_with_mask_sagittal, image_z=(0, image.GetSize()[0] - 1), fixed=fixed(image), moving=fixed(mask))
def manual_ps(data, notebook=False): """ Manual Phase correction using matplotlib A matplotlib widget is used to manually correct the phase of a Fourier transformed dataset. If the dataset has more than 1 dimensions, the first trace will be picked up for phase correction. Clicking the 'Set Phase' button will print the current linear phase parameters to the console. A ipywidget is provided for use with Jupyter Notebook to avoid changing backends. This can be accessed with notebook=True option in this function .. note:: Needs matplotlib with an interactive backend. Parameters ---------- data : ndarray Array of NMR data. notebook : Bool True for plotting interactively in Jupyter Notebook Uses ipywidgets instead of matplotlib widgets Returns ------- p0, p1 : float Linear phase correction parameters. Zero and first order phase corrections in degrees calculated from pc0, pc1 and pivot displayed in the interactive window. Examples -------- >>> import nmrglue as ng >>> p0, p1 = ng.process.proc_autophase.manual_ps(data) >>> # do manual phase correction and close window >>> phased_data = ng.proc_base.ps(data, p0=p0, p1=p1) If you are using a Jupyter Notebook:: In [1] ng.process.proc_autophase.manual_ps(data) Out [1] # do manual phase correction. p0 and p1 values will be updated # continuously as you do so and are printed below the plot In [2] phased_data = ng.proc_base.ps(data, p0=p0, p1=p1) """ if len(data.shape) == 2: data = data[0, ...] elif len(data.shape) == 3: data = data[0, 0, ...] elif len(data.shape) == 4: data = data[0, 0, 0, ...] if notebook: from ipywidgets import interact, fixed import matplotlib.pyplot as plt def phasecorr(dataset, phcorr0, phcorr1, pivot): fig, ax = plt.subplots(figsize=(10, 7)) phaseddata = dataset * np.exp( 1j * (phcorr0 + phcorr1 * ( np.arange(-pivot, -pivot+dataset.size)/dataset.size))) ax.plot(np.real(phaseddata)) ax.set(ylim=(np.min(np.real(data))*2, np.max(np.real(data))*2)) ax.axvline(pivot, color='r', alpha=0.5) plt.show() p0 = np.round( (phcorr0 - phcorr1 * pivot/dataset.size) * 360 / 2 / np.pi, 3) p1 = np.round(phcorr1*360/2/np.pi, 3) print('p0 =', p0, 'p1 =', p1) interact( phasecorr, dataset=fixed(data), phcorr0=(-np.pi, np.pi, 0.01), phcorr1=(-10*np.pi, 10*np.pi, 0.01), pivot=(0, data.size, 1)) else: from matplotlib.widgets import Slider, Button import matplotlib.pyplot as plt plt.subplots_adjust(left=0.25, bottom=0.35) interactive, = plt.plot(data.real, lw=1, color='black') axcolor = 'white' axpc0 = plt.axes([0.25, 0.10, 0.65, 0.03], facecolor=axcolor) axpc1 = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor) axpiv = plt.axes([0.25, 0.20, 0.65, 0.03], facecolor=axcolor) axpst = plt.axes([0.25, 0.25, 0.15, 0.04], facecolor=axcolor) spc0 = Slider(axpc0, 'p0', -360, 360, valinit=0) spc1 = Slider(axpc1, 'p1', -360, 360, valinit=0) spiv = Slider(axpiv, 'pivot', 0, data.size, valinit=0) axps = Button(axpst, 'Set Phase', color=axcolor) def update(val): pc0 = spc0.val * np.pi / 180 pc1 = spc1.val * np.pi / 180 pivot = spiv.val interactive.set_ydata((data * np.exp( 1.0j * (pc0 + (pc1 * np.arange(-pivot, -pivot + data.size) / data.size))).astype(data.dtype)).real) plt.draw() def setphase(val): p0 = spc0.val-spc1.val*spiv.val/data.size p1 = spc1.val print(p0, p1) spc0.on_changed(update) spc1.on_changed(update) spiv.on_changed(update) axps.on_clicked(setphase) plt.show(block=True) p0 = spc0.val-spc1.val*spiv.val/data.size p1 = spc1.val return p0, p1
#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np from ipywidgets import interact, fixed def optimaler_winkel(v_0, z_0, g=9.81): return np.rad2deg(np.arcsin(v_0/np.sqrt(2 * (v_0**2 + z_0 * g)))) def bahnkurve(alpha=45, v_0=13.5, z_0=0, g=9.81): """ alpha - Wurfwinkel [°], v_0 - Anfangsgeschwindigkeit [m/s], z_0 - Anfangshöhe [m], g - Fallbeschleunigung [m/s²] """ x = np.arange(0, 25, 0.1) # horizontale Koordinate [m] print("Optimaler Wurfwinkel: {:4.2f}".format(optimaler_winkel(v_0, z_0, g))) tan_alpha = np.tan(np.deg2rad(alpha)) z = -g * (1 + tan_alpha**2) / 2 / v_0**2 * x**2 + tan_alpha * x + z_0 # Bahn z(x) print("Höchster Punkt: z_max = {:4.2f} m bei x = {:4.2f} m".format(z.max(), x[z.argmax()])) ende = np.where(z < 0)[0][0] # Index der Wurfweite print("Wurfweite: {:5.2f} m".format(x[ende])) plt.figure(figsize=[10, 6]) plt.plot(x[:ende], z[:ende]) plt.xlabel("Ort x [m]") plt.ylabel("Höhe z [m]") plt.title("Bahnkurve beim Kugelstoßen (EPI/2.3)") plt.show() interact(bahnkurve, alpha=(0.0, 90.0 ,1.0), v_0=(1, 15, .5), z_0=(0, 3, .1), g=fixed(9.81));
def interact_drug_data(): from ipywidgets import interact, fixed # all we need to do is specify here what function we are interacting with interact(drug_plot, drug=an_epic_party, drug_use=fixed(drug_use))
orientation='horizontal', style=style, layout=layout) D = FloatSlider(min=0, max=5, step=0.1, value=best_D, description='Disk Prefactor', readout_format='.2f', orientation='horizontal', style=style, layout=layout) #rc = FloatSlider(min=0, max=5, step=0.1, value=best_rc, description='Halo Core Radius [kpc]', readout_format='.2f', orientation='horizontal', style=style, layout=layout) rc = fixed(best_rc) #rho00 = fixed(best_rho00) rho00 = FloatSlider(min=0, max=1e9, step=1e7, value=best_rho00, description=r'Halo Surface Density [$M_{\odot} / pc^3$]', readout_format='.2e', orientation='horizontal', style=style, layout=layout) # Interactive widget def interactive_plot(f):
def plot_design(design): output_notebook() sel_mult = SelectMultiple(options = [x for x in design.layers]) interactive_plot = interactive(layer_select, m=sel_mult, design=fixed(design)) display(interactive_plot)