def IterativeMethods3D(start=[0, 0, 0]): """ Method called by notebook. Produces UI and calls iterative functions Parameters ---------- start: array_like starting points for iteration """ eqnOpt = {'Sys. 1': 1, 'Sys. 2': 2} tol_slider = widgets.FloatLogSlider(0.1, min=-10, max=-1, step=1, description='Tolerance', continuous_update=False) printOut_check = widgets.Checkbox(value=False, description='Show Iterations') showSurf_check = widgets.Checkbox(value=False, description='Show Surfaces') eqns_drop = widgets.Dropdown(options=eqnOpt) display(widgets.VBox([ widgets.HBox([ tol_slider, eqns_drop, printOut_check, showSurf_check ]), widgets.interactive_output(iterative3D, { 'tol': tol_slider, 'showIts': printOut_check, 'sysSelect': eqns_drop, 'showSurfs': showSurf_check, 'start': widgets.fixed(start) }) ]))
def __init__( self, tag, value=None, units="", slider=wd.FloatLogSlider(), mathRep="", ): ''' Parameters --------------- tag: string The tag to replace in the template file value: float The value of the parameter units: string the units of the parameter - does nothing slider: ipywidgets.FloatSlider() a widget to modify this.value mathRep : str, optional The Latex representation of the parameter, e,g, $k_{att}$ ''' self._slider = slider super().__init__(tag, self.slider.value, units, mathRep=mathRep) # self._floatBox = wd.FloatText() # self._link wd.link((self._slider,'value'),(self._floatBox,'value')) self.buildui()
def spectrogram_explorer(ax, signal): from IPython.display import display import ipywidgets as ipyw NFFT = ipyw.IntSlider(value=256, min=8, max=1024, step=1, description="NFFT:") shift = ipyw.IntSlider(value=128, min=8, max=1024, step=1, description="shift:") compress = ipyw.FloatLogSlider(value=0, base=10, min=-2, max=5, step=0.2, description="compress:") thresh = r_max = osc.max() * 1.2 thresh_w = ipyw.FloatSlider(value=thresh, min=0, max=r_max, step=r_max / 100, description="Threshold:", continuous_update=False) display(thresh_w) ax1.plot(time, osc) line, = ax1.plot((time[0], time[-1]), (thresh, thresh), 'k') points, = ax1.plot([], [], 'ro') def update(thresh): from quickspikes.tools import filter_times line.set_ydata((thresh, thresh)) det = qs.detector(thresh, 40) spike_t = filter_times(det.send(osc), 10, osc.size - 20) if spike_t: spike_t = np.asarray(spike_t) spike_w = np.asarray(qs.peaks(osc, spike_t, 10, 20)) plot_some_spikes(ax2, spike_w, color='k', alpha=0.2) points.set_xdata(time[spike_t]) points.set_ydata(osc[spike_t]) ax1.figure.canvas.draw() ipyw.interactive_output(update, {"thresh": thresh_w})
def get_dash_app_prior_demo_ipywidgets(): layout = widgets.Layout(width='auto') # set slider label width disp = interact( lambda num_samples, length_scale, number_of_variables: get_plot_cov_and_samples(length_scale=length_scale, num_samples=num_samples, number_of_variables=number_of_variables), num_samples=widgets.IntSlider(min=1, max=100, step=10, value=10, description='Number of samples', layout=layout, style={'description_width': 'initial'}), length_scale=widgets.FloatLogSlider( base=10, min=-2, max=0, step=0.2, value=0.2, description='Length scale', readout_format='.2f', layout=layout, style={'description_width': 'initial'}), number_of_variables=widgets.IntSlider( min=2, max=100, step=10, value=20, description='Number of variables', layout=layout, style={'description_width': 'initial'}))
def __init__(self, iquery, similarity=None): self._iquery = iquery self._options = [{ 'name': 'One TokenEmbedding', 'multiple': False, 'weights': False, 'make': self._make_one }, { 'name': 'Mixed Embeddings', 'multiple': True, 'weights': True, 'make': self._make_mixed }, { 'name': 'Maximum Similarity', 'multiple': True, 'weights': False, 'make': self._make_max }, { 'name': 'Minimum Similarity', 'multiple': True, 'weights': False, 'make': self._make_min }] self._operator = widgets.Dropdown( options=[x['name'] for x in self._options], value=self._options[0]['name'], description='Similarity:', disabled=False, layout={'width': '20em'}, style=ROOT_LEVEL_STYLE) self._operands_vbox = widgets.VBox([]) self._falloff = widgets.FloatLogSlider(value=1, base=2, min=-3, max=2, step=0.1, description='Falloff:', disabled=False, layout={'width': '30em'}, style=ROOT_LEVEL_STYLE) self._vbox = widgets.VBox([ widgets.HBox([self._operator, self._operands_vbox]), self._falloff ]) self._num_operands = 1 if similarity is not None: emb_i = [x for x, _ in iquery.ordered_encoders ].index(similarity['embedding'].name) self._update_operand_widgets(default_embedding=emb_i) else: self._update_operand_widgets() self._operator.observe(self.on_changed, names='value')
def __init__(self, dashboard): import numpy as np self.dashboard = dashboard self.selection_model = widgets.Dropdown(options=Model, description="model") self.selection_model.observe(dashboard.on_model_selected, names="value") self.selection_alpha = widgets.FloatSlider(min=0, max=1, description="alpha", value=0.5) self.selection_alpha.observe(dashboard.on_alpha_selected, names="value") self.selection_c = widgets.FloatLogSlider(min=np.log10(0.1), max=np.log10(10), description="c") self.selection_c.observe(dashboard.on_c_selected, names="value") self.selection_h = widgets.FloatLogSlider(min=np.log10(0.1), max=np.log10(10), description="h") self.selection_h.observe(dashboard.on_h_selected, names="value") self.selection_l = widgets.FloatLogSlider(min=np.log10(0.1), max=np.log10(10), description="l") self.selection_l.observe(dashboard.on_l_selected, names="value") self.selection_plot = widgets.Dropdown(options=Plot, description="plot") self.selection_plot.observe(dashboard.on_plot_selected, names="value") children = [ self.selection_model, self.selection_alpha, self.selection_c, self.selection_h, self.selection_l, self.selection_plot, ] super().__init__(children, layout=Layout(width="100%"))
def generate_awgn_std_widget(): return widgets.FloatLogSlider(value=-1, base=np.sqrt(2), min=-20, max=4, description='$\sigma_{awgn}$: ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='f')
def new_rho_logfloatslider(lay_name='1',value=rho_default): return widgets.FloatLogSlider( base=10, min=np.log10(rhomin), max=np.log10(rhomax), value=value, step=0.1, continuous_update=False, description=r"$\rho_{" + str(lay_name) + "}$", readout=False, layout=widgets.Layout(width='250px'), **align_kw )
def sensitivity_prospect(): epsilon = 1e-5 _ = widgets.interact_manual(prospect_sensitivity_ssa, leaf_n=widgets.FloatSlider(min=1, max=3, value=1.8), leaf_cab=widgets.FloatSlider(min=0, max=100, value=40.), leaf_car=widgets.FloatSlider(min=0, max=25, value=10.), leaf_cbrown=widgets.FloatSlider(min=0, max=1, value=0.1), leaf_cw=widgets.FloatLogSlider(min=-3, max=-1., value=0.0133), leaf_cm=widgets.FloatLogSlider(min=-3, max=-1., value=0.0053))
def __init__(self, tag, value=None, units=None, slider=None): self.tag = tag self.value = value self.units = units if slider is None: self.slider = wd.FloatLogSlider( value=10, base=10, min=-10, # max exponent of base max=1, # min exponent of base step=0.2, # exponent step description=self.tag) else: self.slider = slider
def spec_box(self): "defines the spectral box widget" self.scale = widgets.FloatLogSlider(description='scale:', value=1.0, min=-1, max=3, step=0.1, tooltip='Set display scale', layout=Layout(height='400px'), continuous_update=p.HEAVY, orientation='vertical') self.scale.observe(self.ob) self.bb('b_redraw', 'Redraw', lambda e: self.display(), layout=Layout(width='80px')) box = VBox([self.b_reset, self.scale, self.b_redraw], layout=Layout(min_width='90px')) return HBox([box, self.fig.canvas])
def _jupySlider(name:str, startvalue: float, minvalue: float, maxvalue: float, callback:Callable, step:float=None, width='80%', log=False): import ipywidgets as ipy if step is None: step = _guessStep(minvalue, maxvalue) fmt = _stepToFormat(step) layout = ipy.Layout(width=width) if not log: s = ipy.FloatSlider(value=startvalue, min=minvalue, max=maxvalue, step=step, description=name, layout=layout, readout_format=fmt) else: s = ipy.FloatLogSlider(value=startvalue, min=minvalue, max=maxvalue, step=step, description=name, layout=layout, readout_format=fmt) if callback: s.observe(lambda change:callback(change['new']), names='value') return s
def serialize_as_ipywidgets(topo_object, toposimplify, topoquantize): from ipywidgets import interact from ipywidgets import fixed import ipywidgets as widgets style = {"description_width": "initial"} ts = toposimplify tq = topoquantize # set to simplification package for speed topo_object.options.simplify_with = "simplification" alg = widgets.RadioButtons( options=[("Douglas-Peucker", "dp"), ("Visvalingam-Whyatt", "vw")], value="dp", description="Simplify algortihm", disabled=False, style=style, ) eps = widgets.FloatSlider( min=ts["min"], max=ts["max"], step=ts["step"], value=ts["value"], description="Toposimplify Factor", style=style, ) qnt = widgets.FloatLogSlider( min=tq["min"], max=tq["max"], step=tq["step"], value=tq["value"], base=tq["base"], description="Topoquantize Factor", style=style, ) return interact(toposimpquant, epsilon=eps, quant=qnt, algo=alg, topo=fixed(topo_object))
def __init__(self, npkd, pkname): if not isinstance(npkd, FTMSData): raise Exception('This modules requires a FTMS Dataset') self.npkd = npkd self.pkname = pkname self.zoom = widgets.FloatRangeSlider(value=[npkd.axis1.lowmass, npkd.axis1.highmass], min=npkd.axis1.lowmass, max=npkd.axis1.highmass, step=0.1, layout=Layout(width='100%'), description='zoom', continuous_update=False, readout=True, readout_format='.1f',) self.zoom.observe(self.display) self.tlabel = Label('threshold (x noise level):') self.thresh = widgets.FloatLogSlider(value=20.0, min=np.log10(3), max=2.0, base=10, step=0.01, layout=Layout(width='30%'), continuous_update=False, readout=True, readout_format='.1f') self.thresh.observe(self.pickpeak) self.peak_mode = widgets.Dropdown(options=['marker', 'bar'],value='marker',description='show as') self.peak_mode.observe(self.display) self.bexport = widgets.Button(description="Export",layout=Layout(width='7%'), button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Export to csv file') self.bexport.on_click(self.pkexport) self.bprint = widgets.Button(description="Print", layout=Layout(width='7%'), button_style='success', tooltip='Print to screen') self.bprint.on_click(self.pkprint) self.bdone = widgets.Button(description="Done", layout=Layout(width='7%'), button_style='warning', tooltip='Fix results') self.bdone.on_click(self.done) # self.spec = Output(layout={'border': '1px solid black'}) self.out = Output(layout={'border': '1px solid red'}) display( VBox([self.zoom, HBox([self.tlabel, self.thresh, self.peak_mode, self.bprint, self.bexport, self.bdone]) ]) ) self.fig, self.ax = plt.subplots() self.npkd.set_unit('m/z').peakpick(autothresh=self.thresh.value, verbose=False, zoom=self.zoom.value).centroid() self.display() display(self.out)
def __init__(self, model, parameter_values, t, return_compartments=None, return_derivatives=None, figsize=(4,4), palette='dark', integrator='dopri5', continuous_update=False, show_grid=False, ): super().__init__() self.model = model self.t = np.array(t) self.colors = [ hex_colors[colorname] for colorname in palettes[palette] ] if return_compartments is None: self.return_compartments = self.model.compartments else: self.return_compartments = return_compartments self.return_derivatives = return_derivatives self.integrator = integrator self.lines = None self.continuous_update = continuous_update output = widgets.Output() with output: self.fig, self.ax = pl.subplots(constrained_layout=True, figsize=figsize) self.ax.set_xlabel('time') self.ax.set_ylabel('frequency') self.ax.grid(show_grid) self.fig.canvas.toolbar_position = 'bottom' # define widgets self.fixed_parameters = {} self.sliders = {} for parameter, value in parameter_values.items(): self.fixed_parameters[parameter] = float(value) if type(value) not in [Range, LogRange]: continue else: these_vals = copy.deepcopy(value) these_vals['description'] = r'\(' + sympy.latex(parameter) + r'\)' these_vals['continuous_update'] = self.continuous_update if type(value) == LogRange: slider = widgets.FloatLogSlider(**these_vals) else: slider = widgets.FloatSlider(**these_vals) self.sliders[parameter] = slider checkb_xscale = widgets.Checkbox( value=False, description='logscale time', ) checkb_yscale = widgets.Checkbox( value=False, description='logscale frequency', ) controls = widgets.VBox( list(self.sliders.values()) + [ checkb_xscale, checkb_yscale, ]) controls.layout = get_box_layout() out_box = widgets.Box([output]) output.layout = get_box_layout() for parameter, slider in self.sliders.items(): slider.observe(self.update_parameters, 'value') checkb_xscale.observe(self.update_xscale, 'value') checkb_yscale.observe(self.update_yscale, 'value') self.children = [controls, output] self.update_parameters()
def interactive_grid_focus(g, n_points, plotfxn=None, **kwargs): """ Interactive ipywidgets for changing focus points. Parameters ---------- grid : pygridgen.Gridgen The base grid from which the grids of new focus points will be generated. n_points : int The number of focal points to add to the grid. plotfxn : callable, optional Function that plots the grid to provide user feedback. The call signature of this function must accept to positional parameters for the x- and y-arrays of node locations, and then accept any remaining keyword arguments. If not provided, *pygridtools.viz.plot_points* is used. Additional Parameters --------------------- All remaining keyword arguments are passed to *plotfxn* Returns ------- newgrid : pygridgen.Gridgen The reshaped grid widget : ipywidgets.interactive Collection of Tab / IntSliders for changing the number focus points along each axis in the grid. Examples -------- >>> from pygridgen import grid >>> from pygridtools import viz, iotools >>> d = numpy.array([ ... (13, 16, 1.00), (18, 13, 1.00), (12, 7, 0.50), ... (10, 10, -0.25), ( 5, 10, -0.25), ( 5, 0, 1.00), ... ( 0, 0, 1.00), ( 0, 15, 0.50), ( 8, 15, -0.25), ... (11, 13, -0.25)]) >>> g = grid.Gridgen(d[:, 0], d[:, 1], d[:, 2], (75, 75), ul_idx=1, focus=None) >>> n = 4 # number of focus objects >>> new_grid, widget = iotools.interactive_grid_focus(g, n) """ if not plotfxn: plotfxn = _plot_points_wrapper # common linear slider options common_opts = dict(min=0.01, max=1, step=0.01, continuous_update=False) # common log slider options common_log_f_opts = dict(min=-2, max=2, step=0.1, continuous_update=False) # we need to create a list of widgets for ipywidgets.Tab() widgets = [] # set up our dummy classes focus_points = [_FocusProperties() for f in range(n_points)] for n, fp in enumerate(focus_points): widget = ipywidgets.interactive( _change_focus, fpoint=ipywidgets.fixed(focus_points[n]), others=ipywidgets.fixed(tuple(focus_points[:n] + focus_points[n + 1:])), axis=ipywidgets.ToggleButtons( options=['x', 'y'], description='Axis:'), pos=ipywidgets.FloatSlider(0.5, **common_opts), # currently the only log slider factor=ipywidgets.FloatLogSlider(1, **common_log_f_opts), extent=ipywidgets.FloatSlider(0.5, **common_opts), g=ipywidgets.fixed(g), plotfxn=ipywidgets.fixed(plotfxn), plotopts=ipywidgets.fixed(kwargs) ) widgets += [widget] tab_nest = ipywidgets.Tab() tab_nest.children = widgets for n in range(len(widgets)): tab_nest.set_title(n, 'Focus {}'.format(n + 1)) return focus_points, tab_nest
def interface(): '''Initiates widgets''' from ipywidgets import interact, interactive, fixed, interact_manual, HBox, VBox, Label import ipywidgets as widgets import numpy as np from demo import demo from read_file import read_file t, C, T = read_file( '/Users/antonvasilev/GitHub/ilt/data/beta/EUNB29b_1-16-2_15_2.DLTS') cut = len(T) - 1 Index = widgets.IntSlider( value=1, min=0, # max exponent of base max=cut, # min exponent of base step=1, # exponent step description='') Methods = widgets.SelectMultiple( options=['L1', 'L2', 'L1+L2', 'Contin'], value=['Contin'], #rows = 10, description='Methods:', disabled=False) Nz = widgets.IntText(value=100, description=r'$N_f=$', disabled=False) Reg_L1 = widgets.FloatLogSlider( value=0.1, base=10, min=-5, # max exponent of base max=0.5, # min exponent of base step=0.2, # exponent step description=r'L1: $\lambda_1$') Reg_L2 = widgets.FloatLogSlider( value=1E-3, base=10, min=-12, # max exponent of base max=-2, # min exponent of base step=0.2, # exponent step description=r'L2: $\lambda_2$') Bounds = widgets.IntRangeSlider(value=[-3, 2], min=-4, max=4, step=1, description=r'$10^{a}\div 10^{b}$:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') Plot = widgets.Checkbox(value=True, description='Plot?', disabled=False) Residuals = widgets.ToggleButton( value=False, description='Plot L-curve', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip= 'Plots L-curve to choose best value of regularization parameter of L2 reg. method', icon='plus') Heatplot = widgets.ToggleButton( value=False, description='Plot heatplot', disabled=False, button_style='warning', # 'success', 'info', 'warning', 'danger' or '' tooltip='Plots heatmap of data from choosed file', icon='plus') left_box = VBox([Methods]) centre_box = VBox([Nz, Reg_L1, Reg_L2, Bounds]) right_box = VBox([Plot, Residuals, Heatplot]) ui = widgets.HBox([left_box, centre_box, right_box]) Slider = widgets.HBox([Label('Transient №'), Index]) out = widgets.interactive_output( demo, { 'Index': Index, 'Nz': Nz, 'Reg_L1': Reg_L1, 'Reg_L2': Reg_L2, 'Bounds': Bounds, 'Methods': Methods, 'Plot': Plot, 'Residuals': Residuals, 'Heatplot': Heatplot }) display(ui, Slider, out)
description='Test:', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.1f', ) # ### FloatLogSlider # The `FloatLogSlider` has a log scale, which makes it easy to have a slider that covers a wide range of positive magnitudes. The `min` and `max` refer to the minimum and maximum exponents of the `base`, and the `value` refers to the actual value of the slider. widgets.FloatLogSlider( value=10, base=10, min=-10, # max exponent of base max=10, # min exponent of base step=0.2, # exponent step description='Log Slider') # ### IntRangeSlider widgets.IntRangeSlider( value=[5, 7], min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal',
def canopy_mtci_exp_gui(): parameters = [ 'n', 'cab', 'car', 'ant', 'cbrown', 'cw', 'cm', 'lai', 'lidf', 'rsoil', 'psoil', 'hspot' ] #parameters = ["leaf_n", "leaf_cab", "leaf_car", "leaf_ant", # "leaf_cbrown", "leaf_cw", "leaf_cm", "lai", "ala", # "rsoil", "psoil", "hspot", "sza", "vza", "raa"] some_buttons = { k: widgets.ToggleButton(description=k, value=False) for k in parameters if k != "cab" } some_buttons['cab'] = widgets.ToggleButton(description="cab", value=True) some_pars = { "SZA": widgets.FloatSlider(min=0, max=90, value=0, description="SZA"), "VZA": widgets.FloatSlider(min=0, max=90, value=30, description="VZA"), "RAA": widgets.FloatSlider(min=0, max=180, value=0, description="RAA"), "obs_unc": widgets.FloatLogSlider(min=-4, max=-0.2, value=0.001, description="Uncertainty"), "bwidth": widgets.IntSlider(min=1, max=50, value=5, description="Bandwidth") } some_buttons.update(some_pars) gui_disp = widgets.VBox([ widgets.HBox( [some_buttons["n"], some_buttons["cab"], some_buttons["car"]]), widgets.HBox( [some_buttons["cbrown"], some_buttons["cw"], some_buttons["cm"]]), widgets.HBox( [some_buttons["lai"], some_buttons["lidf"], some_buttons["hspot"]]), widgets.HBox([some_buttons["rsoil"], some_buttons["psoil"]]), widgets.HBox([some_pars["SZA"], some_pars["VZA"], some_pars["RAA"]]), widgets.HBox([some_pars["obs_unc"], some_pars["bwidth"]]) ]) def on_toggle(**values): nuisance = [p for p in parameters if values[p]] obs_noise = values['obs_unc'] sza = values['SZA'] vza = values['VZA'] raa = values['RAA'] bwidth = values["bwidth"] _ = mtci_experiment( nuisance=nuisance, noise_level=obs_noise, sza=sza, vza=vza, raa=raa, bwidth=bwidth, ) interact_out = widgets.interactive_output(on_toggle, some_buttons) display(gui_disp, interact_out)
def canopy_vi_exp_gui(): parameters = [ 'n', 'cab', 'car', 'ant', 'cbrown', 'cw', 'cm', 'lai', 'lidf', 'rsoil', 'psoil', 'hspot' ] #parameters = ["leaf_n", "leaf_cab", "leaf_car", "leaf_ant", # "leaf_cbrown", "leaf_cw", "leaf_cm", "lai", "ala", # "rsoil", "psoil", "hspot", "sza", "vza", "raa"] some_buttons = { k: widgets.ToggleButton(description=k, value=False) for k in parameters if k != "lai" } some_buttons['lai'] = widgets.ToggleButton(description="LAI", value=True) some_pars = { "SZA": widgets.FloatSlider(min=0, max=90, value=0, description="SZA"), "VZA": widgets.FloatSlider(min=0, max=90, value=30, description="VZA"), "RAA": widgets.FloatSlider(min=0, max=180, value=0, description="RAA"), "obs_unc": widgets.FloatLogSlider(min=-4, max=-0.2, value=0.001, description="Uncertainty"), "index": widgets.Dropdown(options=["NDVI", "SAVI", "OSAVI"], value="NDVI") } some_buttons.update(some_pars) gui_disp = widgets.VBox([ widgets.HBox( [some_buttons["n"], some_buttons["cab"], some_buttons["car"]]), widgets.HBox( [some_buttons["cbrown"], some_buttons["cw"], some_buttons["cm"]]), widgets.HBox( [some_buttons["lai"], some_buttons["lidf"], some_buttons["hspot"]]), widgets.HBox([some_buttons["rsoil"], some_buttons["psoil"]]), widgets.HBox([some_pars["SZA"], some_pars["VZA"], some_pars["RAA"]]), widgets.HBox([some_pars["index"], some_pars["obs_unc"]]) ]) def on_toggle(**values): nuisance = [p for p in parameters if values[p]] obs_noise = values['obs_unc'] sza = values['SZA'] vza = values['VZA'] raa = values['RAA'] veg_index = values["index"] _ = canopy_vi_expt(nuisance=nuisance, obs_noise=obs_noise, sza=sza, vza=vza, raa=raa, vin=veg_index) interact_out = widgets.interactive_output(on_toggle, some_buttons) display(gui_disp, interact_out)
def __init__( self, canvas_size=(700, 500), options: Sequence[str] = (), data_postprocessor: Optional[Callable[[List[dict]], Any]] = None, # **kwargs, ): """Create an annotation widget for images.""" self.canvas = self.CanvasClass(canvas_size, classes=options) self.data_postprocessor = data_postprocessor # controls for the data entry: data_controls = [] self.options = options self.class_selector = widgets.Dropdown( description="Class:", options=options, layout=widgets.Layout(flex="1 1 auto"), ) widgets.link((self, "options"), (self.class_selector, "options")) widgets.link( (self.class_selector, "value"), (self.canvas, "current_class") ) data_controls.append(self.class_selector) extra_buttons = [] button_layout = widgets.Layout( # width="auto", min_width="80px", flex="1 1 auto", max_width="120px", ) self.undo_button = widgets.Button( description="Undo", icon="undo", layout=button_layout ) self.undo_button.on_click(self.undo) extra_buttons.append(self.undo_button) self.skip_button = widgets.Button( description="Skip", icon="fast-forward", layout=button_layout ) self.skip_button.on_click(self.skip) extra_buttons.append(self.skip_button) if hasattr(self.canvas, "editing"): self.edit_button = widgets.ToggleButton( description="Edit", icon="pencil", layout=button_layout ) widgets.link((self.edit_button, "value"), (self.canvas, "editing")) extra_buttons.append(self.edit_button) extra_buttons = widgets.HBox( extra_buttons, layout={ "align_items": "stretch", "justify_content": "flex-end", "flex_flow": "row wrap", }, ) self.submit_button = widgets.Button( description="Submit data", icon="tick", button_style="success", layout=button_layout, ) self.submit_button.on_click(self.submit) self.data_controls = widgets.VBox( children=( widgets.HTML("Data input settings"), widgets.HBox( (self.class_selector,), layout={ "align_items": "stretch", "justify_content": "flex-end", }, ), extra_buttons, widgets.HBox( (self.submit_button,), layout={"justify_content": "flex-end"}, ), ), layout={"flex": "1 1 auto", "max_width": "600px"}, ) # controls for the visualisation of the data: viz_controls = [] if hasattr(self.canvas, "opacity"): self.opacity_slider = widgets.FloatSlider( description="Opacity", value=1, min=0, max=1, step=0.025 ) widgets.link( (self.opacity_slider, "value"), (self.canvas, "opacity") ) viz_controls.append(self.opacity_slider) if hasattr(self.canvas, "point_size"): self.point_size_slider = widgets.IntSlider( description="Point size", value=5, min=1, max=20, step=1 ) widgets.link( (self.point_size_slider, "value"), (self.canvas, "point_size") ) viz_controls.append(self.point_size_slider) self.brightness_slider = widgets.FloatLogSlider( description="Brightness", value=1, min=-1, max=1, step=0.0001 ) widgets.link( (self.brightness_slider, "value"), (self.canvas, "image_brightness"), ) viz_controls.append(self.brightness_slider) self.contrast_slider = widgets.FloatLogSlider( description="Contrast", value=1, min=-1, max=1, step=0.0001 ) widgets.link( (self.contrast_slider, "value"), (self.canvas, "image_contrast") ) viz_controls.append(self.contrast_slider) self.visualisation_controls = widgets.VBox( children=(widgets.HTML("Visualisation settings"), *viz_controls), layout={"flex": "1 1 auto"}, ) self.all_controls = widgets.HBox( children=(self.visualisation_controls, self.data_controls), layout={ "width": f"{self.canvas.size[0]}px", "justify_content": "space-between", }, ) self.submit_callbacks: List[Callable[[Any], None]] = [] self.undo_callbacks: List[Callable[[], None]] = [] self.skip_callbacks: List[Callable[[], None]] = [] super().__init__() self.children = [self.canvas, self.all_controls]
def setting_accord(): model_box = widgets.Box([ widgets.RadioButtons( options=['ImageNet pretrain model', 'Custom pretrain model'], description=''), widgets.Dropdown(options=['ResNet50', 'Xception', 'DenseNet121'], value='ResNet50', description='Model Architecture:', disabled=False, style={'description_width': 'initial'}), widgets.Text(value='example: ./mymodel.h5', description='Model Path:', style={'description_width': 'initial'}, layout=Layout(flex='3 1 0%', width='auto'), disabled=True), ], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='80%')) params_box = widgets.Box(children=[ widgets.Dropdown(options=['8', '16', '32', '64', '128'], description='Batch size:'), widgets.FloatText(value=10, min=1, max=200, description='Epochs:'), widgets.FloatText(value=5, min=2, max=10, description='Early stopping rounds:', style={'description_width': 'initial'}), widgets.FloatLogSlider(value=-5, min=-7, max=-1, step=1, description='Learning rate:', readout_format='.1e'), widgets.FloatSlider(value=0.5, min=0.0, max=0.8, step=0.1, description='Drop-out Rate:', style={'description_width': 'initial'}), ], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='50%')) model_save_box = widgets.Box(children=[ widgets.Text(value='example: ./saved_models/', description='Saved Path:', style={'description_width': 'initial'}, layout=Layout(flex='3 1 0%', width='auto')), widgets.Text(value='example: mymodel.h5', description='Model Name:', style={'description_width': 'initial'}, layout=Layout(flex='3 1 0%', width='auto')) ], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='50%')) tab_accord = widgets.Accordion(selected_index=None) tab_accord.children = [model_box, params_box, model_save_box] tab_accord.set_title(0, 'Model Architecture') tab_accord.set_title(1, 'Training Parameters') tab_accord.set_title(2, 'Save Settings') return tab_accord
def create_widgets(self): self.widget_lighting = widgets.Checkbox(description='lighting', value=self.state.lighting) link((self.state, 'lighting'), (self.widget_lighting, 'value')) link((self.state, 'lighting'), (self.volume, 'lighting')) render_methods = 'NORMAL MAX_INTENSITY'.split() self.widget_render_method = widgets.Dropdown( options=render_methods, value=self.state.render_method, description='method') link((self.state, 'render_method'), (self.widget_render_method, 'value')) link((self.state, 'render_method'), (self.volume, 'rendering_method')) self.size_options = [32, 64, 128, 128 + 64, 256, 256 + 128, 512] options = [(str(k), k) for k in self.size_options] self.widget_max_resolution = widgets.Dropdown( options=options, value=128, description='max resolution') link((self.state, 'max_resolution'), (self.widget_max_resolution, 'value')) link((self.state, 'max_resolution'), (self.volume, 'data_max_shape')) #on_change([(self.state, 'max_resolution')])(self.update) self.widget_data_min = widgets.FloatSlider(description='min', min=0, max=1, value=self.state.vmin, step=0.001) link((self.state, 'vmin'), (self.widget_data_min, 'value')) link((self.state, 'vmin'), (self.volume, 'show_min')) link((self.volume, 'data_min'), (self.widget_data_min, 'min')) link((self.volume, 'data_max'), (self.widget_data_min, 'max')) self.widget_data_max = widgets.FloatSlider(description='max', min=0, max=1, value=self.state.vmax, step=0.001) link((self.state, 'vmax'), (self.widget_data_max, 'value')) link((self.state, 'vmax'), (self.volume, 'show_max')) link((self.volume, 'data_min'), (self.widget_data_max, 'min')) link((self.volume, 'data_max'), (self.widget_data_max, 'max')) self.widget_clamp_min = widgets.Checkbox(description='clamp minimum', value=self.state.clamp_min) link((self.state, 'clamp_min'), (self.widget_clamp_min, 'value')) link((self.state, 'clamp_min'), (self.volume, 'clamp_min')) self.widget_clamp_max = widgets.Checkbox(description='clamp maximum', value=self.state.clamp_max) link((self.state, 'clamp_max'), (self.widget_clamp_max, 'value')) link((self.state, 'clamp_max'), (self.volume, 'clamp_max')) self.widget_color = widgets.ColorPicker(value=self.state.color, description='color') link((self.state, 'color'), (self.widget_color, 'value')) self.widget_opacity = widgets.FloatSlider(description='opacity', min=0, max=1, value=self.state.alpha, step=0.001) link((self.state, 'alpha'), (self.widget_opacity, 'value')) self.widget_opacity_scale = widgets.FloatLogSlider( description='opacity scale', base=10, min=-3, max=3, value=self.state.opacity_scale, step=0.01) link((self.state, 'opacity_scale'), (self.widget_opacity_scale, 'value')) link((self.state, 'opacity_scale'), (self.volume, 'opacity_scale')) on_change([(self.state, 'color', 'alpha') ])(self._update_transfer_function) self.widget_reset_zoom = widgets.Button(description="Reset zoom") def reset_zoom(*ignore): with self.figure: if self.last_shape is not None: ipv.xlim(0, self.last_shape[0]) ipv.ylim(0, self.last_shape[1]) ipv.zlim(0, self.last_shape[2]) self.widget_reset_zoom.on_click(reset_zoom) return widgets.VBox([ self.widget_render_method, self.widget_lighting, self.widget_data_min, self.widget_data_max, self.widget_clamp_min, self.widget_clamp_max, self.widget_max_resolution, self.widget_reset_zoom, self.widget_color, self.widget_opacity, self.widget_opacity_scale ])
import ipywidgets as widgets from IPython.display import display import matplotlib.pyplot as plt import numpy as np widgets.IntSlider(min=0, max=10, step=1, description='Slider:', value=3) slider = widgets.FloatLogSlider(min=-10, max=3) display(slider) btn = widgets.Button(description='Medium') display(btn) output = widgets.Output() plot_output = widgets.Output() display(output) display(plot_output) xpos = np.arange(0, 100) / 100.0 def btn_eventhandler(obj): output.clear_output() plot_output.clear_output() with output: print('Slider is ' + str(slider.value)) with plot_output: plt.figure('Hi there') plt.plot(np.exp(xpos * slider.value)) plt.show() btn.on_click(btn_eventhandler)
def volshow(data, lighting=False, data_min=None, data_max=None, max_shape=256, tf=None, stereo=False, ambient_coefficient=0.5, diffuse_coefficient=0.8, specular_coefficient=0.5, specular_exponent=5, downscale=1, level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, controls=True, max_opacity=0.2, memorder='C', extent=None): """Visualize a 3d array using volume rendering. Currently only 1 volume can be rendered. :param data: 3d numpy array :param origin: origin of the volume data, this is to match meshes which have a different origin :param domain_size: domain size is the size of the volume :param bool lighting: use lighting or not, if set to false, lighting parameters will be overriden :param float data_min: minimum value to consider for data, if None, computed using np.nanmin :param float data_max: maximum value to consider for data, if None, computed using np.nanmax :parap int max_shape: maximum shape for the 3d cube, if larger, the data is reduced by skipping/slicing (data[::N]), set to None to disable. :param tf: transfer function (or a default one) :param bool stereo: stereo view for virtual reality (cardboard and similar VR head mount) :param ambient_coefficient: lighting parameter :param diffuse_coefficient: lighting parameter :param specular_coefficient: lighting parameter :param specular_exponent: lighting parameter :param float downscale: downscale the rendering for better performance, for instance when set to 2, a 512x512 canvas will show a 256x256 rendering upscaled, but it will render twice as fast. :param level: level(s) for the where the opacity in the volume peaks, maximum sequence of length 3 :param opacity: opacity(ies) for each level, scalar or sequence of max length 3 :param level_width: width of the (gaussian) bumps where the opacity peaks, scalar or sequence of max length 3 :param bool controls: add controls for lighting and transfer function or not :param float max_opacity: maximum opacity for transfer function controls :param extent: list of [[xmin, xmax], [ymin, ymax], [zmin, zmax]] values that define the bounds of the volume, otherwise the viewport is used :return: """ fig = gcf() if tf is None: tf = transfer_function(level, opacity, level_width, controls=controls, max_opacity=max_opacity) if data_min is None: data_min = np.nanmin(data) if data_max is None: data_max = np.nanmax(data) if memorder is 'F': data = data.T if extent is None: extent = [(0, k) for k in data.shape[::-1]] if extent: _grow_limits(*extent) vol = ipv.Volume(data_original = data, tf=tf, data_min = data_min, data_max = data_max, show_min = data_min, show_max = data_max, extent_original = extent, data_max_shape = max_shape, ambient_coefficient = ambient_coefficient, diffuse_coefficient = diffuse_coefficient, specular_coefficient = specular_coefficient, specular_exponent = specular_exponent, rendering_lighting = lighting) vol._listen_to(fig) if controls: widget_opacity_scale = ipywidgets.FloatLogSlider(base=10, min=-2, max=2, description="opacity") widget_brightness = ipywidgets.FloatLogSlider(base=10, min=-1, max=1, description="brightness") ipywidgets.jslink((vol, 'opacity_scale'), (widget_opacity_scale, 'value')) ipywidgets.jslink((vol, 'brightness'), (widget_brightness, 'value')) widgets_bottom = [ipywidgets.HBox([widget_opacity_scale, widget_brightness])] current.container.children += tuple(widgets_bottom, ) fig.volumes = fig.volumes + [vol] return vol
def __init__( self, canvas_size=(700, 500), options: Sequence[str] = (), data_postprocessor: Optional[Callable[[List[dict]], Any]] = None, img_data: dict() = None, mask_data: object = None, exp_name: str = None, well_name: str = None, save_path: str = None, field_id: int = 0, chr_id: str = 'chr13', # **kwargs, ): """Create an annotation widget for images.""" self.canvas = self.CanvasClass(canvas_size, classes=options) self.data_postprocessor = data_postprocessor # controls for the data entry: data_controls = [] self.options = options self.exp_name = exp_name self.well_name = well_name self.save_path = save_path self.img_data = img_data self.field_id = field_id self.chr_id = chr_id self.mask_data = mask_data self.class_selector = widgets.Dropdown( description="Class:", options=options, layout=widgets.Layout(flex="1 1 auto"), ) self.class_selector.layout.display = 'none' widgets.link((self, "options"), (self.class_selector, "options")) widgets.link((self.class_selector, "value"), (self.canvas, "current_class")) data_controls.append(self.class_selector) extra_buttons = [] button_layout = widgets.Layout( # width="auto", min_width="80px", flex="1 1 auto", max_width="120px", ) self.undo_button = widgets.Button(description="Undo", icon="undo", layout=button_layout) self.undo_button.on_click(self.undo) extra_buttons.append(self.undo_button) self.skip_button = widgets.Button(description="Skip", icon="fast-forward", layout=button_layout) self.skip_button.on_click(self.skip) extra_buttons.append(self.skip_button) if hasattr(self.canvas, "editing"): self.edit_button = widgets.ToggleButton(description="Edit", icon="pencil", layout=button_layout) widgets.link((self.edit_button, "value"), (self.canvas, "editing")) extra_buttons.append(self.edit_button) extra_buttons = widgets.HBox( extra_buttons, layout={ "align_items": "stretch", "justify_content": "flex-end", "flex_flow": "row wrap", }, ) self.submit_button = widgets.Button( description="Submit data", icon="tick", button_style="success", layout=button_layout, ) self.submit_button.on_click(self.submit) self.data_controls = widgets.VBox( children=( widgets.HTML("Data input settings"), widgets.HBox( (self.class_selector, ), layout={ "align_items": "stretch", "justify_content": "flex-end", }, ), extra_buttons, widgets.HBox( (self.submit_button, ), layout={"justify_content": "flex-end"}, ), widgets.HTML("<h3>" + self.exp_name + " " + self.well_name + "</h3><h4>" + str(self.field_id) + "</h4>"), ), layout={ "flex": "1 1 auto", "max_width": "600px" }, ) # controls for the visualisation of the data: viz_controls = [] if hasattr(self.canvas, "opacity"): self.opacity_slider = widgets.FloatSlider(description="Opacity", value=0.25, min=0, max=1, step=0.025) widgets.link((self.opacity_slider, "value"), (self.canvas, "opacity")) viz_controls.append(self.opacity_slider) if hasattr(self.canvas, "point_size"): self.point_size_slider = widgets.IntSlider( description="Point size", value=5, min=1, max=20, step=1) widgets.link((self.point_size_slider, "value"), (self.canvas, "point_size")) viz_controls.append(self.point_size_slider) self.brightness_slider = widgets.FloatLogSlider( description="Brightness", value=1, min=-1, max=1, step=0.0001) widgets.link( (self.brightness_slider, "value"), (self.canvas, "image_brightness"), ) viz_controls.append(self.brightness_slider) self.contrast_slider = widgets.FloatLogSlider(description="Contrast", value=1, min=-1, max=1, step=0.0001) widgets.link((self.contrast_slider, "value"), (self.canvas, "image_contrast")) viz_controls.append(self.contrast_slider) self.visualisation_controls = widgets.VBox( children=(widgets.HTML("Visualisation settings"), *viz_controls), layout={"flex": "1 1 auto"}, ) self.all_controls = widgets.HBox( children=(self.visualisation_controls, self.data_controls), layout={ "width": f"{self.canvas.size[0]}px", "justify_content": "space-between", }, ) chrs = ['chr13', 'chr18', 'chr21', 'chrY'] img = self.img_data[self.chr_id][self.field_id].copy() img = img.astype(np.float32) img_max = img.max() while img_max == 0: chr_id = chrs.index(self.chr_id) if chr_id < 3: self.chr_id = chrs[chr_id + 1] else: self.chr_id = chrs[0] if self.field_id < 120: self.field_id += 1 else: print("Last field, please restart with other well") return (-1) img = self.img_data[self.chr_id][self.field_id].copy() img = img.astype(np.float32) img_max = img.max() subtitle = widgets.HTML("<h4>" + self.exp_name + " " + self.well_name + " field " + str(self.field_id + 1) + " " + self.chr_id + "</h4>") dcontrols = list(self.data_controls.children) dcontrols[-1] = subtitle self.data_controls.children = tuple(dcontrols) img *= 255.0 / img_max img = img.astype(np.uint8) mask = self.mask_data[self.field_id].copy() mask *= 55 mask = mask.astype(np.uint8) self.zoomed_canvas = ZoomController(mask, width=200, height=200) widgets.link((self.zoomed_canvas, "zoom_scale"), (self.canvas, "zoom_scale")) widgets.link((self.zoomed_canvas.canvas, "x"), (self.canvas, "zoomed_image_x")) widgets.link((self.zoomed_canvas.canvas, "y"), (self.canvas, "zoomed_image_y")) self.submit_callbacks: List[Callable[[Any], None]] = [] self.undo_callbacks: List[Callable[[], None]] = [] self.skip_callbacks: List[Callable[[], None]] = [] super().__init__() self.children = [ self.all_controls, widgets.HBox([self.canvas, self.zoomed_canvas]), ] self.display(img, mask)
def __init__(self, dsp_tty, dsp_bitrate, quantize_bits=DEFAULT_SAMPLE_QUANTIZE_BITS, loglevel=logging.WARNING, loghandler=logging.StreamHandler(sys.__stdout__), logformatter=logging.Formatter('oscillo.py: %(message)s'), dsp_loglevel=logging.WARNING): # Call widgets.HBox.__init__() # Refer https://kapernikov.com/ipywidgets-with-matplotlib/ super().__init__() self.quantize_bits = quantize_bits # Set-up logger for debugging logger = logging.getLogger("oscillo") logger.setLevel(loglevel) loghandler.setFormatter(logformatter) logger.addHandler(loghandler) self.logger = logger # Identify underling OS (Linux, Windows, etc.) and determine asyncio # sleep length if sys.platform == 'win32': self.sleep_len = 0.1 self.logger.info( 'Detected running on Windows, so using a special sleep length.' ) else: self.sleep_len = 0.01 # Connecting to peer DSP self.peer = dsp.DSP(dsp_tty, dsp_bitrate, loglevel=dsp_loglevel) # Creating output object for Matplotlib figure output = widgets.Output() with output: self.fig, self.ax = plt.subplots( constrained_layout=True, figsize=(7, 4)) # Move the toolbar to the bottom self.fig.canvas.toolbar_position = 'bottom' # Initialize other object variables which are related to plotting self.ch_active = 0 # channel currently paying attention by user self.trigmode = None self.trigtype = TriggerType.RisingEdge self.tscale = 0.0 # # Define all widgets here # self.menu_ch = widgets.Dropdown(options=[], layout=H_LAYOUT) self.menu_trig = widgets.Dropdown( options=[ ('Auto', TriggerMode.Auto), ('Normal', TriggerMode.Normal), ('Single', TriggerMode.Single), ], value=TriggerMode.Auto, layout=H_LAYOUT) self.button_single = widgets.Button(description='Reset', disabled=True) self.text_trig_status = widgets.HTML('<b>Trigger Status</b>: Waiting') self.ftext_triglevel = widgets.FloatText( value=0.0, step=0.5, description='', layout=H_LAYOUT) self.button_stop = widgets.Button( description='Ready', button_style='primary') self.button_save_image = widgets.Button( description='Save as Image File') self.button_save_csv = widgets.Button(description='Save as CSV File') self.slider_mag = widgets.FloatSlider( value=1.0, min=0.1, max=1.91, step=0.1, orientation='vertical', layout=V_LAYOUT) self.slider_ypos = widgets.FloatSlider( value=0.0, min=-1.0, max=1.0, orientation='vertical', layout=V_LAYOUT) self.slider_tscale = widgets.FloatLogSlider( value=1 / 1e-3, # reciprocal of time-scale base=10, min=0, max=9, step=1 / 3, orientation='horizontal', readout=False, layout=H_LAYOUT) # Set Trigger Mode according to the menu selection self.trigmode_new = self.menu_trig.value # for synchronous update self.triglevel_new = self.ftext_triglevel.value self.triglevel = 0.0 # # Define callback functions respond GUI operations # @observe(self.menu_ch, 'value') def _(change): self.ch_active = change.new self.slider_mag.value = self.mag[self.ch_active] self.slider_ypos.value = self.ypos[self.ch_active] @observe(self.menu_trig, 'value') def _(change): self.trigmode_new = change.new @self.button_single.on_click def _(b): self.clear_trig = True @observe(self.ftext_triglevel, 'value') def _(change): self.triglevel_new = change.new @self.button_stop.on_click def _(b): if self.stopped: for task in asyncio.all_tasks(): task.cancel() self.start() else: self.stopped = True self.button_stop.button_style = 'danger' @self.button_save_image.on_click def _(b): s = get_filename(".png") plt.savefig(s) @self.button_save_csv.on_click def _(b): self.req_save_csv = True @observe(self.slider_mag, 'value') def _(change): self.mag[self.ch_active] = change.new @observe(self.slider_ypos, 'value') def _(change): self.ypos[self.ch_active] = change.new @observe(self.slider_tscale, 'value') def _(change): self.tscale_new = 1 / change.new # Once call DSP to obtain various information need to set-up variables config_reply = self.peer.config( resolution=self.quantize_bits, trigmode=self.trigmode_new, trigtype=self.trigtype, ch_trig=0, triglevel=self.triglevel, timescale=0.0) # timescale as '0.0' means "Don't update timescale" # Set-up mag and ypos self.mag = [] self.ypos = [] for ch in config_reply.chconfig: self.mag.append(1.0) center = (ch.min + ch.max) / 2 width = (ch.max - ch.min) self.ypos.append(-2.0 * center / width) # Create sub_ax (multiple ax on one subplot) of required numbers self.sub_ax = [] for i in range(len(config_reply.chconfig) - 1): self.sub_ax.append(self.ax.twinx()) # Configure Channel menu self.options = [] self.view_enabled_ch = [] for idx, ch in enumerate(config_reply.chconfig): self.options.append(("{:d}: {:s}".format(idx, ch.name), idx)) self.view_enabled_ch.append(True) self.menu_ch.options = self.options # Configure default time-scale self.tscale_new = config_reply.default_timescale self.slider_tscale.min = math.log10(1 / config_reply.max_timescale) # Finally assemble all widgets in one box self.controls = widgets.HBox([ widgets.VBox([ widgets.VBox([ widgets.Box(layout=Layout(height='10px')), widgets.HTML('Scale Pos'), ], layout=Layout(height='40px')), widgets.HBox([ self.slider_mag, self.slider_ypos, ]) ]), widgets.VBox([ widgets.HTML('<b>Active Channel</b>'), self.menu_ch, widgets.HTML('<b>Trigger Mode</b>'), self.menu_trig, self.button_single, self.text_trig_status, widgets.HTML('<b>Trigger Level</b>'), self.ftext_triglevel, widgets.HTML('<b>Horizontal Scale</b>'), self.slider_tscale, widgets.HTML('<hr>'), self.button_stop, self.button_save_image, self.button_save_csv, ]), ]) self.children = [output, self.controls]
def make_preprocessing(self): ''' This creates all the widgets for preprocessing Author: SMM Date: 13/07/2020 ''' wide_style = {'description_width': 'initial'} this_dict = {} minimum_elevation = widgets.BoundedFloatText( value=0, min=-10000.0, max=10000.0, step=0.1, description='minimum_elevation:', disabled=False, style=wide_style) this_dict.update({"minimum_elevation": minimum_elevation}) maximum_elevation = widgets.BoundedFloatText( value=30000, min=-10000.0, max=30000.0, step=0.1, description='maximum_elevation:', disabled=False, style=wide_style) this_dict.update({"maximum_elevation": maximum_elevation}) min_slope_for_fill = widgets.FloatLogSlider( value=0.0001, base=10, min=-5, # max exponent of base max=-1, # min exponent of base step=0.2, # exponent step description='min_slope_for_fill:', style=wide_style) this_dict.update({"min_slope_for_fill": min_slope_for_fill}) raster_is_filled = widgets.Checkbox(value=False, description='raster_is_filled', disabled=False, indent=False) this_dict.update({"raster_is_filled": raster_is_filled}) remove_seas = widgets.Checkbox(value=True, description='remove_seas', disabled=False, indent=False) this_dict.update({"remove_seas": remove_seas}) carve_before_fill = widgets.Checkbox(value=False, description='carve_before_fill', disabled=False, indent=False) this_dict.update({"carve_before_fill": carve_before_fill}) only_check_parameters = widgets.Checkbox( value=False, description='only_check_parameters', disabled=False, indent=False) this_dict.update({"only_check_parameters": only_check_parameters}) return this_dict
def paramform(self): "draw the processing parameter form" def dropdown(options, value, description): opt = [(v, k) for k, v in U.procparam_MS[options].items()] return widgets.Dropdown(options=opt, value=value, description=description, layout=ly, style=style) chld = [] ly = widgets.Layout(width='50%') style = {'description_width': '30%'} chld.append(widgets.HTML('<h3>Processing</h3>')) chld.append( widgets.RadioButtons(options=['Yes', 'No'], value='Yes', description='center fid', layout=ly, style=style)) opt = U.procparam_MS["apodisations"].keys() chld.append( widgets.Dropdown(options=opt, value='hamming', description='apod todo', layout=ly, style=style)) chld.append( widgets.IntSlider(value=2, min=1, max=4, description='zf level', layout=ly, style=style)) chld.append(dropdown("baseline_correction", "offset", "baseline todo")) chld.append(dropdown("grass_noise", "storage", "grass noise todo")) chld.append( widgets.FloatSlider(value=3, min=1, max=10, description='grass noise level', layout=ly, style=style)) chld.append(widgets.HTML('<h3>Peak Picking</h3>')) chld.append(dropdown("peakpicking", "manual", "peakpicking todo")) chld.append( widgets.FloatLogSlider(value=10, min=0, max=3, description='peakpicking noise level', layout=ly, style=style)) chld.append( widgets.RadioButtons(options=['Yes', 'No'], value='Yes', description='centroid', layout=ly, style=style)) chld.append( widgets.IntText(value=self.MAX_DISP_PEAKS, min=10, max=10000, description='max peak displayed', layout=ly, style=style)) self.form = widgets.VBox(chld)
def __init__(self, result_function, parameter_values, t, return_keys=None, figsize=(4,4), palette='dark', continuous_update=False, show_grid=False, ylabel='frequency', label_converter=str, ): super().__init__() self.t = t self.get_result = result_function self.colors = [ hex_colors[colorname] for colorname in palettes[palette] ] self.return_keys = return_keys self.lines = None self.continuous_update = continuous_update self.lbl = label_converter output = widgets.Output() with output: self.fig, self.ax = pl.subplots(constrained_layout=True, figsize=figsize) self.ax.set_xlabel('time') self.ax.set_ylabel(ylabel) self.ax.grid(show_grid) self.fig.canvas.toolbar_position = 'bottom' # define widgets self.fixed_parameters = {} self.sliders = {} for parameter, value in parameter_values.items(): self.fixed_parameters[parameter] = float(value) if type(value) not in [Range, LogRange]: continue else: these_vals = copy.deepcopy(value) these_vals['description'] = self.lbl(parameter) or parameter these_vals['continuous_update'] = self.continuous_update if type(value) == LogRange: slider = widgets.FloatLogSlider(**these_vals) else: slider = widgets.FloatSlider(**these_vals) self.sliders[parameter] = slider checkb_xscale = widgets.Checkbox( value=False, description='logscale time', ) checkb_yscale = widgets.Checkbox( value=False, description='logscale frequency', ) controls = widgets.VBox( list(self.sliders.values()) + [ checkb_xscale, checkb_yscale, ]) controls.layout = get_box_layout() out_box = widgets.Box([output]) output.layout = get_box_layout() for parameter, slider in self.sliders.items(): slider.observe(self.update_parameters, 'value') checkb_xscale.observe(self.update_xscale, 'value') checkb_yscale.observe(self.update_yscale, 'value') self.children = [controls, output] self.update_parameters()