def make_range_slider(self, **kwargs): """ Parameters ---------- kwargs: passed into RangeSlider constructor Returns ------- """ slider_kwargs = dict(value=self.start_value, min=self.vmin, max=self.vmax, continuous_update=False, readout=True, style={'description_width': 'initial'}, orientation=self.orientation) if self.dtype == 'float': slider_kwargs.update(readout_format='.1f', step=0.1, description='time window (s)', layout=Layout(width='100%')) slider_kwargs.update(kwargs) return widgets.FloatRangeSlider(**slider_kwargs) elif self.dtype == 'int': slider_kwargs.update(description='unit window', layout=Layout(height='100%')) slider_kwargs.update(kwargs) return widgets.IntRangeSlider(**slider_kwargs) else: raise ValueError('Unrecognized dtype: {}'.format(self.dtype))
def ui_prepare(self, k): for typ in k: if typ in ['always_apply', 'p']: continue if type(k[typ]) == float: tmp = widgets.FloatSlider(min=0, max=1, step=0.05, continuous_update=False) self.interact_wds[typ] = tmp if type(k[typ]) == bool: tmp = widgets.ToggleButton() self.interact_wds[typ] = tmp if type(k[typ]) == int: tmp = widgets.IntSlider(min=1, max=50, step=1, continuous_update=False) self.interact_wds[typ] = tmp if type(k[typ]) == tuple: tmp = widgets.IntRangeSlider(value=[50, 70], min=5, max=200, step=1, continuous_update=False) self.interact_wds[typ] = tmp ui_lists = [] for w in self.interact_wds: ui_tmp = widgets.VBox([widgets.Label(w), self.interact_wds[w]]) ui_lists.append(ui_tmp) ui = widgets.HBox(ui_lists) return ui
def int_range_controller(max, min=0, start_range=(0, 30), description='units', orientation='horizontal', continuous_update=False): slider = widgets.IntRangeSlider( value=start_range, min=min, max=max, description=description, continuous_update=continuous_update, orientation=orientation, readout=True, style={'description_width': 'initial'}, layout=Layout(width='100%')) up_button = widgets.Button(description='▲', layout=Layout(width='100%')) up_button.on_click(lambda b: move_range_slider_up(slider)) down_button = widgets.Button(description='▼', layout=Layout(width='100%')) down_button.on_click(lambda b: move_range_slider_down(slider)) controller = widgets.VBox( layout=Layout(width='175px'), children=[ slider, widgets.VBox(children=[up_button, down_button])]) return controller
def FilterFreqs(audioData, freqDom, freqs): """ Produces UI componants for user. Drives plotting of filtered signal (FilterFreqs) ---------- Parameters ---------- audioData: array_like raw audio data freqDom: array_like transformed frequnecy domain data freqs: array_like frequencies """ filter_sldr = widgets.IntRangeSlider(value=[0, 0], min=0, max=23e3, step=1000, continuous_update=False, description='Freq Band') xlim_sldr = widgets.IntRangeSlider(value=[0, 22.5e3], min=0, max=22.5e3, step=1000, continuous_update=False, description='Ax. lim') export_btn = widgets.ToggleButton(value=False, description='Export to .wav') display( widgets.VBox([ widgets.interactive_output( FilterBand, { 'audioData': widgets.fixed(audioData), 'freqDom': widgets.fixed(freqDom), 'freqs': widgets.fixed(freqs), 'filtFreq': filter_sldr, 'FALim': xlim_sldr, 'export': export_btn }), widgets.HBox([xlim_sldr, filter_sldr, export_btn]) ]))
def show_spectrum(node: Spectrum, **kwargs) -> widgets.Widget: check_spectrum(node) data = node.power if "power" in node.fields else node.phase if len(data.shape) == 2: no_channels = data.shape[1] else: no_channels = 1 freqs_all = np.asarray(node.frequencies) channel_slider = widgets.IntRangeSlider( min=1, max=no_channels, step=1, description="Channel Range:", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) freq_slider = widgets.IntRangeSlider( min=0, max=freqs_all[-1], step=1, description="Frequency Range:", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) out = widgets.Output() with out: widgets.interact( lambda channel_range, frequency_range: plot_spectrum_figure( node, channel_range, frequency_range), channel_range=channel_slider, frequency_range=freq_slider, ) return out
def __init__(self, on_interact=None, output=None, overwrite_previous_output=True, feedback=False, run=True, action_kws={}, *args, **kwargs): super().__init__(on_interact=on_interact, output=output, overwrite_previous_output=overwrite_previous_output, feedback=feedback, action_kws=action_kws) self.widget = widgets.IntRangeSlider(*args, **kwargs) if run: self.run()
def make_range_slider(self, **kwargs): """ Parameters ---------- kwargs: passed into RangeSlider constructor Returns ------- """ slider_kwargs = dict( value=self.start_value, min=self.vmin, max=self.vmax, continuous_update=False, readout=True, style={"description_width": "initial"}, orientation=self.orientation, ) if self.dtype == "float": slider_kwargs.update( readout_format=".1f", step=0.1, description="time window (s)", layout=Layout(width="100%"), ) slider_kwargs.update(kwargs) return widgets.FloatRangeSlider(**slider_kwargs) elif self.dtype == "int": slider_kwargs.update(description="unit window", layout=Layout(height="100%")) slider_kwargs.update(kwargs) return widgets.IntRangeSlider(**slider_kwargs) else: raise ValueError("Unrecognized dtype: {}".format(self.dtype))
def MusicNote(audioData, freqDom, freqs): """ Produces UI componants for user. Drives plotting of PlotFourierAnalysis ---------- Parameters ---------- audioData: array_like raw audio data freqDom: array_like transformed frequency domain data freqs: array_like frequencies """ xlim_sldr = widgets.IntRangeSlider(value=[0, 22.5e3], min=0, max=22.5e3, step=1000, continuous_update=False, description='Ax. lim') return widgets.VBox([ widgets.interactive_output( PlotSignal, { 'signal': widgets.fixed(audioData), 'amps': widgets.fixed(freqDom), 'freqs': widgets.fixed(freqs), 'FALim': xlim_sldr }), widgets.HBox([xlim_sldr]) ])
class _dic2struct(): def __init__(self, d, which='sim', do_tr=True): self._dic = d for a, b in d.items(): setattr(self, a, _dic2struct(b) if isinstance(b, dict) else b) def __repr__(self): return str(list(self._dic.keys())) dd = {} dd['cnct'] = wdg.Checkbox(value=False, description="Connected") dd['ip'] = wdg.Text(value='10.0.0.11', description='IP:') dd['λ'] = wdg.IntRangeSlider(value=(xlim[0], xlim[1]), min=xlim[0], max=xlim[1], step=5, description='λ', continuous_update=False) dd['pts'] = wdg.IntSlider(value=50000, min=10, max=100000, step=100, description='Points:', continuous_update=False) dd['pts'].add_class("osa_wavelength") dd['scan'] = wdg.ToggleButtons(options=['Single', 'Repeat', 'Stop'], value='Stop', description='Scan:', disabled=False, button_style='info') dd['scan'].add_class("osa_scan_button")
def slider(self, figsize=(8, 8), exclude_particle_records=['charge', 'mass'], **kw): """ Navigate the simulation using a slider Parameters: ----------- figsize: tuple Size of the figures exclude_particle_records: list of strings List of particle quantities that should not be displayed in the slider (typically because they are less interesting) kw: dict Extra arguments to pass to matplotlib's imshow """ # ----------------------- # Define useful functions # ----------------------- def refresh_field(change=None, force=False): """ Refresh the current field figure Parameters : ------------ change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) This is mainline a place holder ; not used in this function force: bool Whether to force the update """ # Determine whether to do the refresh do_refresh = False if (self.avail_fields is not None): if force or fld_refresh_toggle.value: do_refresh = True # Do the refresh if do_refresh: plt.figure(fld_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if fld_use_button.value: i_power = fld_magnitude_button.value vmin = fld_range_button.value[0] * 10**i_power vmax = fld_range_button.value[1] * 10**i_power else: vmin = None vmax = None self.get_field(t=self.current_t, output=False, plot=True, field=fieldtype_button.value, coord=coord_button.value, m=convert_to_int(mode_button.value), slicing=slicing_button.value, theta=theta_button.value, slicing_dir=slicing_dir_button.value, vmin=vmin, vmax=vmax, cmap=fld_color_button.value) def refresh_ptcl(change=None, force=False): """ Refresh the current particle figure Parameters : ------------ change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) This is mainline a place holder ; not used in this function force: bool Whether to force the update """ # Determine whether to do the refresh do_refresh = False if self.avail_species is not None: if force or ptcl_refresh_toggle.value: do_refresh = True # Do the refresh if do_refresh: plt.figure(ptcl_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if ptcl_use_button.value: i_power = ptcl_magnitude_button.value vmin = ptcl_range_button.value[0] * 10**i_power vmax = ptcl_range_button.value[1] * 10**i_power else: vmin = None vmax = None if ptcl_yaxis_button.value == 'None': # 1D histogram self.get_particle( t=self.current_t, output=False, var_list=[ptcl_xaxis_button.value], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value, use_field_mesh=ptcl_use_field_button.value) else: # 2D histogram self.get_particle( t=self.current_t, output=False, var_list=[ ptcl_xaxis_button.value, ptcl_yaxis_button.value ], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value, use_field_mesh=ptcl_use_field_button.value) def refresh_field_type(change): """ Refresh the field type and disable the coordinates buttons if the field is scalar. Parameter --------- change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) """ if self.avail_fields[change['new']] == 'scalar': coord_button.disabled = True elif self.avail_fields[change['new']] == 'vector': coord_button.disabled = False refresh_field() def refresh_species(change=None): """ Refresh the particle species buttons by populating them with the available records for the current species Parameter --------- change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) """ # Deactivate the particle refreshing to avoid callback # while modifying the widgets saved_refresh_value = ptcl_refresh_toggle.value ptcl_refresh_toggle.value = False # Get available records for this species avail_records = [ q for q in self.avail_record_components[ ptcl_species_button.value] if q not in exclude_particle_records ] # Update the plotting buttons ptcl_xaxis_button.options = avail_records ptcl_yaxis_button.options = avail_records + ['None'] if ptcl_xaxis_button.value not in ptcl_xaxis_button.options: ptcl_xaxis_button.value = avail_records[0] if ptcl_yaxis_button.value not in ptcl_yaxis_button.options: ptcl_yaxis_button.value = 'None' # Update the selection widgets for dropdown_button in ptcl_select_widget.quantity: dropdown_button.options = avail_records # Put back the previous value of the refreshing button ptcl_refresh_toggle.value = saved_refresh_value def change_t(change): "Plot the result at the required time" self.current_t = 1.e-15 * change['new'] refresh_field() refresh_ptcl() def step_fw(b): "Plot the result one iteration further" if self.current_i < len(self.t) - 1: self.current_t = self.t[self.current_i + 1] else: self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 def step_bw(b): "Plot the result one iteration before" if self.current_t > 0: self.current_t = self.t[self.current_i - 1] else: self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 # --------------- # Define widgets # --------------- # Slider slider = widgets.FloatSlider( min=math.ceil(1.e15 * self.tmin), max=math.ceil(1.e15 * self.tmax), step=math.ceil(1.e15 * (self.tmax - self.tmin)) / 20., description="t (fs)") slider.observe(change_t, names='value', type='change') set_widget_dimensions(slider, width=500) # Forward button button_p = widgets.Button(description="+") set_widget_dimensions(button_p, width=40) button_p.on_click(step_fw) # Backward button button_m = widgets.Button(description="-") set_widget_dimensions(button_m, width=40) button_m.on_click(step_bw) # Display the time widgets container = widgets.HBox(children=[button_m, button_p, slider]) display(container) # Field widgets # ------------- if (self.avail_fields is not None): # Field type # ---------- # Field button fieldtype_button = widgets.ToggleButtons( description='Field:', options=sorted(self.avail_fields.keys())) fieldtype_button.observe(refresh_field_type, 'value', 'change') # Coord button if self.geometry == "thetaMode": coord_button = widgets.ToggleButtons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in \ ["1dcartesian", "2dcartesian", "3dcartesian"]: coord_button = widgets.ToggleButtons(description='Coord:', options=['x', 'y', 'z']) coord_button.observe(refresh_field, 'value', 'change') # Mode and theta button (for thetaMode) mode_button = widgets.ToggleButtons(description='Mode:', options=self.avail_circ_modes) mode_button.observe(refresh_field, 'value', 'change') theta_button = widgets.FloatSlider(value=0., description=r'Theta:', min=-math.pi / 2, max=math.pi / 2) set_widget_dimensions(theta_button, width=250) theta_button.observe(refresh_field, 'value', 'change') # Slicing buttons (for 3D) slicing_dir_button = widgets.ToggleButtons( value=self.axis_labels[0], options=self.axis_labels, description='Slicing direction:') slicing_dir_button.observe(refresh_field, 'value', 'change') slicing_button = widgets.FloatSlider(description='Slicing:', min=-1., max=1., value=0.) set_widget_dimensions(slicing_button, width=250) slicing_button.observe(refresh_field, 'value', 'change') # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(description='Figure ', value=0) set_widget_dimensions(fld_figure_button, width=50) # Range of values fld_range_button = widgets.IntRangeSlider(min=-10, max=10) set_widget_dimensions(fld_range_button, width=220) fld_range_button.observe(refresh_field, 'value', 'change') # Order of magnitude fld_magnitude_button = widgets.IntText(description='x 10^', value=9) set_widget_dimensions(fld_magnitude_button, width=50) fld_magnitude_button.observe(refresh_field, 'value', 'change') # Use button fld_use_button = widgets.Checkbox(description=' Use this range', value=False) set_widget_dimensions(fld_use_button, left_margin=100) fld_use_button.observe(refresh_field, 'value', 'change') # Colormap button fld_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), value='jet') set_widget_dimensions(fld_color_button, height=50, width=200) fld_color_button.observe(refresh_field, 'value', 'change') # Resfresh buttons fld_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) fld_refresh_button = widgets.Button(description='Refresh now!') fld_refresh_button.on_click(partial(refresh_field, force=True)) # Containers # ---------- # Field type container if self.geometry == "thetaMode": container_fields = widgets.VBox(children=[ fieldtype_button, coord_button, mode_button, theta_button ]) elif self.geometry in ["1dcartesian", "2dcartesian"]: container_fields = widgets.VBox( children=[fieldtype_button, coord_button]) elif self.geometry == "3dcartesian": container_fields = widgets.VBox(children=[ fieldtype_button, coord_button, slicing_dir_button, slicing_button ]) set_widget_dimensions(container_fields, width=260) # Plotting options container container_fld_magnitude = widgets.HBox( children=[fld_magnitude_button, fld_use_button]) set_widget_dimensions(container_fld_magnitude, height=50) if self.geometry == "1dcartesian": container_fld_plots = widgets.VBox(children=[ fld_figure_button, fld_range_button, container_fld_magnitude ]) else: container_fld_plots = widgets.VBox(children=[ fld_figure_button, fld_range_button, container_fld_magnitude, fld_color_button ]) set_widget_dimensions(container_fld_plots, width=260) # Accordion for the field widgets accord1 = widgets.Accordion( children=[container_fields, container_fld_plots]) accord1.set_title(0, 'Field type') accord1.set_title(1, 'Plotting options') # Complete field container container_fld = widgets.VBox(children=[ accord1, widgets.HBox(children=[fld_refresh_toggle, fld_refresh_button]) ]) set_widget_dimensions(container_fld, width=300) # Particle widgets # ---------------- if (self.avail_species is not None): # Particle quantities # ------------------- # Species selection ptcl_species_button = widgets.Dropdown(options=self.avail_species) set_widget_dimensions(ptcl_species_button, width=250) ptcl_species_button.observe(refresh_species, 'value', 'change') # Get available records for this species avail_records = [ q for q in self.avail_record_components[ ptcl_species_button.value] if q not in exclude_particle_records ] # Particle quantity on the x axis ptcl_xaxis_button = widgets.ToggleButtons(options=avail_records) ptcl_xaxis_button.observe(refresh_ptcl, 'value', 'change') # Particle quantity on the y axis ptcl_yaxis_button = widgets.ToggleButtons(options=avail_records + ['None'], value='None') ptcl_yaxis_button.observe(refresh_ptcl, 'value', 'change') # Particle selection # ------------------ # 3 selection rules at maximum ptcl_select_widget = ParticleSelectWidget(3, avail_records, refresh_ptcl) # Plotting options # ---------------- # Figure number ptcl_figure_button = widgets.IntText(description='Figure ', value=1) set_widget_dimensions(ptcl_figure_button, width=50) # Number of bins ptcl_bins_button = widgets.IntText(description='nbins:', value=100) set_widget_dimensions(ptcl_bins_button, width=60) ptcl_bins_button.observe(refresh_ptcl, 'value', 'change') # Colormap button ptcl_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), value='Blues') set_widget_dimensions(ptcl_color_button, height=50, width=200) ptcl_color_button.observe(refresh_ptcl, 'value', 'change') # Range of values ptcl_range_button = widgets.IntRangeSlider(min=0, max=10, value=(0, 5)) set_widget_dimensions(ptcl_range_button, width=220) ptcl_range_button.observe(refresh_ptcl, 'value', 'change') # Order of magnitude ptcl_magnitude_button = widgets.IntText(description='x 10^', value=9) set_widget_dimensions(ptcl_magnitude_button, width=50) ptcl_magnitude_button.observe(refresh_ptcl, 'value', 'change') # Use button ptcl_use_button = widgets.Checkbox(description=' Use this range', value=False) set_widget_dimensions(ptcl_use_button, left_margin=100) ptcl_use_button.observe(refresh_ptcl, 'value', 'change') # Use field mesh buttons ptcl_use_field_button = widgets.Checkbox( description=' Use field mesh', value=True) set_widget_dimensions(ptcl_use_field_button, left_margin=100) ptcl_use_field_button.observe(refresh_ptcl, 'value', 'change') # Resfresh buttons ptcl_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) ptcl_refresh_button = widgets.Button(description='Refresh now!') ptcl_refresh_button.on_click(partial(refresh_ptcl, force=True)) # Containers # ---------- # Particle quantity container container_ptcl_quantities = widgets.VBox(children=[ ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button ]) set_widget_dimensions(container_ptcl_quantities, width=310) # Particle selection container container_ptcl_select = ptcl_select_widget.to_container() # Plotting options container container_ptcl_bins = widgets.HBox( children=[ptcl_bins_button, ptcl_use_field_button]) container_ptcl_magnitude = widgets.HBox( children=[ptcl_magnitude_button, ptcl_use_button]) set_widget_dimensions(container_ptcl_magnitude, height=50) container_ptcl_plots = widgets.VBox(children=[ ptcl_figure_button, container_ptcl_bins, ptcl_range_button, container_ptcl_magnitude, ptcl_color_button ]) set_widget_dimensions(container_ptcl_plots, width=310) # Accordion for the field widgets accord2 = widgets.Accordion(children=[ container_ptcl_quantities, container_ptcl_select, container_ptcl_plots ]) accord2.set_title(0, 'Particle quantities') accord2.set_title(1, 'Particle selection') accord2.set_title(2, 'Plotting options') # Complete particle container container_ptcl = widgets.VBox(children=[ accord2, widgets.HBox( children=[ptcl_refresh_toggle, ptcl_refresh_button]) ]) set_widget_dimensions(container_ptcl, width=370) # Global container if (self.avail_fields is not None) and \ (self.avail_species is not None): global_container = widgets.HBox( children=[container_fld, container_ptcl]) display(global_container) elif self.avail_species is None: display(container_fld) elif self.avail_fields is None: display(container_ptcl)
def createUI(self): dd = {} # === Connection === # ============================== # connection button dd['cnct'] = wdg.Checkbox(value=False, description="Connected") # IP Address dd['ip'] = wdg.Text(value='10.0.0.11', description='IP:') # Model connected dd['model'] = wdg.Textarea(value='', rows=9, placeholder='', description='Model', disabled=True) # === Scan === # ============================== # Scan type dd['refresh_trace'] = wdg.Button( description='Refresh Trace', button_style='info', tooltip='Fetch the current trace on the instrument', display='flex', flex_flow='row', justify_content='space-between', align_items='stretch', ) # dd['refresh'].add_class("osa_scan_button") dd['scan'] = wdg.ToggleButtons(options=['Single', 'Repeat', 'Stop'], value='Stop', display='flex', flex_flow='row', justify_content='space-between', align_items='stretch', description='Scan:', button_style='info') # dd['scan'].add_class("osa_scan_button") # === Setup === # ============================== # Wavelength range dd['refresh_setup'] = wdg.Button( description='Refresh Setup', button_style='info', tooltip='Fetch the current setup of the instrument', display='flex', flex_flow='row', justify_content='space-between', align_items='stretch', ) dd['λ'] = wdg.IntRangeSlider(value=(0, 2000), min=0, max=2000, step=5, description='λ', continuous_update=False) # Number of pts dd['pts'] = wdg.IntSlider(value=50000, min=1, max=100000, step=100, description='Points:', continuous_update=False) # dd['pts'].add_class("osa_wavelength") # Resolution dd['res'] = wdg.Dropdown(options=[ 'Norm/Hold', 'Norm/Auto', 'Mid', 'High 1', 'High 2', 'High 3' ], description='Resolution:') # Bandiwth self._Bdwt_val = { 0.02: '0.02 nm', 0.05: '0.05 nm', 0.1: '0.1 nm', 0.2: '0.2 nm', 0.5: '0.5 nm', 1: '1 nm', 2: '2 nm' } dd['bandwidth'] = wdg.SelectionSlider(description='Bandwidth:', options=self._Bdwt_val.values(), continuous_update=False) # dd['bandwidth'].add_class("osa_bandwidth") # === Trace === # ============================== # freq/wavelength swith dd['freq_scale'] = wdg.ToggleButtons( options=['Wavelength', 'Frequency'], value='Wavelength', description='X scale', disabled=False, button_style='') # Trace selection dd['trace'] = wdg.Dropdown( options=['Trace A', 'Trace B', 'Trace C', 'Trace D'], value='Trace A', description='Trace:') # clear traces dd['clr'] = wdg.Button( description='Clear Traces', button_style='danger', tooltip='', ) # delete saved trace # clear traces dd['clr_keep'] = wdg.Button( description='Clear Saved', button_style='warning', tooltip='', ) # keep current dd['keep'] = wdg.Button( description='Keep Trace', button_style='success', tooltip='Click me', ) # === Save === # ============================== # save # freq/wavelength swith dd['to_save'] = wdg.ToggleButtons(options=['PC', 'OSA'], value='PC', description='Data', disabled=False, button_style='') dd['save'] = wdg.Button(description='Save Spectra', button_style='info') dd['picker'] = FileChooser(os.path.abspath('./../'), width=300) dd['picker'].use_dir_icons = True dd['picker'].rows = 8 dd['picker'].width = 200 self.ui = _dic2struct(dd) # -- setup the style of the UI -- # -------------------------------- self.ui.trace.layout = { 'width': '285px', 'margin': '20px 7px 20px 0px' } self.ui.trace.style = {"description_width": "45px"} self.ui.keep.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'} self.ui.clr_keep.layout = { 'width': '300px', 'margin': '0px 0px 20px 0px' } self.ui.clr.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'} self.ui.freq_scale.layout = { 'width': '300px', 'margin': '0px 0px 20px 0px' } self.ui.freq_scale.style = { "button_width": "95px", "description_width": "45px" } self.ui.refresh_trace.layout = { 'width': '300px', 'margin': '40px 0px 20px 0px' } self.ui.refresh_trace.style = {"button_width": "55px"} self.ui.scan.layout = {'width': '300px', 'margin': '20px 0px 20px 0px'} self.ui.scan.style = { "button_width": "55px", "description_width": "45px" } self.ui.ip.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'} self.ui.ip.style = {"description_width": "45px"} self.ui.model.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'} self.ui.model.style = {"description_width": "45px"} self.ui.cnct.layout = {'width': '300px', 'margin': '20px 0px 20px 0px'} self.ui.cnct.style = {"description_width": "45px"} self.ui.refresh_setup.layout = { 'width': '300px', 'margin': '20px 0px 20px 0px' } self.ui.res.layout = {'width': '300px', 'margin': '20px 0px 20px 0px'} self.ui.res.style = {"description_width": "70px"} self.ui.bandwidth.layout = { 'width': '300px', 'margin': '0px 0px 20px 0px' } self.ui.bandwidth.style = {"description_width": "70px"} self.ui.pts.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'} self.ui.pts.style = {"description_width": "70px"} self.ui.λ.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'} self.ui.λ.style = {"description_width": "70px"} self.ui.to_save.layout = { 'width': '300px', 'margin': '20px 0px 20px 0px' } self.ui.to_save.style = { "button_width": "90px", "description_width": "45px" } self.ui.save.layout = {'width': '300px', 'margin': '0px 0px 20px 0px'} self.ui.picker.layout = wdg.Layout(display='inline', flex_flow='column', flex_wrap='wrap', align_content='stretch', justify_content='center', align_items='stretch', width='300px') self.ui.picker.width = 200 self.ui.picker.rows = 8 # -- diplaying with style -- box_layout = wdg.Layout(display='flex', flex_flow='column', flex_wrap='wrap', align_content='stretch', justify_content='center', align_items='stretch', width='28%', height='500px') outp_layout = wdg.Layout(display='flex', flex_flow='column', flex_wrap='wrap', align_content='stretch', justify_content='center', align_items='stretch', width='72%') figure = wdg.Box(children=[self.figOSA], layout=outp_layout) v_layout = wdg.Layout(display='flex', flex_flow='column', align_items='center', align_content='center', width='100%') items = [wdg.Label('') for i in range(4)] left_box = wdg.VBox([items[0], items[1]]) right_box = wdg.VBox([items[2], items[3]]) spacer = wdg.HBox([left_box, right_box]) Connection = wdg.VBox([self.ui.cnct, self.ui.ip, self.ui.model], layout=v_layout) Scan = wdg.VBox([self.ui.refresh_trace, self.ui.scan], layout=v_layout) Setup = wdg.VBox([ self.ui.refresh_setup, self.ui.res, self.ui.bandwidth, self.ui.pts, self.ui.λ ], layout=v_layout) Trace = wdg.VBox([ self.ui.trace, self.ui.freq_scale, self.ui.keep, self.ui.clr_keep, self.ui.clr ], layout=v_layout) Save = wdg.VBox([self.ui.to_save, self.ui.save, self.ui.picker], layout=v_layout) children = [Connection, Scan, Setup, Trace, Save] tab = wdg.Tab(layout=box_layout) tab.children = children titles = ['Connection', 'Scan', 'Setup', 'Trace', 'Save'] for it, tt in enumerate(titles): tab.set_title(it, tt) end_layout = wdg.Layout(display='flex', flex_flow='row', align_items='center', align_content='center', width='100%') endUI = wdg.HBox([tab, figure], layout=end_layout) # -- Dispaying -- display(endUI)
def show(self): # current schema name self.box2 = widgets.HBox([ widgets.Label("Pre. Index Separator", layout=widgets.Layout(width='15%')), widgets.Text(value='_', layout=widgets.Layout(width='5%')) ]) self.box2b = widgets.HBox([ widgets.Label("Untouched filename part:", layout=widgets.Layout(width="20%")), widgets.Label("", layout=widgets.Layout(width='40%')), widgets.IntRangeSlider(value=[0, 2], min=0, max=len(self.basename), step=1) ]) self.int_range_slider = self.box2b.children[2] self.int_range_slider.observe(self.change_int_range_slider, names='value') self.basename_selected_by_user = self.box2b.children[1] self.box4 = widgets.HBox([ widgets.Label("Current Name Schema: ", layout=widgets.Layout(width='20%')), widgets.Label(self.current_naming_schema(), layout=widgets.Layout(width='30%')), widgets.Label("Random Input:", layout=widgets.Layout(width='15%')), widgets.Dropdown(options=self.random_input_list, value=self.random_input_list[0], layout=widgets.Layout(width='50%')) ]) self.box2.children[1].on_trait_change(self.pre_index_text_changed, 'value') before = widgets.VBox([self.box2, self.box2b, self.box4]) self.random_input_checkbox = self.box4.children[3] self.random_input_checkbox.observe( self.random_input_checkbox_value_changed, 'value') # new naming schema box_text_width = '10%' self.box1 = widgets.HBox([ widgets.Label("New prefix File Name", layout=widgets.Layout(width='10%')), widgets.Checkbox(value=True, description='Use previous prefix name', layout=widgets.Layout(width='30%')) ]) self.use_previous_prefix_widget = self.box1.children[1] self.box1.children[1].observe(self.changed_use_previous_prefix_name, names='value') self.box1b = widgets.HBox([ widgets.Label("", layout=widgets.Layout(width='10%')), widgets.Checkbox(value=False, description='Use new prefix', layout=widgets.Layout(width='20%')), widgets.Text(value='image', disabled=True, layout=widgets.Layout(width='25%')) ]) self.box1b.children[2].observe(self.changed_use_new_prefix_name, names='value') self.new_prefix_text_widget = self.box1b.children[2] self.user_new_prefix_widget = self.box1b.children[1] self.user_new_prefix_widget.observe(self.changed_use_new_prefix_name, names='value') self.box5 = widgets.HBox([ widgets.Label("New Index Separator", layout=widgets.Layout(width='15%')), widgets.Text(value='_', layout=widgets.Layout(width=box_text_width)) ]) self.box7 = widgets.HBox([ widgets.Label("Number of digits", layout=widgets.Layout(width='15%')), widgets.IntText(value=4, layout=widgets.Layout(width=box_text_width)) ]) self.box8 = widgets.HBox([ widgets.Label("Offset", layout=widgets.Layout(width='15%')), widgets.IntText(value=0, layout=widgets.Layout(width=box_text_width)) ]) self.box6 = widgets.HBox([ widgets.Label("New Name Schema: ", layout=widgets.Layout(width='20%')), widgets.Label(self.new_naming_schema(), layout=widgets.Layout(width='40%')) ]) self.box1.children[1].on_trait_change(self.post_text_changed, 'value') self.box5.children[1].on_trait_change(self.post_text_changed, 'value') self.box7.children[1].on_trait_change(self.post_text_changed, 'value') self.box8.children[1].on_trait_change(self.post_text_changed, 'value') after = widgets.VBox([ self.box1, self.box1b, self.box5, self.box7, self.box8, self.box6 ]) accordion = widgets.Accordion(children=[before, after]) accordion.set_title(0, 'Current Schema Name') accordion.set_title(1, 'New Naming Schema') output_ui_1 = widgets.HBox([ widgets.Label("Example of naming: ", layout=widgets.Layout(width='20%')) ]) self.output_ui_2 = widgets.HBox([ widgets.Label("Old name: ", layout=widgets.Layout(width='40%')), widgets.Label("", layout=widgets.Layout(width='60%')) ]) self.output_ui_3 = widgets.HBox([ widgets.Label("New name: ", layout=widgets.Layout(width='40%')), widgets.Label("", layout=widgets.Layout(width='60%')) ]) self.output_ui_3.children[1].add_class("result_label") vbox = widgets.VBox( [accordion, output_ui_1, self.output_ui_2, self.output_ui_3]) display(vbox) self.demo_output_file_name() self.change_int_range_slider() self.changed_use_new_prefix_name()
def _create(self): default_layout = widgets.Layout(width='auto', height='auto') self.wg['organization'] = widgets.Text(value='', description='Organization', layout=default_layout) self.wg['filter'] = widgets.Text( description='Filter', placeholder='Repository names must contain', layout=default_layout) self.wg['filename'] = widgets.Text(value='exercice.py', description='Filename', layout=default_layout) self.wg['request_url'] = widgets.Text( description='Request URL', value= f'https://raw.githubusercontent.com/{self.wg["organization"].value}/%RepositoryName%/master/{self.wg["filename"].value}', layout=default_layout, disabled=True) self.wg['get_files'] = widgets.Button(description='Fetch submissions') self.wg['get_files_status'] = widgets.Valid(value=True, description='Ready', layout=default_layout) self.wg['previous_button'] = widgets.Button(description='Previous') self.wg['next_button'] = widgets.Button(description='Next') self.wg['open_in_browser'] = widgets.Button( description='Open in GitHub', layout=default_layout) self.wg['open_file'] = widgets.Checkbox(description='File only', layout=default_layout) self.wg['repository_select'] = widgets.Dropdown( description='Select', layout=widgets.Layout(width='600px')) self.wg['max_preview_lines'] = widgets.IntText( value=100, disabled=False, layout=widgets.Layout(width='50px')) self.wg['preview_lines_range'] = widgets.IntRangeSlider( value=[0, 20], min=0, max=self.wg['max_preview_lines'].value, step=1, description='Lines range:', continuous_update=True, orientation='horizontal', readout=True, readout_format='d', layout=widgets.Layout(width='500px')) self.wg['repository_grading'] = widgets.HTML( layout=widgets.Layout(width='auto', height='auto', border='solid 1px', padding='2px 10px 2px 10px')) html_layout = widgets.Layout(width='auto', height='auto', padding='20px 100px 0px 20px') self.wg['file_preview_stats'] = widgets.HTML(layout=html_layout) self.wg['file_preview'] = widgets.HTML(layout=html_layout) self.wg['file_view_stats'] = widgets.HTML(layout=html_layout) self.wg['file_view'] = widgets.HTML(layout=html_layout) file_preview_box = widgets.HBox( (self.wg['file_preview'], self.wg['file_preview_stats'])) file_view_box = widgets.HBox( (self.wg['file_view'], self.wg['file_view_stats'])) lines_range_box = widgets.HBox( (self.wg['preview_lines_range'], self.wg['max_preview_lines'])) self.wg['accordion'] = widgets.Accordion(children=[ widgets.VBox((lines_range_box, file_preview_box)), file_view_box ]) self.wg['accordion'].set_title(0, 'Preview') self.wg['accordion'].set_title(1, 'File')
def draw_workflow(self, start_end, workflow, name): assert isinstance(workflow, Workflow) start_s = start_end["seconds"]["start"] last_s = start_end["seconds"]["last"] start_t = start_end["time"]["start"] last_t = start_end["time"]["last"] # 1. get main stacked axis list main_stacked_results = [] main_stacked_results.append(("BLANK", "#eeeeee", [ (0, c.from_seconds) for c in chain.from_iterable( s.intervals for s in workflow.start_group.iter_nxtgroups()) ])) for group in workflow.sort_topologically(): _name = group.desc color = getcolor_byint(group.intervals[0], ignore_lr=True) main_stacked_results.append( (_name, color, [(c.from_seconds, c.to_seconds) for c in group.intervals])) # 2. calc main_x_list from main_stacked_results types, colors, main_x_list, main_ys_list =\ _generate_stackeddata(main_stacked_results) # 3. calc and check the arguments x_start_default = 0 y_start_default = 0 x_end_default = last_s * 1.05 y_end_default = workflow.len_reqs def _interact(x, y, selects, color): with self._build_fig("workflowplot", name, figsize=(30, 6)) as fig: ax = fig.add_subplot(1, 1, 1) ax.set_xlabel("lapse (seconds)") ax.set_ylabel("requests") ax.set_xlim(x[0], x[1]) ax.set_ylim(y[0], y[1]) plot_colors = colors[:] if color: for s in selects: plot_colors[s] = color ax.annotate(start_t, xy=(0, 0), xytext=(0, 0)) ax.annotate(last_t, xy=(last_s, 0), xytext=(last_s, 0)) ax.plot([0, last_s], [0, 0], 'r*') ax.stackplot(main_x_list, *main_ys_list, colors=plot_colors, edgecolor="black", linewidth=.1) # ax.legend((mpatches.Patch(color=color) for color in colors), types) if self.out_path: _interact((x_start_default, x_end_default), (y_start_default, y_end_default), [], None) else: from ipywidgets import widgets, interactive_output, fixed, Layout from IPython.display import display layout = Layout(width="99%") w_lapse = widgets.FloatRangeSlider( value=[x_start_default, x_end_default], min=x_start_default, max=x_end_default, step=0.0001, description='x-lapse:', continuous_update=False, readout_format='.4f', layout=layout) w_requests = widgets.IntRangeSlider( value=[y_start_default, y_end_default], min=y_start_default, max=y_end_default, description='y-requests:', continuous_update=False, layout=layout) w_range = widgets.VBox([w_lapse, w_requests]) w_color = widgets.ColorPicker(concise=True, description='Highlight:', value='#ff40ff', layout=layout) options = [types[i] for i in range(1, len(types) - 1)] dedup = defaultdict(lambda: -1) for i, o in enumerate(options): dedup[o] += 1 if dedup[o]: options[i] = ("%s (%d)" % (options[i], dedup[o])) options = [(v, i + 1) for i, v in enumerate(options)] w_select = widgets.SelectMultiple(options=options, rows=min(10, len(options)), description='Steps:', layout=layout) w_highlight = widgets.VBox([w_color, w_select]) w_tab = widgets.Tab() w_tab.children = [w_range, w_highlight] w_tab.set_title(0, "range") w_tab.set_title(1, "highlight") out = widgets.interactive_output( _interact, { 'x': w_lapse, 'y': w_requests, 'selects': w_select, 'color': w_color }) display(w_tab, out)
ha='left', va='center') # More prettifications... ax2.set_xlabel('Valid Time', fontsize=12) ax2.set_xlim((matplotlib.dates.date2num(ensemble['times'][0]), matplotlib.dates.date2num(ensemble['times'][-1]))) ax2.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d/%HZ')) ax2.set_ylabel('Ens. Variance [K$^{2}$]', fontsize=12) ax2.legend(loc=0) ax2.grid() # This uses iPython widgets to build sliders for determining what to assimilate obs_slider = widgets.IntRangeSlider(min=1, max=len(obs), step=1, value=(1, len(obs)), description='Num. Obs. Assimilated') error_slider = widgets.FloatSlider(value=1.0, min=0.25, max=2.0, step=0.25, description='Obs. Error [K$^{2}$]') inflation_slider = widgets.FloatSlider(value=1.0, min=1.0, max=3.0, step=0.5, description='Inflation Factor') show_inflated_prior = widgets.Checkbox(description="Show inflated prior", value=False)
confirmed_w = widgets.IntSlider(min=1, max=100, step=1, value=50, description=r'% of cases confirmed', style=mystyle) mitigation_factor_w = widgets.FloatSlider(min=0.01, max=1.0, step=0.01, value=0.5, style=mystyle, description='Mitigation Factor') mitigation_interval_w = widgets.IntRangeSlider( min=0, max=400, step=5, value=(0, 180), style=mystyle, description='Mitigation Interval') mitigation_enabled_w = widgets.Checkbox(value=False, description='Use mitigation') Axis_w = widgets.RadioButtons(options=['Linear', 'Logarithmic']) plotS_w = widgets.Checkbox(value=False, description='Plot S') plotI_w = widgets.Checkbox(value=True, description='Plot I') plotR_w = widgets.Checkbox(value=False, description='Plot R') stats_w = widgets.Output(style={'border': True}) plot_w = widgets.Output() model_column1 = widgets.VBox(