def renamed_files(self): self.renamed_basename_list_of_files = self.get_renamed_basename_list_of_files( ) basename_list_of_files_that_will_be_extracted = self.basename_list_of_files_that_will_be_extracted question_widget = widgets.Checkbox(value=True, description="Rename files?") question_widget.observe(self.renaming_checkbox_changed, names='value') self.renaming_files_widget = question_widget self.left_vertical_layout = widgets.VBox( [ widgets.Label("Before renaming", layout=widgets.Layout(width='100%')), widgets.Select( options=basename_list_of_files_that_will_be_extracted, layout=widgets.Layout(width='90%', height='400px')) ], layout=widgets.Layout(width='40%')) self.right_vertical_layout = widgets.VBox([ widgets.Label("After renaming", layout=widgets.Layout(width='100%')), widgets.Select(options=self.renamed_basename_list_of_files, layout=widgets.Layout(width='90%', height='400px')) ], layout=widgets.Layout( width='40%')) horizontal_layout = widgets.HBox( [self.left_vertical_layout, self.right_vertical_layout]) full_vertical_layout = widgets.VBox( [question_widget, horizontal_layout]) display(full_vertical_layout)
def _create_pairs_widget(self, key, disabled): # type: (str, bool) -> widgets.HBox """Return an HBox containing the interface to add and remove pairs of available elements. The term "available elements" refers to those elements in the first column of the CSV file's path stored under the parameter's "file" key. Users will not be able to add existing pairs or pairs formed by the same element twice. Keyword Arguments: key -- name of the parameter disabled -- is the parameter/widget disabled? """ # Load the list of available elements from the first column of # the CSV file saved under the parameter's "file" key srcFilePath = self[self._parameters[key]['file']] options = pandas.read_csv(srcFilePath).iloc[:, 0].tolist() # Create two Select widgets with the list of available elements leftSelect = widgets.Select(options=options, rows=4, style=self._style, layout=Layout(width='20%'), disabled=disabled) rightSelect = widgets.Select(options=options, rows=4, style=self._style, layout=Layout(width='20%'), disabled=disabled) # Create the add and remove buttons with the handler to add and # remove pairs, respectively addButton = _TaggedButton(description='Pair >>', tooltip='Add new pair', tag=key, layout=Layout(width='95%'), disabled=disabled) # Add handlerfor when the button is clicked addButton.on_click(self._pairs_add_handler) delButton = _TaggedButton(description='<< Remove', tooltip='Remove selected pair', tag=key, layout=Layout(width='95%'), disabled=disabled) # Add handler for when the button is clicked delButton.on_click(self._pairs_del_handler) layout = Layout(width='21%', justify_content='space-around') # Hold the buttons in a VBox to get the desired layout buttonsBox = widgets.VBox([addButton, delButton], layout=layout) # Create a Select widget with the parameter's list of pairs pairs = [' , '.join(x) for x in self[key]] pairsSelect = widgets.Select(options=pairs, rows=4, style=self._style, layout=Layout(width='28%'), disabled=disabled) layout = Layout(width='46%', justify_content='space-around') return widgets.HBox([leftSelect, rightSelect, buttonsBox, pairsSelect], layout=layout)
def instantiate_objects(self): self.out_graph = widgets.Output() self.out_url = widgets.Output() self.out_func = widgets.Output() self.btn_gen = widgets.Button(description="Generate Vis") self.btn_add = widgets.Button(description="Add Mapping") self.btn_rem = widgets.Button(description="Remove Mapping") self.btn_clear_assigned = widgets.Button(description="Clear") self.sel_cols = widgets.Select(options=[], disabled=False) self.sel_fields = widgets.Select(options=[], disabled=False) self.sel_assigned = widgets.Select(options=[], disabled=False) self.lbl_cols = widgets.Label(value="Columns") self.chk_incidx = widgets.Checkbox(value=False, description='Inc. Index', disabled=False, indent=False) self.lbl_fields = widgets.Label(value="Fields") self.lbl_assigned = widgets.Label(value="Assigned") self.lbl_core = widgets.Label(value="Visualization Core") self.lbl_title = widgets.Label(value="Chart Title:") self.txt_title = widgets.Text(value="My Chart") self.txt_xaxis = widgets.Text(value="") self.txt_yaxis = widgets.Text(value="") self.lbl_xaxis = widgets.Label(value="X Axis") self.lbl_yaxis = widgets.Label(value="Y Axis") self.lbl_charth = widgets.Label(value="Chart Height:") self.lbl_chartw = widgets.Label(value="Chart Width:") self.txt_charth = widgets.Text(value="750") self.txt_chartw = widgets.Text(value="2000") self.lbl_break = widgets.Label( value= "---------------------------------------------------------------------------------" ) self.sel_df = widgets.Select(options=[], description='Data Frame:', disabled=False) self.drp_charts = widgets.Dropdown(options=[], description='Chart Type:', disabled=False)
def get_folder_widget(self): """Return Widget in which a local folder can be selected""" folder_widget_title = widgets.HTML(value='<b>1. Select a folder.</b>') current_dir = os.getcwd() folder_paths = scan_folders(current_dir) for folder_path in folder_paths: files_in_folder = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))] json_files = [f for f in files_in_folder if f.endswith('.json')] self.dir_tree[folder_path] = json_files folder_widget = widgets.Select( options=self.dir_tree.keys(), value=list(self.dir_tree.keys())[0], layout=LAYOUT_FOLDER_WIDGET ) folder_widget.observe( self.folder_widget_change_listener, names='value' ) return widgets.VBox([folder_widget_title, folder_widget])
def make_selection( self, rowiter) -> Union[widgets.ToggleButtons, widgets.Select]: """ Construct buttons/selection to choose a label""" row = rowiter[1] # set value of selector from label column if label column was set if self.label_col is not None and row[self.label_col] in self.options: value = row[self.label_col] else: # set value of selector from target column if the value # in the target column is one of the labels if row[self.target_col] in self.options: value = row[self.target_col] else: value = None if self.button_type == 'button': sel = widgets.ToggleButtons(options=self.options, value=value, layout=Layout(width='100%')) else: sel = widgets.Select(options=self.options, value=value) self.active_selections.append((rowiter, sel)) return sel
def full_list_elements(self): retrieve_material = RetrieveMaterialMetadata(material='all') self.list_returned = retrieve_material.full_list_material() # import pprint # pprint.pprint(list_returned) box4 = widgets.HBox([ widgets.Label("List of elements", layout=widgets.Layout(width=self.label_width)), widgets.Select(options=self.list_returned, layout=widgets.Layout(width='20%')) ]) box5 = widgets.HBox([ widgets.Label("Nbr Bragg Edges", layout=widgets.Layout(width=self.label_width)), widgets.IntText(8, layout=widgets.Layout(width='20%')) ]) vertical_box = widgets.VBox([box4, box5]) display(vertical_box) self.list_elements_ui = box4.children[1] self.nbr_bragg_edges_ui = box5.children[1]
def plot_timeseries(datamart, rows_df=None, plot_fcst=False, use_log_values=False): """Plot meter readings vs time interactively.""" if use_log_values: fact_column = 'fact_log' leak_column = 'leak_log' target_column = 'target_log' fcst_column = 'fcst_log' else: fact_column = 'fact' leak_column = 'leak' target_column = 'target' fcst_column = 'fcst' if plot_fcst: cols = [target_column, fcst_column] else: cols = [leak_column, fact_column, target_column] df_to_plot = datamart.loc[:, ['meter', 'building_id', 'timestamp'] + cols] if rows_df is None: rows_df = datamart[['meter', 'building_id', 'site_id']].drop_duplicates() else: rows_df = rows_df.reset_index()[['meter', 'building_id', 'site_id']] df_to_plot = df_to_plot.merge(rows_df, on=['meter', 'building_id']) df_to_plot.set_index('timestamp', inplace=True) meter_widget = widgets.RadioButtons( options=[('Electricity (0)', 0), ('Chilled water (1)', 1), ('Steam (2)', 2), ('Hot water (3)', 3)]) building_id_widget = widgets.Select() def update_buildings_list(*args): building_id_widget.options = [ (f"{row['building_id']}, site {row['site_id']}", row['building_id']) for _, row in rows_df[ rows_df.meter == meter_widget.value].iterrows() ] meter_widget.observe(update_buildings_list, 'value') update_buildings_list() def plot_meter(meter, building_id): df_to_plot_selected = df_to_plot[(df_to_plot['meter'] == meter) & ( df_to_plot['building_id'] == building_id)][cols] if df_to_plot_selected[cols[0]].isna().all(): df_to_plot_selected.loc['01.01.2016 00:00', cols[0]] = 0 plot = df_to_plot_selected.iplot( asFigure=True, kind='scatter', width=1, theme='ggplot', dimensions=(None, None), margin=(0, 0, 30, 30), # l,r,b,t ) plot['layout']['legend_orientation'] = 'h' display(plot) interact(plot_meter, meter=meter_widget, building_id=building_id_widget)
def mission(): """Mission selection widget Return: dropdown selection widget (Select) """ options = { 'All': ["-"], 'Sentinel-1': ["All S1", "SLC", "GRD", "OCN", "RAW"], 'Sentinel-2': ["All S2", "S2MSI1C", "S2MSI2A", "S2MSI2Ap"], 'Sentinel-3': [ "All S3", "SR_1_SRA___", "SR_1_SRA_A_", "SR_1_SRA_BS", "SR_2_LAN___", "OL_1_EFR___", "OL_1_ERR___", "SL_1_RBT___", "OL_2_LFR___", "OL_2_LRR___", "SL_2_LST___", "OL_2_WFR___", "OL_2_WRR___", "SL_2_WST___", "SR_2_WAT___", "SY_2_SYN___", "SY_2_V10___", "SY_2_VG1___", "SY_2_VGP___" ], 'Sentinel-5 Precursor': [ "All S5P", "L1B_IR_SIR", "L1B_IR_UVN", "L1B_RA_BD1", "L1B_RA_BD2", "L1B_RA_BD3", "L1B_RA_BD4", "L1B_RA_BD5", "L1B_RA_BD6", "L1B_RA_BD7", "L1B_RA_BD8", "L2__AER_AI", "L2__CH4___", "L2__CLOUD_", "L2__SO2___", "L2__CO____", "L2__HCHO__", "L2__NO2___", "L2__O3____", "L2__O3_TCL" ], 'Envisat': ["ASA_IM__0P", "ASA_WS__0P"], 'Landsat-*': ["L1TP"], # 'Copernicus-Land':["All CLand"], # 'Copernicus-Marine':["All CMarine"], # 'Copernicus-Atmosphere':["All Cams"] } m = widgets.Select(options=options) return m
def create_platform_product_gui(platforms: List[str], products: List[str], datacube: datacube.Datacube, default_platform:str = None, default_product:str = None,): """ Description: ----- """ plat_selected = [None] prod_selected = [None] def parse_widget(x): var = datacube.list_products() return var["name"][(var["platform"] == x) & (var["name"].isin(products))] def get_keys(platform): products = [x for x in parse_widget(platform)] product = default_product if default_product in products else products[0] product_widget = widgets.Select(options=products, value=product) product_field = widgets.interactive(get_product, prod=product_widget, continuous_update=True) display(product_field) plat_selected[0] = (platform) return platform def get_product(prod): prod_selected[0] = (prod) return prod platform = default_platform if default_platform in platforms else platforms[0] platform_widget = widgets.Select(options=platforms, value=platform) platform_field = widgets.interactive(get_keys, platform=platform_widget, continuous_update=True) display(platform_field) return [plat_selected, prod_selected]
def __init__(self, callback_function, default_cmap): """ Initialize a set of widgets that select a colorbar. Parameters: ----------- callback_function: callable The function to call when activating/deactivating the range, or when changing the colormap default_cmap: string The name of the colormap that will be used when the widget is initialized """ # Create the colormap widget available_cmaps = sorted(plt.colormaps()) if default_cmap not in available_cmaps: default_cmap = 'jet' self.cmap = widgets.Select(options=available_cmaps, value=default_cmap) # Create the widgets for the range self.active = widgets.Checkbox(value=False) self.low_bound = widgets.FloatText(value=-5.) self.up_bound = widgets.FloatText(value=5.) self.exponent = widgets.FloatText(value=9.) # Add the callback function self.active.observe(callback_function, 'value', 'change') self.exponent.observe(callback_function, 'value', 'change') self.cmap.observe(callback_function, 'value', 'change')
def get_keys(platform): products = [x for x in parse_widget(platform)] product = default_product if default_product in products else products[0] product_widget = widgets.Select(options=products, value=product) product_field = widgets.interactive(get_product, prod=product_widget, continuous_update=True) display(product_field) plat_selected[0] = (platform) return platform
def createSelector(self, opt = ['least squares', 'maximum likelihood'],val = 'least squares', rows=1, desc = 'optimizer'): selector = widgets.Select( options=opt, value=val, rows= rows, description=desc, disabled=False ) return selector
def select_instrument(self): list_instruments = list(LIST_SANS_INSTRUMENTS.keys()) instrument_ui = widgets.HBox([ widgets.Label("Select your instrument", layout=widgets.Layout(width='15%')), widgets.Select(options=list_instruments, layout=widgets.Layout(width='30%', height='50px')) ]) display(instrument_ui) self.instrument_list_ui = instrument_ui.children[1]
def recap_merging_list(self): box0 = widgets.VBox([widgets.Label("List of Runs", layout=widgets.Layout(width='100%')), widgets.Select(options=self.master_list_images_to_combine.keys(), layout=widgets.Layout(width='150px', height='300px'))], layout=widgets.Layout(width="160px")) self.list_of_runs_ui = box0.children[1] box1 = widgets.VBox([widgets.Label("List of positions", layout=widgets.Layout(width='100%')), widgets.Select(options=self.get_list_of_position_for_select_run(), layout=widgets.Layout(width='150px', height='300px'))], layout=widgets.Layout(width="160px")) self.list_of_positions_ui = box1.children[1] box2 = widgets.VBox([widgets.Label("List of Files for this position", layout=widgets.Layout(width='100%')), widgets.Select(options=self.get_list_of_files_for_selected_run_position(), layout=widgets.Layout(width='100%', height='500px'))], layout=widgets.Layout(width="815px")) self.list_of_files_ui = box2.children[1] box3 = widgets.VBox([widgets.Label("Metadata"), widgets.Textarea("", disabled=True), widgets.Label("Error allowed: {}".format(METADATA_ERROR))], layout=widgets.Layout(width="300px")) str_metadata = self.get_str_metadata(metadata_dict=self.get_metadata_for_selected_run_position()) self.metadata_recap_textarea = box3.children[1] self.metadata_recap_textarea.value = str_metadata hori_box = widgets.HBox([box0, box1, box2, box3], layout=widgets.Layout(width='100%')) self.list_of_positions_ui.on_trait_change(self.recap_positions_changed, name='value') self.list_of_runs_ui.on_trait_change(self.recap_runs_changed, name='value') display(hori_box)
def Select(question, options=['Linux', 'Windows', 'OSX']): start_time = time.time() widget = widgets.Select( options=options, value='OSX', # rows=10, description='OS:', disabled=False) display(widget) def on_value_change(change): # Appends to the dictionary answer Answer_Dict[question].append(change["new"]) widget.observe(on_value_change, names='value') button(question, start_time)
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.Select(*args, **kwargs) if run: self.run()
def plot_derivatives(datamart, target_col, derivatives_cols): """Plot derivatives interactively.""" cols = [target_col] + derivatives_cols df_to_plot = datamart.loc[:, ['meter', 'site_id', 'building_id', 'timestamp'] + cols] df_to_plot.set_index('timestamp', inplace=True) rows_df = datamart[['meter', 'building_id', 'site_id']].drop_duplicates() meter_widget = widgets.RadioButtons( options=[('Electricity (0)', 0), ('Chilled water (1)', 1), ('Steam (2)', 2), ('Hot water (3)', 3)]) building_id_widget = widgets.Select() def update_buildings_list(*args): building_id_widget.options = [ (f"{row['building_id']}, site {row['site_id']}", row['building_id']) for _, row in rows_df[ rows_df.meter == meter_widget.value].iterrows() ] meter_widget.observe(update_buildings_list, 'value') update_buildings_list() def plot_meter(meter, building_id): df_to_plot_selected = df_to_plot[(df_to_plot['meter'] == meter) & ( df_to_plot['building_id'] == building_id)][cols] if df_to_plot_selected[cols[0]].isna().all(): df_to_plot_selected.loc['01.01.2016 00:00', cols[0]] = 0 plot = df_to_plot_selected.iplot( asFigure=True, kind='scatter', width=1, theme='ggplot', dimensions=(None, None), margin=(0, 0, 30, 30), # l,r,b,t ) plot['layout']['legend_orientation'] = 'h' display(plot) interact(plot_meter, meter=meter_widget, building_id=building_id_widget)
def __init__(self, callback_function, default_cmap, default_vmin, default_vmax): """ Initialize a set of widgets that select a colorbar. Parameters: ----------- callback_function: callable The function to call when activating/deactivating the range, or when changing the colormap default_cmap: string The name of the colormap that will be used when the widget is initialized default_vmin, default_vmax: float The default value for the initial value of vmin and vmax """ # Create the colormap widget available_cmaps = sorted(plt.colormaps()) if default_cmap not in available_cmaps: default_cmap = 'jet' self.cmap = widgets.Select(options=available_cmaps, value=default_cmap) # Convert default_vmin, default vmax to scientific format max_abs = max(abs(default_vmin), abs(default_vmax)) default_exponent = math.floor(math.log10(max_abs)) default_upbound = default_vmax * 10.**(-default_exponent) default_lowbound = default_vmin * 10.**(-default_exponent) # Create the widgets for the range self.active = create_checkbox(value=False) self.low_bound = widgets.FloatText(value=default_lowbound) self.up_bound = widgets.FloatText(value=default_upbound) self.exponent = widgets.FloatText(value=default_exponent) # Add the callback function self.active.observe(callback_function, 'value', 'change') self.exponent.observe(callback_function, 'value', 'change') self.cmap.observe(callback_function, 'value', 'change')
def on_value_change(self, change, url): next_url = change['new'] if next_url is None: # 'Select...' chosen return if next_url.endswith('.grb'): # File reached return self.select_url(next_url) [w.close() for w in self.elts] links = self.get_links( next_url, href_filter=(self.dir_and_not_data if next_url == self.base_url else self.dir_or_grib)) if not links: return next_dd = widgets.Select( options=links, description='', #urlparse(url).path, ) next_dd.observe(partial(self.on_value_change, url=next_url), names='value') lbl = widgets.Label(urlparse(next_url).path, layout=self.label_layout) hbox = widgets.HBox([lbl, next_dd]) self.elts = [hbox, lbl, next_dd] display(hbox)
def select(self, callback_method, _analyser, options, variable="", description="", index=0, width='100%', height='100%', disabled=False): _analyser.data[variable] = [options[index]] select = widgets.Select(options=options, value=options[index], rows=1, description=description, disabled=disabled, indent=False, layout=widgets.Layout(width=width, height=height, grid_area=variable)) select.observe(callback_method, ['value']) return select
def how_to_extract(self): # how to extract hori_layout_1 = widgets.HBox([ widgets.Label("Extract 1 over ", layout=widgets.Layout(width="10%")), widgets.Dropdown(options=np.arange(1, self.number_of_files), value=2, layout=widgets.Layout(width="5%")), widgets.Label("files", layout=widgets.Layout(width="10%")) ]) self.extracting_ui = hori_layout_1.children[1] # number of files that will be extracted hori_layout_2 = widgets.HBox([ widgets.Label(self.extract_message.format( self.get_number_of_files_to_extract()), layout=widgets.Layout(width="40%")) ]) self.extracting_label_ui = hori_layout_2.children[0] # list of files that will be extracted hori_layout_3 = widgets.HBox([ widgets.Label("List of files extracted", layout=widgets.Layout(width='20%')), widgets.Select(options=self.basename_list_files, layout=widgets.Layout(width='80%', height='400px')) ]) self.list_of_files_that_will_be_extracted_ui = hori_layout_3.children[ 1] verti_layout = widgets.VBox( [hori_layout_1, hori_layout_2, hori_layout_3]) display(verti_layout) self.extracting_ui = hori_layout_1.children[1] self.extracting_ui.observe(self.update_extracting_value, names='value')
def display_metadata(self, list_nexus): self.o_file.shortcut_buttons.close() self.list_nexus = list_nexus self.list_keys = self.retrieve_left_widget_list_keys() self.list_values = self.retrieve_right_widget_list_keys( left_widget_key_selected=list(self.list_keys)[0]) # search box search_box = widgets.HBox([ widgets.Label("Search:"), widgets.Text("", layout=widgets.Layout(width="30%")) ]) # search_text_widget = search_box.children[1] # search_text_widget.observe(self.search_text_changed, names='value') # list of keys hori_box = widgets.HBox([ widgets.Select(options=self.list_keys, layout=widgets.Layout(width="400px", height=self.widget_height)), widgets.SelectMultiple(options=self.list_values, layout=widgets.Layout( width="400px", height=self.widget_height)) ], ) display(hori_box) [self.left_widget_ui, self.right_widget_ui] = hori_box.children self.left_widget_ui.observe(self.left_widget_changed, names='value') self.right_widget_ui.observe(self.right_widget_changed, names='value') display( widgets.Label( "Command + Click: to select more than 1 element in the right widget" ))
def __init__(self, base_url='https://hydro1.gesdisc.eosdis.nasa.gov/data/NLDAS/', **layout_kwargs): self.base_url = base_url self.selected_url = None if 'min_width' not in layout_kwargs: layout_kwargs['min_width'] = '30%' self.label_layout = Layout(**layout_kwargs) dd = widgets.Select( options=self.get_links( base_url, href_filter=self.dir_and_not_data, ), description='', #urlparse(base_url).path, ) dd.observe(partial(self.on_value_change, url=self.base_url), names='value') lbl = widgets.Label(urlparse(self.base_url).path, layout=self.label_layout) hbox = widgets.HBox([lbl, dd]) self.elts = [hbox, lbl, dd] display(hbox)
def __init__(self, *args, **kwargs): self._widget = widgets.Select(*args, **kwargs) self.unique_class_id = f"IJ_selection_{self._widget.model_id}" self._widget.add_class(self.unique_class_id)
def slider(self, figsize=(8, 8), exclude_particle_records=['charge', 'mass'], **kw): """ Navigate the simulation using a slider Parameters: ----------- figsize: tuple Size of the figures exclude_particle_records: list of strings List of particle quantities that should not be displayed in the slider (typically because they are less interesting) kw: dict Extra arguments to pass to matplotlib's imshow """ # ----------------------- # Define useful functions # ----------------------- def refresh_field(change=None, force=False): """ Refresh the current field figure Parameters : ------------ change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) This is mainline a place holder ; not used in this function force: bool Whether to force the update """ # Determine whether to do the refresh do_refresh = False if (self.avail_fields is not None): if force or fld_refresh_toggle.value: do_refresh = True # Do the refresh if do_refresh: plt.figure(fld_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if fld_use_button.value: i_power = fld_magnitude_button.value vmin = fld_range_button.value[0] * 10**i_power vmax = fld_range_button.value[1] * 10**i_power else: vmin = None vmax = None self.get_field(t=self.current_t, output=False, plot=True, field=fieldtype_button.value, coord=coord_button.value, m=convert_to_int(mode_button.value), slicing=slicing_button.value, theta=theta_button.value, slicing_dir=slicing_dir_button.value, vmin=vmin, vmax=vmax, cmap=fld_color_button.value) def refresh_ptcl(change=None, force=False): """ Refresh the current particle figure Parameters : ------------ change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) This is mainline a place holder ; not used in this function force: bool Whether to force the update """ # Determine whether to do the refresh do_refresh = False if self.avail_species is not None: if force or ptcl_refresh_toggle.value: do_refresh = True # Do the refresh if do_refresh: plt.figure(ptcl_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if ptcl_use_button.value: i_power = ptcl_magnitude_button.value vmin = ptcl_range_button.value[0] * 10**i_power vmax = ptcl_range_button.value[1] * 10**i_power else: vmin = None vmax = None if ptcl_yaxis_button.value == 'None': # 1D histogram self.get_particle( t=self.current_t, output=False, var_list=[ptcl_xaxis_button.value], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value, use_field_mesh=ptcl_use_field_button.value) else: # 2D histogram self.get_particle( t=self.current_t, output=False, var_list=[ ptcl_xaxis_button.value, ptcl_yaxis_button.value ], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value, use_field_mesh=ptcl_use_field_button.value) def refresh_field_type(change): """ Refresh the field type and disable the coordinates buttons if the field is scalar. Parameter --------- change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) """ if self.avail_fields[change['new']] == 'scalar': coord_button.disabled = True elif self.avail_fields[change['new']] == 'vector': coord_button.disabled = False refresh_field() def refresh_species(change=None): """ Refresh the particle species buttons by populating them with the available records for the current species Parameter --------- change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) """ # Deactivate the particle refreshing to avoid callback # while modifying the widgets saved_refresh_value = ptcl_refresh_toggle.value ptcl_refresh_toggle.value = False # Get available records for this species avail_records = [ q for q in self.avail_record_components[ ptcl_species_button.value] if q not in exclude_particle_records ] # Update the plotting buttons ptcl_xaxis_button.options = avail_records ptcl_yaxis_button.options = avail_records + ['None'] if ptcl_xaxis_button.value not in ptcl_xaxis_button.options: ptcl_xaxis_button.value = avail_records[0] if ptcl_yaxis_button.value not in ptcl_yaxis_button.options: ptcl_yaxis_button.value = 'None' # Update the selection widgets for dropdown_button in ptcl_select_widget.quantity: dropdown_button.options = avail_records # Put back the previous value of the refreshing button ptcl_refresh_toggle.value = saved_refresh_value def change_t(change): "Plot the result at the required time" self.current_t = 1.e-15 * change['new'] refresh_field() refresh_ptcl() def step_fw(b): "Plot the result one iteration further" if self.current_i < len(self.t) - 1: self.current_t = self.t[self.current_i + 1] else: self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 def step_bw(b): "Plot the result one iteration before" if self.current_t > 0: self.current_t = self.t[self.current_i - 1] else: self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 # --------------- # Define widgets # --------------- # Slider slider = widgets.FloatSlider( min=math.ceil(1.e15 * self.tmin), max=math.ceil(1.e15 * self.tmax), step=math.ceil(1.e15 * (self.tmax - self.tmin)) / 20., description="t (fs)") slider.observe(change_t, names='value', type='change') set_widget_dimensions(slider, width=500) # Forward button button_p = widgets.Button(description="+") set_widget_dimensions(button_p, width=40) button_p.on_click(step_fw) # Backward button button_m = widgets.Button(description="-") set_widget_dimensions(button_m, width=40) button_m.on_click(step_bw) # Display the time widgets container = widgets.HBox(children=[button_m, button_p, slider]) display(container) # Field widgets # ------------- if (self.avail_fields is not None): # Field type # ---------- # Field button fieldtype_button = widgets.ToggleButtons( description='Field:', options=sorted(self.avail_fields.keys())) fieldtype_button.observe(refresh_field_type, 'value', 'change') # Coord button if self.geometry == "thetaMode": coord_button = widgets.ToggleButtons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in \ ["1dcartesian", "2dcartesian", "3dcartesian"]: coord_button = widgets.ToggleButtons(description='Coord:', options=['x', 'y', 'z']) coord_button.observe(refresh_field, 'value', 'change') # Mode and theta button (for thetaMode) mode_button = widgets.ToggleButtons(description='Mode:', options=self.avail_circ_modes) mode_button.observe(refresh_field, 'value', 'change') theta_button = widgets.FloatSlider(value=0., description=r'Theta:', min=-math.pi / 2, max=math.pi / 2) set_widget_dimensions(theta_button, width=250) theta_button.observe(refresh_field, 'value', 'change') # Slicing buttons (for 3D) slicing_dir_button = widgets.ToggleButtons( value=self.axis_labels[0], options=self.axis_labels, description='Slicing direction:') slicing_dir_button.observe(refresh_field, 'value', 'change') slicing_button = widgets.FloatSlider(description='Slicing:', min=-1., max=1., value=0.) set_widget_dimensions(slicing_button, width=250) slicing_button.observe(refresh_field, 'value', 'change') # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(description='Figure ', value=0) set_widget_dimensions(fld_figure_button, width=50) # Range of values fld_range_button = widgets.IntRangeSlider(min=-10, max=10) set_widget_dimensions(fld_range_button, width=220) fld_range_button.observe(refresh_field, 'value', 'change') # Order of magnitude fld_magnitude_button = widgets.IntText(description='x 10^', value=9) set_widget_dimensions(fld_magnitude_button, width=50) fld_magnitude_button.observe(refresh_field, 'value', 'change') # Use button fld_use_button = widgets.Checkbox(description=' Use this range', value=False) set_widget_dimensions(fld_use_button, left_margin=100) fld_use_button.observe(refresh_field, 'value', 'change') # Colormap button fld_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), value='jet') set_widget_dimensions(fld_color_button, height=50, width=200) fld_color_button.observe(refresh_field, 'value', 'change') # Resfresh buttons fld_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) fld_refresh_button = widgets.Button(description='Refresh now!') fld_refresh_button.on_click(partial(refresh_field, force=True)) # Containers # ---------- # Field type container if self.geometry == "thetaMode": container_fields = widgets.VBox(children=[ fieldtype_button, coord_button, mode_button, theta_button ]) elif self.geometry in ["1dcartesian", "2dcartesian"]: container_fields = widgets.VBox( children=[fieldtype_button, coord_button]) elif self.geometry == "3dcartesian": container_fields = widgets.VBox(children=[ fieldtype_button, coord_button, slicing_dir_button, slicing_button ]) set_widget_dimensions(container_fields, width=260) # Plotting options container container_fld_magnitude = widgets.HBox( children=[fld_magnitude_button, fld_use_button]) set_widget_dimensions(container_fld_magnitude, height=50) if self.geometry == "1dcartesian": container_fld_plots = widgets.VBox(children=[ fld_figure_button, fld_range_button, container_fld_magnitude ]) else: container_fld_plots = widgets.VBox(children=[ fld_figure_button, fld_range_button, container_fld_magnitude, fld_color_button ]) set_widget_dimensions(container_fld_plots, width=260) # Accordion for the field widgets accord1 = widgets.Accordion( children=[container_fields, container_fld_plots]) accord1.set_title(0, 'Field type') accord1.set_title(1, 'Plotting options') # Complete field container container_fld = widgets.VBox(children=[ accord1, widgets.HBox(children=[fld_refresh_toggle, fld_refresh_button]) ]) set_widget_dimensions(container_fld, width=300) # Particle widgets # ---------------- if (self.avail_species is not None): # Particle quantities # ------------------- # Species selection ptcl_species_button = widgets.Dropdown(options=self.avail_species) set_widget_dimensions(ptcl_species_button, width=250) ptcl_species_button.observe(refresh_species, 'value', 'change') # Get available records for this species avail_records = [ q for q in self.avail_record_components[ ptcl_species_button.value] if q not in exclude_particle_records ] # Particle quantity on the x axis ptcl_xaxis_button = widgets.ToggleButtons(options=avail_records) ptcl_xaxis_button.observe(refresh_ptcl, 'value', 'change') # Particle quantity on the y axis ptcl_yaxis_button = widgets.ToggleButtons(options=avail_records + ['None'], value='None') ptcl_yaxis_button.observe(refresh_ptcl, 'value', 'change') # Particle selection # ------------------ # 3 selection rules at maximum ptcl_select_widget = ParticleSelectWidget(3, avail_records, refresh_ptcl) # Plotting options # ---------------- # Figure number ptcl_figure_button = widgets.IntText(description='Figure ', value=1) set_widget_dimensions(ptcl_figure_button, width=50) # Number of bins ptcl_bins_button = widgets.IntText(description='nbins:', value=100) set_widget_dimensions(ptcl_bins_button, width=60) ptcl_bins_button.observe(refresh_ptcl, 'value', 'change') # Colormap button ptcl_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), value='Blues') set_widget_dimensions(ptcl_color_button, height=50, width=200) ptcl_color_button.observe(refresh_ptcl, 'value', 'change') # Range of values ptcl_range_button = widgets.IntRangeSlider(min=0, max=10, value=(0, 5)) set_widget_dimensions(ptcl_range_button, width=220) ptcl_range_button.observe(refresh_ptcl, 'value', 'change') # Order of magnitude ptcl_magnitude_button = widgets.IntText(description='x 10^', value=9) set_widget_dimensions(ptcl_magnitude_button, width=50) ptcl_magnitude_button.observe(refresh_ptcl, 'value', 'change') # Use button ptcl_use_button = widgets.Checkbox(description=' Use this range', value=False) set_widget_dimensions(ptcl_use_button, left_margin=100) ptcl_use_button.observe(refresh_ptcl, 'value', 'change') # Use field mesh buttons ptcl_use_field_button = widgets.Checkbox( description=' Use field mesh', value=True) set_widget_dimensions(ptcl_use_field_button, left_margin=100) ptcl_use_field_button.observe(refresh_ptcl, 'value', 'change') # Resfresh buttons ptcl_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) ptcl_refresh_button = widgets.Button(description='Refresh now!') ptcl_refresh_button.on_click(partial(refresh_ptcl, force=True)) # Containers # ---------- # Particle quantity container container_ptcl_quantities = widgets.VBox(children=[ ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button ]) set_widget_dimensions(container_ptcl_quantities, width=310) # Particle selection container container_ptcl_select = ptcl_select_widget.to_container() # Plotting options container container_ptcl_bins = widgets.HBox( children=[ptcl_bins_button, ptcl_use_field_button]) container_ptcl_magnitude = widgets.HBox( children=[ptcl_magnitude_button, ptcl_use_button]) set_widget_dimensions(container_ptcl_magnitude, height=50) container_ptcl_plots = widgets.VBox(children=[ ptcl_figure_button, container_ptcl_bins, ptcl_range_button, container_ptcl_magnitude, ptcl_color_button ]) set_widget_dimensions(container_ptcl_plots, width=310) # Accordion for the field widgets accord2 = widgets.Accordion(children=[ container_ptcl_quantities, container_ptcl_select, container_ptcl_plots ]) accord2.set_title(0, 'Particle quantities') accord2.set_title(1, 'Particle selection') accord2.set_title(2, 'Plotting options') # Complete particle container container_ptcl = widgets.VBox(children=[ accord2, widgets.HBox( children=[ptcl_refresh_toggle, ptcl_refresh_button]) ]) set_widget_dimensions(container_ptcl, width=370) # Global container if (self.avail_fields is not None) and \ (self.avail_species is not None): global_container = widgets.HBox( children=[container_fld, container_ptcl]) display(global_container) elif self.avail_species is None: display(container_fld) elif self.avail_fields is None: display(container_ptcl)
def project_select_gui(project): """ :parameter project: An instance of a :class:`openquake.mbt.project.OQtProject` """ global oqmbtp global model global w_name, w_dir, w_model, w_sources, project_dir, w_types margin = 5 oqmbtp = project models = list(oqmbtp.models.keys()) project_dir = oqmbtp.directory project_pickle_filename = os.environ.get('OQMBT_PROJECT') wdg_list = [] w_title = widgets.HTML(value="<h3>Set model parameters<h3>") # Project name tmp_str = "Project:<br>" tmp_str += "<small>%s</small><br>" % (project_dir) # Filename tmp_str += "Filename: <br>" tmp_str += "<small>%s</small><br><br>" % ( os.path.split(project_pickle_filename)[1]) w_dir = widgets.HTML(value=tmp_str) w_name = widgets.Text(description='Name', value=oqmbtp.name, width=600, margin=margin) wdg_list.append(w_title) wdg_list.append(w_dir) wdg_list.append(w_name) if len(models): model_id = models[0] model = oqmbtp.models[model_id] w_model = widgets.Dropdown(options=models, description='Model', value=model_id) if len(model.sources.keys()): types = sorted(_get_source_types(model)) types.insert(0, 'All') w_types = widgets.Select(options=types, description='Types', margin=margin, value=types[0]) keys_list = sorted(model.sources.keys()) w_sources = widgets.SelectMultiple(options=sorted(keys_list), description='Sources', margin=margin) else: w_sources = widgets.SelectMultiple(options=[], description='Sources:') wdg_list.append(w_model) wdg_list.append(w_types) wdg_list.append(w_sources) w_butt = widgets.Button(description='Done!', width=100, border_color='red') wdg_list.append(w_butt) w_types.on_trait_change(handle_change_type, 'value') w_model.on_trait_change(handle_change) w_butt.on_click(handle_click) return widgets.VBox(children=wdg_list)
def preview_combine_result(self, data_folder): list_of_input_filenames = retrieve_list_of_most_dominant_extension_from_folder( folder=data_folder)[0] self.input_folder = str(Path(list_of_input_filenames[0]).parent) list_of_input_filenames = [ os.path.basename(_file) for _file in list_of_input_filenames ] self.list_of_input_filenames = list_of_input_filenames display( HTML( '<span style="font-size: 20px; color:blue">SELECT ONLY the first images to ' 'combine into 1 image! (Select at least 3 images)</span>')) verti_layout = widgets.VBox([ widgets.SelectMultiple(options=list_of_input_filenames, layout=widgets.Layout(width="100%", height="300px")) ]) display(verti_layout) input_selection_widget = verti_layout.children[0] input_selection_widget.observe(self.input_selection_changed, names='value') hori_layout = widgets.HBox([ widgets.Label("Prefix of new filename will be ->", layout=widgets.Layout(width='20%')), widgets.Label("Not Enough images selected to correctly combine!", layout=widgets.Layout(width='80%')) ]) display(hori_layout) self.prefix_filename_widget = hori_layout.children[1] select_width = "400px" select_height = "300px" new_name_verti_layout = widgets.VBox( [ widgets.Label("New list of files"), widgets.Select(options=[], layout=widgets.Layout(width="100%", height=select_height)) ], layout=widgets.Layout(width=select_width)) new_name_verti_layout.children[1].observe( self.new_list_of_files_selection_changed, names='value') old_name_verti_layout = widgets.VBox( [ widgets.Label("Corresponding combined files"), widgets.Select(options=[], layout=widgets.Layout(width="100%", height=select_height)) ], layout=widgets.Layout(width=select_width)) hori_layout_2 = widgets.HBox([ new_name_verti_layout, widgets.Label(" "), old_name_verti_layout ], layout=widgets.Layout(width="900px")) display(hori_layout_2) self.hori_layout_2 = hori_layout_2 hori_layout_2.layout.visibility = self.get_preview_visibility() self.final_list_of_files_combined_renamed_widget = new_name_verti_layout.children[ 1] self.corresponding_list_of_files_combined = old_name_verti_layout.children[ 1]
def slider(self, figsize=(10, 10), **kw): """ Navigate the simulation using a slider Parameters : ------------ figsize: tuple Size of the figures kw: dict Extra arguments to pass to matplotlib's imshow """ # ----------------------- # Define useful functions # ----------------------- def refresh_field(force=False): "Refresh the current field figure" # Determine whether to do the refresh do_refresh = False if (self.avail_fields is not None): if force == True or fld_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: plt.figure(fld_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if fld_use_button.value == True: i_power = fld_magnitude_button.value vmin = fld_range_button.value[0] * 10**i_power vmax = fld_range_button.value[1] * 10**i_power else: vmin = None vmax = None self.get_field(t=self.current_t, output=False, plot=True, field=fieldtype_button.value, coord=coord_button.value, m=convert_to_int(mode_button.value), slicing=slicing_button.value, theta=theta_button.value, slicing_dir=slicing_dir_button.value, vmin=vmin, vmax=vmax, cmap=fld_color_button.value) def refresh_ptcl(force=False): "Refresh the current particle figure" # Determine whether to do the refresh do_refresh = False if self.avail_species is not None: if force == True or ptcl_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: plt.figure(ptcl_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if ptcl_use_button.value == True: i_power = ptcl_magnitude_button.value vmin = ptcl_range_button.value[0] * 10**i_power vmax = ptcl_range_button.value[1] * 10**i_power else: vmin = None vmax = None if ptcl_yaxis_button.value == 'None': # 1D histogram self.get_particle(t=self.current_t, output=False, var_list=[ptcl_xaxis_button.value], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value) else: # 2D histogram self.get_particle(t=self.current_t, output=False, var_list=[ ptcl_xaxis_button.value, ptcl_yaxis_button.value ], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value) def refresh_ptcl_now(b): "Refresh the particles immediately" refresh_ptcl(force=True) def refresh_fld_now(b): "Refresh the fields immediately" refresh_field(force=True) def change_t(name, value): "Plot the result at the required time" self.current_t = 1.e-15 * value refresh_field() refresh_ptcl() def step_fw(b): "Plot the result one iteration further" if self.current_i < len(self.t) - 1: self.current_t = self.t[self.current_i + 1] else: print("Reached last iteration.") self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 def step_bw(b): "Plot the result one iteration before" if self.current_t > 0: self.current_t = self.t[self.current_i - 1] else: print("Reached first iteration.") self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 # --------------- # Define widgets # --------------- # Slider slider = widgets.FloatSlider( min=math.ceil(1.e15 * self.tmin), max=math.ceil(1.e15 * self.tmax), step=math.ceil(1.e15 * (self.tmax - self.tmin)) / 20., description="t (fs)") slider.on_trait_change(change_t, 'value') # Forward button button_p = widgets.Button(description="+") button_p.on_click(step_fw) # Backward button button_m = widgets.Button(description="-") button_m.on_click(step_bw) # Display the time widgets container = widgets.HBox(children=[button_m, button_p, slider]) display(container) # Field widgets # ------------- if (self.avail_fields is not None): # Field type # ---------- # Field button fieldtype_button = widgets.ToggleButtons( description='Field:', options=sorted(self.avail_fields.keys())) fieldtype_button.on_trait_change(refresh_field) # Coord button if self.geometry == "thetaMode": coord_button = widgets.ToggleButtons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in ["2dcartesian", "3dcartesian"]: coord_button = widgets.ToggleButtons(description='Coord:', options=['x', 'y', 'z']) coord_button.on_trait_change(refresh_field) # Mode and theta button (for thetaMode) mode_button = widgets.ToggleButtons(description='Mode:', options=self.avail_circ_modes) mode_button.on_trait_change(refresh_field) theta_button = widgets.FloatSlider(width=140, value=0., description=r'Theta:', min=-math.pi / 2, max=math.pi / 2) theta_button.on_trait_change(refresh_field) # Slicing buttons (for 3D) slicing_dir_button = widgets.ToggleButtons( value='y', description='Slicing direction:', options=['x', 'y', 'z']) slicing_dir_button.on_trait_change(refresh_field) slicing_button = widgets.FloatSlider(width=150, description='Slicing:', min=-1., max=1., value=0.) slicing_button.on_trait_change(refresh_field) # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(description='Figure ', value=0, width=50) # Range of values fld_range_button = widgets.FloatRangeSlider(min=-10, max=10, width=220) fld_range_button.on_trait_change(refresh_field) # Order of magnitude fld_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) fld_magnitude_button.on_trait_change(refresh_field) # Use button fld_use_button = widgets.Checkbox(description=' Use this range', value=False) fld_use_button.on_trait_change(refresh_field) # Colormap button fld_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='jet') fld_color_button.on_trait_change(refresh_field) # Resfresh buttons fld_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) fld_refresh_button = widgets.Button(description='Refresh now!') fld_refresh_button.on_click(refresh_fld_now) # Containers # ---------- # Field type container if self.geometry == "thetaMode": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, mode_button, theta_button ]) elif self.geometry == "2dcartesian": container_fields = widgets.VBox( width=260, children=[fieldtype_button, coord_button]) elif self.geometry == "3dcartesian": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, slicing_dir_button, slicing_button ]) # Plotting options container container_fld_plots = widgets.VBox(width=260, children=[ fld_figure_button, fld_range_button, widgets.HBox(children=[ fld_magnitude_button, fld_use_button ], height=50), fld_color_button ]) # Accordion for the field widgets accord1 = widgets.Accordion( children=[container_fields, container_fld_plots]) accord1.set_title(0, 'Field type') accord1.set_title(1, 'Plotting options') # Complete field container container_fld = widgets.VBox( width=300, children=[ accord1, widgets.HBox( children=[fld_refresh_toggle, fld_refresh_button]) ]) # Particle widgets # ---------------- if (self.avail_species is not None): # Particle quantities # ------------------- # Species selection ptcl_species_button = widgets.Dropdown(width=250, options=self.avail_species) ptcl_species_button.on_trait_change(refresh_ptcl) # Remove charge and mass (less interesting) avail_ptcl_quantities = [ q for q in self.avail_ptcl_quantities \ if (q in ['charge', 'mass'])==False ] # Particle quantity on the x axis ptcl_xaxis_button = widgets.ToggleButtons( value='z', options=avail_ptcl_quantities) ptcl_xaxis_button.on_trait_change(refresh_ptcl) # Particle quantity on the y axis ptcl_yaxis_button = widgets.ToggleButtons( value='x', options=avail_ptcl_quantities + ['None']) ptcl_yaxis_button.on_trait_change(refresh_ptcl) # Particle selection # ------------------ # 3 selection rules at maximum ptcl_select_widget = ParticleSelectWidget(3, avail_ptcl_quantities, refresh_ptcl) # Plotting options # ---------------- # Figure number ptcl_figure_button = widgets.IntText(description='Figure ', value=1, width=50) # Number of bins ptcl_bins_button = widgets.IntSlider(description='nbins:', min=50, max=300, value=100, width=150) ptcl_bins_button.on_trait_change(refresh_ptcl) # Colormap button ptcl_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='Blues') ptcl_color_button.on_trait_change(refresh_ptcl) # Range of values ptcl_range_button = widgets.FloatRangeSlider(min=0, max=10, width=220, value=(0, 5)) ptcl_range_button.on_trait_change(refresh_ptcl) # Order of magnitude ptcl_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) ptcl_magnitude_button.on_trait_change(refresh_ptcl) # Use button ptcl_use_button = widgets.Checkbox(description=' Use this range', value=False) ptcl_use_button.on_trait_change(refresh_ptcl) # Resfresh buttons ptcl_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) ptcl_refresh_button = widgets.Button(description='Refresh now!') ptcl_refresh_button.on_click(refresh_ptcl_now) # Containers # ---------- # Particle quantity container container_ptcl_quantities = widgets.VBox(width=310, children=[ ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button ]) # Particle selection container container_ptcl_select = ptcl_select_widget.to_container() # Plotting options container container_ptcl_plots = widgets.VBox(width=310, children=[ ptcl_figure_button, ptcl_bins_button, ptcl_range_button, widgets.HBox(children=[ ptcl_magnitude_button, ptcl_use_button ], height=50), ptcl_color_button ]) # Accordion for the field widgets accord2 = widgets.Accordion(children=[ container_ptcl_quantities, container_ptcl_select, container_ptcl_plots ]) accord2.set_title(0, 'Particle quantities') accord2.set_title(1, 'Particle selection') accord2.set_title(2, 'Plotting options') # Complete particle container container_ptcl = widgets.VBox( width=370, children=[ accord2, widgets.HBox( children=[ptcl_refresh_toggle, ptcl_refresh_button]) ]) # Global container if (self.avail_fields is not None) and \ (self.avail_species is not None): global_container = widgets.HBox( children=[container_fld, container_ptcl]) display(global_container) elif self.avail_species is None: display(container_fld) elif self.avail_fields is None: display(container_ptcl)
def rowSelector(df, chosenCol): items = ['All'] + sorted(df[chosenCol].unique().tolist()) w = widgets.Select(options=items) lviews = lambda x: viewWrapper(df=df, chosenCol=chosenCol)( x) #lambda x: view(x, **{'df':df}) return interactive(lviews, x=w)
my_layout = Layout(margin='2px 0px 2px 00px') LAST_NAME = widgets.Text(value="",description="Last name: ",layout=my_layout) FIRST_NAME = widgets.Text(value="",description="First name: ",layout=my_layout) EMAIL = widgets.Text(value="", description="Email:",layout=my_layout) #PROJECT = widgets.Dropdown(description = "Project: ", options=["CORDEX","CMIP6","DKRZ_CDP","ESGF_replication","test","Generic"],**align_kw) PROJECT = widgets.Dropdown(description = "Project: ", options=["CORDEX","CMIP6","DKRZ_CDP","ESGF_replication","test","Generic"],layout=my_layout) KEY = widgets.Text(value="", placeholder=" A key to identify your form", description="An identifier: ",layout=my_layout) # ENTER = widgets.Text(value="", placeholder=" Press \"ENTER\" in this field to initialize your personal form" , description="... " ) ENTER = widgets.Button(value=False, description='Generate form', disabled=False, button_style='', tooltip='click to generate a personal form template', icon='check') #---- for selection files SELECTION = widgets.Button(value=False, description="Save files", disabled=False, button_style='', tooltip='click to save above files') la = widgets.Layout(height='250px', width='500px') #FORMS = widgets.Dropdown(description='Form Name: ',) FORMS = widgets.Select(description='Form Name: ',) FORMS_ENTER = widgets.Button(value=False, description='Take selected form', disabled=False, button_style='', tooltip='click to take the selected value above') TEXT_WIDGETS_DICT = {} FORM_NAME = "UNDEFINED" out = widgets.Output() init_widgets=[LAST_NAME,FIRST_NAME,EMAIL,PROJECT,KEY,widgets.VBox([ENTER,out])] submission_type = widgets.Dropdown(description = "Type of submission: ", options=["initial_version","new_version","retract"]) ## maybe move to config part .. #cordex_sel={} #cordex_sel['terms_of_use'] = ["unrestricted","non-commercial only"] #cordex_sel['qc_status'] = ["QC1","QC2","other","unchecked"]