def _interact_aux(self, options, name, f): select = widgets.SelectionSlider(options=options, value=options[-1], description=name, continuous_update=True, orientation='horizontal') ipywidgets.interact(f, t=select, name=ipywidgets.fixed(name))
def build_widget(self): from ipywidgets import widgets start, end = self.experiment._replay_range options = [] current = start while current <= end: options.append( (current.replace(microsecond=0).time().isoformat(), current)) current += datetime.timedelta(seconds=1) scrubber = widgets.SelectionSlider( description='Current time', options=options, disabled=False, continuous_update=False, ) def advance(change): 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') self.widget = scrubber return scrubber
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.SelectionSlider(*args, **kwargs) if run: self.run()
def plot_table_2d(table, figsize=None): """ Plot table with 2-dimensional domain Parameters ---------- table: geology.src.tables.tables._Table Table to be plotted figsize: tuple """ domain_names = list(table.domain) domain0_value_widget = widgets.SelectionSlider( description=domain_names[0], options=list(sorted(set(table.index.get_level_values(0))))) def update(domain0_value): cropped_table = table.loc[table.index.get_level_values(0) == domain0_value] cropped_table = cropped_table.droplevel(0) cropped_table.domain = [domain_names[1]] plot_table_1d(cropped_table, figsize) interact(update, domain0_value=domain0_value_widget)
dd['res'] = wdg.Dropdown( options=['Norm/Hold', 'Norm/Auto', 'Mid', 'High 1', 'High 2', 'High 3'], description='Resolution:') 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=Bdwt_val.values(), continuous_update=False) dd['bandwidth'].add_class("osa_bandwidth") dd['clr'] = wdg.Button( description='Clear Trace', button_style='info', tooltip='Click me', ) dd['clr'].add_class("osa_clear") dd['save'] = wdg.Button(description='Save Spectra', button_style='info') dd['save'].add_class("osa_save") dd['picker'] = FileChooser('./../') dd['picker'].use_dir_icons = True dd['picker'].rows = 5 dd['picker'].width = 200
def defaultWidgets(**kwargs): #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ proj_vars = [ 'absGenJet2p5Rapidity0', 'absGenJet2p5Rapidity1', 'absGenJet2p5Rapidity2', 'absGenJet2p5Rapidity3', 'absGenRapidity', 'genJet2p5Pt0', 'genJet2p5Pt1', 'genJet2p5Pt2', 'genJet2p5Pt3', 'genPt' ] proj_keys = [ '|y| leading jet', '|y| subleading jet', '|y| 3rd leading jet', '|y| 4th leading jet', '|y| di-photon', 'pt leading jet', 'pt subleading jet', 'pt 3rd leading jet', 'pt 4th leading jet', 'pt di-photon' ] proj_var_dict = OrderedDict(zip(proj_keys, proj_vars)) #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ widgetparams['w_inputDir'] = widgets.Text( value='./classifiers', placeholder='directory to the classifiers', description='inputDir:', disabled=False, ) widgetparams['w_dataDir'] = widgets.Text( value='./data', placeholder='directory to data files', description='dataDir:', disabled=False) #widgetparams['w_inputName'] = widgets.Dropdown( # description='Classifier:', # options=class_dict, # ) widgetparams['w_Load'] = widgets.Checkbox(value=False, description='Load classifier', disabled=False) widgetparams['w_varName_x'] = widgets.Dropdown(options=proj_var_dict, description='x-axis:') widgetparams['w_varName_y'] = widgets.Dropdown( options=proj_var_dict, description='y-axis:', ) widgetparams['w_mres_cat'] = widgets.ToggleButtons( options={ 'good': 0, 'medium': 1, 'bad': 2 }, description='Di-photon mass resolution:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Description', ) widgetparams['w_noJets'] = widgets.SelectionSlider( options=OrderedDict(zip(['0', '1', '2', '3', '>3'], [0, 1, 2, 3, 4])), description='Number of jets:', ) widgetparams['w_detector_eff'] = widgets.Checkbox( value=False, description='detector efficiency', disabled=False) widgetparams['w_prodProc'] = widgets.SelectMultiple( options={ 'ggF': 0, 'ttH': 1, 'VBF': 2, 'VH': 3 }, #value=['ggF','ttH','VBF','VH'], description='production process', disabled=False)
def __init__(self, plot_mpl_cls, run_dir_options=None, fig=None, output_widget=None, **kwargs): """ Parameters ---------- run_dir_options: list list of tuples with label and filepath plot_mpl_cls: a valid plot_mpl class handle (not string!) Specifies the underlying plot_mpl visualizer that will be used. fig: a matplotlib figure instance.(optional) If no figure is provided, the widget will create its own figure. Otherwise the widget will draw into the provided figure and will not create its own. output_widget: None or instance of ipywidgets.Output used for capturing messages from the visualizers. If None, a new output widget is created and displayed as a child. If not None, it is not displayed but only used for capturing output and the owner of the output is responsible for displaying it. kwargs: options for plotting, passed on to matplotlib commands. """ widgets.VBox.__init__(self) if output_widget is not None: # for a given output widget we don't add # it to the children but rely on the owner # of the widget to display it somewhere assert isinstance(output_widget, widgets.Output) add_out_to_children = False else: output_widget = widgets.Output( layout={'border': '1px solid black'}) add_out_to_children = True self.output_widget = output_widget # if no figure is given, we create one and add it to children # if one is given, we don't add it as part of children add_fig_to_children = fig is None # setting of figure and ax self.fig = None self.ax = None self._init_fig_and_ax(fig, **kwargs) # create the PIConGPU visualizer instance but do not set # any run directories yet self.plot_mpl = plot_mpl_cls(None, ax=self.ax) self.label_path_lut = None self._create_label_path_lookup(run_dir_options) # widgets for selecting the simulation and the simulation step # dependent on the derived class which widget it should be # use the simulation labels of the plot_mpl visualizer from picongpu self.sim_drop = self._create_sim_dropdown( sorted(list(self.label_path_lut.keys()))) self.sim_drop.observe(self._handle_run_dir_selection_callback, names='value') self.sim_time_slider = widgets.SelectionSlider( description='Time [s]', options=[""], continuous_update=False, # layout=widgets.Layout(width='65%', height='10%')) ) self.sim_time_slider.observe(self._visualize_callback, names='value') # widgets that this specific widget might need # to expose the parameters of the plot_mpl object. self.widgets_for_vis_args = \ self._create_widgets_for_vis_args() # Its changes will result in changes to the plot for _, widg in self.widgets_for_vis_args.items(): widg.observe(self._visualize_callback, names='value') # register the ui elements that will be displayed # as children of this object. vis_widgets = widgets.VBox(children=[ self.sim_drop, widgets.VBox(children=list(self.widgets_for_vis_args.values())) ]) if add_fig_to_children: top = widgets.HBox(children=[vis_widgets, self.fig.canvas]) else: top = vis_widgets if add_out_to_children: bottom = widgets.VBox( children=[self.sim_time_slider, self.output_widget]) else: bottom = self.sim_time_slider self.children = [top, bottom]
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
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 build_interactive(self, n: int = 0): # get reference dataset d_ref = self.datasets[0] time = np.array(d_ref.axes["time"]) iteration = np.array(d_ref.axes["iteration"]) dropdown = widgets.Dropdown( options=["File Index", "Iteration", "Time"], value="File Index", disabled=False, layout=Layout(max_width="100px"), continuous_update=False, ) slider = widgets.SelectionSlider( options=[f"{i}" for i in np.arange(len(iteration))], value=f"{n}", disabled=False, continuous_update=False, orientation="horizontal", readout=True, ) def dropdown_change(change): if change.old in ["Time", "Iteration"]: options = np.array(slider.options).astype(np.float) n = np.argmax(options >= float(slider.value)).item() else: n = int(slider.value) with out.hold_trait_notifications(): if change.new == "Time": slider.options = [f"{i:.2f}" for i in time] slider.value = f"{time[n]:.2f}" elif change.new == "Iteration": slider.options = [f"{i:d}" for i in iteration] slider.value = f"{iteration[n]:d}" else: slider.options = [ f"{i:n}" for i in np.arange(len(iteration)) ] slider.value = f"{n:d}" dropdown.observe(dropdown_change, names=["value"], type="change") ui = widgets.HBox([dropdown, slider]) def update_figure(sel): if dropdown.value == "Time": n = np.argmax(time >= float(sel)).item() elif dropdown.value == "Iteration": n = np.argmax(iteration >= int(sel)).item() else: n = int(sel) f_a = [] for a in self.axes: a_p = [] for p in a.plots: a_p.append(PlotPlan(dataset=p.dataset[n], style=p.style)) f_a.append(AxesPlan(axes=None, plots=a_p, style=a.style)) f_p = FigurePlan(fig=None, axes=f_a, style=self.style) # build figure fig = f_p.build() return fig.show() out = widgets.interactive_output(update_figure, {"sel": slider}) display(ui, out)
def make_iter_slider(iters): # print(iters) return widgets.SelectionSlider(options=iters, value=1, description='SGD Iterations: ', disabled=False)
## TODO: CLASSify code in these cells. from ipywidgets import ( interact, interactive, interactive_output, fixed, interact_manual, widgets, ) from IPython.display import clear_output init_zoom = 55.0 init_pan = 30.40 max_zoom = 72.0 Case = widgets.SelectionSlider(options=list(c2.index.levels[0]), description="Case") Gear = widgets.SelectionSlider(options=["g1"], description="Gear") Zoom = widgets.FloatSlider(init_zoom, min=1.0, max=max_zoom, step=4.0, description="Zoom") Pan = widgets.FloatSlider(init_pan, min=0.0, max=max_zoom, step=0.4, description="Pan") IsPyAlgoGears = widgets.Checkbox(False, description="Plot PyAlgo Gear flags?") IsAccdbGears = widgets.Checkbox(False, description="Plot AccDB Gear flags?") PyAlgoSignals = widgets.SelectMultiple(rows=7, description="Pyalgo signals") AccDBSignals = widgets.SelectMultiple(rows=7, description="AccDB signals")
def __init__(self): self.fig = plt.figure(figsize=(7, 4)) self.col_ax = self.fig.add_subplot(111) self.m2 = 5 self.v2i = -6 self.m1_selector_widget = widgets.FloatSlider( value=4.0, min=1.0, max=10.0, step=0.1, description='m_1 (kg):', continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) self.m1_selector_widget.observe(self.refresh) self.v1_selector_widget = widgets.FloatSlider( value=6.0, min=1.0, max=10.0, step=0.1, description='v1_init (m/s):', continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) self.v1_selector_widget.observe(self.refresh) self.generate_data() self.sweep_selector = widgets.SelectionSlider( options=[('{:0.2f}'.format(t), i) for i, t in enumerate(sorted(self.ts))], description='time = ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, layout=widgets.Layout(width='60%')) self.sweep_selector.observe(self.redraw) self.play_button = widgets.Button(description='Play') self.play_button.on_click(self.play) self.image_widget = widgets.Image( format='png', width=600, ) self.v1_f_label = widgets.Label(f'v_1f: {self.v1f:0.2f} m/s') self.v2_f_label = widgets.Label(f'v_2f: {self.v2f:0.2f} m/s') self.control_panel = widgets.VBox([ self.image_widget, widgets.VBox([ self.m1_selector_widget, self.v1_selector_widget, ]), widgets.HBox([ self.sweep_selector, self.play_button, ]), widgets.VBox([ self.v1_f_label, self.v2_f_label, ]) ]) self.refresh() self.display_frame(0) self.interact()
def plot_dataset( data, start: int = 0, xrange: Optional[Sequence[Numbers]] = None, yrange: Optional[Sequence[Numbers]] = None, xscale: Optional[Union[Scale, str]] = None, yscale: Optional[Union[Scale, str]] = None, xlabel: Optional[str] = None, ylabel: Optional[str] = None, xticks: Optional[Union[Ticks, Sequence[Numbers]]] = None, yticks: Optional[Union[Ticks, Sequence[Numbers]]] = None, title: Optional[str] = None, aspect: Optional[str] = None, size: Optional[Sequence[Numbers]] = None, theme: Optional[Union[Theme, str]] = None, kind: Optional[PlotKind] = None, ): try: from IPython.display import display from ipywidgets import Layout from ipywidgets import widgets interact = True except ImportError: interact = False if interact: if start not in range(len(data)): raise ValueError("invalid start index") dropdown = widgets.Dropdown( options=["Index", data.time.label], value="Index", disabled=False, layout=Layout(max_width="100px"), continuous_update=False, ) slider = widgets.SelectionSlider( options=[f"{i}" for i in range(len(data))], value=f"{start}", disabled=False, continuous_update=False, orientation="horizontal", readout=True, ) def dropdown_change(change): if change.old in [data.time.label]: options = np.array(slider.options).astype(np.float) n = np.argmax(options >= float(slider.value)).item() else: n = int(slider.value) with out.hold_trait_notifications(): if change.new == data.time.label: slider.options = [f"{i:.2f}" for i in data.time.to_numpy()] slider.value = f"{data.time[n].to_numpy():.2f}" else: slider.options = [f"{i:n}" for i in range(len(data))] slider.value = f"{n:d}" dropdown.observe(dropdown_change, names=["value"], type="change") ui = widgets.HBox([dropdown, slider]) def update_figure(sel): if dropdown.value == data.time.label: n = np.argmax(data.time.to_numpy() >= float(sel)).item() else: n = int(sel) fig = data[n].plot( xrange=xrange, yrange=yrange, xscale=xscale, yscale=yscale, xlabel=xlabel, ylabel=ylabel, xticks=xticks, yticks=yticks, title=title, aspect=aspect, size=size, theme=theme, kind=kind, ) return fig.show() out = widgets.interactive_output(update_figure, {"sel": slider}) display(ui, out) else: warn( "interactivity unavailable, please run `pip install nata[jupyter]`" ) return data[start].plot( xrange=xrange, yrange=yrange, xscale=xscale, yscale=yscale, xlabel=xlabel, ylabel=ylabel, xticks=xticks, yticks=yticks, title=title, aspect=aspect, size=size, theme=theme, kind=kind, )
def hyperExplore(df,initial_axis,initial_surface_axis,legend_group,hover_items): data = df.assign(x=df[initial_axis[0]],y=df[initial_axis[1]])\ .sort_values(legend_group)\ .reset_index(drop=True) group_ops = data[legend_group].sort_values().unique() num_groups = len(group_ops) axis_ops = data.columns.values lenSlide = '500px' fig = px.scatter(data, x="x", y="y", color=legend_group,hover_data=hover_items, log_x=True, title='Hyperparameter Exploration',height=600) fig.update_layout( legend=dict( orientation="v", yanchor="top", y=1.02, xanchor="left", x=1), xaxis=dict(title=initial_axis[0], titlefont=dict(size=14)), yaxis=dict(title=initial_axis[1], titlefont=dict(size=14)) ) fig.update_traces(marker=dict(size=20,line=dict(width=1.5, color='DarkSlateGrey')), selector=dict(mode='markers')) fig.update_layout(plot_bgcolor='rgba(0,0,0,0)') fig.update_xaxes(showgrid=True, gridwidth=.1, gridcolor='lightgrey') fig.update_yaxes(showgrid=True, gridwidth=.1, gridcolor='lightgrey') param_drop1 = Dropdown( value='None', options=np.insert(axis_ops,0,'None'), description='Parameter 1:' ) slider1 = widgets.SelectionSlider( options=['Select Parameter'], value='Select Parameter', layout=Layout(width=lenSlide), continuous_update=True ) size_drop = Dropdown( value='None', options=np.insert(axis_ops,0,'None'), description='Size:' ) size_slider = widgets.IntSlider( value=20, min=10, max=50, step=1, disabled=False, continuous_update=True, orientation='horizontal', layout=Layout(width=lenSlide), readout=True, readout_format='d' ) slider_group1 = widgets.HBox([param_drop1, slider1]) slider_group2 = widgets.HBox([size_drop, size_slider]) xaxis = Dropdown( value=initial_axis[0], options=axis_ops, description='X-axis:' ) yaxis = Dropdown( value=initial_axis[1], options=axis_ops, description='Y-axis:' ) container = widgets.VBox(children=[slider_group1,slider_group2,xaxis,yaxis]) g = go.FigureWidget(data=fig, layout=go.Layout( title=dict( text='Hyperparameter Exploration' ) )) x_surface = Dropdown( value=initial_surface_axis[0], options=axis_ops, description='X-axis' ) y_surface = Dropdown( value=initial_surface_axis[1], options=axis_ops, description='Y-axis' ) z_surface = Dropdown( value=initial_surface_axis[2], options=axis_ops, description='Z-axis' ) surface_buttons = widgets.RadioButtons( options=group_ops, value=group_ops[0], # Defaults to 'pineapple' description=legend_group+":", disabled=False ) z_vals = data.query('{} == "{}"'\ .format(legend_group,surface_buttons.value))[[x_surface.value,y_surface.value,z_surface.value]]\ .groupby([x_surface.value,y_surface.value])\ .median().reset_index()\ .pivot(index=x_surface.value,columns=y_surface.value,values=z_surface.value) fig2 = go.Figure(data=[go.Surface(z=z_vals)]) fig2.update_layout(title='Hyperparameter Surface: '+surface_buttons.value, autosize=False, margin=dict(l=65, r=50, b=65, t=90), height=600) layout = go.Layout( scene = dict( xaxis = dict( title = initial_surface_axis[0]), yaxis = dict( title = initial_surface_axis[1]), zaxis = dict( title = initial_surface_axis[2]), )) fig2.update_layout(layout) container2 = widgets.HBox(children=[surface_buttons,x_surface,y_surface,z_surface]) g2 = go.FigureWidget(data=fig2, layout=go.Layout( title=dict( text='Hyperparameter Surface: '+surface_buttons.value ) )) def axis_response(change): with g.batch_update(): #Gets the widget that was altered modified = change.owner.description if modified == xaxis.description: for i in range(num_groups): #Get data for legend group filtered_data = data.query("{} == '{}'".format(legend_group,g.data[i].name)) #Query filtered data for slider specs query_filt(filtered_data,i) g.layout.xaxis.title = xaxis.value elif modified == yaxis.description: for i in range(num_groups): #Get data for legend group filtered_data = data.query("{} == '{}'".format(legend_group,g.data[i].name)) #Query filtered data for slider specs query_filt(filtered_data,i) g.layout.yaxis.title = yaxis.value def slider1_response(change): with g.batch_update(): for i in range(num_groups): #Get data for legend group filtered_data = data.query("{} == '{}'".format(legend_group,g.data[i].name))#make key var that iters #Query filtered data for slider specs query_filt(filtered_data,i) def query_filt(filtered_data,i): #Query filtered data for slider specs # filt_bool = (filtered_data.learning_rate == lr_slider.value)#make learning_rate var if param_drop1.value == 'None': #Assign data to graph g.data[i].x = filtered_data[xaxis.value] g.data[i].y = filtered_data[yaxis.value] else: filt_bool = (filtered_data[param_drop1.value] == slider1.value)#make learning_rate var #Filter out data xfilt = [v if b else None for v,b in zip(filtered_data[xaxis.value],filt_bool)] yfilt = [v if b else None for v,b in zip(filtered_data[yaxis.value],filt_bool)] #Assign data to graph g.data[i].x = xfilt g.data[i].y = yfilt def create_slider_options(drop_value): if drop_value == 'None': slide_ops = ['Select Parameter'] else: slide_ops = data[drop_value].sort_values().unique() return slide_ops def param_update(change): #everytime we change param, update the slider options and current value slider1.options = create_slider_options(param_drop1.value) slider1.value = slider1.options[0] def size_response(change): with g.batch_update(): if size_drop.value == 'None': g.update_traces(marker=dict(size=size_slider.value)) else: sizeFig = px.scatter(data, x="x", y="y", color="model", size=size_drop.value, size_max=size_slider.value) traceSizes = [x.marker.size for x in sizeFig.data] for i in range(num_groups): g.data[i].marker.size = traceSizes[i] g.data[i].marker.sizeref = sizeFig.data[0].marker.sizeref g.data[i].marker.sizemode = sizeFig.data[0].marker.sizemode g.data[i].marker.sizemin = 4 def surface_response(change): with g.batch_update(): z_vals = data.query('{} == "{}"'\ .format(legend_group,surface_buttons.value))[[x_surface.value,y_surface.value,z_surface.value]]\ .groupby([x_surface.value,y_surface.value])\ .median().reset_index()\ .pivot(index=x_surface.value,columns=y_surface.value,values=z_surface.value) g2.data[0].z = z_vals.values layout = go.Layout( scene = dict( xaxis = dict( title = x_surface.value), yaxis = dict( title = y_surface.value), zaxis = dict( title = z_surface.value), ), title=dict( text='Hyperparameter Surface: '+surface_buttons.value )) g2.update_layout(layout) surface_buttons.observe(surface_response,"value") x_surface.observe(surface_response,"value") y_surface.observe(surface_response,"value") z_surface.observe(surface_response,"value") size_drop.observe(size_response,"value") size_slider.observe(size_response, "value") slider1.observe(slider1_response, names="value") xaxis.observe(axis_response, names="value") yaxis.observe(axis_response, names="value") param_drop1.observe(param_update, names="value") scatterTab = widgets.VBox([container,g]) surfaceTab = widgets.VBox([container2,g2]) tab = widgets.Tab([scatterTab,surfaceTab]) tab.set_title(0,'Scatter') tab.set_title(1,'Surface') return tab
def process_interactive(value, kind=None): INVALID = f"invalid interactive combination between a value of type \ {type(value)} and a widget of kind {kind}" if isinstance(value, (int, float)): value = float(value) if kind == "text": return widgets.FloatText(value=value, ) elif kind == "slider": return widgets.FloatSlider(value=value, min=2 * value * (value < 0), max=2 * value * (value > 0)) elif kind is not None: raise ValueError(INVALID) elif isinstance(value, tuple): # infer tuple range values if len(value) > 3: raise ValueError(f"tuple values should be at most of length \ 3, not {len(value)}") elif len(value) == 1: return EcoGraph.process_interactive(value[0], kind=kind) elif len(value) >= 2: lower, default, upper = value[0], np.mean(value[:2]), value[1] step = value[2] if len(value) == 3 else 1 # create interactive from infered values if kind == "text": return widgets.BoundedFloatText(value=default, min=lower, max=upper, step=step) elif kind == "slider": return widgets.FloatSlider(value=default, min=lower, max=upper, step=step) elif kind == "dropdown": return widgets.Dropdown(options=range(int(lower), int(upper), int(step)), value=int(default)) elif kind is not None: raise ValueError(INVALID) elif isinstance(value, list): if kind == "slider": return widgets.SelectionSlider(options=value, value=value[0]) elif kind == "dropdown": return widgets.Dropdown(options=value, value=value[0]) elif kind == "option": return widgets.RadioButtons(options=value) elif kind is not None: raise ValueError(INVALID) elif isinstance(value, bool): return EcoGraph.process_interactive([value, not value]) return value