def _createAccordion(self): if self._userFiles: arq = self._userFiles else: arq = self._files box = list() for v in arq.values(): accordion = widgets.Accordion(children=[self.nestTable(v)]) accordion.set_title(0, v) box.append(accordion) self._filesBox.children = [i for i in box] return (self._filesBox)
def get_accordion(items): children = [] titles = [] for item in items: children.append(item.render()) titles.append(get_name(item)) accordion = widgets.Accordion(children=children) for id, title in enumerate(titles): accordion.set_title(id, title) return accordion
def __plot_project_specific_accordion(project_name): # TODO: change condition inside to project_name project_specific_table_info = TableRanderer.get_project_specific_table_info(project_name) accordion = widgets.Accordion(children=[ __build_table_widget(project_specific_table_info.reset_index()) ], selected_index=None, layout=Layout(border='solid 1px', width='75.5%')) accordion.set_title( 0, 'show info of tables: ' + ", ".join(list(project_specific_table_info.index))) return accordion
def showUI(self): tab = widgets.Accordion(children= ( widgets.VBox([ self.wJobPath]), widgets.VBox([self.wKappa, widgets.Label(value="Elasticity coefficient $\mathbb{C}$ of the matrix phase"), self.wC11, self.wC12, self.wC44, self.wSubmit ]) ) ) for i, title in enumerate(['Working folder', 'Benchmark parameters']): tab.set_title(i, title ) display(tab)
def recursive_build(t): frames = [] frames.append(widgets.HTML(get_type_html(t))) if isinstance(t, hl.tstruct): append_struct_frames(t, frames) elif isinstance(t, hl.ttuple): if len(t) == 0: frames.append(widgets.HTML('<big>No fields.</big>')) else: frames.append(widgets.HTML('<big>Fields:</big>')) acc = widgets.Accordion([recursive_build(x) for x in t.types]) for i, fd in enumerate(t.types): acc.set_title(i, f'[{i}] ({format_type(fd)})') acc.selected_index = None frames.append(acc) elif isinstance(t, (hl.tarray, hl.tset)): acc = widgets.Accordion([recursive_build(t.element_type)]) acc.set_title(0, f'<element> ({format_type(t.element_type)})') acc.selected_index = None frames.append(acc) elif isinstance(t, hl.tdict): acc = widgets.Accordion( [recursive_build(t.key_type), recursive_build(t.value_type)]) acc.set_title(0, f'<key> ({format_type(t.key_type)})') acc.set_title(1, f'<value> ({format_type(t.element_type)})') acc.selected_index = None frames.append(acc) elif isinstance(t, (hl.tinterval)): acc = widgets.Accordion([recursive_build(t.point_type)]) acc.set_title(0, f'<point> ({format_type(t.point_type)})') acc.selected_index = None frames.append(acc) return widgets.VBox(frames)
def show_neurodata_base(node: NWBDataInterface, neurodata_vis_spec: dict) -> widgets.Widget: """ Gets a pynwb object and returns a Vertical Box containing textual info and an expandable Accordion with it's children. """ field_lay = widgets.Layout(max_height='40px', max_width='500px', min_height='30px', min_width='180px') info = [] # string data type, exposed as a Text widget neuro_data = [] # more complex data types, also with children labels = [] for key, value in node.fields.items(): if isinstance(value, (str, datetime)): lbl_key = widgets.Label(key + ':', layout=field_lay) lbl_val = widgets.Label(str(value), layout=field_lay) info.append(widgets.HBox(children=[lbl_key, lbl_val])) elif key == 'related_publications': pub_list = [] for pub in value: pub_list.append( widgets.HTML(value="<a href=http://dx.doi.org/" + pub[4:] + ">" + pub + "</a>")) lbl_key = widgets.Label(key + ':', layout=field_lay) pub_list.insert(0, lbl_key) info.append(widgets.HBox(children=pub_list)) elif key == 'experimenter': lbl_experimenter = widgets.Label('Experimenter:', layout=field_lay) if isinstance(value, (list, tuple)): lbl_names = widgets.Label(', '.join(value), layout=field_lay) else: lbl_names = widgets.Label(value, layout=field_lay) hbox_exp = widgets.HBox(children=[lbl_experimenter, lbl_names]) info.append(hbox_exp) elif (isinstance(value, Iterable) and len(value)) or value: neuro_data.append( view.nwb2widget(value, neurodata_vis_spec=neurodata_vis_spec)) labels.append(key) accordion = widgets.Accordion(children=neuro_data, selected_index=None) for i, label in enumerate(labels): if hasattr(node.fields[label], 'description') and node.fields[label].description: accordion.set_title(i, label + ': ' + node.fields[label].description) else: accordion.set_title(i, label) return widgets.VBox(info + [accordion])
def _ipython_display_(self): """ Displays the help message in ipython. First tries to use ipywidgets if available, otherwise builds an html string """ from IPython.display import HTML, display try: from ipywidgets import widgets #pylint: disable=import-error description = f""" <div> {self._cls.__name__} iterable parameters: </div> """ accordions = [] for group in self.param_groups: group_name = group['group_name'] description = "" description += f"""<div class="alert alert-info" style="margin: 10px 0px">' {group.get("help", "").strip()}</div>""" description += "<div>Explicitly supported keys:</div><ul><li>" description += "</li><li>".join(group["keys"]) description += "</li></ul>" if group.get("condition") is not None: description += "<div>Key matching condition: " description += f'<code>{inspect.getsource(group["condition"]).strip()}</code>' description += "</div>" accordion = widgets.Accordion([widgets.HTML(description)], selected_index=None) accordion.set_title(0, group_name) accordions.append(accordion) intro = HTML( f"<div>{self._cls.__name__} iterable parameters:</div>") display(intro, *accordions) except ModuleNotFoundError: display(HTML(self._repr_html_()))
def __plot_project_specific_member_level_accordion(project_name): table_info_used_here = TableRanderer.get_project_specific_member_level_table_info( project_name) accordion = widgets.Accordion(children=[ __build_table_widget(table_info_used_here.reset_index(), with_subtable=True, current_level='member', next_level='table', previous_condition=project_name) ], selected_index=None, layout=Layout(border='solid 1px', width='99.5%')) accordion.set_title( 0, 'show info of members: ' + ", ".join(list(table_info_used_here.index))) return accordion
def display(self): # title_widget = widgets.HTML('<em>Vertical Box Example</em>') self._stop_button.layout.display = '' self._stop_button.layout.display = 'none' control_box = widgets.HBox([self._stop_button, self._label]) accordion = widgets.Accordion( children=[self._output_widget, self._command_label], selected_index=None) accordion.set_title(0, 'Full log') accordion.set_title(1, 'Run command') vbox = widgets.VBox([control_box, accordion]) # display(accordion) display(vbox) self._is_displayed = True
def dict2accordion(d: dict, neurodata_vis_spec: dict, **pass_kwargs) -> widgets.Accordion: children = [widgets.HTML('Rendering...') for _ in d] accordion = widgets.Accordion(children=children, selected_index=None) for i, label in enumerate(d): if hasattr(d[label], 'description') and d[label].description: accordion.set_title(i, label + ': ' + d[label].description) else: accordion.set_title(i, label) accordion.set_title(i, label) def on_selected_index(change): if change.new is not None and isinstance(change.owner.children[change.new], widgets.HTML): children[change.new] = nwb2widget(list(d.values())[change.new], neurodata_vis_spec=neurodata_vis_spec, **pass_kwargs) change.owner.children = children accordion.observe(on_selected_index, names='selected_index') return accordion
def __plot_member_specific_accordion(member_name, project_name=None): # [V] change previous_condition to project_name # [V] change condition to member_name if project_name != None: member_specific_table_info = TableRanderer.get_project_member_specific_table_info( project_name, member_name) else: member_specific_table_info = TableRanderer.get_member_specific_table_info( member_name) accordion = widgets.Accordion(children=[ __build_table_widget(member_specific_table_info.reset_index()) ], selected_index=None, layout=Layout(border='solid 1px', width='75.5%')) accordion.set_title( 0, 'show info of tables: ' + ", ".join(list(member_specific_table_info.index))) return accordion
def show_neurodata_base(node): info = [] neuro_data = [] labels = [] for key, value in node.fields.items(): if isinstance(value, str): info.append( widgets.Text(value=repr(value), description=key, disabled=True)) elif (isinstance(value, Iterable) and len(value)) or value: neuro_data.append(view.nwb2widget(value)) labels.append(key) accordion = widgets.Accordion(children=neuro_data, selected_index=None) for i, label in enumerate(labels): if hasattr(node.fields[label], 'description') and node.fields[label].description: accordion.set_title(i, label + ': ' + node.fields[label].description) else: accordion.set_title(i, label) return widgets.VBox(info + [accordion])
def i_list_apps(): """ Show apps saved in the Balsam database """ import os from ipywidgets import widgets, Layout from IPython.display import display, clear_output apps = get_apps() children = [ widgets.Textarea(value=str(app), layout=Layout(flex='1 1 auto', width='400px', height='200px')) for app in apps ] tab = widgets.Accordion(children=children, layout=Layout(flex='1 1 auto', width='500px', height='auto')) for i, app in enumerate(apps): tab.set_title(i, app.name) print(f'Apps in the Balsam database {os.environ["BALSAM_DB_PATH"]}:') display(tab) return
def __init__(self): self.container = widgets.VBox(width="100%", background_color="#EEEEEE") # Flux self.flux_box = widgets.HBox(padding='10px', width="100%") self.flux = widgets.BoundedFloatText(description="Source flux: ", min=0.0, max=1.0e30, value=23.0) self.funits = widgets.Dropdown( value='abmag', options=['abmag', 'njy', 'ujy', 'mjy', 'jy']) atwave = widgets.HTML(value=" at ", margin='5px') self.wave = widgets.BoundedFloatText(min=0.1, max=99999.0, value=1.5) waveunits = widgets.HTML(value="microns", margin='5px') self.flux_box.children = [ self.flux, self.funits, atwave, self.wave, waveunits ] # SED self.sed_box = widgets.HBox(padding='10px', width="100%") self.sed_select = widgets.Dropdown(description="SED type: ", options=[ 'flat', 'phoenix', 'blackbody', 'extragalactic', 'star', 'power-law' ], value='flat') self.bb_temp = widgets.BoundedFloatText(description="Temp (K): ", min=0.0, max=99999.0, value=6500.0, width=75) phoenix_config_file = os.path.join(refdata, 'sed', 'phoenix', 'spectra.json') self.phoenix_config = get_config(phoenix_config_file) self.phoenix = widgets.Dropdown(options=sorted(self.phoenix_config)) gal_config_file = os.path.join(refdata, 'sed', 'brown', 'spectra.json') self.gal_config = get_config(gal_config_file) self.galaxies = widgets.Dropdown(options=sorted(self.gal_config)) star_config_file = os.path.join(refdata, 'sed', 'hst_calspec', 'spectra.json') self.star_config = get_config(star_config_file) self.star = widgets.Dropdown(options=sorted(self.star_config)) self.pl_index = widgets.FloatText(description="Index: ", value=1.0, width=50) # We have to define anything we're going to use from the beginning, so we do that, and then # run the helper function that displays the selected (default) item and hides the rest. self.on_sed_change(dummy) self.sed_box.children = [ self.sed_select, self.phoenix, self.pl_index, self.bb_temp, self.star, self.galaxies ] self.sed_select.observe(self.on_sed_change) # Advanced # Geometry # The selector goes in one box, and all the geometry selections goes in another so that items can be activated/ # deactivated as needed. self.geom_box = widgets.VBox(width="100%") self.source_box = widgets.HBox(width="100%") #profile_config_file = os.path.join(refdata, 'source', 'config.json') #self.profile_config = get_config(profile_config_file) self.src_select = widgets.Dropdown(description="Profile: ", options=[ 'Point Source', 'Flat', '2D Gaussian', 'Sersic (Scale Radius)' ], value='Point Source') self.source_box.children = [self.src_select] self.prof_box = widgets.VBox(width="100%") style = {'description_width': 'initial'} # We have to define anything we're going to use from the beginning, so we do that, and then # run the helper function that displays the selected (default) item and its attendant pieces, and hides the rest. self.major = widgets.FloatText(description="Semimajor (arcsec): ", value=0.5, style=style) self.minor = widgets.FloatText(description="Semiminor (arcsec): ", value=0.25, style=style) #self.r_core = widgets.FloatText(description="Core Radius (arcsec): ", value=0.005, style=style) self.pos_a = widgets.BoundedFloatText( description="Orientation (deg): ", value=0, min=0, max=359.9, style=style) self.sersic = widgets.FloatSlider(description="Sersic Index: ", value=0.5, min=0.3, max=4, readout_format='.1f', style=style) #self.power = widgets.FloatSlider(description="Power Index: ", value=1, min=0.1, max=10, style=style) self.norm = widgets.Dropdown( description="Normalize at: ", options=['infinity', 'scale radius', 'center'], style=style) self.norm_flat = widgets.Dropdown(description="Normalize at: ", options=['infinity', 'center'], style=style) #self.prof_box.children = [self.major, self.minor, self.r_core, self.pos_a, self.norm, self.sersic, self.power] self.prof_box.children = [ self.major, self.minor, self.pos_a, self.norm, self.sersic ] self.geom_box.children = [self.source_box, self.prof_box] # Position self.pos_box = widgets.HBox(padding='10px', width="100%") self.pos_x = widgets.BoundedFloatText(description="X Position: ", min=-37.5, max=37.5) self.pos_y = widgets.BoundedFloatText(description="Y Position: ", min=-37.5, max=37.5) self.pos_box.children = [self.pos_x, self.pos_y] # Redshift and Extinction self.red_box = widgets.HBox(padding='10px', width="100%") self.redshift = widgets.BoundedFloatText(description="Redshift:", min=0.0, max=99999.0, value=0.0, width=70) self.red_box.children = [self.redshift] self.advanced_options = widgets.Accordion( children=[self.pos_box, self.geom_box, self.red_box]) self.advanced_options.set_title(0, "Position") self.advanced_options.set_title(1, "Geometry") self.advanced_options.set_title(2, "Redshift") self.advanced_options.selected_index = None self.advanced_drop = widgets.Accordion( children=[self.advanced_options]) self.advanced_drop.set_title(0, "ADVANCED") self.advanced_drop.selected_index = None self.container.children = [ self.flux_box, self.sed_box, self.advanced_drop ] self.on_prof_change(dummy) self.src_select.observe(self.on_prof_change)
def __init__(self, fig): super().__init__() self.fig = fig self.nSubs = sum(['xaxis' in i for i in fig['layout']]) # Layout control widgets field_lay = widgets.Layout(max_height='40px', max_width='120px', min_height='30px', min_width='70px') fonts_names = ["Arial", "Balto", "Courier New", "Droid Sans", "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman"] fonts_list = [(fnt, i+1) for i, fnt in enumerate(fonts_names)] tickoptions_names = ['inside', 'outside', ''] tickoptions_list = [(v, i+1) for i, v in enumerate(tickoptions_names)] # General -------------------------------------------------------------- chk_general_autosize = widgets.Checkbox( value=fig.layout.autosize, description='Autosize') self.txt_gen_width = widgets.FloatText(value=fig.layout.width, layout=field_lay) self.txt_gen_height = widgets.FloatText(value=fig.layout.height, layout=field_lay) hb_dims = HBox([widgets.Label('width/height:'), self.txt_gen_width, self.txt_gen_height]) txt_fontsize = widgets.FloatText(value=fig.layout.font.size, layout=field_lay) drd_fontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.font.family)+1) drd_fontfamily.observe(self.set_gen_fontfamily, names='label') clr_font = widgets.ColorPicker(concise=True, value=fig.layout.font.color) hb_font = HBox([widgets.Label('font:'), txt_fontsize, drd_fontfamily, clr_font]) clr_paperbg = widgets.ColorPicker(layout=field_lay, concise=True, value=fig.layout.paper_bgcolor, description='paper_bgcolor') clr_plotbg = widgets.ColorPicker(layout=field_lay, concise=True, value=fig.layout.plot_bgcolor, description='plot_bgcolor') hb_colorbg = HBox([clr_paperbg, clr_plotbg]) drd_hovermode = widgets.Dropdown( options=[('Closest', 1), ('x', 2), ('y', 3), ('False', 4)], value=1, layout=field_lay) drd_hovermode.observe(self.set_gen_hovermode, names='label') hb_hovermode = HBox([widgets.Label('hovermode:'), drd_hovermode]) vb_general = VBox([chk_general_autosize, hb_dims, hb_font, hb_colorbg, hb_hovermode]) controls_general = { 'autosize': chk_general_autosize, 'width': self.txt_gen_width, 'height': self.txt_gen_height, 'fontsize': txt_fontsize, 'fontcolor': clr_font, 'paperbgcolor': clr_paperbg, 'plotbgcolor': clr_plotbg, } widgets.interactive_output(self.set_general, controls_general) # Title ---------------------------------------------------------------- txt_titletext = widgets.Text(value=fig.layout.title.text, description='Text:') txt_titlefontsize = widgets.FloatText(value=fig.layout.titlefont.size, layout=field_lay) drd_titlefontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.titlefont.family)+1) drd_titlefontfamily.observe(self.set_gen_titlefontfamily, names='label') clr_titlefont = widgets.ColorPicker(concise=True, value=fig.layout.titlefont.color) hb_title = HBox([widgets.Label('font:'), txt_titlefontsize, drd_titlefontfamily, clr_titlefont]) vb_title = VBox([txt_titletext, hb_title]) controls = { 'title_text': txt_titletext, 'title_fontsize': txt_titlefontsize, 'title_fontcolor': clr_titlefont, } widgets.interactive_output(self.set_title, controls) # X axis --------------------------------------------------------------- chk_xaxis_visible = widgets.Checkbox( value=fig.layout.xaxis.visible, description='Visible') clr_xaxis = widgets.ColorPicker(concise=True, value=fig.layout.xaxis.color) hb0_xaxis = HBox([chk_xaxis_visible, clr_xaxis]) txt_xaxis_fontsize = widgets.FloatText(value=fig.layout.xaxis.titlefont.size, layout=field_lay) drd_xaxis_fontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.xaxis.titlefont.family)+1) drd_xaxis_fontfamily.observe(self.set_xaxis_titlefontfamily, names='label') clr_xaxis_font = widgets.ColorPicker(concise=True, value=fig.layout.xaxis.titlefont.color) hb1_xaxis = HBox([widgets.Label('font:'), txt_xaxis_fontsize, drd_xaxis_fontfamily, clr_xaxis_font]) drd_xaxis_ticks = widgets.Dropdown( options=tickoptions_list, layout=field_lay, value=tickoptions_names.index(fig.layout.xaxis.ticks)+1) drd_xaxis_ticks.observe(self.set_xaxis_ticks, names='label') txt_xaxis_nticks = widgets.IntText(value=fig.layout.xaxis.nticks, layout=field_lay) hb2_xaxis = HBox([widgets.Label('ticks:'), drd_xaxis_ticks, txt_xaxis_nticks]) txt_xaxis_ticklen = widgets.FloatText(value=fig.layout.xaxis.ticklen, layout=field_lay) txt_xaxis_tickwid = widgets.FloatText(value=fig.layout.xaxis.tickwidth, layout=field_lay) clr_xaxis_tick = widgets.ColorPicker(concise=True, value=fig.layout.xaxis.tickcolor) hb3_xaxis = HBox([widgets.Label('ticks len/wid:'), txt_xaxis_ticklen, txt_xaxis_tickwid, clr_xaxis_tick]) chk_xaxis_showticklabels = widgets.Checkbox( value=fig.layout.xaxis.showticklabels, description='Show tick labels') chk_xaxis_tickangle = widgets.Checkbox( value=not isinstance(fig.layout.xaxis.tickangle, (int, float)), description='auto') self.txt_xaxis_tickangle = widgets.FloatText( value=fig.layout.xaxis.tickangle if fig.layout.xaxis.tickangle != 'auto' else 0, layout=field_lay) hb4_xaxis = HBox([widgets.Label('ticks angle:'), chk_xaxis_tickangle, self.txt_xaxis_tickangle]) vb_xaxis = VBox([hb0_xaxis, hb1_xaxis, hb2_xaxis, hb3_xaxis, chk_xaxis_showticklabels, hb4_xaxis]) xaxis_controls = { 'visible': chk_xaxis_visible, 'color': clr_xaxis, 'title_fontsize': txt_xaxis_fontsize, 'title_fontcolor': clr_xaxis_font, 'nticks': txt_xaxis_nticks, 'ticklen': txt_xaxis_ticklen, 'tickwid': txt_xaxis_tickwid, 'tickcolor': clr_xaxis_tick, 'showticklabels': chk_xaxis_showticklabels, 'tickangleauto': chk_xaxis_tickangle, 'tickangle': self.txt_xaxis_tickangle, } widgets.interactive_output(self.set_xaxis, xaxis_controls) # Y axis --------------------------------------------------------------- chk_yaxis_visible = widgets.Checkbox( value=fig.layout.yaxis.visible, description='Visible') clr_yaxis = widgets.ColorPicker(concise=True, value=fig.layout.yaxis.color) hb0_yaxis = HBox([chk_yaxis_visible, clr_yaxis]) txt_yaxis_fontsize = widgets.FloatText(value=fig.layout.yaxis.titlefont.size, layout=field_lay) drd_yaxis_fontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.yaxis.titlefont.family)+1) drd_yaxis_fontfamily.observe(self.set_yaxis_titlefontfamily, names='label') clr_yaxis_font = widgets.ColorPicker(concise=True, value=fig.layout.yaxis.titlefont.color) hb1_yaxis = HBox([widgets.Label('font:'), txt_yaxis_fontsize, drd_yaxis_fontfamily, clr_yaxis_font]) drd_yaxis_ticks = widgets.Dropdown( options=tickoptions_list, layout=field_lay, value=tickoptions_names.index(fig.layout.yaxis.ticks)+1) drd_yaxis_ticks.observe(self.set_yaxis_ticks, names='label') txt_yaxis_nticks = widgets.IntText(value=fig.layout.yaxis.nticks, layout=field_lay) hb2_yaxis = HBox([widgets.Label('ticks:'), drd_yaxis_ticks, txt_yaxis_nticks]) txt_yaxis_ticklen = widgets.FloatText(value=fig.layout.yaxis.ticklen, layout=field_lay) txt_yaxis_tickwid = widgets.FloatText(value=fig.layout.yaxis.tickwidth, layout=field_lay) clr_yaxis_tick = widgets.ColorPicker(concise=True, value=fig.layout.yaxis.tickcolor) hb3_yaxis = HBox([widgets.Label('ticks len/wid:'), txt_yaxis_ticklen, txt_yaxis_tickwid, clr_yaxis_tick]) chk_yaxis_showticklabels = widgets.Checkbox( value=fig.layout.yaxis.showticklabels, description='Show tick labels') chk_yaxis_tickangle = widgets.Checkbox( value=not isinstance(fig.layout.yaxis.tickangle, (int, float)), description='auto') self.txt_yaxis_tickangle = widgets.FloatText( value=fig.layout.yaxis.tickangle if fig.layout.yaxis.tickangle != 'auto' else 0, layout=field_lay) hb4_yaxis = HBox([widgets.Label('ticks angle:'), chk_yaxis_tickangle, self.txt_yaxis_tickangle]) vb_yaxis = VBox([hb0_yaxis, hb1_yaxis, hb2_yaxis, hb3_yaxis, chk_yaxis_showticklabels, hb4_yaxis]) yaxis_controls = { 'visible': chk_yaxis_visible, 'color': clr_yaxis, 'title_fontsize': txt_yaxis_fontsize, 'title_fontcolor': clr_yaxis_font, 'nticks': txt_yaxis_nticks, 'ticklen': txt_yaxis_ticklen, 'tickwid': txt_yaxis_tickwid, 'tickcolor': clr_yaxis_tick, 'showticklabels': chk_yaxis_showticklabels, 'tickangleauto': chk_yaxis_tickangle, 'tickangle': self.txt_yaxis_tickangle, } widgets.interactive_output(self.set_yaxis, yaxis_controls) # Export --------------------------------------------------------------- # Organize buttons layout ---------------------------------------------- self.tab_nest = widgets.Tab() self.tab_nest.children = [vb_general, vb_title, vb_xaxis, vb_yaxis] self.tab_nest.set_title(0, 'General') self.tab_nest.set_title(1, 'Title') self.tab_nest.set_title(2, 'X axis') self.tab_nest.set_title(3, 'Y axis') acc_all = widgets.Accordion( children=[self.tab_nest], selected_index=None ) acc_all.set_title(0, 'Edit layout') self.children = [acc_all, fig]
def old_initiate(self): tab_children = [] ########################### # data 1 box d1_vbox_childs = [] ## ### d1_button_next = widgets.Button(description='next measurement') d1_button_prev = widgets.Button(description='prev measurement') d1_button_next.on_click(self.on_d1_botton_next) d1_button_prev.on_click(self.on_d1_botton_prev) d1_box_h_1 = widgets.HBox([d1_button_prev, d1_button_next]) ### d1_vbox_childs.append(d1_box_h_1) ## ### d1_text_path = widgets.Text(placeholder='path name', disabled=False) self.d1_text_path = d1_text_path d1_vbox_childs.append(d1_text_path) ## d1_vbox = widgets.VBox(d1_vbox_childs) tab_children.append({'element': d1_vbox, 'title': 'iMet'}) ############################ # data 2 box d2_vbox_childs = [] ## ### d2_button_next = widgets.Button(description='next measurement') d2_button_prev = widgets.Button(description='prev measurement') self.d2_dropdown_fnames = widgets.Dropdown( options=[ 1 ], #[i.name for i in self.controller.data.dataset2.path2data_list], value=1, #self.controller.data.dataset2.path2active.name, # description='N', disabled=False, ) d2_button_next.on_click(self.on_d2_botton_next) d2_button_prev.on_click(self.on_d2_botton_prev) self.d2_dropdown_fnames.observe(self.on_change_d2_dropdown_fnames) d2_box_h_1 = widgets.HBox( [d2_button_prev, d2_button_next, self.d2_dropdown_fnames]) ### d2_vbox_childs.append(d2_box_h_1) ## ### # text field showing the path d2_text_path = widgets.Text(placeholder='path name', disabled=False) self.d2_text_path = d2_text_path d2_vbox_childs.append(d2_text_path) ## d2_vbox = widgets.VBox(d2_vbox_childs) tab_children.append({'element': d2_vbox, 'title': 'POPS'}) # others box # Tab tab = widgets.Tab([child['element'] for child in tab_children]) for e, child in enumerate(tab_children): tab.set_title(e, child['title']) # accordeon self.accordeon_assigned = widgets.Valid( value=False, description='bound?', ) self.dropdown_popssn = widgets.Dropdown( options=['00', '14', '18'], # value='2', description='popssn', disabled=False, ) self.inttext_deltat = widgets.IntText(value=0, description='deltat', disabled=False) self.inttext_deltat.observe(self.on_inttext_deltat) self.dropdown_gps_bar_bad = widgets.Dropdown( options=[ 'gps', 'baro', 'bad', 'bad_but_usable_gps', 'bad_but_usable_baro' ], value='gps', description='which alt to use:', disabled=False, ) self.button_bind_measurements = widgets.ToggleButton( description='bind/unbind measurements') # button_bind_measurements.on_click(self.deprecated_on_button_bind_measurements) self.button_bind_measurements.observe(self.on_button_bind_measurements) accordon_box = widgets.VBox([ self.accordeon_assigned, self.dropdown_popssn, self.inttext_deltat, self.dropdown_gps_bar_bad, self.button_bind_measurements ]) accordion_children = [accordon_box] accordion = widgets.Accordion(children=accordion_children) accordion.set_title(0, 'do_stuff') # messages self.messages = widgets.Textarea('\n'.join(self.controller._message), layout={'width': '100%'}) # message_box = widgets.HBox([self.messages]) # OverVbox overVbox = widgets.VBox([tab, accordion, self.messages]) display(overVbox) #################### self.update_d1() self.update_d2() self.update_accordeon()
def manual_qc_interface( df, variable_list: list, flags: dict or str, review_flag: str = "_review_flag", comment_column: str = "_review_comment", default_flag=None, ): """ Manually QC interface to manually QC oceanographic data, through a Jupyter notebook. :param default_flag: :param comment_column: :param df: DataFrame input to QC :param variable_list: Variable List to review :param flags: Flag convention used :param review_flag: """ # # Generate a copy of the provided dataframe which will be use for filtering and plotting data| # df_temp = df # Retrieve Flag Convention if type(flags) is str: flag_convention = flags flags = flag_conventions[flags] flag_descriptor = f"{flag_convention}\n" + "\n".join([ f"{key} = {item['Meaning']}" for key, item in flag_conventions[flag_convention].items() ]) else: flag_descriptor = "\n".join( [f"{key} = {item}" for key, item in flags.items()]) # Set Widgets of the interface yaxis = widgets.Dropdown( options=variable_list, value=variable_list[0], description="Y Axis:", disabled=False, ) xaxis = widgets.Dropdown( options=["depth", "time"], value="time", description="X Axis:", disabled=False, ) filter_by = widgets.Text( value=None, description="Filter by", placeholder="ex: 20<depth<30", disabled=False, ) filter_by_result = filter_by_result = widgets.HTML( value="{0} records available".format(len(df)), ) apply_filter = widgets.Button( value=False, description="Apply Filter", disabled=False, button_style="success", # 'success', 'info', 'warning', 'danger' or '' tooltip="Apply Filter to the full dataset.", ) flag_selection = widgets.Dropdown(options=list(flags.keys()), description=flag_descriptor, disabled=False) flag_comment = widgets.Textarea( value="", placeholder="Add review comment", description="Comment:", disabled=False, ) apply_flag = widgets.Button( value=False, description="Apply Flag", disabled=False, button_style="success", # 'success', 'info', 'warning', 'danger' or '' tooltip="Apply Flag to select records.", ) accordion = widgets.Accordion() accordion.selected_index = None show_selection = widgets.Button( value=False, description="Show Selection", disabled=False, button_style="success", # 'success', 'info', 'warning', 'danger' or '' tooltip="Present selected records in table.", ) selected_table = widgets.Output() def get_filtered_data(df): """Apply query if available otherwise give back the full dataframe""" try: return df.query(filter_by.value) except ValueError: return df # Create the initial plots # Plot widget with def _get_plots(): """Generate plots based on the dataframe df, yaxis and xaxis values present within the respective widgets and flags in seperate colors""" plots = [] for flag_name, flag_value in flags.items(): if type(flag_value) is dict and "Color" in flag_value: flag_color = flag_value["Color"] flag_meaning = flag_value["Meaning"] else: flag_color = flag_value flag_meaning = flag_value df_temp = get_filtered_data(df) df_flag = df_temp.loc[df_temp[yaxis.value + review_flag] == flag_name] plots += [ go.Scattergl( x=df_flag[xaxis.value], y=df_flag[yaxis.value], mode="markers", name=flag_meaning, marker={ "color": flag_color, "opacity": 1 }, ) ] return tuple(plots) # Initialize Figure Widget and layout f = go.FigureWidget(data=_get_plots(), layout=go.Layout(barmode="overlay")) f.update_layout(margin=dict(l=50, r=20, t=50, b=20)) f.layout.xaxis.title = xaxis.value f.layout.yaxis.title = yaxis.value f.layout.title = "Review" f.update_layout( showlegend=True, legend={ "orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "right", "x": 1, }, ) # Set the update to figure if the drop menu is changed figure_data = f.data def update_filter(query_string=None): """Update filter report below the filter_by cell""" df_temp = get_filtered_data(df) if len(df_temp) == 0: # Give a message back saying no match and don't change anything else filter_by_result.value = "<p style='color:red;'>0 records found</p>" else: # Update text back and update plot with selection filter_by_result.value = "{0} records found".format(len(df_temp)) def update_figure(_): """Update figure with present x and y items in menu""" update_axes(xaxis.value, yaxis.value) def update_axes(xvar, yvar): """ Update figure, based on x,y axis provided :param xvar: :param yvar: """ kk = 0 with f.batch_update(): f.layout.xaxis.title = xvar f.layout.yaxis.title = yvar for plot in _get_plots(): f.data[kk].x = plot.x f.data[kk].y = plot.y kk += 1 def _get_selected_records(): """Method to retrieve the x and y coordinates of the records selected with the plotly lasso tool.""" xs = [] ys = [] for layer in figure_data: if layer["selectedpoints"]: xs += list(layer.x[list(layer["selectedpoints"])]) ys += list(layer.y[list(layer["selectedpoints"])]) return xs, ys def _get_selected_indexes(xs, ys): """Method to retrieve dataframe indexes of the selected x,y records shown on the figure.""" df_temp = get_filtered_data(df) is_indexes_selected = (df_temp[[xaxis.value, yaxis.value]].apply( tuple, axis=1).isin(tuple(zip(xs, ys)))) return df_temp.index[is_indexes_selected].tolist() def selection_fn(_): """Method to update the table showing the selected records.""" xs, ys = _get_selected_records() selected_indexes = _get_selected_indexes(xs, ys) if selected_indexes: with selected_table: selected_table.clear_output() display(df.loc[selected_indexes]) def update_flag_in_dataframe(_): """Tool triggered when flag is applied to selected records.""" # Retrieve selected records and flag column xs, ys = _get_selected_records() selected_indexes = _get_selected_indexes(xs, ys) flag_name = yaxis.value + review_flag comment_name = yaxis.value + comment_column # Create a column for the manual flag if it doesn't exist if flag_name not in df: df[flag_name] = default_flag # Print below the interface what's happening print( "Apply {0} to {1} records to {2}".format(flag_selection.value, len(selected_indexes), flag_name), end="", ) if flag_comment.value: print(" and add comment: {0}".format(flag_comment.value), end="") print(" ... ", end="") # Update flag value within the data frame df.loc[selected_indexes, flag_name] = flag_selection.value # Update comment if flag_comment.value: df.loc[selected_indexes, comment_name] = flag_comment.value # Update figure with the new flags update_figure(True) print("Completed") # Setup the interaction between the different components axis_dropdowns = interactive(update_axes, yvar=yaxis, xvar=xaxis) show_selection.on_click(selection_fn) apply_filter.on_click(update_figure) apply_flag.on_click(update_flag_in_dataframe) filter_data = interactive(update_filter, query_string=filter_by) # Create the interface layout plot_interface = VBox(axis_dropdowns.children) flag_interface = VBox( (flag_selection, flag_comment, apply_flag), layout={"align_items": "flex-end"}, ) filter_by_interface = VBox((filter_by, filter_by_result), layout={"align_items": "flex-end"}) filter_interface = HBox((filter_by_interface, apply_filter)) upper_menu_left = VBox((plot_interface, filter_interface)) upper_menu = HBox((upper_menu_left, flag_interface), layout={"justify_content": "space-between"}) selection_table = VBox((show_selection, selected_table)) return VBox(( upper_menu, f, selection_table, ))
def _tags_assign(self): tags = self.controller.database.get_available_tags() # tag_dict = {'conditions': {'options': ['cloudi', 'clear', 'precip_snow', 'precip_rain']}} tag_dict = {'conditions': {'options': tags}} def on_add_tag(evt, box, options, new_tag, all_checkboxes): if new_tag.value in options: return elif new_tag.value.strip() == '': returnpath2database = path2database else: options.append(new_tag.value) newcb = widgets.Checkbox(description=new_tag.value) newcb.observe(on_cb_change, names=['_property_lock']) all_checkboxes.append(newcb) box_child_list = list(box.children + (newcb, )) box_child_list.sort(key=lambda x: x.description) box.children = box_child_list self.controller.tp_box = box return def on_add_tag_new(evt, box, options, all_checkboxes, all_values): if evt.value in options: return elif evt.value.strip() == '': return else: options.append(evt.value) newcb = widgets.Checkbox(description=evt.value, indent=False, value=False) newcb.observe( lambda x: on_cb_change(x, all_checkboxes, all_values), names=['_property_lock']) newtext = widgets.Text(placeholder=evt.value) newtext.on_submit( lambda x: on_cb_change(x, all_checkboxes, all_values)) newbox = widgets.HBox([newcb, newtext]) all_checkboxes.append(newcb) all_values.append(newtext) box_child_list = list(box.children + (newbox, )) # box_child_list.sort(key=lambda x: x.children[0].description) box.children = box_child_list self.controller.tp_box = box return def on_cb_change(evt, cbs, values): tp = type(evt).__name__ if type(evt).__name__ == 'Bunch': cb = evt['owner'] tag = cb.description text = [txt for txt in values if txt.placeholder == tag][0] new = evt['new'] # not sure why the following was necessary if len(new) != 1: return cb_value = new['value'] elif type(evt).__name__ == 'Text': text = evt tag = evt.placeholder cb = [cb for cb in cbs if cb.description == tag][0] cb_value = cb.value # print('{}: {} -> {}'.format(tp, cb , text)) # return # print('{}: cb: {}, tx: {}'.format(tag, cb_value, text.value)) # return self.controller.send_message('set tag {}:{} ({})'.format( tag, cb_value, text.value)) self.controller.database.set_tag(tag, cb_value, text.value) radio_button_list = [] all_checkboxes = [] all_values = [] self.tag_values = all_values self.tags = all_checkboxes #This loop not really used currently ... only one element for tag_type in tag_dict.keys(): # rb = widgets.RadioButtons(options = tags[tag_type]['options']) cb_box = widgets.VBox( ) # needs to be defined here since used by new_tag # new tag new_tag = widgets.Text(placeholder='enter new tag') new_tag.on_submit( lambda x: on_add_tag_new(x, cb_box, tag_dict[tag_type][ 'options'], all_checkboxes, all_values)) add_box = widgets.HBox([ new_tag, ]) cbs = [] for opt in tag_dict[tag_type]['options']: cb = widgets.Checkbox(description=opt, indent=False) cb.observe( lambda x: on_cb_change(x, all_checkboxes, all_values), names=['_property_lock']) text = widgets.Text(placeholder=opt) text.on_submit( lambda x: on_cb_change(x, all_checkboxes, all_values)) cbs.append(widgets.HBox([cb, text])) all_checkboxes.append(cb) all_values.append(text) # cb_box = widgets.VBox([add_box]+cbs) cb_box.children = [add_box] + cbs # box it # box = widgets.HBox([cb_box, add_box]) radio_button_list.append(cb_box) acc = widgets.Accordion(radio_button_list) for e, tag_type in enumerate(tag_dict.keys()): acc.set_title(e, tag_type) return acc
def _plot_settings(self): pc = self.controller.view.plot.plot_content self.plot_setting_accordion = widgets.Accordion([]) if not isinstance(pc, type(None)): self._plot_settings_accordion_initiate() return self.plot_setting_accordion
def make_workspace_widget(model_dict: dict, aks_dict: dict) -> widgets.Widget: """ :param model_dict: :param aks_dict: :return: """ ws_image = widgets.HTML( value= '<img src="https://raw.githubusercontent.com/microsoft/AI-Utilities/master/docs/studio.png">' ) model_vbox = make_vbox(model_dict) aks_box = make_vbox(aks_dict) deployment_accordion = widgets.Accordion(children=[ws_image, model_vbox]) deployment_accordion.set_title(0, "Workspace") deployment_accordion.set_title(1, "Model") application_insights_images = [ widgets.HTML( value= '<img src="https://raw.githubusercontent.com/microsoft/AI-Utilities/master/docs/app_insights_1.png' '">'), widgets.HTML( value= '<img src="https://raw.githubusercontent.com/microsoft/AI-Utilities/master/docs' '/app_insights_availability.png">'), widgets.HTML( value= '<img src="https://raw.githubusercontent.com/microsoft/AI-Utilities/master/docs' '/app_insights_perf_dash.png">'), widgets.HTML( value= '<img src="https://raw.githubusercontent.com/microsoft/AI-Utilities/master/docs/app_insights_perf' '.png">'), ] application_insights_accordion = widgets.Accordion( children=application_insights_images) application_insights_accordion.set_title(0, "Main") application_insights_accordion.set_title(1, "Availability") application_insights_accordion.set_title(2, "Performance") application_insights_accordion.set_title(3, "Load Testing") kubernetes_image = widgets.HTML( value= '<img src="https://raw.githubusercontent.com/microsoft/AI-Utilities/master/docs/kubernetes.png">' ) kubernetes_accordion = widgets.Accordion( children=[aks_box, kubernetes_image]) kubernetes_accordion.set_title(0, "Main") kubernetes_accordion.set_title(1, "Performance") tab_nest = widgets.Tab() tab_nest.children = [ deployment_accordion, kubernetes_accordion, application_insights_accordion, ] tab_nest.set_title(0, "ML Studio") tab_nest.set_title(1, "Kubernetes") tab_nest.set_title(2, "Application Insights") return tab_nest
def show(self): # current schema name self.box2 = widgets.HBox([ widgets.Label("Pre. Index Separator", layout=widgets.Layout(width='15%')), widgets.Text(value='_', layout=widgets.Layout(width='5%')) ]) self.box2b = widgets.HBox([ widgets.Label("Untouched filename part:", layout=widgets.Layout(width="20%")), widgets.Label("", layout=widgets.Layout(width='40%')), widgets.IntRangeSlider(value=[0, 2], min=0, max=len(self.basename), step=1) ]) self.int_range_slider = self.box2b.children[2] self.int_range_slider.observe(self.change_int_range_slider, names='value') self.basename_selected_by_user = self.box2b.children[1] self.box4 = widgets.HBox([ widgets.Label("Current Name Schema: ", layout=widgets.Layout(width='20%')), widgets.Label(self.current_naming_schema(), layout=widgets.Layout(width='30%')), widgets.Label("Random Input:", layout=widgets.Layout(width='15%')), widgets.Dropdown(options=self.random_input_list, value=self.random_input_list[0], layout=widgets.Layout(width='50%')) ]) self.box2.children[1].on_trait_change(self.pre_index_text_changed, 'value') before = widgets.VBox([self.box2, self.box2b, self.box4]) self.random_input_checkbox = self.box4.children[3] self.random_input_checkbox.observe( self.random_input_checkbox_value_changed, 'value') # new naming schema box_text_width = '10%' self.box1 = widgets.HBox([ widgets.Label("New prefix File Name", layout=widgets.Layout(width='10%')), widgets.Checkbox(value=True, description='Use previous prefix name', layout=widgets.Layout(width='30%')) ]) self.use_previous_prefix_widget = self.box1.children[1] self.box1.children[1].observe(self.changed_use_previous_prefix_name, names='value') self.box1b = widgets.HBox([ widgets.Label("", layout=widgets.Layout(width='10%')), widgets.Checkbox(value=False, description='Use new prefix', layout=widgets.Layout(width='20%')), widgets.Text(value='image', disabled=True, layout=widgets.Layout(width='25%')) ]) self.box1b.children[2].observe(self.changed_use_new_prefix_name, names='value') self.new_prefix_text_widget = self.box1b.children[2] self.user_new_prefix_widget = self.box1b.children[1] self.user_new_prefix_widget.observe(self.changed_use_new_prefix_name, names='value') self.box5 = widgets.HBox([ widgets.Label("New Index Separator", layout=widgets.Layout(width='15%')), widgets.Text(value='_', layout=widgets.Layout(width=box_text_width)) ]) self.box7 = widgets.HBox([ widgets.Label("Number of digits", layout=widgets.Layout(width='15%')), widgets.IntText(value=4, layout=widgets.Layout(width=box_text_width)) ]) self.box8 = widgets.HBox([ widgets.Label("Offset", layout=widgets.Layout(width='15%')), widgets.IntText(value=0, layout=widgets.Layout(width=box_text_width)) ]) self.box6 = widgets.HBox([ widgets.Label("New Name Schema: ", layout=widgets.Layout(width='20%')), widgets.Label(self.new_naming_schema(), layout=widgets.Layout(width='40%')) ]) self.box1.children[1].on_trait_change(self.post_text_changed, 'value') self.box5.children[1].on_trait_change(self.post_text_changed, 'value') self.box7.children[1].on_trait_change(self.post_text_changed, 'value') self.box8.children[1].on_trait_change(self.post_text_changed, 'value') after = widgets.VBox([ self.box1, self.box1b, self.box5, self.box7, self.box8, self.box6 ]) accordion = widgets.Accordion(children=[before, after]) accordion.set_title(0, 'Current Schema Name') accordion.set_title(1, 'New Naming Schema') output_ui_1 = widgets.HBox([ widgets.Label("Example of naming: ", layout=widgets.Layout(width='20%')) ]) self.output_ui_2 = widgets.HBox([ widgets.Label("Old name: ", layout=widgets.Layout(width='40%')), widgets.Label("", layout=widgets.Layout(width='60%')) ]) self.output_ui_3 = widgets.HBox([ widgets.Label("New name: ", layout=widgets.Layout(width='40%')), widgets.Label("", layout=widgets.Layout(width='60%')) ]) self.output_ui_3.children[1].add_class("result_label") vbox = widgets.VBox( [accordion, output_ui_1, self.output_ui_2, self.output_ui_3]) display(vbox) self.demo_output_file_name() self.change_int_range_slider() self.changed_use_new_prefix_name()
def __init__(self, nmrproblem=None): super().__init__() if not isinstance(nmrproblem, nmrProblem.NMRproblem): self.nmrproblem = nmrproblem self.df = pd.DataFrame() else: self.nmrproblem = nmrproblem self.df = nmrproblem.df # create debug label widget for output self.debugLabel = widgets.Label(value="", layout=widgets.Layout(width="400px")) # create save problem widgets self.saveProblemButtonW = widgets.Button(description="Save Problem") # widgets to obtain problem working directory self.prDirW = widgets.Text(value='', placeholder='problem directory', description='problem directory', disabled=False) self.prDirB = widgets.Button(description='Set Directory') self.upload_problemdir = ipywidgets.widgets.FileUpload( multiple=True, description="Open Existing Problem ", description_tooltip="choose all files in problem directory", layout=widgets.Layout(width='300px')) self.problemNameL = widgets.Label(value=" Problem Name", layout=widgets.Layout(width='100px')) self.spacerL = widgets.Label(value=" ", layout=widgets.Layout(width='50px')) self.problemNameW = widgets.Text(value="Problem Name", description="", layout=widgets.Layout(width='150px')) self.newproblemB = widgets.Button(description="Start New Problem") self.prDirLayout = widgets.HBox([ self.upload_problemdir, self.spacerL, self.problemNameL, self.problemNameW, self.spacerL, self.newproblemB ]) # widgets to obtain info on the molecule # number and tye of atoms in molecule # number of proton resonances in molecule # number of carbon resonance in molecule self.moleculeAtomsW = widgets.Text(value='', placeholder='atoms in molecule', description='atoms', disabled=False) self.pGrpsW = widgets.IntText(value=1, placeholder='H1 groups in spectrum', description='H1 groups', disabled=False) self.cGrpsW = widgets.IntText(value=1, description='C13 groups', disabled=False) self.moleculesSubmitB = widgets.Button(description="Update Molecule") self.moleculeLayout = widgets.VBox([ self.moleculeAtomsW, self.pGrpsW, self.cGrpsW, self.moleculesSubmitB ]) # widgets to set 1D spectral parameters for proton and carbon self.pLabelW = widgets.Label("$^{1}H$") self.pSpecWidthW = widgets.FloatText(value=12.0, tooltip='proton spectral width', description='sw (ppm)', disabled=False) self.pObsFreqW = widgets.FloatText(value=400.0, description='obs (MHz)', disabled=False) self.pTofW = widgets.FloatText(value=5.0, description='tof (ppm)', diabled=False) self.pSizeW = widgets.IntText(value=32768, description='size (pts)', disabled=False) self.pLineBroadeningW = widgets.FloatText(value=0.5, description='lb (Hz)', disabled=False) self.cLabelW = widgets.Label("$^{13}C$") self.cSpecWidthW = widgets.FloatText(value=210.0, description='sw (ppm)', disabled=False) self.cObsFreqW = widgets.FloatText(value=100.0, description='obs (MHz)', disabled=False) self.cTofW = widgets.FloatText(value=5.0, description='tof (ppm)', diabled=False) self.cSizeW = widgets.IntText(value=32768, description='size (pts)', disabled=False) self.cLineBroadeningW = widgets.FloatText(value=0.5, description='lb (Hz)', disabled=False) self.specSubmitB = widgets.Button(description="Update Spectra") self.specLayout = widgets.HBox([ widgets.VBox([ self.pLabelW, self.pObsFreqW, self.pSpecWidthW, self.pTofW, self.pSizeW, self.pLineBroadeningW, self.specSubmitB ]), widgets.VBox([ self.cLabelW, self.cObsFreqW, self.cSpecWidthW, self.cTofW, self.cSizeW, self.cLineBroadeningW ]) ]) self.old = 'All' self.new = 'ALL' self.toggleDF = widgets.ToggleButtons( options=['All', 'integrals-ppm', 'COSY', 'HSQC-HMBC'], description='Display:', disabled=False, button_style='', tooltips=[ 'Show full Dataframe', 'Show COSY Input', 'Show HSQC/HMBC Input' ]) self.sheet1 = ipysheet.from_dataframe(self.df) self.toggleDF.observe(self.toggleValue) self.dfWarningTextW = widgets.Label("Table Messages: OK") self.dfUpdateTableB = widgets.Button(description="update table") self.dfRunAnalysisB = widgets.Button(description="update and run") self.dfButtonsLayout = widgets.HBox( [self.dfUpdateTableB, self.dfRunAnalysisB]) self.dfLayout = widgets.VBox([ self.toggleDF, self.dfWarningTextW, self.sheet1, self.dfButtonsLayout ]) self.accordion = widgets.Accordion(children=[ self.prDirLayout, self.moleculeLayout, self.specLayout, self.dfLayout ]) self.accordion.set_title(0, "Problem Directory") self.accordion.set_title(1, "Molecule") self.accordion.set_title(2, "Spectroscopy") self.accordion.set_title(3, "DataSet") self.page1 = widgets.VBox( [self.accordion, self.saveProblemButtonW, self.debugLabel]) self.H1C131DplotsLayout = widgets.VBox( [widgets.Output(), self.saveProblemButtonW]) self.ymlTitle = widgets.HTML("yml description of problem") self.ymlText = widgets.Textarea( layout=widgets.Layout(width="400px", height="500px")) self.problemYML = widgets.VBox([self.ymlTitle, self.ymlText]) self.children = [self.page1, self.H1C131DplotsLayout, self.problemYML] self.set_title(0, 'Problem Setup') self.set_title(1, 'Problem Plots') self.set_title(2, 'Problem YML') self.upload_problemdir.observe( lambda change: self.on_upload_problemdir(change), names='value') self.moleculesSubmitB.on_click(self.onButtonClicked) self.specSubmitB.on_click(self.onButtonClicked) self.dfUpdateTableB.on_click(self.onButtonClicked) self.dfRunAnalysisB.on_click(self.onButtonClicked) self.saveProblemButtonW.on_click(self.onButtonClicked) self.newproblemB.on_click(self.onButtonClicked)
def __init__(self): style = {'description_width': 'initial'} self.container = widgets.VBox(width="100%", background_color="#AAAAAA") strat_lab = widgets.HTML( value="<b>Spectroscopic Aperture Extraction</b>", margin='5px') self.target_box = widgets.HBox(padding='10px', width="100%") targ_lab = widgets.HTML(value="Extraction Target: ", margin='5px') self.target_x = widgets.BoundedFloatText(description="X:", min=-37.5, max=37.5, value=0, width=30) self.target_y = widgets.BoundedFloatText(description="Y:", min=-37.5, max=37.5, value=0, width=30) self.target_box.children = [targ_lab, self.target_x, self.target_y] self.reference_wavelength = widgets.BoundedFloatText( description="Wavelength of Interest", min=0.95, max=1.8, value=1.3, width=30, style=style) self.advanced = widgets.VBox(width="100%", background_color="#AAAAAA") self.aperture_box = widgets.HBox(padding='10px', width="100%") ap_lab = widgets.HTML(value="Aperture half-height (arcsec): ", margin='5px') self.ap_size = widgets.BoundedFloatText(min=0.0, max=999.0, value=0.1, width=30) self.ap_size.on_trait_change(self.check_ann, 'value') self.aperture_box.children = [ap_lab, self.ap_size] self.background_box = widgets.VBox(width="100%", background_color="#AAAAAA") bg_lab = widgets.HTML(value="Sky Sample Region (arcsec): ", margin='5px') self.ann_inner = widgets.BoundedFloatText(description="inner", min=0.0, max=999.0, value=0.2, width=30) self.ann_inner.on_trait_change(self.check_ann_inner, 'value') self.ann_outer = widgets.BoundedFloatText(description="outer", min=0.0, max=999.0, value=0.3, width=30) self.ann_outer.on_trait_change(self.check_ann_outer, 'value') self.background_box.children = [bg_lab, self.ann_inner, self.ann_outer] self.advanced.children = [self.aperture_box, self.background_box] self.advanced_drop = widgets.Accordion(children=[self.advanced]) self.advanced_drop.set_title(0, "ADVANCED") self.advanced_drop.selected_index = None self.container.children = [ strat_lab, self.target_box, self.reference_wavelength, self.advanced_drop ]
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 get_accordion(self, children: List, titles: List): accordion = widgets.Accordion(children=children) for i in range(len(titles)): accordion.set_title(i, titles[i]) return accordion
def initiate(self): tab_children = [] ########################### # data 1 box d1_vbox_childs = [] ## ### d1_button_next = widgets.Button(description='next measurement') d1_button_prev = widgets.Button(description='prev measurement') d1_button_next.on_click(self.on_d1_botton_next) d1_button_prev.on_click(self.on_d1_botton_prev) d1_dropdown_fnames_options = [ i.name for i in self.controller.data.dataset1.path2data_list ] d1_dropdown_fnames_value = self.controller.data.dataset1.path2active.name self.d1_dropdown_fnames = widgets.Dropdown( options=d1_dropdown_fnames_options, value=d1_dropdown_fnames_value, # description='N', # disabled=disable_data_2, ) self.d1_dropdown_fnames.observe(self.on_change_d1_dropdown_fnames) d1_box_h_1 = widgets.HBox( [d1_button_prev, d1_button_next, self.d1_dropdown_fnames]) ### d1_vbox_childs.append(d1_box_h_1) ## ### d1_text_path = widgets.Text(placeholder='path name', disabled=False) self.d1_text_path = d1_text_path d1_vbox_childs.append(d1_text_path) ## d1_vbox = widgets.VBox(d1_vbox_childs) tab_children.append({'element': d1_vbox, 'title': 'iMet'}) ############################ # data 2 box if isinstance(self.controller.data.dataset2, type(None)): disable_data_2 = True d2_dropdown_fnames_options = [] d2_dropdown_fnames_value = None else: disable_data_2 = False d2_dropdown_fnames_options = [ i.name for i in self.controller.data.dataset2.path2data_list ] d2_dropdown_fnames_value = self.controller.data.dataset2.path2active.name d2_vbox_childs = [] ## ### d2_button_next = widgets.Button(description='next measurement', disabled=disable_data_2) d2_button_prev = widgets.Button(description='prev measurement', disabled=disable_data_2) self.d2_dropdown_fnames = widgets.Dropdown( options=d2_dropdown_fnames_options, value=d2_dropdown_fnames_value, # description='N', disabled=disable_data_2, ) d2_button_next.on_click(self.on_d2_botton_next) d2_button_prev.on_click(self.on_d2_botton_prev) self.d2_dropdown_fnames.observe(self.on_change_d2_dropdown_fnames) d2_box_h_1 = widgets.HBox( [d2_button_prev, d2_button_next, self.d2_dropdown_fnames]) ### d2_vbox_childs.append(d2_box_h_1) ## ### # text field showing the path d2_text_path = widgets.Text(placeholder='path name', disabled=False) self.d2_text_path = d2_text_path d2_vbox_childs.append(d2_text_path) ## d2_vbox = widgets.VBox(d2_vbox_childs) tab_children.append({'element': d2_vbox, 'title': 'POPS'}) # others box # Tab tab = widgets.Tab([child['element'] for child in tab_children]) for e, child in enumerate(tab_children): tab.set_title(e, child['title']) # accordeon self.accordeon_start = widgets.Text(value='', placeholder='hit z key', description='start:', disabled=False) self.accordeon_end = widgets.Text(value='', placeholder='hit x key', description='end:', disabled=False) self.accordeon_alt = widgets.Text(value='', placeholder='hit a key', description='altitude:', disabled=False) hbox_accordeon_start_stop = widgets.HBox( [self.accordeon_start, self.accordeon_end]) self.dropdown_gps_bar_bad = widgets.Dropdown( options=[ 'gps', 'baro', 'bad', 'bad_but_usable_gps', 'bad_but_usable_baro' ], value='gps', description='which alt to use:', disabled=False, ) self.button_save_unsave_flight = widgets.Button( description='save/unsave flight') # button_bind_measurements.on_click(self.deprecated_on_button_bind_measurements) self.button_save_unsave_flight.on_click(self.on_button_save_flight) hbox_accordeon_alt_source = widgets.HBox( [self.dropdown_gps_bar_bad, self.accordeon_alt]) # self.accordeon_assigned = widgets.Valid(value=False, # description='bound?', # ) # # # self.inttext_deltat = widgets.IntText(value=0, # description='deltat', # disabled=False # ) # self.inttext_deltat.observe(self.on_inttext_deltat) # # self.button_bind_measurements = widgets.ToggleButton(description = 'bind/unbind measurements') # # button_bind_measurements.on_click(self.deprecated_on_button_bind_measurements) # self.button_bind_measurements.observe(self.on_button_bind_measurements) # # # accordon_box = widgets.VBox( [ hbox_accordeon_start_stop, hbox_accordeon_alt_source, self.button_save_unsave_flight ] ) #[self.accordeon_assigned, self.dropdown_popssn, self.inttext_deltat, self.button_bind_measurements]) accordion_children = [accordon_box] accordion = widgets.Accordion(children=accordion_children) accordion.set_title(0, 'do_stuff') # messages self.messages = widgets.Textarea('\n'.join(self.controller._message), layout={'width': '100%'}) # message_box = widgets.HBox([self.messages]) # OverVbox overVbox = widgets.VBox([tab, accordion, self.messages]) display(overVbox) #################### self.update_d1() self.update_d2() self.update_accordeon()
def initiate(self): tab_children = [] ########################### # data 1 box d1_vbox_childs = [] ## ### d1_button_next = widgets.Button(description='next measurement') d1_button_prev = widgets.Button(description='prev measurement') d1_button_next.on_click(self.on_d1_botton_next) d1_button_prev.on_click(self.on_d1_botton_prev) d1_dropdown_fnames_options = [ i.name for i in self.controller.data.dataset1.path2data_list ] d1_dropdown_fnames_value = self.controller.data.dataset1.path2active.name self.d1_dropdown_fnames = widgets.Dropdown( options=d1_dropdown_fnames_options, value=d1_dropdown_fnames_value, # description='N', # disabled=disable_data_2, ) self.d1_dropdown_fnames.observe(self.on_change_d1_dropdown_fnames) d1_box_h_1 = widgets.HBox( [d1_button_prev, d1_button_next, self.d1_dropdown_fnames]) ### d1_vbox_childs.append(d1_box_h_1) ## ### d1_text_path = widgets.Text(placeholder='path name', disabled=False) self.d1_text_path = d1_text_path d1_vbox_childs.append(d1_text_path) ## d1_vbox = widgets.VBox(d1_vbox_childs) tab_children.append({'element': d1_vbox, 'title': 'iMet'}) ############################ # data 2 box if isinstance(self.controller.data.dataset2, type(None)): disable_data_2 = True d2_dropdown_fnames_options = [] d2_dropdown_fnames_value = None else: disable_data_2 = False d2_dropdown_fnames_options = [ i.name for i in self.controller.data.dataset2.path2data_list ] d2_dropdown_fnames_value = self.controller.data.dataset2.path2active.name d2_vbox_childs = [] ## ### d2_button_next = widgets.Button(description='next measurement', disabled=disable_data_2) d2_button_prev = widgets.Button(description='prev measurement', disabled=disable_data_2) self.d2_dropdown_fnames = widgets.Dropdown( options=d2_dropdown_fnames_options, value=d2_dropdown_fnames_value, # description='N', disabled=disable_data_2, ) d2_button_next.on_click(self.on_d2_botton_next) d2_button_prev.on_click(self.on_d2_botton_prev) self.d2_dropdown_fnames.observe(self.on_change_d2_dropdown_fnames) d2_box_h_1 = widgets.HBox( [d2_button_prev, d2_button_next, self.d2_dropdown_fnames]) ### d2_vbox_childs.append(d2_box_h_1) ## ### ## text field showing the path d2_text_path = widgets.Text(placeholder='path name', disabled=False) self.d2_text_path = d2_text_path d2_vbox_childs.append(d2_text_path) ## d2_vbox = widgets.VBox(d2_vbox_childs) tab_children.append({'element': d2_vbox, 'title': 'POPS'}) # others box # Tab tab = widgets.Tab([child['element'] for child in tab_children]) for e, child in enumerate(tab_children): tab.set_title(e, child['title']) # accordeon txt = 'keymap:\t' txt += ' - '.join([ '{}:{}'.format(i[0], i[1]) for i in self.controller.view.plot.keymap.items() ]) box_layout = widgets.Layout(border='solid 1px') description = widgets.Box((widgets.Label(txt), ), layout=box_layout) # items = [widgets.Label('change point'), widgets.Label('followed by'), widgets.Label('')] self.gridbox = widgets.GridBox( [], layout=widgets.Layout(grid_template_columns="repeat(3, 200px)")) self.populate_gridbox_from_database() self.controller.tp_gb = self.gridbox self.button_gridbox_reinitiate = widgets.Button( description='sort by datetime') self.button_gridbox_reinitiate.on_click( self.populate_gridbox_from_database) # the old one # self.accordeon_start = widgets.Text(value='', # placeholder='hit z key', # description='start:', # disabled=False # ) # self.accordeon_end = widgets.Text(value='', # placeholder='hit x key', # description='end:', # disabled=False # ) # self.accordeon_alt = widgets.Text(value='', # placeholder='hit a key', # description='altitude:', # disabled=False # ) # hbox_accordeon_start_stop = widgets.HBox([self.accordeon_start, self.accordeon_end]) # self.dropdown_gps_bar_bad= widgets.Dropdown(options=['gps', 'baro', 'bad', 'bad_but_usable_gps', 'bad_but_usable_baro'], # value='gps', # description='which alt to use:', # disabled=False, # ) # self.button_save_unsave_flight = widgets.Button(description = 'save/unsave flight') # self.button_save_unsave_flight.on_click(self.on_button_save_flight) # hbox_accordeon_alt_source = widgets.HBox([self.dropdown_gps_bar_bad, self.accordeon_alt]) accordon_box = widgets.VBox( [description, self.button_gridbox_reinitiate, self.gridbox] ) #,hbox_accordeon_start_stop, hbox_accordeon_alt_source, self.button_save_unsave_flight]) accordion_children = [accordon_box] accordion = widgets.Accordion(children=accordion_children) accordion.set_title(0, 'do_stuff') # messages self.messages = widgets.Textarea('\n'.join(self.controller._message), layout={'width': '100%'}) # message_box = widgets.HBox([self.messages]) # OverVbox overVbox = widgets.VBox([tab, accordion, self.messages]) display(overVbox) #################### self.update_d1() self.update_d2() self.update_accordeon()
def slider(self, figsize=(10, 10), **kw): """ Navigate the simulation using a slider Parameters : ------------ figsize: tuple Size of the figures kw: dict Extra arguments to pass to matplotlib's imshow """ # ----------------------- # Define useful functions # ----------------------- def refresh_field(force=False): "Refresh the current field figure" # Determine whether to do the refresh do_refresh = False if (self.avail_fields is not None): if force == True or fld_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: plt.figure(fld_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if fld_use_button.value == True: i_power = fld_magnitude_button.value vmin = fld_range_button.value[0] * 10**i_power vmax = fld_range_button.value[1] * 10**i_power else: vmin = None vmax = None self.get_field(t=self.current_t, output=False, plot=True, field=fieldtype_button.value, coord=coord_button.value, m=convert_to_int(mode_button.value), slicing=slicing_button.value, theta=theta_button.value, slicing_dir=slicing_dir_button.value, vmin=vmin, vmax=vmax, cmap=fld_color_button.value) def refresh_ptcl(force=False): "Refresh the current particle figure" # Determine whether to do the refresh do_refresh = False if self.avail_species is not None: if force == True or ptcl_refresh_toggle.value == True: do_refresh = True # Do the refresh if do_refresh == True: plt.figure(ptcl_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() if ptcl_use_button.value == True: i_power = ptcl_magnitude_button.value vmin = ptcl_range_button.value[0] * 10**i_power vmax = ptcl_range_button.value[1] * 10**i_power else: vmin = None vmax = None if ptcl_yaxis_button.value == 'None': # 1D histogram self.get_particle(t=self.current_t, output=False, var_list=[ptcl_xaxis_button.value], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value) else: # 2D histogram self.get_particle(t=self.current_t, output=False, var_list=[ ptcl_xaxis_button.value, ptcl_yaxis_button.value ], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, vmin=vmin, vmax=vmax, cmap=ptcl_color_button.value, nbins=ptcl_bins_button.value) def refresh_ptcl_now(b): "Refresh the particles immediately" refresh_ptcl(force=True) def refresh_fld_now(b): "Refresh the fields immediately" refresh_field(force=True) def change_t(name, value): "Plot the result at the required time" self.current_t = 1.e-15 * value refresh_field() refresh_ptcl() def step_fw(b): "Plot the result one iteration further" if self.current_i < len(self.t) - 1: self.current_t = self.t[self.current_i + 1] else: print("Reached last iteration.") self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 def step_bw(b): "Plot the result one iteration before" if self.current_t > 0: self.current_t = self.t[self.current_i - 1] else: print("Reached first iteration.") self.current_t = self.t[self.current_i] slider.value = self.current_t * 1.e15 # --------------- # Define widgets # --------------- # Slider slider = widgets.FloatSlider( min=math.ceil(1.e15 * self.tmin), max=math.ceil(1.e15 * self.tmax), step=math.ceil(1.e15 * (self.tmax - self.tmin)) / 20., description="t (fs)") slider.on_trait_change(change_t, 'value') # Forward button button_p = widgets.Button(description="+") button_p.on_click(step_fw) # Backward button button_m = widgets.Button(description="-") button_m.on_click(step_bw) # Display the time widgets container = widgets.HBox(children=[button_m, button_p, slider]) display(container) # Field widgets # ------------- if (self.avail_fields is not None): # Field type # ---------- # Field button fieldtype_button = widgets.ToggleButtons( description='Field:', options=sorted(self.avail_fields.keys())) fieldtype_button.on_trait_change(refresh_field) # Coord button if self.geometry == "thetaMode": coord_button = widgets.ToggleButtons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in ["2dcartesian", "3dcartesian"]: coord_button = widgets.ToggleButtons(description='Coord:', options=['x', 'y', 'z']) coord_button.on_trait_change(refresh_field) # Mode and theta button (for thetaMode) mode_button = widgets.ToggleButtons(description='Mode:', options=self.avail_circ_modes) mode_button.on_trait_change(refresh_field) theta_button = widgets.FloatSlider(width=140, value=0., description=r'Theta:', min=-math.pi / 2, max=math.pi / 2) theta_button.on_trait_change(refresh_field) # Slicing buttons (for 3D) slicing_dir_button = widgets.ToggleButtons( value='y', description='Slicing direction:', options=['x', 'y', 'z']) slicing_dir_button.on_trait_change(refresh_field) slicing_button = widgets.FloatSlider(width=150, description='Slicing:', min=-1., max=1., value=0.) slicing_button.on_trait_change(refresh_field) # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(description='Figure ', value=0, width=50) # Range of values fld_range_button = widgets.FloatRangeSlider(min=-10, max=10, width=220) fld_range_button.on_trait_change(refresh_field) # Order of magnitude fld_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) fld_magnitude_button.on_trait_change(refresh_field) # Use button fld_use_button = widgets.Checkbox(description=' Use this range', value=False) fld_use_button.on_trait_change(refresh_field) # Colormap button fld_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='jet') fld_color_button.on_trait_change(refresh_field) # Resfresh buttons fld_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) fld_refresh_button = widgets.Button(description='Refresh now!') fld_refresh_button.on_click(refresh_fld_now) # Containers # ---------- # Field type container if self.geometry == "thetaMode": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, mode_button, theta_button ]) elif self.geometry == "2dcartesian": container_fields = widgets.VBox( width=260, children=[fieldtype_button, coord_button]) elif self.geometry == "3dcartesian": container_fields = widgets.VBox(width=260, children=[ fieldtype_button, coord_button, slicing_dir_button, slicing_button ]) # Plotting options container container_fld_plots = widgets.VBox(width=260, children=[ fld_figure_button, fld_range_button, widgets.HBox(children=[ fld_magnitude_button, fld_use_button ], height=50), fld_color_button ]) # Accordion for the field widgets accord1 = widgets.Accordion( children=[container_fields, container_fld_plots]) accord1.set_title(0, 'Field type') accord1.set_title(1, 'Plotting options') # Complete field container container_fld = widgets.VBox( width=300, children=[ accord1, widgets.HBox( children=[fld_refresh_toggle, fld_refresh_button]) ]) # Particle widgets # ---------------- if (self.avail_species is not None): # Particle quantities # ------------------- # Species selection ptcl_species_button = widgets.Dropdown(width=250, options=self.avail_species) ptcl_species_button.on_trait_change(refresh_ptcl) # Remove charge and mass (less interesting) avail_ptcl_quantities = [ q for q in self.avail_ptcl_quantities \ if (q in ['charge', 'mass'])==False ] # Particle quantity on the x axis ptcl_xaxis_button = widgets.ToggleButtons( value='z', options=avail_ptcl_quantities) ptcl_xaxis_button.on_trait_change(refresh_ptcl) # Particle quantity on the y axis ptcl_yaxis_button = widgets.ToggleButtons( value='x', options=avail_ptcl_quantities + ['None']) ptcl_yaxis_button.on_trait_change(refresh_ptcl) # Particle selection # ------------------ # 3 selection rules at maximum ptcl_select_widget = ParticleSelectWidget(3, avail_ptcl_quantities, refresh_ptcl) # Plotting options # ---------------- # Figure number ptcl_figure_button = widgets.IntText(description='Figure ', value=1, width=50) # Number of bins ptcl_bins_button = widgets.IntSlider(description='nbins:', min=50, max=300, value=100, width=150) ptcl_bins_button.on_trait_change(refresh_ptcl) # Colormap button ptcl_color_button = widgets.Select(options=sorted( plt.cm.datad.keys()), height=50, width=200, value='Blues') ptcl_color_button.on_trait_change(refresh_ptcl) # Range of values ptcl_range_button = widgets.FloatRangeSlider(min=0, max=10, width=220, value=(0, 5)) ptcl_range_button.on_trait_change(refresh_ptcl) # Order of magnitude ptcl_magnitude_button = widgets.IntText(description='x 10^', value=9, width=50) ptcl_magnitude_button.on_trait_change(refresh_ptcl) # Use button ptcl_use_button = widgets.Checkbox(description=' Use this range', value=False) ptcl_use_button.on_trait_change(refresh_ptcl) # Resfresh buttons ptcl_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) ptcl_refresh_button = widgets.Button(description='Refresh now!') ptcl_refresh_button.on_click(refresh_ptcl_now) # Containers # ---------- # Particle quantity container container_ptcl_quantities = widgets.VBox(width=310, children=[ ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button ]) # Particle selection container container_ptcl_select = ptcl_select_widget.to_container() # Plotting options container container_ptcl_plots = widgets.VBox(width=310, children=[ ptcl_figure_button, ptcl_bins_button, ptcl_range_button, widgets.HBox(children=[ ptcl_magnitude_button, ptcl_use_button ], height=50), ptcl_color_button ]) # Accordion for the field widgets accord2 = widgets.Accordion(children=[ container_ptcl_quantities, container_ptcl_select, container_ptcl_plots ]) accord2.set_title(0, 'Particle quantities') accord2.set_title(1, 'Particle selection') accord2.set_title(2, 'Plotting options') # Complete particle container container_ptcl = widgets.VBox( width=370, children=[ accord2, widgets.HBox( children=[ptcl_refresh_toggle, ptcl_refresh_button]) ]) # Global container if (self.avail_fields is not None) and \ (self.avail_species is not None): global_container = widgets.HBox( children=[container_fld, container_ptcl]) display(global_container) elif self.avail_species is None: display(container_fld) elif self.avail_fields is None: display(container_ptcl)
def slider(self, figsize=(6, 5), exclude_particle_records=['charge', 'mass'], **kw): """ Navigate the simulation using a slider Parameters: ----------- figsize: tuple Size of the figures exclude_particle_records: list of strings List of particle quantities that should not be displayed in the slider (typically because they are less interesting) kw: dict Extra arguments to pass to matplotlib's imshow (e.g. cmap, etc.). This will be applied both to the particle plots and field plots. Note that `kw` sets the initial plotting options, but the user can then still modify these options through the slider interface. """ # Check that the dependencies have been installed if not dependencies_installed: raise RuntimeError( "Failed to load the openPMD-viewer slider.\n" "(Make sure that ipywidgets and matplotlib are installed.)") # ----------------------- # Define useful functions # ----------------------- def refresh_field(change=None, force=False): """ Refresh the current field figure Parameters : ------------ change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) This is mainline a place holder ; not used in this function force: bool Whether to force the update """ # Determine whether to do the refresh do_refresh = False if (self.avail_fields is not None): if force or fld_refresh_toggle.value: do_refresh = True # Do the refresh if do_refresh: plt.figure(fld_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): if ipywidgets_version < 7: clear_output() else: import warnings warnings.warn( "\n\nIt seems that you are using ipywidgets 7 and " "`%matplotlib inline`. \nThis can cause issues when " "using `slider`.\nIn order to avoid this, you " "can either:\n- use `%matplotlib notebook`\n- or " "downgrade to ipywidgets 6 (with `pip` or `conda`).", UserWarning) # Handle plotting options kw_fld = kw.copy() vmin, vmax = fld_color_button.get_range() kw_fld['vmin'] = vmin kw_fld['vmax'] = vmax kw_fld['cmap'] = fld_color_button.cmap.value # Determine range of the plot from widgets plot_range = [ fld_hrange_button.get_range(), fld_vrange_button.get_range() ] # Call the method get_field self.get_field(iteration=self.current_iteration, output=False, plot=True, field=fieldtype_button.value, coord=coord_button.value, m=convert_to_int(mode_button.value), slicing=slicing_button.value, theta=theta_button.value, slicing_dir=slicing_dir_button.value, plot_range=plot_range, **kw_fld) def refresh_ptcl(change=None, force=False): """ Refresh the current particle figure Parameters : ------------ change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) This is mainline a place holder ; not used in this function force: bool Whether to force the update """ # Determine whether to do the refresh do_refresh = False if self.avail_species is not None: if force or ptcl_refresh_toggle.value: do_refresh = True # Do the refresh if do_refresh: plt.figure(ptcl_figure_button.value, figsize=figsize) plt.clf() # When working in inline mode, in an ipython notebook, # clear the output (prevents the images from stacking # in the notebook) if 'inline' in matplotlib.get_backend(): clear_output() # Handle plotting options kw_ptcl = kw.copy() vmin, vmax = ptcl_color_button.get_range() kw_ptcl['vmin'] = vmin kw_ptcl['vmax'] = vmax kw_ptcl['cmap'] = ptcl_color_button.cmap.value # Determine range of the plot from widgets plot_range = [ ptcl_hrange_button.get_range(), ptcl_vrange_button.get_range() ] if ptcl_yaxis_button.value == 'None': # 1D histogram self.get_particle( iteration=self.current_iteration, output=False, var_list=[ptcl_xaxis_button.value], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, nbins=ptcl_bins_button.value, plot_range=plot_range, use_field_mesh=ptcl_use_field_button.value, **kw_ptcl) else: # 2D histogram self.get_particle( iteration=self.current_iteration, output=False, var_list=[ ptcl_xaxis_button.value, ptcl_yaxis_button.value ], select=ptcl_select_widget.to_dict(), species=ptcl_species_button.value, plot=True, nbins=ptcl_bins_button.value, plot_range=plot_range, use_field_mesh=ptcl_use_field_button.value, **kw_ptcl) def refresh_field_type(change): """ Refresh the field type and disable the coordinates buttons if the field is scalar. Parameter --------- change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) """ if self.avail_fields[change['new']] == 'scalar': coord_button.disabled = True elif self.avail_fields[change['new']] == 'vector': coord_button.disabled = False refresh_field() def refresh_species(change=None): """ Refresh the particle species buttons by populating them with the available records for the current species Parameter --------- change: dictionary Dictionary passed by the widget to a callback functions whenever a change of a widget happens (see docstring of ipywidgets.Widget.observe) """ # Deactivate the particle refreshing to avoid callback # while modifying the widgets saved_refresh_value = ptcl_refresh_toggle.value ptcl_refresh_toggle.value = False # Get available records for this species avail_records = [ q for q in self.avail_record_components[ ptcl_species_button.value] if q not in exclude_particle_records ] # Update the plotting buttons ptcl_xaxis_button.options = avail_records ptcl_yaxis_button.options = avail_records + ['None'] if ptcl_xaxis_button.value not in ptcl_xaxis_button.options: ptcl_xaxis_button.value = avail_records[0] if ptcl_yaxis_button.value not in ptcl_yaxis_button.options: ptcl_yaxis_button.value = 'None' # Update the selection widgets for dropdown_button in ptcl_select_widget.quantity: dropdown_button.options = avail_records # Put back the previous value of the refreshing button ptcl_refresh_toggle.value = saved_refresh_value def change_iteration(change): "Plot the result at the required iteration" # Find the closest iteration self._current_i = abs(self.iterations - change['new']).argmin() self.current_iteration = self.iterations[self._current_i] refresh_field() refresh_ptcl() def step_fw(b): "Plot the result one iteration further" if self._current_i < len(self.t) - 1: self.current_iteration = self.iterations[self._current_i + 1] else: self.current_iteration = self.iterations[self._current_i] slider.value = self.current_iteration def step_bw(b): "Plot the result one iteration before" if self._current_i > 0: self.current_iteration = self.iterations[self._current_i - 1] else: self.current_iteration = self.iterations[self._current_i] slider.value = self.current_iteration # --------------- # Define widgets # --------------- # Slider iteration_min = self.iterations.min() iteration_max = self.iterations.max() step = max(int((iteration_max - iteration_min) / 20.), 1) slider = widgets.IntSlider(description="iteration", min=iteration_min, max=iteration_max + step, step=step) slider.observe(change_iteration, names='value', type='change') set_widget_dimensions(slider, width=500) # Forward button button_p = widgets.Button(description="+") set_widget_dimensions(button_p, width=40) button_p.on_click(step_fw) # Backward button button_m = widgets.Button(description="-") set_widget_dimensions(button_m, width=40) button_m.on_click(step_bw) # Display the time widgets container = widgets.HBox(children=[button_m, button_p, slider]) display(container) # Field widgets # ------------- if (self.avail_fields is not None): # Field type # ---------- # Field button fieldtype_button = create_toggle_buttons( description='Field:', options=sorted(self.avail_fields.keys())) fieldtype_button.observe(refresh_field_type, 'value', 'change') # Coord button if self.geometry == "thetaMode": coord_button = create_toggle_buttons( description='Coord:', options=['x', 'y', 'z', 'r', 't']) elif self.geometry in \ ["1dcartesian", "2dcartesian", "3dcartesian"]: coord_button = create_toggle_buttons(description='Coord:', options=['x', 'y', 'z']) coord_button.observe(refresh_field, 'value', 'change') # Mode and theta button (for thetaMode) mode_button = create_toggle_buttons(description='Mode:', options=self.avail_circ_modes) mode_button.observe(refresh_field, 'value', 'change') theta_button = widgets.FloatSlider(value=0., min=-math.pi / 2, max=math.pi / 2) set_widget_dimensions(theta_button, width=190) theta_button.observe(refresh_field, 'value', 'change') # Slicing buttons (for 3D) slicing_dir_button = create_toggle_buttons( value=self.axis_labels[0], options=self.axis_labels, description='Slice normal:') slicing_dir_button.observe(refresh_field, 'value', 'change') slicing_button = widgets.FloatSlider(min=-1., max=1., value=0.) set_widget_dimensions(slicing_button, width=180) slicing_button.observe(refresh_field, 'value', 'change') # Plotting options # ---------------- # Figure number fld_figure_button = widgets.IntText(value=0) set_widget_dimensions(fld_figure_button, width=50) # Colormap button fld_color_button = ColorBarSelector( refresh_field, default_cmap=kw.get('cmap', 'viridis'), default_vmin=kw.get('vmin', -5.e9), default_vmax=kw.get('vmax', 5.e9)) # Range buttons fld_hrange_button = RangeSelector(refresh_field, default_value=10., title='Horizontal axis:') fld_vrange_button = RangeSelector(refresh_field, default_value=10., title='Vertical axis:') # Refresh buttons fld_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) fld_refresh_button = widgets.Button(description='Refresh now!') fld_refresh_button.on_click(partial(refresh_field, force=True)) # Containers # ---------- # Field type container if self.geometry == "thetaMode": container_fields = widgets.VBox(children=[ fieldtype_button, coord_button, mode_button, add_description('Theta:', theta_button) ]) elif self.geometry in ["1dcartesian", "2dcartesian"]: container_fields = widgets.VBox( children=[fieldtype_button, coord_button]) elif self.geometry == "3dcartesian": container_fields = widgets.VBox(children=[ fieldtype_button, coord_button, slicing_dir_button, add_description("Slicing:", slicing_button) ]) set_widget_dimensions(container_fields, width=330) # Plotting options container container_fld_cbar = fld_color_button.to_container() container_fld_hrange = fld_hrange_button.to_container() container_fld_vrange = fld_vrange_button.to_container() if self.geometry == "1dcartesian": container_fld_plots = widgets.VBox(children=[ add_description("<b>Figure:</b>", fld_figure_button), container_fld_vrange, container_fld_hrange ]) else: container_fld_plots = widgets.VBox(children=[ add_description("<b>Figure:</b>", fld_figure_button), container_fld_cbar, container_fld_vrange, container_fld_hrange ]) set_widget_dimensions(container_fld_plots, width=330) # Accordion for the field widgets accord1 = widgets.Accordion( children=[container_fields, container_fld_plots]) accord1.set_title(0, 'Field type') accord1.set_title(1, 'Plotting options') # Complete field container container_fld = widgets.VBox(children=[ accord1, widgets.HBox(children=[fld_refresh_toggle, fld_refresh_button]) ]) set_widget_dimensions(container_fld, width=370) # Particle widgets # ---------------- if (self.avail_species is not None): # Particle quantities # ------------------- # Species selection ptcl_species_button = widgets.Dropdown(options=self.avail_species) set_widget_dimensions(ptcl_species_button, width=250) ptcl_species_button.observe(refresh_species, 'value', 'change') # Get available records for this species avail_records = [ q for q in self.avail_record_components[ ptcl_species_button.value] if q not in exclude_particle_records ] # Particle quantity on the x axis ptcl_xaxis_button = create_toggle_buttons(options=avail_records) ptcl_xaxis_button.observe(refresh_ptcl, 'value', 'change') # Particle quantity on the y axis ptcl_yaxis_button = create_toggle_buttons(options=avail_records + ['None'], value='None') ptcl_yaxis_button.observe(refresh_ptcl, 'value', 'change') # Particle selection # ------------------ # 3 selection rules at maximum ptcl_select_widget = ParticleSelectWidget(3, avail_records, refresh_ptcl) # Plotting options # ---------------- # Figure number ptcl_figure_button = widgets.IntText(value=1) set_widget_dimensions(ptcl_figure_button, width=50) # Number of bins ptcl_bins_button = widgets.IntText(value=100) set_widget_dimensions(ptcl_bins_button, width=60) ptcl_bins_button.observe(refresh_ptcl, 'value', 'change') # Colormap button ptcl_color_button = ColorBarSelector( refresh_ptcl, default_cmap=kw.get('cmap', 'Blues'), default_vmin=kw.get('vmin', -5.e9), default_vmax=kw.get('vmax', 5.e9)) # Range buttons ptcl_hrange_button = RangeSelector(refresh_ptcl, default_value=10., title='Horizontal axis:') ptcl_vrange_button = RangeSelector(refresh_ptcl, default_value=10., title='Vertical axis:') # Use field mesh buttons ptcl_use_field_button = widgets.ToggleButton( description=' Use field mesh', value=True) ptcl_use_field_button.observe(refresh_ptcl, 'value', 'change') # Resfresh buttons ptcl_refresh_toggle = widgets.ToggleButton( description='Always refresh', value=True) ptcl_refresh_button = widgets.Button(description='Refresh now!') ptcl_refresh_button.on_click(partial(refresh_ptcl, force=True)) # Containers # ---------- # Particle quantity container container_ptcl_quantities = widgets.VBox(children=[ ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button ]) set_widget_dimensions(container_ptcl_quantities, width=310) # Particle selection container container_ptcl_select = ptcl_select_widget.to_container() # Plotting options container container_ptcl_fig = widgets.HBox(children=[ add_description("<b>Figure:</b>", ptcl_figure_button), add_description("Bins:", ptcl_bins_button) ]) container_ptcl_cbar = ptcl_color_button.to_container() container_ptcl_hrange = ptcl_hrange_button.to_container() container_ptcl_vrange = ptcl_vrange_button.to_container() container_ptcl_plots = widgets.VBox(children=[ container_ptcl_fig, container_ptcl_cbar, container_ptcl_vrange, container_ptcl_hrange, ptcl_use_field_button ]) set_widget_dimensions(container_ptcl_plots, width=310) # Accordion for the field widgets accord2 = widgets.Accordion(children=[ container_ptcl_quantities, container_ptcl_select, container_ptcl_plots ]) accord2.set_title(0, 'Particle quantities') accord2.set_title(1, 'Particle selection') accord2.set_title(2, 'Plotting options') # Complete particle container container_ptcl = widgets.VBox(children=[ accord2, widgets.HBox( children=[ptcl_refresh_toggle, ptcl_refresh_button]) ]) set_widget_dimensions(container_ptcl, width=370) # Global container if (self.avail_fields is not None) and \ (self.avail_species is not None): global_container = widgets.HBox( children=[container_fld, container_ptcl]) display(global_container) elif self.avail_species is None: display(container_fld) elif self.avail_fields is None: display(container_ptcl)
def _create(self): default_layout = widgets.Layout(width='auto', height='auto') self.wg['organization'] = widgets.Text(value='', description='Organization', layout=default_layout) self.wg['filter'] = widgets.Text( description='Filter', placeholder='Repository names must contain', layout=default_layout) self.wg['filename'] = widgets.Text(value='exercice.py', description='Filename', layout=default_layout) self.wg['request_url'] = widgets.Text( description='Request URL', value= f'https://raw.githubusercontent.com/{self.wg["organization"].value}/%RepositoryName%/master/{self.wg["filename"].value}', layout=default_layout, disabled=True) self.wg['get_files'] = widgets.Button(description='Fetch submissions') self.wg['get_files_status'] = widgets.Valid(value=True, description='Ready', layout=default_layout) self.wg['previous_button'] = widgets.Button(description='Previous') self.wg['next_button'] = widgets.Button(description='Next') self.wg['open_in_browser'] = widgets.Button( description='Open in GitHub', layout=default_layout) self.wg['open_file'] = widgets.Checkbox(description='File only', layout=default_layout) self.wg['repository_select'] = widgets.Dropdown( description='Select', layout=widgets.Layout(width='600px')) self.wg['max_preview_lines'] = widgets.IntText( value=100, disabled=False, layout=widgets.Layout(width='50px')) self.wg['preview_lines_range'] = widgets.IntRangeSlider( value=[0, 20], min=0, max=self.wg['max_preview_lines'].value, step=1, description='Lines range:', continuous_update=True, orientation='horizontal', readout=True, readout_format='d', layout=widgets.Layout(width='500px')) self.wg['repository_grading'] = widgets.HTML( layout=widgets.Layout(width='auto', height='auto', border='solid 1px', padding='2px 10px 2px 10px')) html_layout = widgets.Layout(width='auto', height='auto', padding='20px 100px 0px 20px') self.wg['file_preview_stats'] = widgets.HTML(layout=html_layout) self.wg['file_preview'] = widgets.HTML(layout=html_layout) self.wg['file_view_stats'] = widgets.HTML(layout=html_layout) self.wg['file_view'] = widgets.HTML(layout=html_layout) file_preview_box = widgets.HBox( (self.wg['file_preview'], self.wg['file_preview_stats'])) file_view_box = widgets.HBox( (self.wg['file_view'], self.wg['file_view_stats'])) lines_range_box = widgets.HBox( (self.wg['preview_lines_range'], self.wg['max_preview_lines'])) self.wg['accordion'] = widgets.Accordion(children=[ widgets.VBox((lines_range_box, file_preview_box)), file_view_box ]) self.wg['accordion'].set_title(0, 'Preview') self.wg['accordion'].set_title(1, 'File')