def __init__(self, mol): super().__init__(mol) self._widgetshapes = {} self._atom_labels = [] # All numbers here are assumed angstroms and radians for now ... self._highlighted_bonds = [] self._highlighted_atoms = [] self.original_position = self.mol.positions.copy() self.clear_button = ipy.Button(description='Clear selection') self.clear_button.on_click(self.clear_selection) self.label_box = ipy.Checkbox(description='Label atoms', value=False) self.label_box.observe(self.label_atoms, 'value') # Viewer self.selection_description = ipy.HTML() self.subtools.children = (HBox([self.clear_button, self.label_box]), self.selection_description) traitlets.directional_link((self.viewer, 'selected_atom_indices'), (self.selection_description, 'value'), self.get_first_atom) # Atom manipulation tools - self.{x,y,z}_slider self.sliders = [] for dim, name in enumerate('xyz'): slider = ReadoutFloatSlider( min=-self.MAXDIST, max=self.MAXDIST, description='<span style="color: {c}"><b>{n}</b><span>'.format( n=name, c=self.viewer.AXISCOLORS[name]), format=self.POSFMT) slider.dim = dim setattr(self, name + '_slider', slider) self.sliders.append(slider) slider.observe(self.set_atom_pos, 'value') # Bond manipulation tools self.rigid_mol_selector = ipy.ToggleButtons( description='Position adjustment', options={ 'selected atoms only': False, 'rigid molecule': True }, value=True) self.length_slider = ReadoutFloatSlider(min=0.1, max=self.MAXDIST, format=self.POSFMT) self.length_slider.observe(self.set_distance, 'value') self.angle_slider = ReadoutFloatSlider(min=1.0, max=179.0, step=2.0, format=self.DEGFMT) self.angle_slider.observe(self.set_angle, 'value') self.dihedral_slider = ReadoutFloatSlider(min=-90.0, max=360.0, step=4.0, format=self.DEGFMT) self.dihedral_slider.observe(self.set_dihedral, 'value') self.bond_tools = VBox((self.rigid_mol_selector, self.length_slider, self.angle_slider, self.dihedral_slider)) self.movement_selector = ipy.ToggleButtons( description='Move:', value='atom', options=['atom', 'residue', 'chain']) self.atom_tools = VBox((self.movement_selector, self.x_slider, self.y_slider, self.z_slider)) self.reset_button = ipy.Button(description='Reset geometry') self.reset_button.on_click(self.reset_geometry) self.tool_holder = VBox() self.toolpane.children = (self.tool_holder, self.reset_button) self.viewer.observe(self._set_tool_state, names='selected_atom_indices')
color = ['gray', '#01ac66'] # dynavox green labelKeybd = ['win10 Eye Control', 'tobii Windows Control'] labelKeybdMean = ['win10 Eye Control Mean', 'tobii Windows Control Mean'] perSubjTaskWpm, perSubjTaskTotErrRate, perSubjTaskSentenceNo = ([[] for i in range(amountSubject * amountTask * amountKeyboard)] for j in range(3)) # readSentences() filenames = ['1Greta_s1Transcribe_winEyeControl', '1Greta_s2Transcribe_tobiiWinControl', '2Carlota_s1Transcribe_winEyeControl', '2Carlota_s2FreeConv_winEyeControl', '2Carlota_s3Transcribe_tobiiWinControl', '2Carlota_s4FreeConv_tobiiWinControl', '3Barbara_s1Transcribe_tobiiWinControl', '3Barbara_s2FreeConv_tobiiWinControl', '3Barbara_s3Transcribe_winEyeControl', '3Barbara_s4FreeConv_winEyeControl'] for item in filenames: readSentences(item, sentences) # define UI controls contrMetric = widgets.ToggleButtons( options=['Speed', 'Accuracy', 'Speed & Accuracy', 'Learning Curve', 'Speed vs. Accuracy'], description = 'Metric: ', value = 'Speed', disabled = False ) contrOfTask = widgets.Select( options = ['Both Tasks', 'Sentence Transcription', 'Q&A Conversation', 'Between Tasks'], description = 'Of Task: ', value = 'Sentence Transcription', disabled = False ) contrOfSubject = widgets.Select( options = ['All Subjects', '#1', '#2', '#3', 'Between Subjects'], description = 'Of Subject: ', value = 'All Subjects', disabled = False ) display(contrMetric, widgets.HBox([contrOfTask, contrOfSubject]))
def open_data_widget(m): """A widget for opening local vector/raster data. Args: m (object): geemap.Map """ tool_output = widgets.Output() tool_output_ctrl = WidgetControl(widget=tool_output, position="topright") if m.tool_output_ctrl is not None and m.tool_output_ctrl in m.controls: m.remove_control(m.tool_output_ctrl) file_type = widgets.ToggleButtons( options=["Shapefile", "GeoJSON", "GeoTIFF"], tooltips=[ "Open a shapefile", "Open a GeoJSON file", "Open a GeoTIFF", ], ) file_chooser = FileChooser(os.getcwd()) file_chooser.filter_pattern = "*.shp" file_chooser.use_dir_icons = True style = {"description_width": "initial"} layer_name = widgets.Text( value="Shapefile", description="Enter a layer name:", tooltip="Enter a layer name for the selected file", style=style, layout=widgets.Layout(width="454px", padding="0px 0px 0px 5px"), ) convert_bool = widgets.Checkbox( description="Convert to ee.FeatureCollection?", indent=False, layout=widgets.Layout(padding="0px 0px 0px 5px"), ) convert_hbox = widgets.HBox([convert_bool]) ok_cancel = widgets.ToggleButtons( value=None, options=["Apply", "Reset", "Close"], tooltips=["Apply", "Reset", "Close"], button_style="primary", ) bands = widgets.Text( value="1", description="Bands:", tooltip="Enter a list of band indices", style=style, layout=widgets.Layout(width="110px"), ) colormap = widgets.Dropdown( options=[], value=None, description="colormap:", layout=widgets.Layout(width="172px"), style=style, ) x_dim = widgets.Text( value="x", description="x_dim:", tooltip="The x dimension", style=style, layout=widgets.Layout(width="80px"), ) y_dim = widgets.Text( value="y", description="y_dim:", tooltip="The xydimension", style=style, layout=widgets.Layout(width="80px"), ) raster_options = widgets.HBox() main_widget = widgets.VBox( [file_type, file_chooser, layer_name, convert_hbox, raster_options, ok_cancel] ) tool_output.clear_output() with tool_output: display(main_widget) # def chooser_callback(chooser): # if len(layer_name.value) == 0 and file_chooser.selected is not None: # layer_name.value = os.path.splitext(file_chooser.selected_filename)[0] def bands_changed(change): if change["new"] and "," in change["owner"].value: colormap.value = None colormap.disabled = True else: colormap.disabled = False bands.observe(bands_changed, "value") def file_type_changed(change): ok_cancel.value = None file_chooser.default_path = os.getcwd() file_chooser.reset() layer_name.value = file_type.value if change["new"] == "Shapefile": file_chooser.filter_pattern = "*.shp" raster_options.children = [] convert_hbox.children = [convert_bool] elif change["new"] == "GeoJSON": file_chooser.filter_pattern = "*.geojson" raster_options.children = [] convert_hbox.children = [convert_bool] elif change["new"] == "GeoTIFF": import matplotlib.pyplot as plt file_chooser.filter_pattern = "*.tif" colormap.options = plt.colormaps() colormap.value = "terrain" raster_options.children = [bands, colormap, x_dim, y_dim] convert_hbox.children = [] def ok_cancel_clicked(change): if change["new"] == "Apply": m.default_style = {"cursor": "wait"} file_path = file_chooser.selected if file_path is not None: ext = os.path.splitext(file_path)[1] with tool_output: if ext.lower() == ".shp": if convert_bool.value: ee_object = shp_to_ee(file_path) m.addLayer(ee_object, {}, layer_name.value) m.centerObject(ee_object) else: m.add_shapefile( file_path, style=None, layer_name=layer_name.value ) elif ext.lower() == ".geojson": if convert_bool.value: ee_object = geojson_to_ee(file_path) m.addLayer(ee_object, {}, layer_name.value) m.centerObject(ee_object) else: m.add_geojson( file_path, style=None, layer_name=layer_name.value ) elif ext.lower() == ".tif": sel_bands = [int(b.strip()) for b in bands.value.split(",")] m.add_raster( image=file_path, bands=sel_bands, layer_name=layer_name.value, colormap=colormap.value, x_dim=x_dim.value, y_dim=y_dim.value, ) else: print("Please select a file to open.") m.toolbar_reset() m.default_style = {"cursor": "default"} elif change["new"] == "Reset": file_chooser.reset() tool_output.clear_output() with tool_output: display(main_widget) m.toolbar_reset() elif change["new"] == "Close": if m.tool_output_ctrl is not None and m.tool_output_ctrl in m.controls: m.remove_control(m.tool_output_ctrl) m.tool_output_ctrl = None m.toolbar_reset() ok_cancel.value = None file_type.observe(file_type_changed, names="value") ok_cancel.observe(ok_cancel_clicked, names="value") # file_chooser.register_callback(chooser_callback) m.add_control(tool_output_ctrl) m.tool_output_ctrl = tool_output_ctrl
def show_notebook_interface_wfi(instrument): # Widget related imports. # (Currently not a hard dependency for the full webbpsf package, so we import # within the function.) import ipywidgets as widgets from IPython.display import display, clear_output from matplotlib import pyplot as plt try: import pysynphot except ImportError: raise ImportError( "For now, PySynphot must be installed to use the notebook interface" ) # Clean up some warnings we know about so as not to scare the users import warnings from matplotlib.cbook import MatplotlibDeprecationWarning warnings.simplefilter('ignore', MatplotlibDeprecationWarning) warnings.simplefilter('ignore', fits.verify.VerifyWarning) def make_binding_for_attribute(attribute): def callback(trait_name, new_value): setattr(instrument, attribute, new_value) return callback filter_selection = widgets.ToggleButtons(options=instrument.filter_list, value=instrument.filter, description='Filter:') filter_selection.on_trait_change(make_binding_for_attribute('filter'), name='selected_label') display(filter_selection) monochromatic_wavelength = widgets.BoundedFloatText( value=0.76, min=0.6, max=2.0, ) monochromatic_wavelength.disabled = True monochromatic_toggle = widgets.Checkbox( description='Monochromatic calculation?') def update_monochromatic(trait_name, new_value): filter_selection.disabled = new_value monochromatic_wavelength.disabled = not new_value monochromatic_toggle.on_trait_change(update_monochromatic, name='value') display( widgets.HTML(value='''<p style="padding: 1em 0;"> <span style="font-style:italic; font-size:1.0em"> Monochromatic calculations can be performed for any wavelength in the 0.6 to 2.0 µm range. </span></p>''')) # kludge monochromatic_controls = widgets.HBox(children=( monochromatic_toggle, widgets.HTML( value='<span style="display: inline-block; width: 0.6em;"></span>' ), monochromatic_wavelength, widgets.HTML( value= '<span style="display: inline-block; width: 0.25em;"></span> µm ' ), )) display(monochromatic_controls) display(widgets.HTML(value="<hr>")) source_selection = widgets.Select(options=poppy.specFromSpectralType( '', return_list=True), value='G0V', description="Source spectrum") display(source_selection) display(widgets.HTML(value="<hr>")) sca_selection = widgets.Dropdown(options=instrument.detector_list, value=instrument.detector, description='Detector:') sca_selection.on_trait_change(make_binding_for_attribute('detector'), name='selected_label') display(sca_selection) detector_field_points = [ ('Top left', (4.0, 4092.0)), ('Bottom left', (4.0, 4.0)), ('Center', (2048.0, 2048.0)), ('Top right', (4092.0, 4092.0)), ('Bottom right', (4092.0, 4.0)), ] # enforce ordering of buttons detector_field_point_labels = [a[0] for a in detector_field_points] detector_field_points = dict(detector_field_points) def set_field_position(trait_name, new_value): instrument.detector_position = detector_field_points[new_value] field_position = widgets.ToggleButtons(options=detector_field_point_labels, value='Center', description='Detector field point:') field_position.on_trait_change(set_field_position, name='selected_label') display(field_position) calculate_button = widgets.Button(description="Calculate PSF", width='10em', color='white', background_color='#00c403', border_color='#318732') display_osys_button = widgets.Button(description="Display Optical System", width='13em', color='white', background_color='#005fc4', border_color='#224A75') clear_button = widgets.Button(description="Clear Output", width='10em', color='white', background_color='#ed4747', border_color='#911C1C') progress = widgets.HTML(value='<progress>') OUTPUT_FILENAME = 'psf.fits' DOWNLOAD_BUTTON_HTML = """ <a class="btn btn-info" href="files/{}" target="_blank"> Download FITS image from last calculation </a> """ download_link = widgets.HTML( value=DOWNLOAD_BUTTON_HTML.format(OUTPUT_FILENAME)) def disp(*args): progress.visible = True plt.figure(figsize=(12, 8)) instrument.display() progress.visible = None def calc(*args): progress.visible = True if monochromatic_toggle.value is True: psf = instrument.calcPSF( monochromatic=monochromatic_wavelength.value * 1e-6, display=True, outfile=OUTPUT_FILENAME, clobber=True) else: source = poppy.specFromSpectralType(source_selection.value) _log.debug("Got source type {}: {}".format(source_selection.value, source)) psf = instrument.calcPSF(source=source, display=True, outfile=OUTPUT_FILENAME, clobber=True) fig, (ax_oversamp, ax_detsamp) = plt.subplots(1, 2) poppy.display_PSF(psf, ax=ax_oversamp) poppy.display_PSF(psf, ax=ax_detsamp, ext='DET_SAMP') progress.visible = None download_link.visible = True def clear(*args): clear_output() progress.visible = None download_link.visible = None calculate_button.on_click(calc) display_osys_button.on_click(disp) clear_button.on_click(clear) display(widgets.HTML(value="<br/>")) # kludge buttons = widgets.HBox( children=[calculate_button, display_osys_button, clear_button]) display(buttons) # Insert the progress bar, hidden by default display(progress) progress.visible = None # and the download link display(download_link) download_link.visible = None
def __init__(self, sme, segment=0): self.sme = sme self.wave = sme.wave self.spec = sme.spec self.mask = sme.mask self.smod = sme.synth self.nsegments = len(self.wave) self.segment = segment self.wind = sme.wind self.wran = sme.wran self.lines = sme.linelist self.vrad = sme.vrad self.vrad = [v if v is not None else 0 for v in self.vrad] self.mask_type = "good" data, annotations = self.create_plot(self.segment) self.annotations = annotations # Add segment slider steps = [] for i in range(self.nsegments): step = { "label": f"Segment {i}", "method": "update", "args": [ {"visible": [v == i for v in self.visible]}, { "title": f"Segment {i}", "annotations": annotations[i], "xaxis": {"range": list(self.wran[i])}, "yaxis": {"autorange": True}, }, ], } steps += [step] layout = { "dragmode": "select", "selectdirection": "h", "title": f"Segment {segment}", "xaxis": {"title": "Wavelength [Å]"}, "yaxis": {"title": "Intensity"}, "annotations": annotations[self.segment], "sliders": [{"active": 0, "steps": steps}], "legend": {"traceorder": "reversed"}, } self.fig = go.FigureWidget(data=data, layout=layout) # add selection callback self.fig.data[0].on_selection(self.selection_fn) # Add button to save figure self.button_save = widgets.Button(description="Save") self.button_save.on_click(self.save) # Add buttons for Mask selection self.button_mask = widgets.ToggleButtons( options=["Good", "Bad", "Continuum", "Line"], description="Mask" ) self.button_mask.observe(self.on_toggle_click, "value") self.widget = widgets.VBox([self.button_mask, self.button_save, self.fig]) if in_notebook: display(self.widget)
def training(path): print('Using fit_one_cycle') button = widgets.Button(description='Train') style = {'description_width': 'initial'} layout = { 'width': '90%', 'height': '50px', 'border': 'solid', 'fontcolor': 'lightgreen' } layout_two = { 'width': '100%', 'height': '200px', 'border': 'solid', 'fontcolor': 'lightgreen' } style_green = { 'handle_color': 'green', 'readout_color': 'red', 'slider_color': 'blue' } style_blue = { 'handle_color': 'blue', 'readout_color': 'red', 'slider_color': 'blue' } training.cl = widgets.FloatSlider(min=1, max=64, step=1, value=1, continuous_update=False, layout=layout, style=style_green, description="Cycle Length") training.lr = widgets.ToggleButtons( options=['1e-6', '1e-5', '1e-4', '1e-3', '1e-2', '1e-1'], description='Learning Rate:', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' style=style, value='1e-2', tooltips=['Choose a suitable learning rate'], ) display(training.cl, training.lr) display(button) out = widgets.Output() display(out) def on_button_clicked(b): with out: clear_output() lr_work() print('Training....' '\n' 'Learning Rate: ', lr_work.info) dashboard_one.datain.value, dashboard_one.norma.value, dashboard_one.archi.value, dashboard_one.pretrain_check.value, dashboard_one.f.value, dashboard_one.m.value, dashboard_two.doflip.value, dashboard_two.dovert.value, dashboard_two.two.value, dashboard_two.three.value, dashboard_two.seven.value, dashboard_two.four.value, dashboard_two.five.value, dashboard_two.six.value, dashboard_one.norma.value, metrics_list( mets_list) metrics_list(mets_list) batch_val = int(dashboard_one.f.value) # batch size image_val = int(dashboard_one.m.value) # image size r = dashboard_one.pretrain_check.value #t = metrics_list(mets_list) tfms = get_transforms(do_flip=dashboard_two.doflip.value, flip_vert=dashboard_two.dovert.value, max_zoom=dashboard_two.three.value, p_affine=dashboard_two.four.value, max_lighting=dashboard_two.five.value, p_lighting=dashboard_two.six.value, max_warp=dashboard_two.seven.value, max_rotate=dashboard_two.two.value, xtra_tfms=None) data = ImageDataBunch.from_folder(path, ds_tfms=tfms, bs=batch_val, size=image_val, test='test') learn = cnn_learner(data, base_arch=arch_work.info, pretrained=r, metrics=metrics_list(mets_list), custom_head=None, callback_fns=ShowGraph) cycle_l = int(training.cl.value) learn.fit_one_cycle(cycle_l, slice(lr_work.info)) button.on_click(on_button_clicked)
def image_ui(profile, elements_of_interest): experiment_dir = profile.experiment_dir plot_area = iw.Output() status_indicator = iw.Output() group_indicator = iw.Output() with group_indicator: display(iw.HTML('<h3 style="color:orange">No Group Selected</h3>')) with status_indicator: display(iw.HTML('<h3 style="color:green">Ready</h3>')) # Making the controls layout_kwargs = dict(width='100%', border='1px solid black') #settings_layout = dict(width='20%', border='1px solid blue') depth_selector = PropSelector(profile.depths, orientation='horizontal', title='Depths to plot', description_func=lambda d: d.depth, **layout_kwargs) element_filter = ElementFilterPanel(profile, orientation='horizontal', experiment_dir=experiment_dir) filter_settings = SettingsController(element_filter, orientation='horizontal') element_plot_selector = PropSelector(elements_of_interest, orientation='horizontal', title='Elements to plot', **layout_kwargs) element_group_selector = PropSelector(elements_of_interest, orientation='horizontal', title='Groups to show', **layout_kwargs) combine_detsums_checkbox = iw.Checkbox(value=False, indent=False, description='Combine Detsums') update_button = iw.Button(description='Update') raw_data_toggle = iw.ToggleButtons(value='Filtered', options=['Filtered', 'Raw']) show_groups_toggle = iw.ToggleButton(value=True, description='Show Groups') exclusive_groups_toggle = iw.ToggleButtons( value='Exclusive', options=['Exclusive', 'Nonexclusive']) controls_bottom = iw.HBox([ update_button, show_groups_toggle, exclusive_groups_toggle, raw_data_toggle, status_indicator ], layout=iw.Layout(padding='5px', **layout_kwargs)) controls_top = iw.VBox([ depth_selector.widget, element_plot_selector.widget, element_filter.widget, filter_settings.widget, element_group_selector.widget, group_indicator ]) controls = iw.VBox([controls_top, controls_bottom]) rows = [] rows_raw = [] rows_groups_exclusive = [] rows_groups_exclusive_raw = [] rows_groups_nonexclusive = [] rows_groups_nonexclusive_raw = [] current_group = [] def show_plots(val): plot_area.clear_output() show = show_groups_toggle.value exclusive = exclusive_groups_toggle.value == 'Exclusive' with plot_area: if raw_data_toggle.value == 'Raw': if show and exclusive: display(iw.VBox(rows_groups_exclusive_raw)) elif show and not exclusive: display(iw.VBox(rows_groups_nonexclusive_raw)) elif not show: display(iw.VBox(rows_raw)) elif raw_data_toggle.value == 'Filtered': if show and exclusive: display(iw.VBox(rows_groups_exclusive)) if show and not exclusive: display(iw.VBox(rows_groups_nonexclusive)) elif not show: display(iw.VBox(rows)) status_indicator.clear_output() with status_indicator: display(iw.HTML('<h3 style="color:green">Ready</h3>')) def update_group(element, val): nonlocal current_group if val: current_group.append(element) elif not val: current_group.remove(element) sorted_group = [ elements_of_interest[elements_of_interest.index(element)] if element in current_group else None for element in elements_of_interest ] sorted_group = list(filter(lambda x: x, sorted_group)) group_indicator.clear_output() with group_indicator: if not current_group: display( iw.HTML('<h3 style="color:orange">No group selected</h3>')) else: group_str = ' | '.join(sorted_group) display( iw.HTML( f'<h3 style="color:red">Group Selected: {group_str}</hp>' )) current_group = sorted_group def generate_plots(b): element_filter.save_settings() status_indicator.clear_output() with status_indicator: display(iw.HTML('<h3 style="color:red">Working....</h3>')) depths_to_plot = depth_selector.selected_props if not depths_to_plot: status_indicator.clear_output() with status_indicator: display( iw.HTML( '<h3 style="color:orange">No Depth Selected!</h3>')) return elements_to_plot = element_plot_selector.selected_props group = '|'.join(element_group_selector.selected_props) for depth in depths_to_plot: depth.apply_element_filter( element_filter.filter_dict[depth.depth], combine_detsums=combine_detsums_checkbox.value) def get_row(depth, elements, raw, show_groups, exclusive): detsums = sorted(depth.detsums, key=lambda d: d.element) plots = [] #group = '|'.join(current_group) for scan in depth.scans: data = scan.data['element_group'].values.reshape( scan.detsums[0].shape) for detsum in scan.detsums: if detsum.element not in elements: continue fig, ax = plt.subplots(figsize=(15, 15)) detsum.plot(raw=raw, ax=ax) if show_groups and current_group: fn = np.vectorize(lambda group: utils.check_groups( group, current_group, exclusive=exclusive)) rows, cols = np.where(fn(data)) ax.scatter(cols, rows, s=20, color='red') plot = encode_matplotlib_fig(fig) plt.close() plots.append(iw.HTML(plot)) return plots nonlocal rows nonlocal rows_raw nonlocal rows_groups_exclusive nonlocal rows_groups_exclusive_raw nonlocal rows_groups_nonexclusive nonlocal rows_groups_nonexclusive_raw rows = [ iw.HBox(get_row(depth, elements_to_plot, False, False, False)) for depth in depths_to_plot ] rows_raw = [ iw.HBox(get_row(depth, elements_to_plot, True, False, False)) for depth in depths_to_plot ] rows_groups_exclusive = [ iw.HBox(get_row(depth, elements_to_plot, False, True, True)) for depth in depths_to_plot ] rows_groups_exclusive_raw = [ iw.HBox(get_row(depth, elements_to_plot, True, True, True)) for depth in depths_to_plot ] rows_groups_nonexclusive = [ iw.HBox(get_row(depth, elements_to_plot, False, True, False)) for depth in depths_to_plot ] rows_groups_nonexclusive_raw = [ iw.HBox(get_row(depth, elements_to_plot, True, True, False)) for depth in depths_to_plot ] show_plots(0) update_button.on_click(generate_plots) raw_data_toggle.observe(show_plots, 'value') show_groups_toggle.observe(show_plots, 'value') exclusive_groups_toggle.observe(show_plots, 'value') element_group_selector.observe(update_group) # for selector in depth_selectors.values(): # selector.observe(update_plot) display(iw.VBox([controls, plot_area]))
moon = widgets.RadioButtons(options=moon_dict, value='E', description='Moon Dist. Min:', disabled=False, style=style) skybright = widgets.RadioButtons(options=skybright_dict, value='B', description='Sky Brightness Max:', disabled=False, style=style) plate = widgets.ToggleButtons( options=['PLATE_A', 'PLATE_B', 'LIFU'], description='Plate:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' value='PLATE_A') hour_angle_range = widgets.FloatRangeSlider( value=[-2.0, 2.0], min=-5.0, max=5.0, step=0.1, description='HA range:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', )
'colorscale': colorscale, 'showscale': True, 'colorbar': {'tickvals': [0, 1, 2], 'ticktext': ['None', 'Red', 'Blue']}}, mode='markers'), go.Parcats(domain={'y': [0, 0.4]}, dimensions=dimensions, line={'colorscale': colorscale, 'cmin': cmin, 'cmax': cmax, 'color': color, 'shape': 'hspline'})] ) fig.update_layout(height=800, xaxis={'title': 'Horsepower'}, yaxis={'title': 'MPG', 'domain': [0.6, 1]}, dragmode='lasso', hovermode='closest') # Build color selection widget color_toggle = widgets.ToggleButtons( options=['None', 'Red', 'Blue'], index=1, description='Brush Color:', disabled=False) # Update color callback def update_color(trace, points, state): # Compute new color array new_color = np.array(fig.data[0].marker.color) new_color[points.point_inds] = color_toggle.index with fig.batch_update(): # Update scatter color fig.data[0].marker.color = new_color # Update parcats colors fig.data[1].line.color = new_color
def show(self, caller_is_main: bool) -> bool: self.figure_display = widgets.Output() # Icons: https://en.wikipedia.org/wiki/Media_control_symbols️ ⏮ ⏭ ⏺ ⏏ self.play_button = widgets.Button(description="▶ Play") self.play_button.on_click(self.play) self.pause_button = widgets.Button(description="▌▌ Pause") self.pause_button.on_click(self.pause) self.step_button = widgets.Button(description="Step") self.step_button.on_click(self.step) self.interrupt_button = widgets.Button(description="⏏ Break") self.interrupt_button.on_click(self.interrupt) self.progression_buttons = [ self.play_button, self.pause_button, self.step_button, self.interrupt_button ] for button in self.progression_buttons: button.layout.visibility = 'hidden' self.status = widgets.Label(value=self._get_status()) self.field_select = widgets.Dropdown(options=[*self.fields, 'Scalars'], value=self.fields[0], description='Display:') self.field_select.layout.visibility = 'visible' if len( self.app.field_names) > 1 else 'hidden' self.field_select.observe(lambda change: self.show_field(change['new']) if change['type'] == 'change' and change[ 'name'] == 'value' else None) dim_sliders = [] for sel_dim in parse_dim_order(self.config.get('select', [])): slider = widgets.IntSlider(value=0, min=0, max=0, description=sel_dim, continuous_update=False) self.dim_sliders[sel_dim] = slider dim_sliders.append(slider) slider.observe( lambda e: None if IGNORE_EVENTS else self.update_widgets(), 'value') self.vector_select = widgets.ToggleButtons( options=['🡡', 'x', 'y', 'z', '⬤'], value='🡡', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Vectors as arrows', 'x component as heatmap', 'y component as heatmap', 'z component as heatmap', 'vector length as heatmap' ], # icons=['check'] * 3 ) self.vector_select.style.button_width = '30px' self.vector_select.observe( lambda e: None if IGNORE_EVENTS else self.update_widgets(), 'value') control_components = [] for control in self.app.controls: val_min, val_max = value_range(control) if control.control_type == int: control_component = widgets.IntSlider(control.initial, min=val_min, max=val_max, step=1, description=display_name( control.name)) elif control.control_type == float: if is_log_control(control): val_min, val_max = log10(val_min), log10(val_max) control_component = widgets.FloatLogSlider( control.initial, base=10, min=val_min, max=val_max, description=display_name(control.name)) else: control_component = widgets.FloatSlider( control.initial, min=val_min, max=val_max, description=display_name(control.name)) elif control.control_type == bool: control_component = widgets.Checkbox(control.initial, description=display_name( control.name)) elif control.control_type == str: if not val_max: control_component = widgets.Text( value=control.initial, placeholder=control.initial, description=display_name(control.name)) else: control_component = widgets.Dropdown( options=control.value_range, value=control.initial, description=display_name(control.name)) else: raise ValueError( f'Illegal control type: {control.control_type}') control_component.observe(lambda e, c=control: None if IGNORE_EVENTS else self.app. set_control_value(c.name, e['new']), 'value') control_components.append(control_component) action_buttons = [] for action in self.app.actions: button = widgets.Button(description=display_name(action.name)) button.on_click(lambda e, act=action: self.run_action(act)) action_buttons.append(button) layout = VBox([ HBox(self.progression_buttons + action_buttons), self.status, HBox(dim_sliders), VBox(control_components), HBox([self.field_select, self.vector_select], layout=widgets.Layout(height='35px')), self.figure_display ]) # Show initial value and display UI self.update_widgets() display(layout)
def cluster_interact(self, fig_size=1, circular=True, kind='seed'): r""" Start an interactive window for cluster seed mutations. Only in *Jupyter notebook mode*. Not to be called directly. Use the interact methods of ClusterSeed and ClusterQuiver instead. INPUT: - ``fig_size`` -- (default: 1) factor by which the size of the plot is multiplied. - ``circular`` -- (default: ``True``) if ``True``, the circular plot is chosen, otherwise >>spring<< is used. - ``kind`` -- either ``"seed"`` (default) or ``"quiver"`` TESTS:: sage: S = ClusterSeed(['A',4]) sage: S.interact() # indirect doctest VBox(children=... """ if kind not in ['seed', 'quiver']: raise ValueError('kind must be "seed" or "quiver"') show_seq = widgets.Checkbox(value=True, description="Display mutation sequence") show_vars = widgets.Checkbox(value=True, description="Display cluster variables") show_matrix = widgets.Checkbox(value=True, description="Display B-matrix") show_lastmutation = widgets.Checkbox( value=True, description="Show last mutation vertex") mut_buttons = widgets.ToggleButtons(options=list(range(self._n)), style={'button_width': 'initial'}, description='Mutate at: ') out = widgets.Output() seq = [] def print_data(): if show_seq.value: pretty_print(html("Mutation sequence: ${}$".format(seq))) if show_vars.value and kind == 'seed': pretty_print(html("Cluster variables:")) table = "$\\begin{align*}\n" for i in range(self._n): table += "\tv_{%s} &= " % i + latex( self.cluster_variable(i)) + "\\\\ \\\\\n" table += "\\end{align*}$" pretty_print(html(table)) if show_matrix.value: pretty_print(html("B-Matrix:")) pretty_print(html(self._M)) def refresh(w): k = mut_buttons.value with out: clear_output(wait=True) if show_lastmutation.value: self.show(fig_size=fig_size, circular=circular, mark=k) else: self.show(fig_size=fig_size, circular=circular) print_data() def do_mutation(*args, **kwds): k = mut_buttons.value self.mutate(k) seq.append(k) with out: clear_output(wait=True) if show_lastmutation.value: self.show(fig_size=fig_size, circular=circular, mark=k) else: self.show(fig_size=fig_size, circular=circular) print_data() mut_buttons.on_msg(do_mutation) show_seq.observe(refresh, 'value') if kind == 'seed': show_vars.observe(refresh, 'value') show_matrix.observe(refresh, 'value') show_lastmutation.observe(refresh, 'value') mut_buttons.on_displayed(refresh) if kind == 'seed': top = widgets.HBox([show_seq, show_vars]) else: top = widgets.HBox([show_seq]) return widgets.VBox([ top, widgets.HBox([show_matrix, show_lastmutation]), mut_buttons, out ])
from aima_mdp import * textbook_grid = GridMDP([[-0.04, -0.04, -0.04, +1], [-0.04, None, -0.04, -1], [-0.04, -0.04, -0.04, -0.04]], terminals=[(3, 2), (3, 1)]) value_iteration(textbook_grid) columns = 4 rows = 3 U_over_time = policy_iteration_instru(textbook_grid) plot_grid_step = make_plot_grid_step_function(columns, rows, U_over_time) import ipywidgets as widgets from IPython.display import display iteration_slider = widgets.IntSlider(min=1, max=15, step=1, value=0) w = widgets.interactive(plot_grid_step, iteration=iteration_slider) display(w) visualize_callback = make_visualize(iteration_slider) visualize_button = widgets.ToggleButton(description="Visualize", value=False) time_select = widgets.ToggleButtons( description='Extra Delay:', options=['0', '0.1', '0.2', '0.5', '0.7', '1.0']) a = widgets.interactive(visualize_callback, Visualize=visualize_button, time_step=time_select) display(a)
def _add_user_actions_to_widgets(self): self._interact_action_widgets = {} if (self._default_user_set is None): self._interact_action_widgets["UserSet"] = widgets.ToggleButtons( options=['UserSet1', 'UserSet2', 'UserSet3'], value=self._camera.UserSetSelector.GetValue(), description='User Set', layout=widgets.Layout(**self._default_layout), style={ **self._default_style, **{ "button_width": "120px" } }) self._interact_action_widgets["UserSet"].observe( lambda x: self._camera.UserSetSelector.SetValue(x['new']), names='value') else: self._camera.UserSetSelector.SetValue(self._default_user_set) self._interact_action_widgets["LoadConfig"] = widgets.Button( description='Load configuration', button_style='warning', icon='cloud-upload', tooltip='Load configuration from selected UserSet', layout=widgets.Layout(**self._default_layout), style={ **self._default_style, **{ "button_width": "100px" } }) self._interact_action_widgets["LoadConfig"].on_click( self._button_clicked) self._interact_action_widgets["SaveConfig"] = widgets.Button( description='Save configuration', button_style='warning', icon='save', tooltip='Save configuration to selected UserSet', layout=widgets.Layout(**self._default_layout), style={ **self._default_style, **{ "button_width": "100px" } }) self._interact_action_widgets["SaveConfig"].on_click( self._button_clicked) self._interact_action_widgets["ContinuousShot"] = widgets.Button( description='Continuous shot', button_style='success', icon='film', tooltip='Grab and display continuous stream', layout=widgets.Layout(**self._default_layout), style={ **self._default_style, **{ "button_width": "100px" } }) self._interact_action_widgets["ContinuousShot"].on_click( self._button_clicked) self._interact_action_widgets["SingleShot"] = widgets.Button( description='Single shot', button_style='success', icon='image', tooltip='Grab one image and display', layout=widgets.Layout(**self._default_layout), style={ **self._default_style, **{ "button_width": "100px" } }) self._interact_action_widgets["SingleShot"].on_click( self._button_clicked) self._interact_action_widgets["StatusLabel"] = widgets.Label( value="Status: Connection was established", layout=widgets.Layout(**{**self._default_layout}), style=self._default_style)
width='auto', margin='0px 0px 0px 0px') slot_middle = widgets.Box(children=items, layout=box_layout) slot = widgets.VBox(children=[slot_top, slot_middle, slot_bottom], layout=widgets.Layout(display='flex', flex_flow='column', align_items='center', width='auto', margin='0px 0px 0px 0px')) slot._stored_ints = [] imgs = [ 'waiting.png', 'bell.png', 'cherry.png', 'grape.png', 'lemon.png', 'orange.png', 'strawberry.png', 'watermelon.png', 'seven.png' ] slot._images = {} for kk, img in enumerate(imgs): slot._images[kk - 1] = open(script_dir + "/symbols/%s" % img, "rb").read() gen = widgets.ToggleButtons( options=['Simulator', 'ibmq_5_tenerife', 'ANU QRNG'], description='', disabled=False, button_style='') out = widgets.Output() opts = widgets.HBox(children=[gen, out], layout=widgets.Layout(border='1px solid black'))
def dashboard_one(): style = {'description_width': 'initial'} dashboard_one.datain = widgets.ToggleButtons( options=['Folder'], description='Data In:', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Data in folder', 'Data in csv format - NOT ACTIVE', 'Data in dataframe - NOT ACTIVE' ], ) dashboard_one.norma = widgets.ToggleButtons( options=['Imagenet', 'Custom', 'Cifar', 'Mnist'], description='Normalization:', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Imagenet stats', 'Create your own', 'Cifar stats', 'Mnist stats' ], style=style) dashboard_one.archi = widgets.ToggleButtons( options=[ 'alexnet', 'BasicBlock', 'densenet121', 'densenet161', 'densenet169', 'densenet201', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'squeezenet1_0', 'squeezenet1_1', 'vgg16_bn', 'vgg19_bn', 'xresnet18', 'xresnet34', 'xresnet50', 'xresnet101', 'xresnet152' ], description='Architecture:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=[], ) layout = widgets.Layout(width='auto', height='40px') #set width and height xres_text = widgets.Button( description= 'FOR Xresnet models: Are not pretrained so have to UNCHECK Pretrain box to avoid errors.', disabled=True, display='flex', flex_flow='column', align_items='stretch', layout=layout) dashboard_one.pretrain_check = widgets.Checkbox( options=['Yes', "No"], description='Pretrained:', disabled=False, value=True, box_style='success', button_style= 'lightgreen', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Default: Checked = use pretrained weights, Unchecked = No pretrained weights' ], ) layout = { 'width': '90%', 'height': '50px', 'border': 'solid', 'fontcolor': 'lightgreen' } layout_two = { 'width': '100%', 'height': '200px', 'border': 'solid', 'fontcolor': 'lightgreen' } style_green = { 'handle_color': 'green', 'readout_color': 'red', 'slider_color': 'blue' } style_blue = { 'handle_color': 'blue', 'readout_color': 'red', 'slider_color': 'blue' } dashboard_one.f = widgets.FloatSlider(min=8, max=64, step=8, value=32, continuous_update=False, layout=layout, style=style_green, description="Batch size") dashboard_one.m = widgets.FloatSlider(min=0, max=360, step=16, value=128, continuous_update=False, layout=layout, style=style_green, description='Image size') display(dashboard_one.datain, dashboard_one.norma, dashboard_one.archi, xres_text, dashboard_one.pretrain_check, dashboard_one.f, dashboard_one.m)
continuous_update=False) l1l2_widget = ipywidgets.Dropdown(value='l1', options=['l1', 'l2'], description='Regularization:', continuous_update=False) # %% SELECT WIDGETS plot_widget = ipywidgets.SelectMultiple( value=[], options=['Projected Data', 'Covariance Ellipse', 'Projection Line'], rows=4, description='Plot', disabled=False) fold_widget = ipywidgets.ToggleButtons(value=1, options=[1, 2, 3, 4, 5], description='Validation fold:', continuous_update=False) # %% BUTTONS resample_button = ipywidgets.ToggleButton(description="Resample!") next_feature_button = ipywidgets.Button(description="Next Feature") remove_feature_button = ipywidgets.Button(description="Remove Feature Feature") assign_center_button = ipywidgets.Button(description="Assign Center") update_mean_button = ipywidgets.Button(description="Update Means") restart_button = ipywidgets.Button(description="Restart") run_button = ipywidgets.Button(description="Run Algorithm")
def metrics_dashboard(path): button = widgets.Button(description="Metrics") batch_val = int(dashboard_one.f.value) # batch size image_val = int(dashboard_one.m.value) # image size tfms = get_transforms(do_flip=dashboard_two.doflip.value, flip_vert=dashboard_two.dovert.value, max_zoom=dashboard_two.three.value, p_affine=dashboard_two.four.value, max_lighting=dashboard_two.five.value, p_lighting=dashboard_two.six.value, max_warp=dashboard_two.seven.value, max_rotate=dashboard_two.two.value, xtra_tfms=None) data = ImageDataBunch.from_folder(path, ds_tfms=tfms, bs=batch_val, size=image_val, test='test') layout = { 'width': '90%', 'height': '50px', 'border': 'solid', 'fontcolor': 'lightgreen' } style_green = { 'button_color': 'green', 'handle_color': 'green', 'readout_color': 'red', 'slider_color': 'blue' } metrics_dashboard.error_choice = widgets.ToggleButtons( options=['Yes', 'No'], description='Error Choice:', value='No', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltips=[''], ) metrics_dashboard.accuracy = widgets.ToggleButtons( options=['Yes', 'No'], description='Accuracy:', value='No', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltips=[''], ) metrics_dashboard.topk = widgets.ToggleButtons( options=['Yes', 'No'], description='Top K:', value='No', disabled=False, button_style='warning', # 'success', 'info', 'warning', 'danger' or '' tooltips=[''], ) metrics_dashboard.recall = widgets.ToggleButtons( options=['Yes', 'No'], description='Recall:', value='No', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltips=[''], ) metrics_dashboard.precision = widgets.ToggleButtons( options=['Yes', 'No'], description='Precision:', value='No', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltips=[''], ) metrics_dashboard.dice = widgets.ToggleButtons( options=['Yes', 'No'], description='Dice:', value='No', disabled=False, button_style='warning', # 'success', 'info', 'warning', 'danger' or '' tooltips=[''], ) layout = widgets.Layout(width='auto', height='40px') #set width and height centre_t = widgets.Button(description='', disabled=True, display='flex', flex_flow='column', align_items='stretch', layout=layout) ui = widgets.HBox([ metrics_dashboard.error_choice, metrics_dashboard.accuracy, metrics_dashboard.topk ]) ui2 = widgets.HBox([ metrics_dashboard.recall, metrics_dashboard.precision, metrics_dashboard.dice ]) ui3 = widgets.VBox([ui, centre_t, ui2]) r = dashboard_one.pretrain_check.value display(ui3) print('Click to view choosen metrics') display(button) out = widgets.Output() display(out) def on_button_clicked(b): with out: clear_output() print('Training Metrics' '\n') #metrics_list(mets_list) print('arch:', arch_work(), '\n' 'pretrain: ', dashboard_one.pretrain_check.value, '\n', 'Choosen metrics: ', metrics_list(mets_list)) #metrics_list(mets_list) #learn = cnn_learner(data, base_arch=arch_work.info, pretrained=r, metrics=metrics_list(mets_list), custom_head=None) #learn.fit_one_cycle(1, slice(0.9)) button.on_click(on_button_clicked)
def view(self, data=None): """The main UI of the GLMUtility""" def view_one_way(var, transform, obs, fitted, model, ci, data): if data is None: temp = pd.pivot_table( data=self.transformed_data, index=[var], values=[self.dependent, self.weight, "Fitted Avg"], aggfunc=np.sum, ) else: temp = pd.pivot_table( data=self.predict(data), index=[var], values=[self.dependent, self.weight, "Fitted Avg"], aggfunc=np.sum, ) temp["Observed"] = temp[self.dependent] / temp[self.weight] temp["Fitted"] = temp["Fitted Avg"] / temp[self.weight] temp = temp.merge( self.PDP[var][["Model", "CI_U", "CI_L"]], how="inner", left_index=True, right_index=True, ) if transform == "Predicted Value": for item in ["Model", "CI_U", "CI_L"]: temp[item] = self._link_transform(temp[item], "predicted value") else: for item in ["Observed", "Fitted"]: temp[item] = self._link_transform(temp[item], "linear predictor") y_range = Range1d(start=0, end=temp[self.weight].max() * 1.8) hover = HoverTool(tooltips=[("(x,y)", "($x{0.00 a}, $y{0.00 a})")], mode="mouse") # 'vline') if type(temp.index ) == pd.core.indexes.base.Index: # Needed for categorical p = figure( plot_width=800, y_range=y_range, x_range=list(temp.index), toolbar_location="right", toolbar_sticky=False, ) else: p = figure( plot_width=800, y_range=y_range, toolbar_location="right", toolbar_sticky=False, ) # setting bar values p.add_tools(hover) p.add_layout( Title(text=var, text_font_size="12pt", align="center"), "above") p.yaxis[0].axis_label = self.weight p.yaxis[0].formatter = NumeralTickFormatter(format="0.00 a") p.add_layout( LinearAxis(y_range_name="foo", axis_label=self.dependent + "/" + self.weight), "right", ) h = np.array(temp[self.weight]) # Correcting the bottom position of the bars to be on the 0 line. adj_h = h / 2 # add bar renderer p.rect(x=temp.index, y=adj_h, width=0.4, height=h, color="#e5e500") # add line to secondondary axis p.extra_y_ranges = { "foo": Range1d( start=min(temp["Observed"].min(), temp["Model"].min()) / 1.1, end=max(temp["Observed"].max(), temp["Model"].max()) * 1.1, ) } # p.add_layout(LinearAxis(y_range_name="foo"), 'right') # Observed Average line values if obs == True: p.line( temp.index, temp["Observed"], line_width=2, color="#ff69b4", y_range_name="foo", ) if fitted == True: p.line( temp.index, temp["Fitted"], line_width=2, color="#006400", y_range_name="foo", ) if model == True: p.line( temp.index, temp["Model"], line_width=2, color="#00FF00", y_range_name="foo", ) if ci == True: p.line( temp.index, temp["CI_U"], line_width=2, color="#db4437", y_range_name="foo", ) p.line( temp.index, temp["CI_L"], line_width=2, color="#db4437", y_range_name="foo", ) p.xaxis.major_label_orientation = math.pi / 4 show(p) var = widgets.Dropdown(options=self.independent, description="Field:", value=self.independent[0]) transform = widgets.ToggleButtons( options=["Linear Predictor", "Predicted Value"], button_style="", value="Predicted Value", description="Transform:", ) obs = widgets.ToggleButton(value=True, description="Observed Value", button_style="info") fitted = widgets.ToggleButton(value=True, description="Fitted Value", button_style="info") model = widgets.ToggleButton(value=False, description="Model Value", button_style="warning") ci = widgets.ToggleButton(value=False, description="Conf. Interval", button_style="warning") vw = interactive( view_one_way, var=var, transform=transform, obs=obs, fitted=fitted, model=model, ci=ci, data=fixed(data), ) return widgets.VBox(( widgets.HBox((var, transform)), widgets.HBox((obs, fitted, model, ci)), vw.children[-1], ))
def create_tools(self): self.tools = [] tool_actions = [] tool_actions_map = {u"pan/zoom": self.panzoom} tool_actions.append(u"pan/zoom") # self.control_widget.set_title(0, "Main") self._main_widget = widgets.VBox() self._main_widget_1 = widgets.HBox() self._main_widget_2 = widgets.HBox() if 1: # tool_select: self.brush = bqplot.interacts.BrushSelector(x_scale=self.scale_x, y_scale=self.scale_y, color="green") tool_actions_map["select"] = self.brush tool_actions.append("select") self.brush.observe(self.update_brush, ["selected", "selected_x"]) # fig.interaction = brush # callback = self.dataset.signal_selection_changed.connect(lambda dataset: update_image()) # callback = self.dataset.signal_selection_changed.connect(lambda *x: self.update_grid()) # def cleanup(callback=callback): # self.dataset.signal_selection_changed.disconnect(callback=callback) # self._cleanups.append(cleanup) self.button_select_nothing = widgets.Button(description="", icon="trash-o") self.button_reset = widgets.Button(description="", icon="refresh") import copy self.start_limits = copy.deepcopy(self.limits) def reset(*args): self.limits = copy.deepcopy(self.start_limits) with self.scale_y.hold_trait_notifications(): self.scale_y.min, self.scale_y.max = self.limits[1] with self.scale_x.hold_trait_notifications(): self.scale_x.min, self.scale_x.max = self.limits[0] self.plot.update_grid() self.button_reset.on_click(reset) self.button_select_nothing.on_click(lambda *ignore: self.plot.select_nothing()) self.tools.append(self.button_select_nothing) self.modes_names = "replace and or xor subtract".split() self.modes_labels = "replace and or xor subtract".split() self.button_selection_mode = widgets.Dropdown(description='select', options=self.modes_labels) self.tools.append(self.button_selection_mode) def change_interact(*args): # print "change", args self.figure.interaction = tool_actions_map[self.button_action.value] tool_actions = ["pan/zoom", "select"] # tool_actions = [("m", "m"), ("b", "b")] self.button_action = widgets.ToggleButtons(description='', options=[(action, action) for action in tool_actions], icons=["arrows", "pencil-square-o"]) self.button_action.observe(change_interact, "value") self.tools.insert(0, self.button_action) self.button_action.value = "pan/zoom" # tool_actions[-1] if len(self.tools) == 1: tools = [] # self._main_widget_1.children += (self.button_reset,) self._main_widget_1.children += (self.button_action,) self._main_widget_1.children += (self.button_select_nothing,) # self._main_widget_2.children += (self.button_selection_mode,) self._main_widget.children = [self._main_widget_1, self._main_widget_2] self.control_widget.children += (self._main_widget,) self._update_grid_counter = 0 # keep track of t self._update_grid_counter_scheduled = 0 # keep track of t
def toggles(description, options, value, **kwopts): # pylint: disable=W0613 return widgets.ToggleButtons(**kwargser(locals()))
def __init__(self, backend, dataset, x, y=None, z=None, w=None, grid=None, limits=None, shape=128, what="count(*)", f=None, vshape=16, selection=None, grid_limits=None, normalize=None, colormap="afmhot", figure_key=None, fig=None, what_kwargs={}, grid_before=None, vcount_limits=None, controls_selection=False, **kwargs): super(PlotBase, self).__init__(x=x, y=y, z=z, w=w, what=what, vcount_limits=vcount_limits, grid_limits=grid_limits, f=f, **kwargs) self.backend = backend self.vgrids = [None, None, None] self.vcount = None self.dataset = dataset self.limits = self.get_limits(limits) self.shape = shape self.selection = selection #self.grid_limits = grid_limits self.grid_limits_visible = None self.normalize = normalize self.colormap = colormap self.what_kwargs = what_kwargs self.grid_before = grid_before self.figure_key = figure_key self.fig = fig self.vshape = vshape self._new_progressbar() self.output = widgets.Output() # with self.output: if 1: self._cleanups = [] self.progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0, step=0.01) self.progress.layout.width = "95%" self.progress.layout.max_width = '500px' self.progress.description = "progress" self.backend.create_widget(self.output, self, self.dataset, self.limits) self.control_widget = widgets.VBox() # self.create_tools() self.widget = widgets.VBox([widgets.HBox([self.backend.widget, self.control_widget]), self.progress, self.output]) if grid is None: self.update_grid() else: self.grid = grid self.widget_f = widgets.Dropdown(options=[('identity', 'identity'), ('log', 'log'), ('log10', 'log10'), ('log1p', 'log1p')]) widgets.link((self, 'f'), (self.widget_f, 'value')) self.observe(lambda *__: self.update_image(), 'f') self.add_control_widget(self.widget_f) self.widget_grid_limits_min = widgets.FloatSlider(value=0, min=0, max=100, step=0.1, description='vmin%') self.widget_grid_limits_max = widgets.FloatSlider(value=100, min=0, max=100, step=0.1, description='vmax%') widgets.link((self.widget_grid_limits_min, 'value'), (self, 'grid_limits_min')) widgets.link((self.widget_grid_limits_max, 'value'), (self, 'grid_limits_max')) #widgets.link((self.widget_grid_limits_min, 'f'), (self.widget_f, 'value')) self.observe(lambda *__: self.update_image(), ['grid_limits_min', 'grid_limits_max']) self.add_control_widget(self.widget_grid_limits_min) self.add_control_widget(self.widget_grid_limits_max) self.widget_grid_limits = None selections = _ensure_list(self.selection) selections = [_translate_selection(k) for k in selections] selections = [k for k in selections if k] self.widget_selection_active = widgets.ToggleButtons(options=list(zip(selections, selections)), description='selection') self.controls_selection = controls_selection if self.controls_selection: self.add_control_widget(self.widget_selection_active) modes = ['replace', 'and', 'or', 'xor', 'subtract'] self.widget_selection_mode = widgets.ToggleButtons(options=modes, description='mode') self.add_control_widget(self.widget_selection_mode) self.widget_selection_undo = widgets.Button(options=modes, description='undo', icon='arrow-left') self.widget_selection_redo = widgets.Button(options=modes, description='redo', icon='arrow-right') self.add_control_widget(widgets.HBox([widgets.Label('history', layout={'width': '80px'}), self.widget_selection_undo, self.widget_selection_redo])) def redo(*ignore): selection = _translate_selection(self.widget_selection_active.value) self.dataset.selection_redo(name=selection) check_undo_redo() self.widget_selection_redo.on_click(redo) def undo(*ignore): selection = _translate_selection(self.widget_selection_active.value) self.dataset.selection_undo(name=selection) check_undo_redo() self.widget_selection_undo.on_click(undo) def check_undo_redo(*ignore): selection = _translate_selection(self.widget_selection_active.value) self.widget_selection_undo.disabled = not self.dataset.selection_can_undo(selection) self.widget_selection_redo.disabled = not self.dataset.selection_can_redo(selection) self.widget_selection_active.observe(check_undo_redo, 'value') check_undo_redo() callback = self.dataset.signal_selection_changed.connect(check_undo_redo) callback = self.dataset.signal_selection_changed.connect(lambda *x: self.update_grid()) def _on_limits_change(*args): self._progressbar.cancel() self.update_grid() self.backend.observe(_on_limits_change, "limits") for attrname in "x y z vx vy vz".split(): def _on_change(change, attrname=attrname): limits_index = {'x': 0, 'y': 1, 'z': 2}.get(attrname) if limits_index is not None: self.backend.limits[limits_index] = None self.update_grid() self.observe(_on_change, attrname) self.observe(lambda *args: self.update_grid(), "what") self.observe(lambda *args: self.update_image(), "vcount_limits")
def tool_click(b): with output: output.clear_output() if b.icon == "folder-open": display(filechooser_widget) m.add_control(output_ctrl) elif b.icon == "gears": import whiteboxgui.whiteboxgui as wbt if hasattr(m, "whitebox") and m.whitebox is not None: if m.whitebox in m.controls: m.remove_control(m.whitebox) tools_dict = wbt.get_wbt_dict() wbt_toolbox = wbt.build_toolbox( tools_dict, max_width="800px", max_height="500px" ) wbt_control = WidgetControl(widget=wbt_toolbox, position="bottomright") m.whitebox = wbt_control m.add_control(wbt_control) elif b.icon == "map-marker": fc = FileChooser(data_dir) fc.use_dir_icons = True fc.filter_pattern = ["*.csv"] x_widget = widgets.Dropdown( description="X:", layout=widgets.Layout(width="122px", padding="0px"), style={"description_width": "initial"}, ) y_widget = widgets.Dropdown( description="Y:", layout=widgets.Layout(width="122px", padding="0px"), style={"description_width": "initial"}, ) label_widget = widgets.Dropdown( description="Label:", layout=widgets.Layout(width="248px", padding="0px"), style={"description_width": "initial"}, ) layer_widget = widgets.Text( description="Layer name: ", value="Marker cluster", layout=widgets.Layout(width="248px", padding="0px"), style={"description_width": "initial"}, ) btns = widgets.ToggleButtons( value=None, options=["Read data", "Display", "Close"], tooltips=["Read data", "Display", "Close"], button_style="primary", ) btns.style.button_width = "80px" def btn_click(change): if change["new"] == "Read data" and fc.selected is not None: import pandas as pd df = pd.read_csv(fc.selected) col_names = df.columns.values.tolist() x_widget.options = col_names y_widget.options = col_names label_widget.options = col_names if "longitude" in col_names: x_widget.value = "longitude" if "latitude" in col_names: y_widget.value = "latitude" if "name" in col_names: label_widget.value = "name" elif change["new"] == "Display": if x_widget.value is not None and (y_widget.value is not None): m.add_points_from_csv( fc.selected, x=x_widget.value, y=y_widget.value, label=label_widget.value, layer_name=layer_widget.value, ) elif change["new"] == "Close": fc.reset() m.remove_control(output_ctrl) btns.observe(btn_click, "value") csv_widget = widgets.VBox( [ fc, widgets.HBox([x_widget, y_widget]), label_widget, layer_widget, btns, ] ) display(csv_widget) m.add_control(output_ctrl)
def vis(model, trained_model, pixel_array): #if path is provided as model load model if type(trained_model) == str: model_path = trained_model #load model trained_model = tf.keras.models.load_model(model_path, compile=False) else: pass #get weights loaded_weights = trained_model.get_weights() #new_model.summary() model.set_weights(loaded_weights) #transform pixel array from (depth,length,width) to (1,depth,length,width,1) if len(np.shape(pixel_array)) == 3: pixel_array = np.expand_dims(pixel_array, 3) pixel_array = np.expand_dims(pixel_array, 0) #call the interpretability methods print("Calculating the saliency maps. This may take several minutes.") capi_vsali = methods.call_vsaliency(model, model_modifier, loss, pixel_array) capi_sali = methods.call_smooth(model, model_modifier, loss, pixel_array) capi_grad = methods.call_grad(model, model_modifier, loss, pixel_array) capi_gradplus = methods.call_gradplus(model, model_modifier, loss, pixel_array) capi_faster_scorecam = methods.call_faster_scorecam( model, model_modifier, loss, pixel_array) #clear print statement clear_output(wait=True) #define the widgets layer = widgets.IntSlider(description='Slice:', min=0, max=(np.shape(pixel_array)[1] - 1), orientation='horizontal') method = widgets.ToggleButtons( options=[ 'Vanilla Saliency', 'SmoothGrad', 'GradCam', 'GradCam++', 'ScoreCam' ], description='Method:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Description of slow', 'Description of regular', 'Description of fast' ], # icons=['check'] * 3 ) attention = widgets.ToggleButtons( options=['Slice-wise', "Max"], description='Attention:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Description of slow', 'Description of regular', 'Description of fast' ], # icons=['check'] * 3 ) alpha = widgets.FloatSlider( value=0.5, min=0, max=1.0, step=0.001, description='Overlay:', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='.1f', ) play = widgets.Play(value=0, min=0, max=(np.shape(pixel_array)[1] - 1), step=1, interval=500, description="Press play", disabled=False) widgets.jslink((play, 'value'), (layer, 'value')) #assemble the widget ui = widgets.VBox([attention, method, layer, alpha, play]) #create the overlay of original image and heatmap def explore_3dimage(layer, attention, method, alpha): #define the visualize if attention == "Slice-wise": attention_mode = 'slice' # elif attention == "Average": # attention_mode = 'mean' elif attention == "Max": attention_mode = 'max' #load interpretability method if method == 'Vanilla Saliency': heatmap = mode(attention_mode, capi_vsali) capi = capi_vsali elif method == 'SmoothGrad': heatmap = mode(attention_mode, capi_sali) capi = capi_sali elif method == 'GradCam': heatmap = mode(attention_mode, capi_grad) capi = capi_grad elif method == 'GradCam++': heatmap = mode(attention_mode, capi_gradplus) capi = capi_gradplus elif method == 'ScoreCam': heatmap = mode(attention_mode, capi_faster_scorecam) capi = capi_faster_scorecam fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8)) gs = gridspec.GridSpec(1, 2, width_ratios=[2, 1.5]) ax1 = plt.subplot(gs[0]) ax2 = plt.subplot(gs[1]) mri_image_slice = np.squeeze(pixel_array)[layer, :, :] mri_image_slice = np.float64(mri_image_slice) #max methods: if len(np.shape(heatmap)) == 2: heatmap_slice = heatmap #slice methods elif len(np.shape(heatmap)) == 3: heatmap_slice = np.squeeze(heatmap)[layer, :, :] heatmap_slice = np.float64(heatmap_slice) ax1.imshow(mri_image_slice) ax1.imshow(heatmap_slice, cmap='jet', alpha=alpha) ax1.set_title(method + " - " + attention, fontsize=18) ax1.axis('off') ax2.set_xlabel('Slice', fontsize=13) ax2.set_ylabel('Pixel intensities', fontsize=13) ax2.set_title("Attention histogram", fontsize=18) # calculate GAP in z-direction capi = np.squeeze(capi) capi_gap = np.apply_over_axes(np.mean, capi, [1, 2]) # normalize capi_gap_norm = (capi_gap - min(capi_gap)) / (max(capi_gap) - min(capi_gap)) max_slice = np.argmax(capi_gap, axis=0) ax2.plot(np.squeeze(capi_gap)) plt.vlines(x=max_slice, ymin=0, ymax=max(capi_gap), linestyle="--") plt.text(max_slice + 0.5, 0.1 * max(capi_gap), "max slice: \n" + str(max_slice[0][0])) plt.vlines(x=layer, ymin=0, ymax=np.squeeze(capi_gap)[layer], linestyle="dotted", color="b") plt.text(layer + 0.5, 0.03 * max(capi_gap), "current slice: \n" + str(layer)) plt.grid(axis=('both'), linestyle="--") xt = ax2.get_xticks() plt.ylim(0) ax2.set_xticks(xt) ax2.set_xticklabels(xt) plt.xlim(left=0, right=(np.shape(pixel_array)[1] - 1)) fig.subplots_adjust(wspace=0.5) return layer #interactive output out = widgets.interactive_output(explore_3dimage, { 'attention': attention, 'method': method, 'layer': layer, 'alpha': alpha }) #ensure smoother sliding through the layers out.layout.height = '550px' display(ui, out)
def main_toolbar(m): padding = "0px 0px 0px 5px" # upper, right, bottom, left toolbar_button = widgets.ToggleButton( value=False, tooltip="Toolbar", icon="wrench", layout=widgets.Layout(width="28px", height="28px", padding=padding), ) close_button = widgets.ToggleButton( value=False, tooltip="Close the tool", icon="times", button_style="primary", layout=widgets.Layout(height="28px", width="28px", padding=padding), ) toolbar = widgets.HBox([toolbar_button]) def close_click(change): if change["new"]: toolbar_button.close() close_button.close() toolbar.close() close_button.observe(close_click, "value") rows = 2 cols = 2 grid = widgets.GridspecLayout( rows, cols, grid_gap="0px", layout=widgets.Layout(width="62px") ) icons = ["folder-open", "map", "gears", "map-marker"] for i in range(rows): for j in range(cols): grid[i, j] = widgets.Button( description="", button_style="primary", icon=icons[i * rows + j], layout=widgets.Layout(width="28px", padding="0px"), ) toolbar = widgets.VBox([toolbar_button]) def toolbar_click(change): if change["new"]: toolbar.children = [widgets.HBox([close_button, toolbar_button]), grid] else: toolbar.children = [toolbar_button] toolbar_button.observe(toolbar_click, "value") toolbar_ctrl = WidgetControl(widget=toolbar, position="topright") m.add_control(toolbar_ctrl) output = widgets.Output() output_ctrl = WidgetControl(widget=output, position="topright") buttons = widgets.ToggleButtons( value=None, options=["Apply", "Reset", "Close"], tooltips=["Apply", "Reset", "Close"], button_style="primary", ) buttons.style.button_width = "80px" data_dir = os.path.abspath("./data") fc = FileChooser(data_dir) fc.use_dir_icons = True fc.filter_pattern = ["*.shp", "*.geojson"] filechooser_widget = widgets.VBox([fc, buttons]) def button_click(change): if change["new"] == "Apply" and fc.selected is not None: if fc.selected.endswith(".shp"): m.add_shapefile(fc.selected, layer_name="Shapefile") elif fc.selected.endswith(".geojson"): m.add_geojson(fc.selected, layer_name="GeoJSON") elif change["new"] == "Reset": fc.reset() elif change["new"] == "Close": fc.reset() m.remove_control(output_ctrl) buttons.value = None buttons.observe(button_click, "value") def tool_click(b): with output: output.clear_output() if b.icon == "folder-open": display(filechooser_widget) m.add_control(output_ctrl) elif b.icon == "gears": import whiteboxgui.whiteboxgui as wbt if hasattr(m, "whitebox") and m.whitebox is not None: if m.whitebox in m.controls: m.remove_control(m.whitebox) tools_dict = wbt.get_wbt_dict() wbt_toolbox = wbt.build_toolbox( tools_dict, max_width="800px", max_height="500px" ) wbt_control = WidgetControl(widget=wbt_toolbox, position="bottomright") m.whitebox = wbt_control m.add_control(wbt_control) elif b.icon == "map-marker": fc = FileChooser(data_dir) fc.use_dir_icons = True fc.filter_pattern = ["*.csv"] x_widget = widgets.Dropdown( description="X:", layout=widgets.Layout(width="122px", padding="0px"), style={"description_width": "initial"}, ) y_widget = widgets.Dropdown( description="Y:", layout=widgets.Layout(width="122px", padding="0px"), style={"description_width": "initial"}, ) label_widget = widgets.Dropdown( description="Label:", layout=widgets.Layout(width="248px", padding="0px"), style={"description_width": "initial"}, ) layer_widget = widgets.Text( description="Layer name: ", value="Marker cluster", layout=widgets.Layout(width="248px", padding="0px"), style={"description_width": "initial"}, ) btns = widgets.ToggleButtons( value=None, options=["Read data", "Display", "Close"], tooltips=["Read data", "Display", "Close"], button_style="primary", ) btns.style.button_width = "80px" def btn_click(change): if change["new"] == "Read data" and fc.selected is not None: import pandas as pd df = pd.read_csv(fc.selected) col_names = df.columns.values.tolist() x_widget.options = col_names y_widget.options = col_names label_widget.options = col_names if "longitude" in col_names: x_widget.value = "longitude" if "latitude" in col_names: y_widget.value = "latitude" if "name" in col_names: label_widget.value = "name" elif change["new"] == "Display": if x_widget.value is not None and (y_widget.value is not None): m.add_points_from_csv( fc.selected, x=x_widget.value, y=y_widget.value, label=label_widget.value, layer_name=layer_widget.value, ) elif change["new"] == "Close": fc.reset() m.remove_control(output_ctrl) btns.observe(btn_click, "value") csv_widget = widgets.VBox( [ fc, widgets.HBox([x_widget, y_widget]), label_widget, layer_widget, btns, ] ) display(csv_widget) m.add_control(output_ctrl) for i in range(rows): for j in range(cols): tool = grid[i, j] tool.on_click(tool_click)
def display(self): ch = 0 self.x = (np.arange(self.size) - self.osc[ch].regset.cfg_pre) / self.osc[ch].sample_rate buff = [np.zeros(self.size) for ch in self.channels] rmax = 1.0 #output_notebook(resources=INLINE) output_notebook() colors = ('red', 'blue') tools = "pan,wheel_zoom,box_zoom,reset,crosshair" self.p = figure(plot_height=500, plot_width=900, title="oscilloscope", toolbar_location="above", tools=(tools)) self.p.xaxis.axis_label = 'time [s]' #self.p.yaxis.axis_label = 'voltage [V]' self.p.x_range = Range1d(self.x[0], self.x[-1]) self.p.y_range = Range1d(-rmax, +rmax) self.p.extra_y_ranges = { str(ch): Range1d(-rmax, +rmax) for ch in self.channels } for ch in self.channels: self.p.add_layout( LinearAxis(y_range_name=str(ch).format(ch), axis_label='CH {} voltage [V]'.format(ch)), 'left') self.r = [ self.p.line(self.x, buff[ch], line_width=1, line_alpha=0.7, color=colors[ch], y_range_name=str(ch)) for ch in self.channels ] # trigger time/amplitude ch = 0 if self.osc[ch].edg is 'pos': level = self.osc[ch].level[1] else: level = self.osc[ch].level[0] self.h_trigger_t = [ self.p.line([0, 0], [-rmax, +rmax], color="black", line_width=1, line_alpha=0.75), self.p.quad(left=[0], right=[self.osc[ch].holdoff], bottom=[-rmax], top=[+rmax], color="grey", alpha=0.25) ] self.h_trigger_a = [ self.p.line([self.x[0], self.x[-1]], [level] * 2, color="black", line_width=1, line_alpha=0.75), self.p.quad(bottom=[self.osc[ch].level[0]], top=[self.osc[ch].level[1]], left=[self.x[0]], right=[self.x[-1]], color="grey", alpha=0.25) ] # configure hover tool hover = HoverTool(mode='vline', tooltips=[("T", "@x"), ("V", "@y")], renderers=self.r) self.p.add_tools(hover) # style #self.p.yaxis[0].major_tick_line_color = None #self.p.yaxis[0].minor_tick_line_color = None self.p.yaxis[0].visible = False # get an explicit handle to update the next show cell with self.target = show(self.p, notebook_handle=True) # create widgets self.w_enable = ipw.ToggleButton(value=False, description='input enable') self.w_x_scale = ipw.SelectionSlider(value=self.x_scales[-1], options=self.x_scales, description='X scale') self.w_x_position = ipw.FloatSlider(value=0, min=-rmax, max=+rmax, step=0.02, description='X position') self.w_t_source = ipw.ToggleButtons(value=self.t_source, options=[0, 1], description='T source') # style widgets self.w_enable.layout = ipw.Layout(width='100%') self.w_x_scale.layout = ipw.Layout(width='100%') self.w_x_position.layout = ipw.Layout(width='100%') self.w_enable.observe(self.clb_enable, names='value') self.w_x_scale.observe(self.clb_x_scale, names='value') self.w_x_position.observe(self.clb_x_position, names='value') self.w_t_source.observe(self.clb_t_source, names='value') display(self.w_x_scale, self.w_t_source) for ch in self.channels: self.osc[ch].display()
return ['background-color: red' if re.search('^DPS$', str(y)) else 'black' for y in x] def highlight_ducm(x): return ['background-color: blue' if re.search('^DUCM$', str(y)) else 'black' for y in x] def parametros(s): return ['background-color: '+pie_colors[v] if v in list(pie_colors.keys()) else '' for v in s] def color_negative(val): color = 'white' if val in ['DPS', 'DUCM'] else '' return 'color: %s' % color from plotly.offline import iplot, init_notebook_mode import plotly.graph_objects as go from plotly.subplots import make_subplots tipo = widgets.ToggleButtons(options=['ASV', 'OTU']) tipo.style.button_width = '60px' tipo.style.font_weight = 'bold' boton_data = Box(children=[tipo], layout= Layout(border='1px solid pink', width='69px', height='63px')) limite = widgets.Dropdown(options= range(0, 30050, 50), value = 100, description='Threshold:', layout=Layout(width='200px', height='25px')) EspecieS_asv = widgets.Dropdown(options= list(database_level_1_asv['Species'].keys()), description='', layout=Layout(width='250px', height='28px')) EspecieS_otu = widgets.Dropdown(options= list(database_level_1_otu['Species'].keys()), description='', layout=Layout(width='250px', height='28px')) bg_color = {'White':"plotly_white", 'Black':"plotly_dark"} tema = widgets.SelectionSlider(options=list(bg_color.keys()), value='White', description='Theme:', disabled=False, continuous_update=False, orientation='horizontal', readout=True)
def tool_template(m=None): widget_width = "250px" padding = "0px 0px 0px 5px" # upper, right, bottom, left toolbar_button = widgets.ToggleButton( value=False, tooltip="Toolbar", icon="gear", layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"), ) close_button = widgets.ToggleButton( value=False, tooltip="Close the tool", icon="times", button_style="primary", layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"), ) checkbox = widgets.Checkbox( description="Checkbox", indent=False, layout=widgets.Layout(padding=padding, width=widget_width), ) dropdown = widgets.Dropdown( options=["Option 1", "Option 2", "Option 3"], value=None, description="Dropdown:", layout=widgets.Layout(width=widget_width, padding=padding), style={"description_width": "initial"}, ) int_slider = widgets.IntSlider( min=1, max=100, description="Int Slider: ", readout=False, continuous_update=True, layout=widgets.Layout(width="220px", padding=padding), style={"description_width": "initial"}, ) int_slider_label = widgets.Label() widgets.jslink((int_slider, "value"), (int_slider_label, "value")) float_slider = widgets.FloatSlider( min=1, max=100, description="Float Slider: ", readout=False, continuous_update=True, layout=widgets.Layout(width="220px", padding=padding), style={"description_width": "initial"}, ) float_slider_label = widgets.Label() widgets.jslink((float_slider, "value"), (float_slider_label, "value")) color = widgets.ColorPicker( concise=False, description="Color:", value="white", style={"description_width": "initial"}, layout=widgets.Layout(width=widget_width, padding=padding), ) text = widgets.Text( value="", description="Textbox:", placeholder="Placeholder", style={"description_width": "initial"}, layout=widgets.Layout(width=widget_width, padding=padding), ) textarea = widgets.Textarea( placeholder="Placeholder", layout=widgets.Layout(width=widget_width), ) buttons = widgets.ToggleButtons( value=None, options=["Apply", "Reset", "Close"], tooltips=["Apply", "Reset", "Close"], button_style="primary", ) buttons.style.button_width = "80px" output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding)) toolbar_widget = widgets.VBox() toolbar_widget.children = [toolbar_button] toolbar_header = widgets.HBox() toolbar_header.children = [close_button, toolbar_button] toolbar_footer = widgets.VBox() toolbar_footer.children = [ checkbox, widgets.HBox([int_slider, int_slider_label]), widgets.HBox([float_slider, float_slider_label]), dropdown, text, color, textarea, buttons, output, ] toolbar_event = ipyevents.Event( source=toolbar_widget, watched_events=["mouseenter", "mouseleave"] ) def handle_toolbar_event(event): if event["type"] == "mouseenter": toolbar_widget.children = [toolbar_header, toolbar_footer] elif event["type"] == "mouseleave": if not toolbar_button.value: toolbar_widget.children = [toolbar_button] toolbar_button.value = False close_button.value = False toolbar_event.on_dom_event(handle_toolbar_event) def toolbar_btn_click(change): if change["new"]: close_button.value = False toolbar_widget.children = [toolbar_header, toolbar_footer] else: if not close_button.value: toolbar_widget.children = [toolbar_button] toolbar_button.observe(toolbar_btn_click, "value") def close_btn_click(change): if change["new"]: toolbar_button.value = False if m is not None: if m.tool_control is not None and m.tool_control in m.controls: m.remove_control(m.tool_control) m.tool_control = None toolbar_widget.close() close_button.observe(close_btn_click, "value") def button_clicked(change): if change["new"] == "Apply": with output: output.clear_output() print("Running ...") elif change["new"] == "Reset": textarea.value = "" output.clear_output() elif change["new"] == "Close": if m is not None: m.toolbar_reset() if m.tool_control is not None and m.tool_control in m.controls: m.remove_control(m.tool_control) m.tool_control = None toolbar_widget.close() buttons.value = None buttons.observe(button_clicked, "value") toolbar_button.value = True if m is not None: toolbar_control = WidgetControl(widget=toolbar_widget, position="topright") if toolbar_control not in m.controls: m.add_control(toolbar_control) m.tool_control = toolbar_control else: return toolbar_widget
def dashboard_two(): button = widgets.Button(description="View") print('Augmentations') layout = { 'width': '90%', 'height': '50px', 'border': 'solid', 'fontcolor': 'lightgreen' } layout_two = { 'width': '100%', 'height': '200px', 'border': 'solid', 'fontcolor': 'lightgreen' } style_green = { 'handle_color': 'green', 'readout_color': 'red', 'slider_color': 'blue' } style_blue = { 'handle_color': 'blue', 'readout_color': 'red', 'slider_color': 'blue' } dashboard_two.doflip = widgets.ToggleButtons( options=['Yes', "No"], description='Do Flip:', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Description of slow', 'Description of regular', 'Description of fast' ], ) dashboard_two.dovert = widgets.ToggleButtons( options=['Yes', "No"], description='Do Vert:', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltips=[ 'Description of slow', 'Description of regular', 'Description of fast' ], ) dashboard_two.two = widgets.FloatSlider(min=0, max=20, step=1, value=10, description='Max Rotate', orientation='vertical', style=style_green, layout=layout_two) dashboard_two.three = widgets.FloatSlider(min=1.1, max=4, step=1, value=1.1, description='Max Zoom', orientation='vertical', style=style_green, layout=layout_two) dashboard_two.four = widgets.FloatSlider(min=0.25, max=1.0, step=0.1, value=0.75, description='p_affine', orientation='vertical', style=style_green, layout=layout_two) dashboard_two.five = widgets.FloatSlider(min=0.2, max=0.9, step=0.1, value=0.2, description='Max Lighting', orientation='vertical', style=style_blue, layout=layout_two) dashboard_two.six = widgets.FloatSlider(min=0.25, max=1.1, step=0.1, value=0.75, description='p_lighting', orientation='vertical', style=style_blue, layout=layout_two) dashboard_two.seven = widgets.FloatSlider(min=0.1, max=0.9, step=0.1, value=0.2, description='Max warp', orientation='vertical', style=style_green, layout=layout_two) ui2 = widgets.VBox([dashboard_two.doflip, dashboard_two.dovert]) ui = widgets.HBox([ dashboard_two.two, dashboard_two.three, dashboard_two.seven, dashboard_two.four, dashboard_two.five, dashboard_two.six ]) ui3 = widgets.HBox([ui2, ui]) display(ui3) print( 'Press button to view augmentations. Pressing the button again will let you view additional augmentations below' ) display(button) def on_button_clicked(b): print('displaying augmetations') display_augs() button.on_click(on_button_clicked)
def collect_samples(m): full_widget = widgets.VBox() layout = widgets.Layout(width="100px") prop_label = widgets.Label( value="Property", layout=widgets.Layout(display="flex", justify_content="center", width="100px"), ) value_label = widgets.Label( value="Value", layout=widgets.Layout(display="flex", justify_content="center", width="100px"), ) color_label = widgets.Label( value="Color", layout=widgets.Layout(display="flex", justify_content="center", width="100px"), ) prop_text1 = widgets.Text(layout=layout, placeholder="Required") value_text1 = widgets.Text(layout=layout, placeholder="Integer") prop_text2 = widgets.Text(layout=layout, placeholder="Optional") value_text2 = widgets.Text(layout=layout, placeholder="String") color = widgets.ColorPicker( concise=False, value="#3388ff", layout=layout, style={"description_width": "initial"}, ) buttons = widgets.ToggleButtons( value=None, options=["Apply", "Clear", "Close"], tooltips=["Apply", "Clear", "Close"], button_style="primary", ) buttons.style.button_width = "99px" def button_clicked(change): if change["new"] == "Apply": if len(color.value) != 7: color.value = "#3388ff" draw_control = DrawControl( marker={"shapeOptions": {"color": color.value}, "repeatMode": True}, rectangle={"shapeOptions": {"color": color.value}, "repeatMode": True}, polygon={"shapeOptions": {"color": color.value}, "repeatMode": True}, circlemarker={}, polyline={}, edit=False, remove=False, ) controls = [] old_draw_control = None for control in m.controls: if isinstance(control, DrawControl): controls.append(draw_control) old_draw_control = control else: controls.append(control) m.controls = tuple(controls) old_draw_control.close() m.draw_control = draw_control train_props = {} if prop_text1.value != "" and value_text1.value != "": try: _ = int(value_text1.value) except Exception as _: value_text1.placeholder = "Integer only" value_text1.value = "" return train_props[prop_text1.value] = int(value_text1.value) if prop_text2.value != "" and value_text2.value != "": train_props[prop_text2.value] = value_text2.value if color.value != "": train_props["color"] = color.value # Handles draw events def handle_draw(target, action, geo_json): from .geemap import ee_tile_layer try: geom = geojson_to_ee(geo_json, False) m.user_roi = geom if len(train_props) > 0: feature = ee.Feature(geom, train_props) else: feature = ee.Feature(geom) m.draw_last_json = geo_json m.draw_last_feature = feature if action == "deleted" and len(m.draw_features) > 0: m.draw_features.remove(feature) m.draw_count -= 1 else: m.draw_features.append(feature) m.draw_count += 1 collection = ee.FeatureCollection(m.draw_features) m.user_rois = collection ee_draw_layer = ee_tile_layer( collection, {"color": "blue"}, "Drawn Features", False, 0.5 ) draw_layer_index = m.find_layer_index("Drawn Features") if draw_layer_index == -1: m.add_layer(ee_draw_layer) m.draw_layer = ee_draw_layer else: m.substitute_layer(m.draw_layer, ee_draw_layer) m.draw_layer = ee_draw_layer except Exception as e: m.draw_count = 0 m.draw_features = [] m.draw_last_feature = None m.draw_layer = None m.user_roi = None m.roi_start = False m.roi_end = False print("There was an error creating Earth Engine Feature.") raise Exception(e) draw_control.on_draw(handle_draw) elif change["new"] == "Clear": prop_text1.value = "" value_text1.value = "" prop_text2.value = "" value_text2.value = "" color.value = "#3388ff" elif change["new"] == "Close": m.toolbar_reset() if m.training_ctrl is not None and m.training_ctrl in m.controls: m.remove_control(m.training_ctrl) full_widget.close() buttons.value = None buttons.observe(button_clicked, "value") full_widget.children = [ widgets.HBox([prop_label, value_label, color_label]), widgets.HBox([prop_text1, value_text1, color]), widgets.HBox([prop_text2, value_text2, color]), buttons, ] widget_control = WidgetControl(widget=full_widget, position="topright") m.add_control(widget_control) m.training_ctrl = widget_control
def create_gui(geometry=None, callback=None, opts_choice=None, opts_range=None, opts_color=None, initial_values=None, layout=None, height=400, width=400, background='gray', orthographic=False, camera_position=[0, 0, -10], view=(10, -10, -10, 10), fov=50, add_objects=True, add_labels=True, show_object_info=False, otype_column=None, jslink=True): """ creates simple gui to visualise 3d geometry, with a callback to update geometry according to option widgets Properties ---------- geometry : pandas3js.models.GeometricCollection callback : function callback(GeometricCollection, options_dict) opts_choice : None or dict {opt_name:(initial, list)} create dropdown boxes with callbacks to callback opts_range : None or dict {opt_name:(initial, list)} create select slider with callbacks to callback opts_color : None or list {opt_name:init_color,...} create select color palette with callbacks to callback inital_values : None or dict initial values for options (default is first value of list) layout : None or list (tab_name,[option_name, ...]) pairs, if nested list, then these will be vertically aligned by default all go in 'Other' tab height : int renderer height width : int renderer width background : str renderer background color (html) orthographic : bool use orthographic camera (True) or perspective (False) camera_position : tuple position of camera in scene view : tuple initial view extents (top,bottom,left,right) (orthographic only) fov : float camera field of view (perspective only) add_objects : bool add objects to scene add_labels : bool add object labels to scene show_object_info : bool if True, show coordinate of object under mouse (currently only works for Perspective) jslink : bool if True, where possible, create client side links http://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html#The-difference-between-linking-in-the-kernel-and-linking-in-the-client Returns ------- gui : widgets.Box containing rendered scene and option widgets gcollect : pandas3js.GeometricCollection the collection of current geometric objects options_view : dict_items a view of the current options values Examples -------- >>> import pandas3js as pjs >>> import pandas as pd >>> data = {1:{'id':[0],'position':[(0,0,0)], ... 'c1':'red','c2':'blue'}, ... 2:{'id':[0],'position':[(1,2,3)], ... 'c1':'red','c2':'blue'}} ... >>> def callback(geometry,options): ... df = pd.DataFrame(data[options['config']]) ... ctype = options.get('color','c1') ... df['color'] = df[ctype] ... df['label'] = 'myobject' ... df['otype'] = 'pandas3js.models.Sphere' ... geometry.change_by_df(df[['id','position','otype', ... 'color','label']],otype_column='otype') ... >>> gui, collect, opts = pjs.views.create_gui(callback=callback, ... opts_choice={'color':['c1','c2']}, ... opts_range={'config':[1,2]}) ... >>> [pjs.utils.obj_to_str(c) for c in gui.children] ['ipywidgets.widgets.widget_selectioncontainer.Tab', 'pythreejs.pythreejs.Renderer'] >>> collect.trait_df().loc[0] color red groups (all,) id 0 label myobject label_color red label_transparency 1 label_visible False other_info otype pandas3js.models.idobject.Sphere position (0.0, 0.0, 0.0) radius 1 transparency 1 visible True Name: 0, dtype: object >>> config_select = gui.children[0].children[1].children[1].children[1] >>> pjs.utils.obj_to_str(config_select) 'ipywidgets.widgets.widget_selection.SelectionSlider' >>> config_select.value = 2 >>> collect.trait_df().loc[0] color red groups (all,) id 0 label myobject label_color red label_transparency 1 label_visible False other_info otype pandas3js.models.idobject.Sphere position (1.0, 2.0, 3.0) radius 1 transparency 1 visible True Name: 0, dtype: object >>> color_select = gui.children[0].children[1].children[1].children[0] >>> pjs.utils.obj_to_str(color_select) 'ipywidgets.widgets.widget_selection.ToggleButtons' >>> color_select.value = 'c2' >>> collect.trait_df().loc[0] color blue groups (all,) id 0 label myobject label_color red label_transparency 1 label_visible False other_info otype pandas3js.models.idobject.Sphere position (1.0, 2.0, 3.0) radius 1 transparency 1 visible True Name: 0, dtype: object """ ## intialise options init_vals = {} if initial_values is None else initial_values opts_choice = {} if opts_choice is None else opts_choice all_options = { label: init_vals[label] if label in init_vals else options[0] for label, options in opts_choice.items() } opts_range = {} if opts_range is None else opts_range all_options.update({ label: init_vals[label] if label in init_vals else options[0] for label, options in opts_range.items() }) opts_color = {} if opts_color is None else opts_color all_options.update({ label: init_vals[label] if label in init_vals else init for label, init in opts_color.items() }) if len(all_options ) != len(opts_choice) + len(opts_range) + len(opts_color): raise ValueError( 'options in opts_choice, opts_slide, and opts_color are not unique' ) ## intialise layout layout = [] if layout is None else layout layout_dict = OrderedDict(layout) if len(layout_dict) != len(layout): raise ValueError('layout tab names are not unique') ## initialise renderer if geometry is None: gcollect = pjs.models.GeometricCollection() else: gcollect = geometry scene = pjs.views.create_js_scene_view(gcollect, add_objects=add_objects, add_labels=add_labels, jslink=jslink) camera, renderer = pjs.views.create_jsrenderer( scene, orthographic=orthographic, camera_position=camera_position, view=view, fov=fov, height=height, width=width, background=background) ## create minimal callback if callback is None: def callback(geometry, options): return ## initialise geometry in renderer with renderer.hold_trait_notifications(): callback(gcollect, all_options) ## Create controls and callbacks controls = {} # a check box for showing labels if add_labels: toggle = widgets.Checkbox(value=False, description='View Label:') def handle_toggle(change): for obj in gcollect.idobjects: obj.label_visible = change.new toggle.observe(handle_toggle, names='value') controls['View Label'] = toggle # zoom sliders for orthographic if orthographic: top, bottom, left, right = view axiszoom = widgets.FloatSlider( value=0, min=-10, max=10, step=0.1, description='zoom', continuous_update=True, ) def handle_axiszoom(change): if change.new > 1: zoom = 1. / change.new elif change.new < -1: zoom = -change.new else: zoom = 1 with renderer.hold_trait_notifications(): camera.left = zoom * left camera.right = zoom * right camera.top = zoom * top camera.bottom = zoom * bottom axiszoom.observe(handle_axiszoom, names='value') controls['Orthographic Zoom'] = axiszoom # add additional options dd_min = 4 # min amount of options before switch to toggle buttons for label in opts_choice: options = opts_choice[label] initial = init_vals[label] if label in init_vals else options[0] assert initial in list( options), "initial value {0} for {1} not in range: {2}".format( initial, label, list(options)) if (len(options) == 2 and True in options and False in options and isinstance(options[0], bool) and isinstance(options[1], bool)): ddown = widgets.Checkbox(value=initial, description=label) elif len(options) < dd_min: ddown = widgets.ToggleButtons(options=list(options), description=label, value=initial) else: ddown = widgets.Dropdown(options=list(options), description=label, value=initial) handle = _create_callback(renderer, ddown, callback, gcollect, all_options) ddown.observe(handle, names='value') controls[label] = ddown for label in opts_range: options = opts_range[label] initial = init_vals[label] if label in init_vals else options[0] assert initial in list( options), "initial value {0} for {1} not in range: {2}".format( initial, label, list(options)) slider = widgets.SelectionSlider(description=label, value=initial, options=list(options), continuous_update=False) handle = _create_callback(renderer, slider, callback, gcollect, all_options) slider.observe(handle, names='value') controls[label] = slider for label in opts_color: option = init_vals[label] if label in init_vals else opts_color[label] color = widgets.ColorPicker(description=label, value=option, concise=False) handle = _create_callback(renderer, color, callback, gcollect, all_options) color.observe(handle, names='value') controls[label] = slider # add mouse hover information box # TODO doesn't work for orthographic https://github.com/jovyan/pythreejs/issues/101 if not orthographic and show_object_info: # create information box click_picker = tjs.Picker(root=scene.children[0], event='mousemove') infobox = widgets.HTMLMath() def change_info(change): if click_picker.object: infobox.value = 'Object Coordinate: ({1:.3f}, {2:.3f}, {3:.3f})<br>{0}'.format( click_picker.object.other_info, *click_picker.object.position) else: infobox.value = '' click_picker.observe(change_info, names=['object']) renderer.controls = renderer.controls + [click_picker] renderer = widgets.HBox([renderer, infobox]) if not controls: return (renderer, gcollect, all_options.viewitems() if hasattr( all_options, 'viewitems') else all_options.items() ) # python 2/3 compatability ## layout tabs and controls tabs = OrderedDict() for tab_name, clist in layout_dict.items(): vbox_list = [] for cname in clist: if isinstance(cname, list): hbox_list = [controls.pop(subcname) for subcname in cname] vbox_list.append(widgets.HBox(hbox_list)) else: vbox_list.append(controls.pop(cname)) tabs[tab_name] = widgets.VBox(vbox_list) if 'Orthographic Zoom' in controls: tabs.setdefault('View', widgets.Box()) tabs['View'] = widgets.VBox( [tabs['View'], controls.pop('Orthographic Zoom')]) if 'View Label' in controls: tabs.setdefault('View', widgets.Box()) tabs['View'] = widgets.VBox([tabs['View'], controls.pop('View Label')]) # deal with remaining controls if controls: vbox_list = [] for cname in natural_sort(controls): vbox_list.append(controls.pop(cname)) tabs.setdefault('Other', widgets.Box()) tabs['Other'] = widgets.VBox([tabs['Other'], widgets.VBox(vbox_list)]) options = widgets.Tab(children=tuple(tabs.values())) for i, name in enumerate(tabs): options.set_title(i, name) return (widgets.VBox([options, renderer]), gcollect, all_options.viewitems() if hasattr(all_options, 'viewitems') else all_options.items() ) # python 2/3 compatability