def __init__(self, fper='morgan', smiles='c1ccccc1O', dpi=200): self.initialize_ipython() if isinstance(fper, str): self.fper = features.get(fper) else: self.fper = fper self.smiles_input = Text(smiles, description='smiles') self.smiles_input.on_submit(self.update_smiles) self.smiles_input.observe(self.typing) self.valid = Valid(True) self.dropdown = Dropdown(options=[], description='bit') self.dropdown.observe(self.plot) self.dpi_input = Text(str(dpi), description='dpi') self.dpi_input.on_submit(self.plot) self.ui = VBox([ HTML('<h2>Visualizer</h2>'), HBox([self.smiles_input, self.valid]), self.dropdown, self.dpi_input ]) self.update_smiles(None) self.display()
def __init__(self, data, dimensions, **kwargs): GluePlotly.__init__(self, data, dimensions, **kwargs) self.options['title'] = Text(description='Title:', value="") self.options['title'].observe( lambda v: self.UpdateLayout({'title': v['new']}), names='value') self.options['xaxis'] = Text(description='Xaxis Title:', value=self.dimensions[0]) self.options['xaxis'].observe( lambda v: self.UpdateLayout({'scene.xaxis.title': v['new']}), names='value') self.options['yaxis'] = Text(description='Yaxis Title:', value=self.dimensions[1]) self.options['yaxis'].observe( lambda v: self.UpdateLayout({'scene.yaxis.title': v['new']}), names='value') self.options['zaxis'] = Text(description='Zaxis Title:', value=self.dimensions[2]) self.options['zaxis'].observe( lambda v: self.UpdateLayout({'scene.zaxis.title': v['new']}), names='value') self.options['marker_size'] = BoundedIntText( description='Markers size:', value=3, min=0, max=15) self.options['marker_size'].observe( lambda v: self.UpdateTraces({'marker.size': v['new']}), names='value') self.DefaultLegend('v', 1.02, 1.0) self.updateRender()
def __init__(self): # Add the required widgets self.wt_url = Text(placeholder='Add URL', description='API URL:', disabled=False) self.wt_user = Text(placeholder='Username', description='API User:'******'******', description='API Password:'******'Member State', description='Member State:', disabled=False) self.wdd_year = Dropdown(options=['2020', '2019', '2018'], placeholder='Year', description='Year:', disabled=False) self.wdd_ptype = Dropdown(options=['', 'm', 'g', 'b'], placeholder='Type', description='Type:', disabled=False) super().__init__([self.wt_url, self.wt_user, self.wt_pass, self.wt_ms, \ self.wdd_year, self.wdd_ptype])
def __init__(self): # initialize the base class super().__init__() # Add additional elements self.wt_signals = Text(placeholder='Signal Table', description='Signal Table:', disabled=False) self.wt_histtable = Text(placeholder='Hist. Table', description='Hist. Table:', disabled=False) self.wt_sm_table = Text(placeholder='Sen. Table', description='Sen. Table:', disabled=False) self.wrb_cloud = RadioButtons( options=['True', 'False'], value='True', # Defaults to 'pineapple' description='Cloud Free:', disabled=False) self.wdp_start_date = DatePicker(description='Start date:', disabled=False) self.wdp_end_date = DatePicker(description='Stop date:', disabled=False) children = [*super().children, self.wt_signals, self.wt_histtable, \ self.wt_sm_table, self.wrb_cloud, self.wdp_start_date, \ self.wdp_end_date] self.children = children
def __init__(self, *args, **kwargs): # Compute selected and unselected values options = kwargs.get('options', {}) if isinstance(options, list): options = named_objs([(opt, opt) for opt in options]) self._reverse_lookup = {v: k for k, v in options.items()} selected = [self._reverse_lookup[v] for v in kwargs.get('value', [])] unselected = [k for k in options if k not in selected] # Define whitelist and blacklist self._lists = { False: SelectMultiple(options=unselected), True: SelectMultiple(options=selected) } self._lists[False].observe(self._update_selection, 'value') self._lists[True].observe(self._update_selection, 'value') # Define buttons button_layout = Layout(width='50px') self._buttons = { False: Button(description='<<', layout=button_layout), True: Button(description='>>', layout=button_layout) } self._buttons[False].on_click(self._apply_selection) self._buttons[True].on_click(self._apply_selection) # Define search self._search = { False: Text(placeholder='Filter available options'), True: Text(placeholder='Filter selected options') } self._search[False].observe(self._filter_options, 'value') self._search[True].observe(self._filter_options, 'value') # Define Layout no_margin = Layout(margin='0') row_layout = Layout(margin='0', display='flex', justify_content='space-between') search_row = HBox([self._search[False], self._search[True]]) search_row.layout = row_layout button_box = VBox([self._buttons[True], self._buttons[False]], layout=Layout(margin='auto 0')) tab_row = HBox([self._lists[False], button_box, self._lists[True]]) tab_row.layout = row_layout self._composite = VBox([search_row, tab_row], layout=no_margin) self.observe(self._update_options, 'options') self.observe(self._update_value, 'value') self._selected = {False: [], True: []} self._query = {False: '', True: ''} super(CrossSelect, self).__init__(*args, **dict(kwargs, options=options))
def getCP(self): self.setLabel() self.usrTW = Text(value='', placeholder='', description='Username:'******'values') self.pwdPW = Password(value='', placeholder='', description='Password:'******'value') self.st = widgets.DatePicker(description='Start Date', value=datetime(2020, 4, 20), disabled=False, layout=Layout(width='220px')) self.et = widgets.DatePicker(description='End Date', value=datetime(2020, 4, 30), disabled=False, layout=Layout(width='220px')) self.st.observe(self.startDate) self.et.observe(self.endDate) self.latitude = Text(value='24.42', description='Latitude:', disabled=False, layout=Layout(width='220px')) self.longitude = Text(value='54.43', description='Longitude:', disabled=False, layout=Layout(width='220px')) self.latitude.observe(self.set_lat_val, names='value') self.longitude.observe(self.set_lon_val, names='value') self.plotms = Button(description='Plot in m/s', disabled=False, layout={ 'width': 'auto', 'border': '3px outset' }) self.plotms.on_click(self.plotWindRose_ms) self.plotkt = Button(description='Plot in kt', disabled=False, layout={ 'width': 'auto', 'border': '3px outset' }) self.plotkt.on_click(self.plotWindRose_kt) self.inpUSR.children += (HBox([ VBox([self.st, self.latitude, self.longitude]), VBox([self.et, self.plotms, self.plotkt]) ], layout={'overflow': 'visible'}), ) with self.out_cp: self.out_cp.clear_output() display(self.getCP) return self.cp
def notes(path, ds=None, parcel=None): info = HTML( value="Add a note for the parcel", placeholder='Notes', ) aoi = Text(value=ds, placeholder='MS or ragion', description='AOI:', disabled=False) try: y_ = int(ds[-4:]) except: y_ = 2000 year = BoundedIntText(value=y_, min=1980, max=2100, step=1, description='Year:', disabled=False, layout=Layout(width='180px')) pid = Text(value=parcel, placeholder='12345', description='Parcel ID:', disabled=False) note = Textarea(value=None, placeholder='', description='Note:', disabled=False, layout=Layout(width='60%')) save = Button(value=False, disabled=False, button_style='info', tooltip='Save note to notes table.', icon='save', layout=Layout(width='35px')) new = HBox([aoi, year, pid]) progress = Output() def outlog(*text): with progress: print(*text) @save.on_click def save_on_click(b): progress.clear_output() df = pd.DataFrame([[aoi.value, year.value, pid.value, note.value]]) df.to_csv(f'{path}notes.csv', mode='a', header=False) outlog(f"The note is saved in {path}notes.csv") wbox = VBox([info, new, HBox([note, save]), progress]) return wbox
def DefaultLayoutTitles(self, title, xaxis, yaxis): self.options['title'] = Text(description='Title:', value=title) self.options['title'].observe( lambda v: self.UpdateLayout({'title': v['new']}), names='value') self.options['xaxis'] = Text(description='Xaxis Title:', value=xaxis) self.options['xaxis'].observe( lambda v: self.UpdateLayout({'xaxis.title': v['new']}), names='value') self.options['yaxis'] = Text(description='Yaxis Title:', value=yaxis) self.options['yaxis'].observe( lambda v: self.UpdateLayout({'yaxis.title': v['new']}), names='value')
def getCP(self): self.setLabel() self.plon = 54.43 self.plat = 24.42 self.dateSelection = datetime.now() self.dateLast = datetime(1950, 1, 1) self.selectVar = 'AOD' self.selectTime = 0 self.sdateSW = DatePicker(description='Start Date', layout=Layout(width='auto'), value=self.startDate, disabled=False) self.edateSW = DatePicker(description='End Date', layout=Layout(width='auto'), value=self.endDate, disabled=False) self.varSW = Dropdown(options=[ 'AOD', 'DUST_PM', 'SALT_PM', 'ORG_CARB', 'BLK_CARB', 'SO4', 'PM2.5' ], value='AOD', layout=Layout(width='280px'), description='Variable:', disabled=False) self.latSW = Text(description='Latitude:', disabled=False, value='24.42', layout=Layout(width='180px')) self.lonSW = Text(description='Longitude:', disabled=False, value='54.43', layout=Layout(width='180px')) self.plotPB = Button(description='Time Series Plot', disabled=False, layout={ 'width': 'auto', 'border': '3px outset' }) self.inpUSR.children += (HBox([ VBox([self.sdateSW, self.edateSW, self.varSW]), VBox([self.latSW, self.lonSW, self.plotPB]) ], layout={'overflow': 'visible'}), ) self.sdateSW.observe(self.sdateSWCB) self.edateSW.observe(self.edateSWCB) self.varSW.observe(self.varSWCB, names='value') self.latSW.observe(self.latSWCB, names='value') self.lonSW.observe(self.lonSWCB, names='value') self.plotPB.on_click(self.plotTS) return self.cp
def __init__(self, rows=20, directory_only=False, ignore_dotfiles=True): self._callback = None self._directory_only = directory_only self._ignore_dotfiles = ignore_dotfiles self._empty_selection = True self._selected_dir = os.getcwd() self._item_layout = Layout(width='auto') self._nb_rows = rows self._file_selector = Select(options=self._get_selector_options(), rows=min( len(os.listdir(self._selected_dir)), self._nb_rows), layout=self._item_layout) self._open_button = Button(description='Open', layout=Layout(flex='auto 1 auto', width='auto')) self._select_button = Button(description='Select', layout=Layout(flex='auto 1 auto', width='auto')) self._cancel_button = Button(description='Cancel', layout=Layout(flex='auto 1 auto', width='auto')) self._parent_button = Button(icon='chevron-up', layout=Layout(flex='auto 1 auto', width='auto')) self._selection = Text(value=os.path.join(self._selected_dir, self._file_selector.value), disabled=True, layout=Layout(flex='1 1 auto', width='auto')) self._filename = Text(value='', layout=Layout(flex='1 1 auto', width='auto')) self._parent_button.on_click(self._parent_button_clicked) self._open_button.on_click(self._open_button_clicked) self._select_button.on_click(self._select_button_clicked) self._cancel_button.on_click(self._cancel_button_clicked) self._file_selector.observe(self._update_path) self._widget = VBox([ HBox([ self._parent_button, HTML(value='Look in:'), self._selection, ]), self._file_selector, HBox([ HTML(value='File name'), self._filename, self._open_button, self._select_button, self._cancel_button, ]), ])
def __init__(self, parent_widget=None, proposed_db_name='db'): super().__init__(parent_widget=parent_widget) if isinstance(proposed_db_name, Database): self.filenamer = Text( value=proposed_db_name.get_db_info(), placeholder='db info', description='DB:', disabled=True ) self.db = proposed_db_name else: self.filenamer = Text( value=proposed_db_name, placeholder='enter object name', description='DB:', disabled=False ) self.scope_picker = Dropdown( options=[ ' ', ], value=' ', description='Scope:', disabled=False, ) self.design_picker = Dropdown( options=[ ' ', ], value=' ', description='Design:', disabled=False, ) self.filenamer.observe(self.check_db_status) self.scope_picker.observe(self.update_current_scope_from_db) self.design_picker.observe(self.update_current_design_from_db) self.make_stack( self.filenamer, self.scope_picker, self.design_picker, ) self.next_button.on_click(lambda x: self._parent_widget.load_selection_library()) with self.header: display(HTML("<h1>Scope Manager</h1>")) self.check_db_status(None)
def widget_plots(self): return interact( self.show_plots, plots=SelectMultiple(options=self.ERROR_FUNCTION_NAMES, value=["mean", "max"], description="Plots"), datasets=SelectMultiple(options=["raw", "image"], value=["image"], description="Datasets"), error_type=Dropdown(options={"Absolute": "absolute", "Relative": "relative"}, value="absolute", description='Error'), xmin=Text(value="", placeholder="Type a number or leave blank to disable", description='Min x'), xmax=Text(value="", placeholder="Type a number or leave blank to disable", description='Max x'), ymin=Text(value="", placeholder="Type a number or leave blank to disable", description='Min y'), ymax=Text(value="", placeholder="Type a number or leave blank to disable", description='Max y'), width=IntSlider(value=15, min=5, max=50, step=1, continuous_update=False, description="Subplot width"), height=IntSlider(value=15, min=5, max=50, step=1, continuous_update=False, description="Subplot height") )
def api(mode=None): """""" values = config.read() wt_url = Text( value=values['api']['url'], placeholder='Add URL', description='API URL:', disabled=False ) wt_user = Text( value=values['api']['user'], placeholder='Username', description='API User:'******'api']['pass'], placeholder='******', description='API Password:'******'Save', disabled=False, icon='save' ) progress = Output() def outlog(*text): with progress: print(*text) @wb_save.on_click def wb_save_on_click(b): progress.clear_output() config.set_value(['api', 'url'], str(wt_url.value).replace(' ', '')) config.set_value(['api', 'user'], str(wt_user.value).replace(' ', '')) if wt_pass.value != '': config.set_value(['api', 'pass'], str( wt_pass.value).replace(' ', '')) outlog("The RESTful API credentials are saved.") wbox = VBox([HBox([wt_url, Label("Format: http://0.0.0.0/ or https://0.0.0.0/")]), wt_user, wt_pass, HBox([wb_save, progress])]) return wbox
def __init__(self, url=None, token=None, regexpr=None, fields=None, callbacks=None): """Instantiate a UI controller. """ super().__init__() self.fields = fields self.callbacks = callbacks or [] # toolbar self.ht = HTML("<b>Host/Owner:</b>") self.tx_desc = "Repo owner URL, eg. https://github.com/python" self.tx = Text( url or "", placeholder=self.tx_desc, description_tooltip="Repo owner URL, press enter to scan!", layout=Layout(width="200px")) self.tx.on_submit(self.start_scan) tok_desc = "GitHub API Access Token" self.tok = Password(token, placeholder=tok_desc, description_tooltip=tok_desc, layout=Layout(width="175px")) self.tok.on_submit(self.start_scan) self.btn = Button(description="Scan", button_style="info", layout=Layout(width="100px")) self.btn.on_click(self.start_scan) rx_desc = "Regex to match repo names" self.rx = Text(regexpr, placeholder=rx_desc, description_tooltip=rx_desc, layout=Layout(width="60px")) self.rx.on_submit(self.start_scan) self.toolbar = HBox([self.ht, self.tx, self.tok, self.rx, self.btn]) # content area self.sx = HTML(layout=Layout(width="100pc")) self.tabout = VBox() self.pbout = Output() self.out = Output() self.cont = VBox([self.sx, self.tabout, self.pbout, self.out]) # entire area self.children = [self.toolbar, self.cont] self.scanner = None
def visualize_simulant_treatments(self, enter_sim_id=False, extra_title_key="", starting_sim_id=None): data = self.data unique_sims = data.reset_index().simulant.drop_duplicates( ).sort_values() if not enter_sim_id: arg = (1, len(unique_sims), 1) else: arg = Text(value=str(unique_sims[0]), placeholder='simulant id' ) if not starting_sim_id else str(starting_sim_id) @interact(simulant=arg, treatment_graph_style=['bar', 'line']) def _visualize_simulant_treatments(simulant, treatment_graph_style): if isinstance(simulant, str): sim_id = int(simulant) else: sim_id = unique_sims.loc[simulant] simulant = data.loc[sim_id] tx_changes = track_treatment_changes(simulant) plt.title( f'{extra_title_key.capitalize()}: Treatment transitions for simulant {sim_id}.' ) plot_treatments(tx_changes, treatment_graph_style) return _visualize_simulant_treatments(arg, 'bar')
def build_ui_controls(self): # Buttons self.buttons = { "plot": Button(description="Plot"), "load_preset": Button(description="Load"), "save_preset": Button(description="Save"), "save_image": Button(description="Img"), } self.presets_dd = Dropdown(options=self.presets) self.textbox = Text() def build_handler(f): def handler(_): return f() return handler for name, button in self.buttons.items(): button.on_click(build_handler(getattr(self, name))) ui_controls = HBox([ self.buttons["plot"], self.presets_dd, self.buttons["load_preset"], self.textbox, self.buttons["save_preset"], self.buttons["save_image"], ]) return ui_controls
def _init_ui(self) -> VBox: "Initialize the widget UI and return the UI." self._search_input = Text(placeholder="What images to search for?") self._count_input = BoundedIntText(placeholder="How many pics?", value=10, min=1, max=5000, step=1, layout=Layout(width='60px')) self._size_input = Dropdown(options=_img_sizes.keys(), value='>400*300', layout=Layout(width='120px')) self._download_button = Button(description="Search & Download", icon="download", layout=Layout(width='200px')) self._download_button.on_click(self.on_download_button_click) self._output = Output() self._controls_pane = HBox([ self._search_input, self._count_input, self._size_input, self._download_button ], layout=Layout(width='auto', height='40px')) self._heading = "" self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>" self._preview_header = widgets.HTML(self._heading, layout=Layout(height='60px')) self._img_pane = Box(layout=Layout(display='inline')) return VBox( [self._controls_pane, self._preview_header, self._img_pane])
def new_child(self) -> DOMWidget: """ Widget for creating new child for this `Tier`. """ child = self.tier.child_cls options = child.get_templates() mapping = {path.name: path for path in options} selection = Select( options=mapping.keys(), description='Template') def create(name, template, description): with form.status: obj = child(*self.tier.identifiers, name) obj.setup_files(mapping[template]) obj.description = description display(widgetify_html(obj._repr_html_())) form = InputSequence(create, Text(description=f'Identifier', placeholder=f'{child.id_regex}'), selection, Textarea(description='Motivation')) return form.as_widget()
def __get_widgets(self, chromosomes, browser, frame=None): if frame is None: frame = HTML() tracks = self.__get_tracks_name(browser) widgets = OrderedDict([ ("chromosomes_list", Dropdown(options=chromosomes)), ("left_button", Button(icon="arrow-left")), ("right_button", Button(icon="arrow-right")), ("zoom_out_button", Button(icon="search-minus")), ("zoom_in_button", Button(icon="search-plus")), ("range_textbox", Text(placeholder="genome range like: 'chr1:10000-20000'")), ("go_button", Button(description="Go")), ("range_slider", IntRangeSlider(continuous_update=False, readout=False, layout=Layout(width='90%'))), ("range_min_label", Label("", layout=Layout(width='2%'))), ("range_max_label", Label("", layout=Layout(width='20%'))), ("auto_check_box", Checkbox(value=True, description="Auto Range", layout=Layout(width='120px'), style={'description_width': 'initial'})), ("track_min_val_float_text", FloatText(value=0.0001, description="Track's min value:", step=0.5, disabled=True, layout=Layout(width='30%'), style={'description_width': 'initial'})), ("track_max_val_float_text", FloatText(value=10, description="Track's max value:", step=0.5, disabled=True, layout=Layout(width='30%'), style={'description_width': 'initial'})), ("track_dropdown", Dropdown(options=[ALL_BW_MARK] + tracks, value=ALL_BW_MARK, description="Select track", disabled=True, )), ("frame", frame) ]) return widgets
def __init__(self, n_days_old_satimg=1): t = datetime.datetime.now() - datetime.timedelta(days=n_days_old_satimg) t_str = t.strftime("%Y-%m-%d") self.m = Map( layers=[ basemap_to_tiles(basemaps.NASAGIBS.ModisTerraTrueColorCR, t_str), ], center=(52.204793, 360.121558), zoom=2, ) self.domain_coords = [] self.polygon = None self.marker_locs = {} self.m.on_interaction(self._handle_map_click) button_reset = Button(description="reset") button_reset.on_click(self._clear_domain) button_save = Button(description="save domain") button_save.on_click(self._save_domain) self.name_textfield = Text(value="domain_name", width=10) self.m.add_control(WidgetControl(widget=button_save, position="bottomright")) self.m.add_control(WidgetControl(widget=button_reset, position="bottomright")) self.m.add_control( WidgetControl(widget=self.name_textfield, position="bottomright") )
def __init__(self, mk_signals: list): """ Summary : Object constructor. Arguments : mk_signals : list of signals available for performing the action. Returns: Nothing. """ # Add a selection box, to select the signals on which the action should # be performed self.label = Label("Action: " + self.__class__._type) self.wsm_signals = SelectMultipleOrdered(options=mk_signals, description="Signals:", placeholder="Signals", disabled=False) # Textbox with the name of the output signal self.wt_outsig = Text(description="Output name:", placeholder="output", disabled=False) super().__init__([self.label, self.wsm_signals, self.wt_outsig], layout=Layout(border='1px solid black'))
def controls(self): get_supercell = ToggleButton( value=False, description='Get supercell', disabled=False, button_style='', tooltip='Click to show supercell' ) get_supercell.observe(self.supercell_callback, 'value') run_command = Button( description='Run Command', disabled=False ) run_command.on_click(self.run_cmd_callback) self.command_text = Text( value='spin on', placeholder='spin on', description='Command:', disabled=False ) data_filter_vbox = VBox( [HBox([get_supercell]), HBox([self.command_text, run_command])]) return data_filter_vbox
def get_interactive_keyword(suite: TestSuite, keyword): """Get an interactive widget for testing a keyword.""" name = keyword.name arguments = [normalize_argument(arg) for arg in keyword.args] # Make a copy of the suite, the suite the widget operates on must no be # the same as the main one suite_copy = deepcopy(suite) execute_key = partial(execute_keyword, suite_copy, name, arguments) widgets = [] controls = OrderedDict() out = Output() for arg in arguments: input_widget = Text(description=arg[1] + "=", value=arg[2]) widgets.append(input_widget) controls[arg[1]] = input_widget button = Button(description=name) button.on_click( partial(on_button_execute, execute_key, controls, out, widgets)) widgets.insert(0, button) return VBox((HBox(widgets), out))
def login(self): username_text = Text(value=None, placeholder="username", description="Username: "******"<font color='black'>Waiting for login</font>") login_button = Button(description="Login", button_style="success", layout=Layout(width="10%")) login_link_box = Output() base_url = "https://hugs.acquire-aaai.com/t" def do_login(a): user = User(username=username_text.value, identity_url=f"{base_url}/identity") with login_link_box: user.request_login() if user.wait_for_login(): status_text.value = "<font color='green'>Login success</font>" else: status_text.value = "<font color='red'>Login failure</font>" self._user = user login_button.on_click(do_login) return VBox(children=[ username_text, login_button, status_text, login_link_box ])
def freetext_submission(self, sender: widgets.Text): """Handle a submission by the free-text widget. This is a separate method from `submit`, because it doesn't actually submit the data. Instead, it adds the free-text as an option, and toggles that option to `True`. Parameters ---------- sender : widgets.Text """ if sender is self.freetext_widget and sender.value: value = sender.value # check if this is a new option: if value not in self.options: self.options = self.options + [value] def _undo_callback(): self.options = [ opt for opt in self.options if opt != value ] self._undo_queue.append(_undo_callback) if value not in self.data: self.data = self.data + [value] sender.value = "" self._freetext_timestamp = time.time()
def _make_affix_box(self, a_e): aff = getattr(self._rgx_mchr, a_e[0]) err = getattr(self._rgx_mchr, a_e[1]) dct = getattr(self._rgx_mchr, a_e[2]) opt = getattr(self._rgx_mchr, a_e[3]) form_item_layout = Layout(display='flex', flex_flow='column', align_items='stretch', display_content='center') ctrl = VBox([ Checkbox( value=opt, description=a_e[0] + 'fix', ), Text(value=aff, ), IntSlider( value=err, min=0, max=6, readout=True, ), SelectMultiple(options=dct), ], layout=form_item_layout) #ctrl.children[1].disabled = not ctrl.children[0].value link((self._rgx_mchr, a_e[0]), (ctrl.children[1], 'value')) link((self._rgx_mchr, a_e[1]), (ctrl.children[2], 'value')) link((self._rgx_mchr, a_e[3]), (ctrl.children[0], 'value')) return ctrl
def interactive_clustermap(self): def do_interact(data_type='expression', sample_subset=self.default_sample_subsets, feature_subset=self.default_feature_subset, metric='euclidean', method='median', list_link='', scale_fig_by_data=True, fig_width='', fig_height=''): for k, v in locals().iteritems(): if k == 'self': continue sys.stdout.write('{} : {}\n'.format(k, v)) if feature_subset != "custom" and list_link != "": raise ValueError( "set feature_subset to \"custom\" to use list_link") if feature_subset == "custom" and list_link == "": raise ValueError("use a custom list name please") if feature_subset == 'custom': feature_subset = list_link elif feature_subset not in self.default_feature_subsets[data_type]: warnings.warn("This feature_subset ('{}') is not available in " "this data type ('{}'). Falling back on all " "features.".format(feature_subset, data_type)) return self.plot_clustermap(sample_subset=sample_subset, feature_subset=feature_subset, data_type=data_type, metric=metric, method=method, scale_fig_by_data=scale_fig_by_data) feature_subsets = Interactive.get_feature_subsets( self, ['expression', 'splicing']) method = ('average', 'weighted', 'single', 'complete', 'ward') metric = ('euclidean', 'seuclidean', 'sqeuclidean', 'chebyshev', 'cosine', 'cityblock', 'mahalonobis', 'minowski', 'jaccard') gui = interact(do_interact, data_type=('expression', 'splicing'), sample_subset=self.default_sample_subsets, feature_subset=feature_subsets, metric=metric, method=method) def save(w): filename, extension = os.path.splitext(savefile.value) self.maybe_make_directory(savefile.value) gui.widget.result.savefig(savefile.value, format=extension.lstrip('.')) savefile = Text(description='savefile', value='figures/clustermap.pdf') save_widget = Button(description='save') gui.widget.children = list( gui.widget.children) + [savefile, save_widget] save_widget.on_click(save) return gui
def _dock_add_text(self, value, callback, validator=None, layout=None): layout = self.dock_layout if layout is None else layout widget = Text(value=value) widget.observe(_generate_callback(callback, to_float=validator), names='value') _ipy_add_widget(layout, widget, self.dock_width) return widget
def __init__(self, a_pid): """通过进程pid初始化ui组件""" self.progress_widget = FloatProgress(value=0, min=0, max=100) self.text_widget = Text('pid={} begin work'.format(a_pid)) # 通过box容器都放到一个里面 self.progress_box = Box([self.text_widget, self.progress_widget]) display(self.progress_box)
def interactive_simulation(observations): return interactive( explore_simulation, {'manual': True}, initial_growth_rate=my_slider(30, 5, 50, 2, 'Initial growth rate, %'), serial_interval=my_slider(6.5, 2, 10, 0.5, 'Mean serial interval, days'), latent_fraction=my_slider(0.71, 0.1, 0.9, 0.1, 'Latent period fraction'), f_cdr=my_slider(4.4, 0.1, 10, 0.1, 'Case detection rate, %'), f_cfr=my_slider(20, 1, 100, 1, 'Case fatality rate, %'), T_detect=my_slider(11, 1, 30, 1, 'Time to detection, days'), T_resolve=my_slider(8, 1, 30, 1, 'Time to recovery, days'), T_death=my_slider(10, 1, 56, 1, 'Time to death, days'), cv_detect=my_slider(50, 1, 99, 1, 'Detection time variability, %'), cv_resolve=my_slider(33, 1, 99, 1, 'Recovery time variability, %'), cv_death=my_slider(50, 1, 99, 1, 'Death time variability, %'), R_0_lockdown=my_slider(1.0, 0.1, 4, 0.1, '$R_0$ during lockdown'), lockdown_release_date=Text(value='2020/06/30', description='Lockdown release date', style={'description_width': 'initial'}), lockdown_release_timeframe_weeks=my_text_box( 26, 1, 9999, 1, 'Number of weeks for lockdown release'), sim_time_weeks=my_text_box(52, 1, 999, 1, 'Simulation length, weeks'), weights=Dropdown(options=[('Cases', [1, 0, 0]), ('Deaths', [0, 0, 1]), ('Cases & deaths', [.5, 0, .5])], description='Fit to ', style={'description_width': 'initial'}), observations=fixed(observations))