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 show_hide_code(default: bool = True) -> None: javascript_functions = {False: "hide()", True: "show()"} button_descriptions = {False: "Show code", True: "Hide code"} def toggle_code(code_state): """ Toggles the JavaScript show()/hide() function on the div.input element. """ output_string = "<script>$(\"div.input\").{}</script>" output_args = (javascript_functions[code_state], ) output = output_string.format(*output_args) display(HTML(output)) def button_action(value): """ Calls the toggle_code function and updates the button description. """ code_state = value.new toggle_code(code_state) value.owner.description = button_descriptions[code_state] state = default toggle_code(state) button = widgets.ToggleButton(state, description=button_descriptions[state]) button.observe(button_action, "value") display(button)
def i_save_job(): """ Adds and returns a new job with the given properties """ from ipywidgets import interact, interact_manual from IPython.display import display, clear_output from balsam.core.models import ApplicationDefinition as App from ipywidgets import widgets import os print(f'Balsam database: {os.environ["BALSAM_DB_PATH"]}') apps = App.objects.all() appnames = [app.name for app in apps] isave = widgets.ToggleButton( value=False, description='save job', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='save job to the balsam database', icon='') im = interact_manual(save_job, name='', workflow='', application=appnames, description='', args='', num_nodes=range(1, 4394), ranks_per_node=range(1, 256), cpu_affinity=['depth', 'none'], data={}, environ_vars='') app_button = im.widget.children[10] app_button.description = 'save job' return
def render(self): if self.sequence_type == "list": widget = get_list(self.content["items"]) elif self.sequence_type == "variable": i1 = self.content["items"][0].render() i2 = self.content["items"][1].render() toggle = widgets.ToggleButton(description="Toggle details") def hide_slider(widg): if widg["new"]: i2.layout.display = "" else: i2.layout.display = "none" toggle.observe(hide_slider, names=["value"]) i2.layout.display = "none" toggle_box = widgets.HBox([toggle]) toggle_box.layout.align_items = "flex-end" toggle_box.layout.object_position = "right center" toggle_box.layout.width = "100%" return widgets.VBox([i1, toggle_box, i2]) elif self.sequence_type in ["tabs", "sections"]: widget = get_tabs(self.content["items"]) elif self.sequence_type == "accordion": widget = get_accordion(self.content["items"]) elif self.sequence_type == "grid": widget = get_row(self.content["items"]) else: raise ValueError("widget type not understood", self.sequence_type) return widget
def SimpleClickProceedSettings(): # Toggle button button = widgets.ToggleButton(description="Proceed", button_style='warning', disabled=False, value=False) def on_button_clicked(args): if args['new'] == True: # changing colour and description button.description = 'Unlock Settings' button.close() # Function called to be done every time settings are locked display( Javascript( 'IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1, IPython.notebook.get_selected_index()+2)' )) else: # Resetting Toggle Locking button.description = 'Lock Settings' button.button_style = 'Danger' button.observe(on_button_clicked, 'value') display(button)
def overlayViewer(im4d, overlay3d, zz=0, tt=0, th=0, oa=1, im_range=None, o_range=None): tt_enable = True if im4d.ndim == 3: im4d = im4d[:,:,:,np.newaxis] tt_enable = False out = widgets.Output() zz_slider = widgets.IntSlider(min=0, max=im4d.shape[2]-1, step=1, value=zz) tt_slider = widgets.IntSlider(min=0, max=im4d.shape[3]-1, step=1, value=tt) oa_slider = widgets.FloatSlider(min=0, max=1, step=0.1, value=oa) if issubclass(overlay3d.dtype.type, np.integer) or overlay3d.dtype == np.bool: th = 1 th_slider = widgets.IntSlider(min=np.amin(overlay3d), max=np.amax(overlay3d), step=1, value=th) th_slider.visible = False oa_slider.visible = True else: th_slider = widgets.FloatSlider(min=np.amin(overlay3d), max=np.amax(overlay3d), step=0.01, value=th) oa_slider.visible = False overlay_button = widgets.ToggleButton(description='Overlay', value=True) if not tt_enable: tt_slider.visible = False with warnings.catch_warnings(): warnings.simplefilter('ignore') w = widgets.interactive(overlayShow, recon=widgets.fixed(im4d), overlay3d=widgets.fixed(overlay3d), zz=zz_slider, tt=tt_slider, th=th_slider, oa=oa_slider, oe=overlay_button, im_range=widgets.fixed(im_range), o_range=widgets.fixed(o_range), out=widgets.fixed(out)) wo = widgets.HBox(children=(w,out)) display(wo)
def i_submit_jobs(): from ipywidgets import interact, widgets inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iwall_minutes = widgets.BoundedIntText(value=10, min=10, max=1440, step=30, description='wall minutes', disabled=False) isave = widgets.Checkbox(value=False, description='save', indent=True) isubmit = widgets.ToggleButton( value=False, description='submit', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='submit job', icon='') # ('check') im = interact( submit_jobs, project='', queue=['debug-flat-quad', 'debug-cache-quad', 'default', 'backfill'], nodes=inodes, wall_minutes=iwall_minutes, job_mode=['mpi', 'serial'], wf_filter='', save=isave, submit=isubmit)
def SimpleToggleLockSettings(WidgList, ExecuteOnLock, ExecuteOnUnlock): # Toggle button button = widgets.ToggleButton(description="Lock Settings", button_style='Danger', disabled=False, value=False) def on_button_clicked(args): if args['new'] == True: # changing colour and description button.description = 'Unlock Settings' button.button_style = 'Success' # Function called to be done every time settings are locked ExecuteOnLock() # Locking Widgets: for widg in WidgList: widg.disabled = True else: # Resetting Toggle Locking button.description = 'Lock Settings' button.button_style = 'Danger' # Unlocking Widgets: for widg in WidgList: widg.disabled = False # execute the programmerdefined function; notice that it comes after the widgets being enabled, # here the programmer can override that and re-disable a widget ExecuteOnUnlock() button.observe(on_button_clicked, 'value') display(button)
def render(self): toggle = widgets.ToggleButton(description=self.content["text"]) toggle.layout.width = "fit-content" toggle_box = widgets.HBox([toggle]) toggle_box.layout.align_items = "flex-end" toggle_box.layout.display = "flex" toggle_box.layout.flex_flow = "column" toggle_box.layout.width = "100%" return toggle_box
def createPlotsPanel(self): components = self.gluemanager.data.components pixel_component_ids = self.gluemanager.data.pixel_component_ids world_component_ids = self.gluemanager.data.world_component_ids v = [] for k in components: if k not in world_component_ids: #k not in pixel_component_ids and kt = str(k) vv = widgets.ToggleButton( value=False, tooltip=kt, description=kt ) v.append(vv) tb = widgets.HBox(v) cr = widgets.Button( description='Create new visualization', disabled=False, button_style='', tooltip='', ) views = self.gluemanager.listPlots() dd = widgets.Dropdown( options=views, value=views[0], disabled=False, ) ss = widgets.Checkbox( value=False, description='Only subsets', disabled=False ) tx = widgets.Text( value='', placeholder='New_Visualization', disabled=False ) hb1 = widgets.HBox([dd,tx,ss,cr]) vb1 = widgets.VBox([tb,hb1]) from IPython.display import display cr.on_click(lambda e : GlueManagerWidget.createNewView(self,e, dd, tb.children, tx, ss)) return vb1
def __init__(self, on_true=None, on_false=None, on_true_output=None, on_false_output=None, \ on_true_overwrite_previous_output=True, on_false_overwrite_previous_output=True, on_true_feedback=False, \ on_false_feedback=False, run=True, layout={'width':'max-content'}, indent=False, on_true_action_kws={}, on_false_action_kws={}, *args, **kwargs): super().__init__(on_true=on_true, on_false=on_false, on_true_output=on_true_output, on_true_action_kws=on_true_action_kws, on_false_output=on_false_output, \ on_true_overwrite_previous_output=on_true_overwrite_previous_output, on_false_overwrite_previous_output=on_false_overwrite_previous_output, on_true_feedback=on_true_feedback, \ on_false_feedback=on_false_feedback, on_false_action_kws=on_false_action_kws) self.widget = widgets.ToggleButton(layout=layout, indent=indent, *args, **kwargs) if run: self.run()
def SimpleClickProceedSettings(FunctionToProceed): # Toggle button button = widgets.ToggleButton(description="Proceed", button_style='warning', disabled=False, value=False) def on_button_clicked(args, FunctionToProceed): if args['new'] == True: # changing colour and description button.close() # Function called to be done every time settings are locked FunctionToProceed button.observe(on_button_clicked(FunctionToProceed), 'value') display(button)
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 make_test_selector(return_button=False): """ Displays or returns the button for selecting whether we are running on test or live data :return: """ def get_description(): return 'TEST' if environment.CONFIG.is_test else 'LIVE' def get_icons(): return ['check', ''] if environment.CONFIG.is_test else ['', 'check'] def get_style(): return 'success' if environment.CONFIG.is_test else 'warning' def get_value(): return environment.CONFIG.is_test def get_tooltip(): return "Click to set to {}".format( "TEST" if not environment.CONFIG.is_test else 'LIVE') b = widgets.ToggleButton(value=get_value(), description=get_description(), button_style=get_style(), tooltip=get_tooltip()) if return_button is True: # If putting inside a box or something else which will # call display return b else: display(b) def callback(j): if not j.new: environment.CONFIG.set_live() if j.new: environment.CONFIG.set_test() b.icons = get_icons() b.button_style = get_style() b.value = get_value() b.description = get_description() b.tooltip = get_tooltip() b.observe(callback, names='value')
def get_widgets_per_param(params): for key, value in params.items(): style = {'description_width': 'initial'} description = key.split("__")[1] if "__" in key else key if isinstance(value, float): yield (key, widgets.FloatText(value=value, step=0.05, description=description, continuous_update=False, disabled=False, layout=Layout(width="90%"), style=style)) elif isinstance(value, bool): yield (key, widgets.ToggleButton(value=value, description=description, disabled=False, layout=Layout(width="90%"), style=style)) elif isinstance(value, int): yield (key, widgets.IntText(value=value, step=1, description=description, continuous_update=False, disabled=False, layout=Layout(width="90%"), style=style)) elif isinstance(value, str): yield (key, widgets.Text(value=value, description=description, continuous_update=False, disabled=False, layout=Layout(width="90%"), style=style))
def manifold_control(manifold, button_col='name'): def on_clicked(b): if b.new == True: # keep this (b.new == True) manifold.depressurize(b.owner.valve) elif b.new == False: # keep this (b.new == False) manifold.pressurize(b.owner.valve) else: pass def sync(b): for button in button_list: button.value = manifold.read_valve(button.valve) button_list = [] for i in range(48): desc = '{} . . . {}'.format(i, manifold.valvemap[button_col][i]) button_list.append( widgets.ToggleButton( valve=i, description=desc, value=manifold.read_valve(i), button_style='' # 'success', 'info', 'warning', 'danger' or '' )) for button in button_list: button.observe(on_clicked) bank_list = [] for i in range(0, 48, 8): bank_list.append( widgets.VBox(button_list[i:i + 8][::-1]) ) sync_button = widgets.Button(icon='fa-retweet', button_style='success', layout=widgets.Layout(width='40px')) sync_button.on_click(sync) display.display(widgets.HBox(bank_list + [sync_button])) display.display(widgets.Label('Dark = De-Pressurized / Open', layout=widgets.Layout(width='300px')))
def slider(self, figsize=(10, 10), **kw): """ Navigate the simulation using a slider Parameters : ------------ figsize: tuple Size of the figures kw: dict Extra arguments to pass to matplotlib's imshow """ # ----------------------- # Define useful functions # ----------------------- def refresh_field(force=False): "Refresh the current field figure" # Determine whether to do the refresh do_refresh = False if (self.avail_fields is not None): if force == True or fld_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: 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 == True: 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(force=False): "Refresh the current particle figure" # Determine whether to do the refresh do_refresh = False if self.avail_species is not None: if force == True or ptcl_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: 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 == True: 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) 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) def refresh_ptcl_now(b): "Refresh the particles immediately" refresh_ptcl(force=True) def refresh_fld_now(b): "Refresh the fields immediately" refresh_field(force=True) def change_t(name, value): "Plot the result at the required time" self.current_t = 1.e-15 * value 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: print("Reached last iteration.") 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: print("Reached first iteration.") 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.on_trait_change(change_t, 'value') # Forward button button_p = widgets.Button(description="+") button_p.on_click(step_fw) # Backward button button_m = widgets.Button(description="-") 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.on_trait_change(refresh_field) # Coord button if self.geometry == "thetaMode": coord_button = widgets.ToggleButtons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in ["2dcartesian", "3dcartesian"]: coord_button = widgets.ToggleButtons(description='Coord:', options=['x', 'y', 'z']) coord_button.on_trait_change(refresh_field) # Mode and theta button (for thetaMode) mode_button = widgets.ToggleButtons(description='Mode:', options=self.avail_circ_modes) mode_button.on_trait_change(refresh_field) theta_button = widgets.FloatSlider(width=140, value=0., description=r'Theta:', min=-math.pi / 2, max=math.pi / 2) theta_button.on_trait_change(refresh_field) # Slicing buttons (for 3D) slicing_dir_button = widgets.ToggleButtons( value='y', description='Slicing direction:', options=['x', 'y', 'z']) slicing_dir_button.on_trait_change(refresh_field) slicing_button = widgets.FloatSlider(width=150, description='Slicing:', min=-1., max=1., value=0.) slicing_button.on_trait_change(refresh_field) # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(description='Figure ', value=0, width=50) # Range of values fld_range_button = widgets.FloatRangeSlider(min=-10, max=10, width=220) fld_range_button.on_trait_change(refresh_field) # Order of magnitude fld_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) fld_magnitude_button.on_trait_change(refresh_field) # Use button fld_use_button = widgets.Checkbox(description=' Use this range', value=False) fld_use_button.on_trait_change(refresh_field) # Colormap button fld_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='jet') fld_color_button.on_trait_change(refresh_field) # 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(refresh_fld_now) # Containers # ---------- # Field type container if self.geometry == "thetaMode": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, mode_button, theta_button ]) elif self.geometry == "2dcartesian": container_fields = widgets.VBox( width=260, children=[fieldtype_button, coord_button]) elif self.geometry == "3dcartesian": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, slicing_dir_button, slicing_button ]) # Plotting options container container_fld_plots = widgets.VBox(width=260, children=[ fld_figure_button, fld_range_button, widgets.HBox(children=[ fld_magnitude_button, fld_use_button ], height=50), fld_color_button ]) # 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( width=300, children=[ accord1, widgets.HBox( children=[fld_refresh_toggle, fld_refresh_button]) ]) # Particle widgets # ---------------- if (self.avail_species is not None): # Particle quantities # ------------------- # Species selection ptcl_species_button = widgets.Dropdown(width=250, options=self.avail_species) ptcl_species_button.on_trait_change(refresh_ptcl) # Remove charge and mass (less interesting) avail_ptcl_quantities = [ q for q in self.avail_ptcl_quantities \ if (q in ['charge', 'mass'])==False ] # Particle quantity on the x axis ptcl_xaxis_button = widgets.ToggleButtons( value='z', options=avail_ptcl_quantities) ptcl_xaxis_button.on_trait_change(refresh_ptcl) # Particle quantity on the y axis ptcl_yaxis_button = widgets.ToggleButtons( value='x', options=avail_ptcl_quantities + ['None']) ptcl_yaxis_button.on_trait_change(refresh_ptcl) # Particle selection # ------------------ # 3 selection rules at maximum ptcl_select_widget = ParticleSelectWidget(3, avail_ptcl_quantities, refresh_ptcl) # Plotting options # ---------------- # Figure number ptcl_figure_button = widgets.IntText(description='Figure ', value=1, width=50) # Number of bins ptcl_bins_button = widgets.IntSlider(description='nbins:', min=50, max=300, value=100, width=150) ptcl_bins_button.on_trait_change(refresh_ptcl) # Colormap button ptcl_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='Blues') ptcl_color_button.on_trait_change(refresh_ptcl) # Range of values ptcl_range_button = widgets.FloatRangeSlider(min=0, max=10, width=220, value=(0, 5)) ptcl_range_button.on_trait_change(refresh_ptcl) # Order of magnitude ptcl_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) ptcl_magnitude_button.on_trait_change(refresh_ptcl) # Use button ptcl_use_button = widgets.Checkbox(description=' Use this range', value=False) ptcl_use_button.on_trait_change(refresh_ptcl) # 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(refresh_ptcl_now) # Containers # ---------- # Particle quantity container container_ptcl_quantities = widgets.VBox(width=310, children=[ ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button ]) # Particle selection container container_ptcl_select = ptcl_select_widget.to_container() # Plotting options container container_ptcl_plots = widgets.VBox(width=310, children=[ ptcl_figure_button, ptcl_bins_button, ptcl_range_button, widgets.HBox(children=[ ptcl_magnitude_button, ptcl_use_button ], height=50), ptcl_color_button ]) # 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( width=370, children=[ accord2, widgets.HBox( children=[ptcl_refresh_toggle, ptcl_refresh_button]) ]) # 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 slider(self, figsize=(6, 5), 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 (e.g. cmap, etc.). This will be applied both to the particle plots and field plots. Note that `kw` sets the initial plotting options, but the user can then still modify these options through the slider interface. """ # Check that the dependencies have been installed if not dependencies_installed: raise RuntimeError( "Failed to load the openPMD-viewer slider.\n" "(Make sure that ipywidgets and matplotlib are installed.)") # ----------------------- # 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(): if ipywidgets_version < 7: clear_output() else: import warnings warnings.warn( "\n\nIt seems that you are using ipywidgets 7 and " "`%matplotlib inline`. \nThis can cause issues when " "using `slider`.\nIn order to avoid this, you " "can either:\n- use `%matplotlib notebook`\n- or " "downgrade to ipywidgets 6 (with `pip` or `conda`).", UserWarning) # Handle plotting options kw_fld = kw.copy() vmin, vmax = fld_color_button.get_range() kw_fld['vmin'] = vmin kw_fld['vmax'] = vmax kw_fld['cmap'] = fld_color_button.cmap.value # Determine range of the plot from widgets plot_range = [ fld_hrange_button.get_range(), fld_vrange_button.get_range() ] # Call the method get_field self.get_field(iteration=self.current_iteration, 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, plot_range=plot_range, **kw_fld) 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() # Handle plotting options kw_ptcl = kw.copy() vmin, vmax = ptcl_color_button.get_range() kw_ptcl['vmin'] = vmin kw_ptcl['vmax'] = vmax kw_ptcl['cmap'] = ptcl_color_button.cmap.value # Determine range of the plot from widgets plot_range = [ ptcl_hrange_button.get_range(), ptcl_vrange_button.get_range() ] if ptcl_yaxis_button.value == 'None': # 1D histogram self.get_particle( iteration=self.current_iteration, output=False, var_list=[ptcl_xaxis_button.value], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, nbins=ptcl_bins_button.value, plot_range=plot_range, use_field_mesh=ptcl_use_field_button.value, **kw_ptcl) else: # 2D histogram self.get_particle( iteration=self.current_iteration, 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, nbins=ptcl_bins_button.value, plot_range=plot_range, use_field_mesh=ptcl_use_field_button.value, **kw_ptcl) 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_iteration(change): "Plot the result at the required iteration" # Find the closest iteration self._current_i = abs(self.iterations - change['new']).argmin() self.current_iteration = self.iterations[self._current_i] refresh_field() refresh_ptcl() def step_fw(b): "Plot the result one iteration further" if self._current_i < len(self.t) - 1: self.current_iteration = self.iterations[self._current_i + 1] else: self.current_iteration = self.iterations[self._current_i] slider.value = self.current_iteration def step_bw(b): "Plot the result one iteration before" if self._current_i > 0: self.current_iteration = self.iterations[self._current_i - 1] else: self.current_iteration = self.iterations[self._current_i] slider.value = self.current_iteration # --------------- # Define widgets # --------------- # Slider iteration_min = self.iterations.min() iteration_max = self.iterations.max() step = max(int((iteration_max - iteration_min) / 20.), 1) slider = widgets.IntSlider(description="iteration", min=iteration_min, max=iteration_max + step, step=step) slider.observe(change_iteration, 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 = create_toggle_buttons( description='Field:', options=sorted(self.avail_fields.keys())) fieldtype_button.observe(refresh_field_type, 'value', 'change') # Coord button if self.geometry == "thetaMode": coord_button = create_toggle_buttons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in \ ["1dcartesian", "2dcartesian", "3dcartesian"]: coord_button = create_toggle_buttons(description='Coord:', options=['x', 'y', 'z']) coord_button.observe(refresh_field, 'value', 'change') # Mode and theta button (for thetaMode) mode_button = create_toggle_buttons(description='Mode:', options=self.avail_circ_modes) mode_button.observe(refresh_field, 'value', 'change') theta_button = widgets.FloatSlider(value=0., min=-math.pi / 2, max=math.pi / 2) set_widget_dimensions(theta_button, width=190) theta_button.observe(refresh_field, 'value', 'change') # Slicing buttons (for 3D) slicing_dir_button = create_toggle_buttons( value=self.axis_labels[0], options=self.axis_labels, description='Slice normal:') slicing_dir_button.observe(refresh_field, 'value', 'change') slicing_button = widgets.FloatSlider(min=-1., max=1., value=0.) set_widget_dimensions(slicing_button, width=180) slicing_button.observe(refresh_field, 'value', 'change') # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(value=0) set_widget_dimensions(fld_figure_button, width=50) # Colormap button fld_color_button = ColorBarSelector( refresh_field, default_cmap=kw.get('cmap', 'viridis'), default_vmin=kw.get('vmin', -5.e9), default_vmax=kw.get('vmax', 5.e9)) # Range buttons fld_hrange_button = RangeSelector(refresh_field, default_value=10., title='Horizontal axis:') fld_vrange_button = RangeSelector(refresh_field, default_value=10., title='Vertical axis:') # Refresh 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, add_description('Theta:', 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, add_description("Slicing:", slicing_button) ]) set_widget_dimensions(container_fields, width=330) # Plotting options container container_fld_cbar = fld_color_button.to_container() container_fld_hrange = fld_hrange_button.to_container() container_fld_vrange = fld_vrange_button.to_container() if self.geometry == "1dcartesian": container_fld_plots = widgets.VBox(children=[ add_description("<b>Figure:</b>", fld_figure_button), container_fld_vrange, container_fld_hrange ]) else: container_fld_plots = widgets.VBox(children=[ add_description("<b>Figure:</b>", fld_figure_button), container_fld_cbar, container_fld_vrange, container_fld_hrange ]) set_widget_dimensions(container_fld_plots, width=330) # 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=370) # 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 = create_toggle_buttons(options=avail_records) ptcl_xaxis_button.observe(refresh_ptcl, 'value', 'change') # Particle quantity on the y axis ptcl_yaxis_button = create_toggle_buttons(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(value=1) set_widget_dimensions(ptcl_figure_button, width=50) # Number of bins ptcl_bins_button = widgets.IntText(value=100) set_widget_dimensions(ptcl_bins_button, width=60) ptcl_bins_button.observe(refresh_ptcl, 'value', 'change') # Colormap button ptcl_color_button = ColorBarSelector( refresh_ptcl, default_cmap=kw.get('cmap', 'Blues'), default_vmin=kw.get('vmin', -5.e9), default_vmax=kw.get('vmax', 5.e9)) # Range buttons ptcl_hrange_button = RangeSelector(refresh_ptcl, default_value=10., title='Horizontal axis:') ptcl_vrange_button = RangeSelector(refresh_ptcl, default_value=10., title='Vertical axis:') # Use field mesh buttons ptcl_use_field_button = widgets.ToggleButton( description=' Use field mesh', value=True) 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_fig = widgets.HBox(children=[ add_description("<b>Figure:</b>", ptcl_figure_button), add_description("Bins:", ptcl_bins_button) ]) container_ptcl_cbar = ptcl_color_button.to_container() container_ptcl_hrange = ptcl_hrange_button.to_container() container_ptcl_vrange = ptcl_vrange_button.to_container() container_ptcl_plots = widgets.VBox(children=[ container_ptcl_fig, container_ptcl_cbar, container_ptcl_vrange, container_ptcl_hrange, ptcl_use_field_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)
from ipywidgets import widgets, interact, interactive from IPython.display import display initial_age = widgets.IntSlider(value=50, min=25, max=100, step=1, description='Age:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='i', slider_color='white') run = widgets.ToggleButton( value=False, description='Run model', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Description', icon='check')
def plotLevelSubsystems(Model, graph_reactions, fig_dpi=100): """ Computes the frequencies of the subsystems of the reactions appearing in the specified graph level which have the specified macrosystem """ GEM = Model.GEM macrosystems = [ 'Amino acid metabolism', 'Carbohydrate metabolism', 'Cell wall biosynthesis', 'Cofactor and vitamin metabolism', 'Energy and maintenance', 'Lipid metabolism', 'Nucleotide metabolism', 'Transport' ] macrosystem_frequencies_per_level = getSystemDistributionPerGraphLevel( GEM, graph_reactions, 'macrosystem') macrosystem_frequencies_across_levels = getSystemDistributionAcrossGraphLevels( GEM, graph_reactions, 'macrosystem') def plot_func(macrosystem, macro_freq_type, level_number, save_fig): if macro_freq_type > 0: macro_frequencies = macrosystem_frequencies_per_level ylabel = 'frequency in level' else: macro_frequencies = macrosystem_frequencies_across_levels ylabel = 'frequency' total_subsystems = {} level_reactions = graph_reactions[level_number] fig, axs = plt.subplots(nrows=2, ncols=1, sharex=False, sharey=False, figsize=(14, 12)) plt.subplots_adjust(wspace=None, hspace=0.3) # Plot macrosystems df1 = pd.DataFrame.from_dict(macro_frequencies[macrosystem]) ax1 = df1.plot.bar(ax=axs[0], rot=0, fontsize=12) for p in ax1.patches: height = round(p.get_height(), 2) if height > 0: ax1.annotate(format(height, '.2f'), (p.get_x() * 1.005, p.get_height() * 1.008)) axs[0].set_title(macrosystem, fontsize=16) axs[0].set_ylabel(ylabel) axs[0].set_xlabel('graph level') # Plot subsystems for source in level_reactions.keys(): subsystems = extractMetabolicSystems(GEM, level_reactions[source], 'subsystem', macrosystem) total_subsystems[source] = getListFrequencies(subsystems) df2 = pd.DataFrame( dict([(k, pd.Series(v)) for k, v in total_subsystems.items()])) try: df2.plot(ax=axs[1], kind='bar', rot=75, fontsize=12) axs[1].set_title('Subsystems in level ' + str(level_number), fontsize=16) axs[1].set_ylabel('frequency') except Exception: axs[1].set_title('No data available', fontsize=16) if save_fig: plt.savefig('figure.png', dpi=fig_dpi, bbox_inches="tight") interact(plot_func, macrosystem=macrosystems, macro_freq_type=widgets.Dropdown(options=[('across graph levels', 0), ('per graph level', 1)], value=0, description='frequency'), level_number=widgets.IntSlider(value=0, min=0, max=20, step=1, description='graph level', readout=True), save_fig=widgets.ToggleButton( value=False, description='Save figure', disabled=False, layout=widgets.Layout(margin='3% 0 3% 8%')))
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 __init__(self, start, next_frame, L=8): self.start = start self.next_frame = next_frame self.L = L self.screen = Screen((400, 400), L=L) layout = self.screen._layout controller = {} controller['blank'] = widgets.ToggleButton(description='', button_style='', layout=layout) controller['up'] = widgets.ToggleButton(description='▲', button_style='', layout=layout) controller['down'] = widgets.ToggleButton(description='▼', button_style='', layout=layout) controller['left'] = widgets.ToggleButton(description='◀︎', button_style='', layout=layout) controller['right'] = widgets.ToggleButton(description='►', button_style='', layout=layout) controller['A'] = widgets.ToggleButton(description='A', button_style='', layout=layout) controller['B'] = widgets.ToggleButton(description='B', button_style='', layout=layout) controller['X'] = widgets.ToggleButton(description='X', button_style='', layout=layout) controller['Y'] = widgets.ToggleButton(description='Y', button_style='', layout=layout) controller['next'] = widgets.ToggleButton( description='Next', button_style='', layout=self.screen._wide_layout) [b, u, d, l, r, A, B, X, Y, c] = [ controller['blank'], controller['up'], controller['down'], controller['left'], controller['right'], controller['A'], controller['B'], controller['X'], controller['Y'], controller['next'] ] interface = [] interface.append( widgets.HBox([self.screen.pixel[x, 0]._button for x in range(L)] + [b, u, b, b, b, X, b])) interface.append( widgets.HBox([self.screen.pixel[x, 1]._button for x in range(L)] + [l, b, r, b, Y, b, A])) interface.append( widgets.HBox([self.screen.pixel[x, 2]._button for x in range(L)] + [b, d, b, b, b, B, b])) interface.append( widgets.HBox([self.screen.pixel[x, 3]._button for x in range(L)] + [c])) for y in range(4, L): interface.append( widgets.HBox( [self.screen.pixel[x, y]._button for x in range(L)])) interface.append(self.screen.pixel['text']._button) self.controller = controller start(self) display(widgets.VBox(interface)) b.observe(self.given_blank) for button in self.controller: if button != 'blank': self.controller[button].observe(self.given_button)
def build_widget(self): from ipywidgets import widgets start, end = self.experiment.usable_replay_range options = [] current = start while current <= end: # Never display microseconds options.append((current.replace(microsecond=0).time().isoformat(), current)) current += datetime.timedelta(seconds=1) # But we need to keep microseconds in the first value, so we don't go before # the experiment start when scrubbing backwards current = current.replace(microsecond=0) scrubber = widgets.SelectionSlider( description="Current time", options=options, disabled=False, continuous_update=False, ) def advance(change): if self.realtime: # We're being driven in realtime, the advancement # here is just to keep the UI in sync return old_status = self.experiment.widget.status self.experiment.widget.status = "Updating" self.experiment.widget.render() self(change["new"]) self.experiment.widget.status = old_status self.experiment.widget.render() scrubber.observe(advance, "value") def realtime_callback(): self.experiment.widget.render() try: scrubber.value = self.experiment._replay_time_index.replace( microsecond=0 ) except Exception: # The scrubber is an approximation of the current time, we shouldn't # bail out if it can't be updated (for example at experiment bounds) pass if not self.realtime: raise StopIteration() play_button = widgets.ToggleButton( value=False, description="", disabled=False, tooltip="Play back in realtime", icon="play", ) def playback(change): import threading if change["new"]: thread = threading.Thread( target=self.in_realtime, kwargs={"callback": realtime_callback} ) thread.start() else: self.realtime = False play_button.observe(playback, "value") self.widget = widgets.HBox(children=[scrubber, play_button]) return self.widget
from ipywidgets import widgets from ipywidgets import Layout, HBox, VBox from IPython.display import display with open('input.txt', 'w') as file: file.write('') b = widgets.ToggleButton(description='', button_style='', layout=Layout(width='50px', height='50px')) u = widgets.ToggleButton(description='▲', button_style='', layout=Layout(width='50px', height='50px')) d = widgets.ToggleButton(description='▼', button_style='', layout=Layout(width='50px', height='50px')) l = widgets.ToggleButton(description='◀︎', button_style='', layout=Layout(width='50px', height='50px')) r = widgets.ToggleButton(description='►', button_style='', layout=Layout(width='50px', height='50px')) o = widgets.ToggleButton(description='O', button_style='', layout=Layout(width='50px', height='50px')) x = widgets.ToggleButton(description='X', button_style='', layout=Layout(width='50px', height='50px')) line = [] line.append(widgets.HBox([b, u, b, b, b, o]))
primary_y = widgets.Dropdown( options=df_column_list ) secondary_y = widgets.Dropdown( options=df_column_list ) container2 = widgets.HBox([primary_y, secondary_y]) logger.debug("gset up widgets - row 3") add_ticker_name = widgets.Text( description="New ticker:" ) add_ticker_button = widgets.ToggleButton( value=False, description='Add Ticker', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Description', icon='plus' ) container3 = widgets.HBox([add_ticker_name, add_ticker_button]) # Assign an empty figure widget with two traces trace0 = go.Scatter( x=df.index, y=df[primary_y.value], opacity=0.75, name=primary_y.value, line={"dash": "solid"} )
def add_toggle(desc): return widgets.ToggleButton(description=desc,layout=widgets.Layout(width='auto'),disabled=False)
def old_initiate(self): tab_children = [] ########################### # data 1 box d1_vbox_childs = [] ## ### d1_button_next = widgets.Button(description='next measurement') d1_button_prev = widgets.Button(description='prev measurement') d1_button_next.on_click(self.on_d1_botton_next) d1_button_prev.on_click(self.on_d1_botton_prev) d1_box_h_1 = widgets.HBox([d1_button_prev, d1_button_next]) ### d1_vbox_childs.append(d1_box_h_1) ## ### d1_text_path = widgets.Text(placeholder='path name', disabled=False) self.d1_text_path = d1_text_path d1_vbox_childs.append(d1_text_path) ## d1_vbox = widgets.VBox(d1_vbox_childs) tab_children.append({'element': d1_vbox, 'title': 'iMet'}) ############################ # data 2 box d2_vbox_childs = [] ## ### d2_button_next = widgets.Button(description='next measurement') d2_button_prev = widgets.Button(description='prev measurement') self.d2_dropdown_fnames = widgets.Dropdown( options=[ 1 ], #[i.name for i in self.controller.data.dataset2.path2data_list], value=1, #self.controller.data.dataset2.path2active.name, # description='N', disabled=False, ) d2_button_next.on_click(self.on_d2_botton_next) d2_button_prev.on_click(self.on_d2_botton_prev) self.d2_dropdown_fnames.observe(self.on_change_d2_dropdown_fnames) d2_box_h_1 = widgets.HBox( [d2_button_prev, d2_button_next, self.d2_dropdown_fnames]) ### d2_vbox_childs.append(d2_box_h_1) ## ### # text field showing the path d2_text_path = widgets.Text(placeholder='path name', disabled=False) self.d2_text_path = d2_text_path d2_vbox_childs.append(d2_text_path) ## d2_vbox = widgets.VBox(d2_vbox_childs) tab_children.append({'element': d2_vbox, 'title': 'POPS'}) # others box # Tab tab = widgets.Tab([child['element'] for child in tab_children]) for e, child in enumerate(tab_children): tab.set_title(e, child['title']) # accordeon self.accordeon_assigned = widgets.Valid( value=False, description='bound?', ) self.dropdown_popssn = widgets.Dropdown( options=['00', '14', '18'], # value='2', description='popssn', disabled=False, ) self.inttext_deltat = widgets.IntText(value=0, description='deltat', disabled=False) self.inttext_deltat.observe(self.on_inttext_deltat) self.dropdown_gps_bar_bad = widgets.Dropdown( options=[ 'gps', 'baro', 'bad', 'bad_but_usable_gps', 'bad_but_usable_baro' ], value='gps', description='which alt to use:', disabled=False, ) self.button_bind_measurements = widgets.ToggleButton( description='bind/unbind measurements') # button_bind_measurements.on_click(self.deprecated_on_button_bind_measurements) self.button_bind_measurements.observe(self.on_button_bind_measurements) accordon_box = widgets.VBox([ self.accordeon_assigned, self.dropdown_popssn, self.inttext_deltat, self.dropdown_gps_bar_bad, self.button_bind_measurements ]) accordion_children = [accordon_box] accordion = widgets.Accordion(children=accordion_children) accordion.set_title(0, 'do_stuff') # messages self.messages = widgets.Textarea('\n'.join(self.controller._message), layout={'width': '100%'}) # message_box = widgets.HBox([self.messages]) # OverVbox overVbox = widgets.VBox([tab, accordion, self.messages]) display(overVbox) #################### self.update_d1() self.update_d2() self.update_accordeon()
def __init__(self, grade_postfixes={"+": -0.3, "-": 0.3}, debug=False): self.file_chooser = FileChooser(str(Path("~").expanduser().resolve()), "") self.path = None self.ignore_cell_edited = False self.grade_postfixes = grade_postfixes self._undo = [] self._redo = [] self._students_fixed_cols = 4 self.debug = debug events = [ "cell_edited", "row_added", "row_removed", ] all_events = [ "instance_created", "cell_edited", "selection_changed", "viewport_changed", "row_added", "row_removed", "filter_dropdown_shown", "filter_changed", "sort_changed", "text_filter_viewport_changed", "json_updated", ] self.file_chooser.register_callback(self.selected_file_changed) self.grid_tasks = qgrid.show_grid( pd.DataFrame(data=dict(Task=["Task 1"], Points=[10])), show_toolbar=True, grid_options=dict( maxVisibleRows=50, minVisibleRows=2, sortable=False, filterable=False, autoEdit=True, enableColumnReorder=False, ), ) self.grid_tasks.on(events, self.tasks_changed) self.grid_tasks.on(["selection_changed", "row_removed"], self.select_last_row) self.grid_students = qgrid.show_grid( pd.DataFrame( data={ "Student": ["Student A"], "Grade": ["4"], "Adjustment": [0], "Total": ["5 (50%)"], "Task 1": [5.0], }), show_toolbar=True, grid_options=dict( maxVisibleRows=50, minVisibleRows=2, sortable=False, filterable=False, autoEdit=True, enableColumnReorder=False, column_definitions={"Total": dict(editable=False)}, ), ) self.grid_students.on(events, self.students_changed) self.grid_students.on(["selection_changed", "row_removed"], self.select_last_row) self.grid_grades = qgrid.show_grid( pd.DataFrame( data={ "Grade": ["1", "2", "3", "4", "5", "6"], "Min Percentage": [85, 70, 55, 40, 20, 0], "Min Points": [8.5, 7, 5.5, 4, 2, 0], "Min Points": [10, 8, 6.5, 5, 3.5, 1.5], }), show_toolbar=True, grid_options=dict( maxVisibleRows=50, minVisibleRows=2, sortable=False, filterable=False, autoEdit=True, enableColumnReorder=False, ), ) self.grid_grades.on(events, self.grades_changed) self.grid_grades.on(["selection_changed", "row_removed"], self.select_last_row) self.grid_score = qgrid.show_grid( pd.DataFrame(data={ "Grade": [], "Amount": [], "Students": [] }), show_toolbar=False, grid_options=dict( maxVisibleRows=50, minVisibleRows=2, sortable=False, filterable=False, autoEdit=False, editable=False, enableColumnReorder=False, ), ) self.grid_points = qgrid.show_grid( pd.DataFrame(data={ "Points": [], "Grade": [], "Amount": [], "Students": [] }), show_toolbar=False, grid_options=dict( maxVisibleRows=50, minVisibleRows=2, sortable=False, filterable=False, autoEdit=False, editable=False, enableColumnReorder=False, ), ) self.output_text = widgets.Output(layout={"border": "1px solid black"}) self.output_plot_score = widgets.Output() self.output_info = widgets.Output() self.button_undo = Button(description="Undo") self.button_redo = Button(description="Redo") self.button_save = Button(description="Save") self.button_load = Button(description="Load") self.button_autosave = widgets.ToggleButton( value=True, description="Autosave enabled", button_style="success", tooltip="Toggles the automatic save feature upon changes.", ) self.button_update = widgets.ToggleButton( value=True, description="Updating enabled", button_style="success", tooltip= "Toggles the automatic recalculation when editing cells in the table. These auto updates might be annoying when trying to edit multiple data fields.", ) self.button_postfix = widgets.ToggleButton( value=False, description="Drop Postfix", disabled=False, button_style="info", # 'success', 'info', 'warning', 'danger' or '' tooltip= "Wether or not the grade overview and plot will aggregate grades with different postfixes into one grade. E.g. the grades '2-','2','2+' will all be shown as '2'.", icon="times", # (FontAwesome names without the `fa-` prefix) ) self.passed_perc = widgets.FloatText(value=40, description="Passed:", disabled=False) self.button_save.on_click(self.click_save) self.button_load.on_click(self.click_load) self.button_undo.on_click(self.click_undo) self.button_redo.on_click(self.click_redo) self.button_autosave.observe(self.switch_autosave) self.button_update.observe(self.switch_disable_update) self.button_postfix.observe(self.switch_aggregate_postfix) self.passed_perc.observe(self.passed_percentage_changed) self.button_bar_files = HBox([ self.button_save, self.button_load, self.button_autosave, ]) self.button_bar_other = HBox([ self.button_undo, self.button_redo, self.button_update, self.button_postfix, self.passed_perc, widgets.Label(value="%"), ]) result = None if self.path is not None: result = self.load() if not result: self.recalculate_totals()
def init(*args, **kwargs): global flag, downflag, shiftflag w = widgets.Image(value=m.system.image_data(), width=600) d = Event(source=w, watched_events=[ 'mousedown', 'mouseup', 'mousemove', 'keyup', 'keydown', 'wheel' ]) no_drag = Event(source=w, watched_events=['dragstart'], prevent_default_action=True) d.on_dom_event(listen_mouse) run = widgets.ToggleButton( value=False, description='Run', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='run the simulation', icon='play') pause = widgets.ToggleButton( value=False, description='Pause', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='pause the simulation', icon='pause') reset = widgets.ToggleButton( value=False, description='Reset', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='reset the simulation', icon='stop') def onToggleRun(b): global flag if run.value: run.button_style = 'success' pause.value = False pause.button_style = '' reset.value = False reset.button_style = '' flag = True else: run.button_style = '' flag = False def onTogglePause(b): global flag if pause.value: pause.button_style = 'success' run.value = False run.button_style = '' reset.value = False reset.button_style = '' flag = False else: pause.button_style = '' flag = True def onToggleReset(b): global flag if reset.value: reset.button_style = 'success' pause.value = False pause.button_style = '' run.value = False run.button_style = '' flag = False m.Universe.reset() else: reset.button_style = '' #w = create_simulation() buttons = widgets.HBox([run, pause, reset]) run.observe(onToggleRun, 'value') pause.observe(onTogglePause, 'value') reset.observe(onToggleReset, 'value') box = widgets.VBox([w, buttons]) display(box) def background_threading(): global flag while True: m.Simulator.context_make_current() if flag: m.step() w.value = m.system.image_data() m.Simulator.context_release() time.sleep(0.01) t = threading.Thread(target=background_threading) t.start()
def __init__(self, layout): self._button = widgets.ToggleButton(description='', button_style='', layout=layout, disabled=True)