def _default_layout(self): return Layout(height='500px', align_self='stretch')
import ipywidgets as widgets from ipywidgets import HBox, VBox, Layout from IPython.display import display from IPython.display import clear_output #Eliminar warnings from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import warnings warnings.filterwarnings("ignore") #Model visualization box_layout = Layout(display='flex', align_items='center', width='auto', justify_content='space-around') #busca los ficheros netCDF en la ruta indicada def busca_modelos(ruta): files = [ os.path.abspath(arch.path) for arch in os.scandir(ruta) if arch.is_file() ] lstFiles = [] for fichero in files: (nombreFichero, extension) = os.path.splitext(fichero) if (extension == ".nc"): lstFiles.append(nombre_modelo(nombreFichero)) #print (nombreFichero+extension)
def __init__(self): tab_height = '520px' tab_height = '550px' tab_layout = Layout( width='900px', # border='2px solid black', height=tab_height) #, overflow_y='scroll') self.output_dir = '.' # self.output_dir = 'tmpdir' max_frames = 1 self.svg_plot = interactive(self.plot_svg, frame=(0, max_frames), continuous_update=False) svg_plot_size = '500px' self.svg_plot.layout.width = svg_plot_size self.svg_plot.layout.height = svg_plot_size self.use_defaults = True self.show_nucleus = 0 # 0->False, 1->True in Checkbox! self.show_edge = 1 # 0->False, 1->True in Checkbox! self.scale_radius = 1.0 self.axes_min = 0.0 self.axes_max = 2000 # hmm, this can change (TODO?) self.fig = plt.figure(figsize=(6, 6)) # self.tab = HBox([svg_plot], layout=tab_layout) self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='Max', # layout=Layout(flex='0 1 auto', width='auto'), #Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) self.show_nucleus_checkbox = Checkbox( description='nucleus', value=False, disabled=False, # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_nucleus_checkbox.observe(self.show_nucleus_cb) self.show_edge_checkbox = Checkbox( description='edge', value=True, disabled=False, # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_edge_checkbox.observe(self.show_edge_cb) # row1 = HBox([Label('(select slider: drag or left/right arrows)'), # self.max_frames, VBox([self.show_nucleus_checkbox, self.show_edge_checkbox])]) # self.max_frames, self.show_nucleus_checkbox], layout=Layout(width='500px')) # self.tab = VBox([row1,self.svg_plot], layout=tab_layout) self.help_label = Label('select slider: drag or left/right arrows', layout=Layout(flex='0 1 auto', width='auto')) # layout=Layout(flex='3 1 auto', width='auto')) items_auto = [ self.help_label, self.max_frames, self.show_nucleus_checkbox, self.show_edge_checkbox, ] #row1 = HBox([Label('(select slider: drag or left/right arrows)'), # max_frames, show_nucleus_checkbox, show_edge_checkbox], # layout=Layout(width='800px')) box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='90%') # row1 = Box(children=items_auto, layout=box_layout) #row1 = Box(children=items_auto) row1 = Box([ self.help_label, Box([ self.max_frames, self.show_nucleus_checkbox, self.show_edge_checkbox ], layout=Layout(border='0px solid black', width='60%', height='', align_items='stretch', flex_direction='row', display='flex')) ]) # self.download_button = Download('svg.zip', style='warning', icon='cloud-download', tooltip='Download results', cb=self.download_cb) #self.download_button = Download('svg.zip', style='warning', icon='cloud-download', tooltip='Download results') # self.tab = VBox([row1, self.svg_plot], layout=tab_layout) # self.tab = VBox([row1, self.svg_plot, self.download_button.w], layout=tab_layout) self.tab = VBox([row1, self.svg_plot], layout=tab_layout)
def _gen_app_layout(self): title = self._widget['title'] toggle_buttons = self._widget['toggle_buttons'] # checkbox = self._widget['checkbox'] label = self._widget['label'] fig = self._widget['fig'] topomap_fig = self._widget['topomap_fig'] dipole_amp_slider = self._widget['amplitude_slider'] tab = self._widget['tab'] output = self._widget['output'] reset_button = self._widget['reset_button'] quickstart = self._widget['quickstart_accordion'] preset = self._widget['preset_dropdown'] dipole_props_col = VBox( [HBox([label['dipole_pos_'], label['dipole_pos']]), HBox([label['dipole_ori_'], label['dipole_ori']])]) # dipole_amp_and_exact_sol_col = VBox( # [label['amplitude_slider'], # dipole_amp_slider, # checkbox['exact_solution']]) dipole_amp_col = VBox( [dipole_amp_slider, label['amplitude_slider']]) grid = GridspecLayout(3, 3, grid_gap='0', width="95%") grid[0, 0] = HBox([label['status'], label['updating']]) grid[1, 0] = preset grid[1, -1] = reset_button grid[2, :3] = HBox([toggle_buttons['mode_selector']], layout=Layout(display='flex', flex_flow='column', align_items='center', width='100%')) main_tab = VBox([grid, # dipole_amp_and_exact_sol_col]), HBox([VBox([label['axis']['x'], fig['x'].canvas], layout=Layout(align_items='center')), VBox([label['axis']['y'], fig['y'].canvas], layout=Layout(align_items='center')), VBox([label['axis']['z'], fig['z'].canvas], layout=Layout(align_items='center'))]), HBox([VBox([label['topomap_mag'], topomap_fig['mag'].canvas], layout=Layout(align_items='center')), VBox([label['topomap_grad'], topomap_fig['grad'].canvas], layout=Layout(align_items='center')), VBox([label['topomap_eeg'], topomap_fig['eeg'].canvas], layout=Layout(align_items='center'))]), dipole_amp_col, dipole_props_col], layout=Layout(align_items='center')) mne_output_tab = VBox([output]) help_tab = VBox([Label('Whoops. Somebody was lazy here.')]) about_text = ('<h3>M/EEG Dipole Simulator</h3>\n' '<p>An interactive demonstration of how dipole location ' 'and orientation affect MEG and EEG sensor signals.' '</p>\n' '<p><b>This is still ' '<a href="https://github.com/hoechenberger/dipoles_demo/issues/26">' 'work in progress</a></b></p>\n' '<h4>Contributors</h4>\n' '<ul>\n' '<li>Idea & Conceptualization: ' '<b>Maximilien Chaumon</b> ' '(<a href="https://github.com/dnacombo">GitHub</a>, ' '<a href="https://twitter.com/@cuttingEEG">Twitter)</a>' '</li>\n' '<li>Conceptualization & Supervision: ' '<b>Alexandre Gramfort</b> ' '(<a href="https://github.com/agramfort">GitHub</a>, ' '<a href="https://twitter.com/agramfort">Twitter</a>)' '</li>\n' '<li>Testing & Feedback: ' '<b>Sophie Herbst</b> ' '(<a href="https://github.com/SophieHerbst">GitHub</a>, ' '<a href="https://twitter.com/herbstso">Twitter</a>) & ' '<b>Virginie van Wassenhove</b> ' '(<a href="https://github.com/virvw">GitHub</a>, ' '<a href="https://twitter.com/virginie_vw">Twitter</a>)' '</li>\n' '<li>Implementation: ' '<b>Richard Höchenberger</b> ' '(<a href="https://github.com/hoechenberger">GitHub</a>, ' '<a href="https://twitter.com/RHoechenberger">Twitter</a>)' '</li>\n' '</ul>\n') about_tab = VBox([HTML(about_text)]) del about_text tab.children = [main_tab, mne_output_tab, help_tab, about_tab] tab.set_title(0, 'Dipole Simulator') tab.set_title(1, 'MNE-Python Output') tab.set_title(2, 'Help') tab.set_title(3, 'About') app = VBox([title, quickstart, tab], layout=Layout(align_items='center')) self._app_layout = app
def __init__(self): items_layout = Layout (flex = '1 1 auto', width = 'auto') self.w_title = HTML('<h3>Форма электродов</h3>') self.w_l_x = Label('Границы изогнутой части электрода по горизонтали:') self.w_x = FloatRangeSlider(value=[0.5,1.], min=0., max=1., step=0.02, continuous_update=False, readout_format='.3f', layout=items_layout) self.w_l_y = Label('Координаты электрода по вертикали:') self.w_l_y0 = Label('y0') layouth = Layout(height='300px') self.w_y0 = FloatSlider(value=0.6, min=0.5, max=1.0, step=0.001, description='y0', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.3f', layout=layouth ) self.w_y1 = FloatSlider(value=0.6, min=0.5, max=1.0, step=0.001, description='y1', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.3f', layout=layouth ) self.w_y2 = FloatSlider(value=0.6, min=0.5, max=1.0, step=0.001, description='y2', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.3f', layout=layouth ) self.w_y3 = FloatSlider(value=0.6, min=0.5, max=1.0, step=0.001, description='y3', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.3f', layout=layouth ) self.w_y4 = FloatSlider(value=0.6, min=0.5, max=1.0, step=0.001, description='y4', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.3f', layout=layouth ) self.out_el = Output() hbox1 = HBox([self.w_y0, self.w_y1, self.w_y2, self.w_y3, self.w_y4], layout=Layout(width='100%')) vbox1 = VBox([self.w_l_x, self.w_x, self.w_l_y, hbox1], layout=Layout(width='50%', padding='5px')) vbox2 = HBox([self.out_el], layout=Layout(width='50%', padding='5px')) hbox = HBox ([vbox1, vbox2], layout=Layout(width='100%')) self.layout = VBox([self.w_title, hbox]) self.interactive_el_form = interactive(self.el_form, x0xm=self.w_x, y0=self.w_y0, y1=self.w_y1, y2=self.w_y2, y3=self.w_y3, y4=self.w_y4)
def create_tables(): """Create essential cbm tables """ l_tb = Label("""Add a short name as prefix for the tables, max 15 characters e.g.:escat2020.""") try: with open(f"{config.get_value(['paths','temp'])}tb_prefix", 'r') as f: prefix = f.read() except Exception: prefix = '' tb_prefix = Text(value=prefix, placeholder='xx2010', description='Table prefix:', disabled=False) checkboxes = {} tbs = db_tables.tables_dict() for key in tbs: checkboxes[key] = Checkbox(value=True, description=tbs[key]['name'], disabled=False, indent=False, layout=Layout(width='150px')) checkboxes["aois"].value = False check_box = HBox([checkboxes[t] for t in checkboxes]) bt_create_tb = Button(description='Create tables', value=False, disabled=False, button_style='info', tooltip='Creat tables', icon='fa-table') progress = Output() def outlog(*text): with progress: print(*text) def on_tb_prefix(change): with open(f"{config.get_value(['paths','temp'])}tb_prefix", 'w+') as f: f.write(tb_prefix.value.replace(' ', '').lower()[:15]) tb_prefix.observe(on_tb_prefix, 'value') @bt_create_tb.on_click def bt_create_tb_on_click(b): progress.clear_output() tb_prefix_clean = tb_prefix.value.replace(' ', '').lower()[:15] if tb_prefix.value != '': for key in tbs: if checkboxes[key].value is True: if database.tb_exist( f"{tb_prefix_clean}_{tbs[key]['table']}") is False: sql = tbs[key]['sql'].replace('\n', '').replace(' ', '') database.execute_sql(sql.format(tb_prefix_clean)) outlog( f"The table {tb_prefix_clean}_{tbs[key]['table']} is created.." ) else: outlog( f"The table {tb_prefix_clean}_{tbs[key]['table']} already exist." ) else: outlog("Please add tables prefix.") wbox = VBox([l_tb, tb_prefix, check_box, bt_create_tb, progress]) return wbox
def __init__(self): micron_units = Label( 'micron') # use "option m" (Mac, for micro symbol) constWidth = '180px' tab_height = '500px' stepsize = 10 #style = {'description_width': '250px'} style = {'description_width': '25%'} layout = {'width': '400px'} name_button_layout = {'width': '25%'} widget_layout = {'width': '15%'} units_button_layout = {'width': '15%'} desc_button_layout = {'width': '45%'} param_name1 = Button(description='seeding_method', disabled=True, layout=name_button_layout) param_name1.style.button_color = 'lightgreen' self.seeding_method = Text(value='box', style=style, layout=widget_layout) param_name2 = Button(description='cell_default_inital_energy', disabled=True, layout=name_button_layout) param_name2.style.button_color = 'tan' self.cell_default_inital_energy = FloatText(value=7.01, step=0.1, style=style, layout=widget_layout) param_name3 = Button(description='cell_default_energy_creation_rate', disabled=True, layout=name_button_layout) param_name3.style.button_color = 'lightgreen' self.cell_default_energy_creation_rate = FloatText( value=0.01, step=0.001, style=style, layout=widget_layout) param_name4 = Button(description='cell_default_energy_use_rate', disabled=True, layout=name_button_layout) param_name4.style.button_color = 'tan' self.cell_default_energy_use_rate = FloatText(value=0.02, step=0.001, style=style, layout=widget_layout) param_name5 = Button(description='cell_default_cycle_energy_threshold', disabled=True, layout=name_button_layout) param_name5.style.button_color = 'lightgreen' self.cell_default_cycle_energy_threshold = FloatText( value=10.0, step=1, style=style, layout=widget_layout) param_name6 = Button(description='cell_default_death_energy_threshold', disabled=True, layout=name_button_layout) param_name6.style.button_color = 'tan' self.cell_default_death_energy_threshold = FloatText( value=6, step=0.1, style=style, layout=widget_layout) param_name7 = Button(description='cell_default_aplha', disabled=True, layout=name_button_layout) param_name7.style.button_color = 'lightgreen' self.cell_default_aplha = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name8 = Button(description='cell_default_beta', disabled=True, layout=name_button_layout) param_name8.style.button_color = 'tan' self.cell_default_beta = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name9 = Button(description='cell_default_gamma', disabled=True, layout=name_button_layout) param_name9.style.button_color = 'lightgreen' self.cell_default_gamma = FloatText(value=0.5, step=0.1, style=style, layout=widget_layout) param_name10 = Button(description='cell_default_rho', disabled=True, layout=name_button_layout) param_name10.style.button_color = 'tan' self.cell_default_rho = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name11 = Button(description='cell_default_phi', disabled=True, layout=name_button_layout) param_name11.style.button_color = 'lightgreen' self.cell_default_phi = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name12 = Button(description='cell_default_chi', disabled=True, layout=name_button_layout) param_name12.style.button_color = 'tan' self.cell_default_chi = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name13 = Button(description='wound_cell_glucose_secretion_rate', disabled=True, layout=name_button_layout) param_name13.style.button_color = 'lightgreen' self.wound_cell_glucose_secretion_rate = FloatText( value=10.0, step=1, style=style, layout=widget_layout) param_name14 = Button(description='wound_cell_ECM_secretion_rate', disabled=True, layout=name_button_layout) param_name14.style.button_color = 'tan' self.wound_cell_ECM_secretion_rate = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name15 = Button(description='anaerobic_cell_alpha', disabled=True, layout=name_button_layout) param_name15.style.button_color = 'lightgreen' self.anaerobic_cell_alpha = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name16 = Button(description='anaerobic_cell_beta', disabled=True, layout=name_button_layout) param_name16.style.button_color = 'tan' self.anaerobic_cell_beta = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name17 = Button(description='anaerobic_cell_gamma', disabled=True, layout=name_button_layout) param_name17.style.button_color = 'lightgreen' self.anaerobic_cell_gamma = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name18 = Button(description='anaerobic_cell_rho', disabled=True, layout=name_button_layout) param_name18.style.button_color = 'tan' self.anaerobic_cell_rho = FloatText(value=0.1, step=0.01, style=style, layout=widget_layout) param_name19 = Button(description='anaerobic_cell_phi', disabled=True, layout=name_button_layout) param_name19.style.button_color = 'lightgreen' self.anaerobic_cell_phi = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name20 = Button(description='anaerobic_cell_chi', disabled=True, layout=name_button_layout) param_name20.style.button_color = 'tan' self.anaerobic_cell_chi = FloatText(value=2.0, step=0.1, style=style, layout=widget_layout) param_name21 = Button(description='anaerobic_ECM_secretion_rate', disabled=True, layout=name_button_layout) param_name21.style.button_color = 'lightgreen' self.anaerobic_ECM_secretion_rate = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name22 = Button(description='anaerobic_glucose_uptake_rate', disabled=True, layout=name_button_layout) param_name22.style.button_color = 'tan' self.anaerobic_glucose_uptake_rate = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name23 = Button(description='aerobic_cell_alpha', disabled=True, layout=name_button_layout) param_name23.style.button_color = 'lightgreen' self.aerobic_cell_alpha = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name24 = Button(description='aerobic_cell_beta', disabled=True, layout=name_button_layout) param_name24.style.button_color = 'tan' self.aerobic_cell_beta = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name25 = Button(description='aerobic_cell_gamma', disabled=True, layout=name_button_layout) param_name25.style.button_color = 'lightgreen' self.aerobic_cell_gamma = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name26 = Button(description='aerobic_cell_rho', disabled=True, layout=name_button_layout) param_name26.style.button_color = 'tan' self.aerobic_cell_rho = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name27 = Button(description='aerobic_cell_phi', disabled=True, layout=name_button_layout) param_name27.style.button_color = 'lightgreen' self.aerobic_cell_phi = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name28 = Button(description='aerobic_cell_chi', disabled=True, layout=name_button_layout) param_name28.style.button_color = 'tan' self.aerobic_cell_chi = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name29 = Button(description='aerobic_ECM_secretion_rate', disabled=True, layout=name_button_layout) param_name29.style.button_color = 'lightgreen' self.aerobic_ECM_secretion_rate = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name30 = Button(description='aerobic_glucose_uptake_rate', disabled=True, layout=name_button_layout) param_name30.style.button_color = 'tan' self.aerobic_glucose_uptake_rate = FloatText(value=1.0, step=0.1, style=style, layout=widget_layout) param_name31 = Button(description='aerobic_oxygen_uptake_rate', disabled=True, layout=name_button_layout) param_name31.style.button_color = 'lightgreen' self.aerobic_oxygen_uptake_rate = FloatText(value=1000.0, step=100, style=style, layout=widget_layout) param_name32 = Button(description='apoptosis_rate', disabled=True, layout=name_button_layout) param_name32.style.button_color = 'tan' self.apoptosis_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) param_name33 = Button(description='proliferation_rate', disabled=True, layout=name_button_layout) param_name33.style.button_color = 'lightgreen' self.proliferation_rate = FloatText(value=0.001, step=0.0001, style=style, layout=widget_layout) param_name34 = Button(description='ECM_diffusion_coeff', disabled=True, layout=name_button_layout) param_name34.style.button_color = 'tan' self.ECM_diffusion_coeff = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) param_name35 = Button(description='ECM_decay_constant', disabled=True, layout=name_button_layout) param_name35.style.button_color = 'lightgreen' self.ECM_decay_constant = FloatText(value=1, step=0.1, style=style, layout=widget_layout) param_name36 = Button(description='glucose_diffusion_coeff', disabled=True, layout=name_button_layout) param_name36.style.button_color = 'tan' self.glucose_diffusion_coeff = FloatText(value=1.6e3, step=100, style=style, layout=widget_layout) param_name37 = Button(description='glucose_decay_constant', disabled=True, layout=name_button_layout) param_name37.style.button_color = 'lightgreen' self.glucose_decay_constant = FloatText(value=0.05, step=0.01, style=style, layout=widget_layout) units_button1 = Button(description='', disabled=True, layout=units_button_layout) units_button1.style.button_color = 'lightgreen' units_button2 = Button(description='a.u', disabled=True, layout=units_button_layout) units_button2.style.button_color = 'tan' units_button3 = Button(description='a.u/min', disabled=True, layout=units_button_layout) units_button3.style.button_color = 'lightgreen' units_button4 = Button(description='a.u/min', disabled=True, layout=units_button_layout) units_button4.style.button_color = 'tan' units_button5 = Button(description='a.u', disabled=True, layout=units_button_layout) units_button5.style.button_color = 'lightgreen' units_button6 = Button(description='a.u', disabled=True, layout=units_button_layout) units_button6.style.button_color = 'tan' units_button7 = Button(description='', disabled=True, layout=units_button_layout) units_button7.style.button_color = 'lightgreen' units_button8 = Button(description='', disabled=True, layout=units_button_layout) units_button8.style.button_color = 'tan' units_button9 = Button(description='', disabled=True, layout=units_button_layout) units_button9.style.button_color = 'lightgreen' units_button10 = Button(description='', disabled=True, layout=units_button_layout) units_button10.style.button_color = 'tan' units_button11 = Button(description='', disabled=True, layout=units_button_layout) units_button11.style.button_color = 'lightgreen' units_button12 = Button(description='', disabled=True, layout=units_button_layout) units_button12.style.button_color = 'tan' units_button13 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button13.style.button_color = 'lightgreen' units_button14 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button14.style.button_color = 'tan' units_button15 = Button(description='', disabled=True, layout=units_button_layout) units_button15.style.button_color = 'lightgreen' units_button16 = Button(description='', disabled=True, layout=units_button_layout) units_button16.style.button_color = 'tan' units_button17 = Button(description='', disabled=True, layout=units_button_layout) units_button17.style.button_color = 'lightgreen' units_button18 = Button(description='', disabled=True, layout=units_button_layout) units_button18.style.button_color = 'tan' units_button19 = Button(description='', disabled=True, layout=units_button_layout) units_button19.style.button_color = 'lightgreen' units_button20 = Button(description='', disabled=True, layout=units_button_layout) units_button20.style.button_color = 'tan' units_button21 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button21.style.button_color = 'lightgreen' units_button22 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button22.style.button_color = 'tan' units_button23 = Button(description='', disabled=True, layout=units_button_layout) units_button23.style.button_color = 'lightgreen' units_button24 = Button(description='', disabled=True, layout=units_button_layout) units_button24.style.button_color = 'tan' units_button25 = Button(description='', disabled=True, layout=units_button_layout) units_button25.style.button_color = 'lightgreen' units_button26 = Button(description='', disabled=True, layout=units_button_layout) units_button26.style.button_color = 'tan' units_button27 = Button(description='', disabled=True, layout=units_button_layout) units_button27.style.button_color = 'lightgreen' units_button28 = Button(description='', disabled=True, layout=units_button_layout) units_button28.style.button_color = 'tan' units_button29 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button29.style.button_color = 'lightgreen' units_button30 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button30.style.button_color = 'tan' units_button31 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button31.style.button_color = 'lightgreen' units_button32 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button32.style.button_color = 'tan' units_button33 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button33.style.button_color = 'lightgreen' units_button34 = Button(description='um2/min', disabled=True, layout=units_button_layout) units_button34.style.button_color = 'tan' units_button35 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button35.style.button_color = 'lightgreen' units_button36 = Button(description='um2/min', disabled=True, layout=units_button_layout) units_button36.style.button_color = 'tan' units_button37 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button37.style.button_color = 'lightgreen' desc_button1 = Button( description= 'Method for seeding. Can be vertical,horizontal, random, or box (default)', disabled=True, layout=desc_button_layout) desc_button1.style.button_color = 'lightgreen' desc_button2 = Button(description='Initialized energy level', disabled=True, layout=desc_button_layout) desc_button2.style.button_color = 'tan' desc_button3 = Button( description='Energy creation rate for bacterial cells', disabled=True, layout=desc_button_layout) desc_button3.style.button_color = 'lightgreen' desc_button4 = Button( description='Energy usage rate for bacterial cells', disabled=True, layout=desc_button_layout) desc_button4.style.button_color = 'tan' desc_button5 = Button( description='Cycling energy threshold for bacterial cells', disabled=True, layout=desc_button_layout) desc_button5.style.button_color = 'lightgreen' desc_button6 = Button( description='Apoptosis energy threshold for bacterial cells', disabled=True, layout=desc_button_layout) desc_button6.style.button_color = 'tan' desc_button7 = Button( description='Energy creation Rate modifier for aerobic cells', disabled=True, layout=desc_button_layout) desc_button7.style.button_color = 'lightgreen' desc_button8 = Button( description='Energy creation Rate modifier for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button8.style.button_color = 'tan' desc_button9 = Button( description='Energy usage modulator for bacterial cells', disabled=True, layout=desc_button_layout) desc_button9.style.button_color = 'lightgreen' desc_button10 = Button( description='Energy degradation rate modifier for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button10.style.button_color = 'tan' desc_button11 = Button( description='Energy creation rate modulator for aerobic cells', disabled=True, layout=desc_button_layout) desc_button11.style.button_color = 'lightgreen' desc_button12 = Button( description='Energy creation rate modulator for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button12.style.button_color = 'tan' desc_button13 = Button( description='Glucose secretion rate for wound cells', disabled=True, layout=desc_button_layout) desc_button13.style.button_color = 'lightgreen' desc_button14 = Button( description='Glucose secretion rate for wound cells', disabled=True, layout=desc_button_layout) desc_button14.style.button_color = 'tan' desc_button15 = Button( description='Energy Creation Rate modifier for aerobic cells', disabled=True, layout=desc_button_layout) desc_button15.style.button_color = 'lightgreen' desc_button16 = Button( description='Energy Creation Rate modifier for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button16.style.button_color = 'tan' desc_button17 = Button( description='Energy usage modulator for bacterial cells', disabled=True, layout=desc_button_layout) desc_button17.style.button_color = 'lightgreen' desc_button18 = Button( description='Energy degradation rate modifier for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button18.style.button_color = 'tan' desc_button19 = Button( description='Energy creation rate modulator for aerobic cells', disabled=True, layout=desc_button_layout) desc_button19.style.button_color = 'lightgreen' desc_button20 = Button( description='Energy creation rate modulator for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button20.style.button_color = 'tan' desc_button21 = Button( description='ECM creation rate for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button21.style.button_color = 'lightgreen' desc_button22 = Button( description='Glucose uptake rate for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button22.style.button_color = 'tan' desc_button23 = Button( description='Energy Creation Rate modifier for aerobic cells', disabled=True, layout=desc_button_layout) desc_button23.style.button_color = 'lightgreen' desc_button24 = Button( description='Energy Creation Rate modifier for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button24.style.button_color = 'tan' desc_button25 = Button( description='Energy usage modulator for bacterial cells', disabled=True, layout=desc_button_layout) desc_button25.style.button_color = 'lightgreen' desc_button26 = Button( description='Energy degradation rate modifier for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button26.style.button_color = 'tan' desc_button27 = Button( description='Energy creation rate modulator for aerobic cells', disabled=True, layout=desc_button_layout) desc_button27.style.button_color = 'lightgreen' desc_button28 = Button( description='Energy creation rate modulator for anaerobic cells', disabled=True, layout=desc_button_layout) desc_button28.style.button_color = 'tan' desc_button29 = Button( description='ECM creation rate for aerobic cells', disabled=True, layout=desc_button_layout) desc_button29.style.button_color = 'lightgreen' desc_button30 = Button( description='Glucose uptake rate for aerobic cells', disabled=True, layout=desc_button_layout) desc_button30.style.button_color = 'tan' desc_button31 = Button( description='Oxygen uptake rate for aerobic cells', disabled=True, layout=desc_button_layout) desc_button31.style.button_color = 'lightgreen' desc_button32 = Button( description='Apoptosis rate for bacterial cells', disabled=True, layout=desc_button_layout) desc_button32.style.button_color = 'tan' desc_button33 = Button( description='Proliferation rate for bacterial cells', disabled=True, layout=desc_button_layout) desc_button33.style.button_color = 'lightgreen' desc_button34 = Button(description='', disabled=True, layout=desc_button_layout) desc_button34.style.button_color = 'tan' desc_button35 = Button(description='', disabled=True, layout=desc_button_layout) desc_button35.style.button_color = 'lightgreen' desc_button36 = Button(description='', disabled=True, layout=desc_button_layout) desc_button36.style.button_color = 'tan' desc_button37 = Button(description='', disabled=True, layout=desc_button_layout) desc_button37.style.button_color = 'lightgreen' row1 = [param_name1, self.seeding_method, units_button1, desc_button1] row2 = [ param_name2, self.cell_default_inital_energy, units_button2, desc_button2 ] row3 = [ param_name3, self.cell_default_energy_creation_rate, units_button3, desc_button3 ] row4 = [ param_name4, self.cell_default_energy_use_rate, units_button4, desc_button4 ] row5 = [ param_name5, self.cell_default_cycle_energy_threshold, units_button5, desc_button5 ] row6 = [ param_name6, self.cell_default_death_energy_threshold, units_button6, desc_button6 ] row7 = [ param_name7, self.cell_default_aplha, units_button7, desc_button7 ] row8 = [ param_name8, self.cell_default_beta, units_button8, desc_button8 ] row9 = [ param_name9, self.cell_default_gamma, units_button9, desc_button9 ] row10 = [ param_name10, self.cell_default_rho, units_button10, desc_button10 ] row11 = [ param_name11, self.cell_default_phi, units_button11, desc_button11 ] row12 = [ param_name12, self.cell_default_chi, units_button12, desc_button12 ] row13 = [ param_name13, self.wound_cell_glucose_secretion_rate, units_button13, desc_button13 ] row14 = [ param_name14, self.wound_cell_ECM_secretion_rate, units_button14, desc_button14 ] row15 = [ param_name15, self.anaerobic_cell_alpha, units_button15, desc_button15 ] row16 = [ param_name16, self.anaerobic_cell_beta, units_button16, desc_button16 ] row17 = [ param_name17, self.anaerobic_cell_gamma, units_button17, desc_button17 ] row18 = [ param_name18, self.anaerobic_cell_rho, units_button18, desc_button18 ] row19 = [ param_name19, self.anaerobic_cell_phi, units_button19, desc_button19 ] row20 = [ param_name20, self.anaerobic_cell_chi, units_button20, desc_button20 ] row21 = [ param_name21, self.anaerobic_ECM_secretion_rate, units_button21, desc_button21 ] row22 = [ param_name22, self.anaerobic_glucose_uptake_rate, units_button22, desc_button22 ] row23 = [ param_name23, self.aerobic_cell_alpha, units_button23, desc_button23 ] row24 = [ param_name24, self.aerobic_cell_beta, units_button24, desc_button24 ] row25 = [ param_name25, self.aerobic_cell_gamma, units_button25, desc_button25 ] row26 = [ param_name26, self.aerobic_cell_rho, units_button26, desc_button26 ] row27 = [ param_name27, self.aerobic_cell_phi, units_button27, desc_button27 ] row28 = [ param_name28, self.aerobic_cell_chi, units_button28, desc_button28 ] row29 = [ param_name29, self.aerobic_ECM_secretion_rate, units_button29, desc_button29 ] row30 = [ param_name30, self.aerobic_glucose_uptake_rate, units_button30, desc_button30 ] row31 = [ param_name31, self.aerobic_oxygen_uptake_rate, units_button31, desc_button31 ] row32 = [ param_name32, self.apoptosis_rate, units_button32, desc_button32 ] row33 = [ param_name33, self.proliferation_rate, units_button33, desc_button33 ] row34 = [ param_name34, self.ECM_diffusion_coeff, units_button34, desc_button34 ] row35 = [ param_name35, self.ECM_decay_constant, units_button35, desc_button35 ] row36 = [ param_name36, self.glucose_diffusion_coeff, units_button36, desc_button36 ] row37 = [ param_name37, self.glucose_decay_constant, units_button37, desc_button37 ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') box1 = Box(children=row1, layout=box_layout) box2 = Box(children=row2, layout=box_layout) box3 = Box(children=row3, layout=box_layout) box4 = Box(children=row4, layout=box_layout) box5 = Box(children=row5, layout=box_layout) box6 = Box(children=row6, layout=box_layout) box7 = Box(children=row7, layout=box_layout) box8 = Box(children=row8, layout=box_layout) box9 = Box(children=row9, layout=box_layout) box10 = Box(children=row10, layout=box_layout) box11 = Box(children=row11, layout=box_layout) box12 = Box(children=row12, layout=box_layout) box13 = Box(children=row13, layout=box_layout) box14 = Box(children=row14, layout=box_layout) box15 = Box(children=row15, layout=box_layout) box16 = Box(children=row16, layout=box_layout) box17 = Box(children=row17, layout=box_layout) box18 = Box(children=row18, layout=box_layout) box19 = Box(children=row19, layout=box_layout) box20 = Box(children=row20, layout=box_layout) box21 = Box(children=row21, layout=box_layout) box22 = Box(children=row22, layout=box_layout) box23 = Box(children=row23, layout=box_layout) box24 = Box(children=row24, layout=box_layout) box25 = Box(children=row25, layout=box_layout) box26 = Box(children=row26, layout=box_layout) box27 = Box(children=row27, layout=box_layout) box28 = Box(children=row28, layout=box_layout) box29 = Box(children=row29, layout=box_layout) box30 = Box(children=row30, layout=box_layout) box31 = Box(children=row31, layout=box_layout) box32 = Box(children=row32, layout=box_layout) box33 = Box(children=row33, layout=box_layout) box34 = Box(children=row34, layout=box_layout) box35 = Box(children=row35, layout=box_layout) box36 = Box(children=row36, layout=box_layout) box37 = Box(children=row37, layout=box_layout) self.tab = VBox([ box1, box2, box3, box4, box5, box6, box7, box8, box9, box10, box11, box12, box13, box14, box15, box16, box17, box18, box19, box20, box21, box22, box23, box24, box25, box26, box27, box28, box29, box30, box31, box32, box33, box34, box35, box36, box37, ])
def make_config(self): layout = Layout() style = {"description_width": "initial"} checkbox1 = Checkbox(description="Show Targets", value=self.net.config["show_targets"], layout=layout, style=style) checkbox1.observe(lambda change: self.set_attr( self.net.config, "show_targets", change["new"]), names='value') checkbox2 = Checkbox(description="Errors", value=self.net.config["show_errors"], layout=layout, style=style) checkbox2.observe(lambda change: self.set_attr( self.net.config, "show_errors", change["new"]), names='value') hspace = IntText(value=self.net.config["hspace"], description="Horizontal space between banks:", style=style, layout=layout) hspace.observe(lambda change: self.set_attr(self.net.config, "hspace", change["new"]), names='value') vspace = IntText(value=self.net.config["vspace"], description="Vertical space between layers:", style=style, layout=layout) vspace.observe(lambda change: self.set_attr(self.net.config, "vspace", change["new"]), names='value') self.feature_bank = Select( description="Features:", value="", options=[""] + [ layer.name for layer in self.net.layers if self.net._layer_has_features(layer.name) ], rows=1) self.feature_bank.observe(self.regenerate, names='value') self.control_select = Select(options=['Test', 'Train'], value='Train', description='Dataset:', rows=1) self.control_select.observe(self.update_control_slider, names='value') column1 = [ self.control_select, self.zoom_slider, hspace, vspace, HBox([checkbox1, checkbox2]), self.feature_bank, self.feature_columns, self.feature_scale ] ## Make layer selectable, and update-able: column2 = [] layer = self.net.layers[-1] self.layer_select = Select( description="Layer:", value=layer.name, options=[layer.name for layer in self.net.layers], rows=1) self.layer_select.observe(self.update_layer_selection, names='value') column2.append(self.layer_select) self.layer_visible_checkbox = Checkbox(description="Visible", value=layer.visible, layout=layout) self.layer_visible_checkbox.observe(self.update_layer, names='value') column2.append(self.layer_visible_checkbox) self.layer_colormap = Select( description="Colormap:", options=[""] + AVAILABLE_COLORMAPS, value=layer.colormap if layer.colormap is not None else "", layout=layout, rows=1) self.layer_colormap_image = HTML( value="""<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))) self.layer_colormap.observe(self.update_layer, names='value') column2.append(self.layer_colormap) column2.append(self.layer_colormap_image) self.layer_mindim = FloatText(description="Leftmost color maps to:", value=layer.minmax[0], style=style) self.layer_maxdim = FloatText(description="Rightmost color maps to:", value=layer.minmax[1], style=style) self.layer_mindim.observe(self.update_layer, names='value') self.layer_maxdim.observe(self.update_layer, names='value') column2.append(self.layer_mindim) column2.append(self.layer_maxdim) output_shape = layer.get_output_shape() self.layer_feature = IntText(value=layer.feature, description="Feature to show:", style=style) self.layer_feature.observe(self.update_layer, names='value') column2.append(self.layer_feature) config_children = HBox([ VBox(column1, layout=Layout(width="100%")), VBox(column2, layout=Layout(width="100%")) ]) accordion = Accordion(children=[config_children]) accordion.set_title(0, self.net.name) accordion.selected_index = None return accordion
def interact(self, ): def update_plot(*args): for b in togPlot: self.plots[b.description] = b.value self.init_figure() with self.output: clear_output(wait=True) self.plot(self.table.get_changed_df(), dofit=tb_plotfit.value, cole_omega_max=ft_cc.value, maxwell_omega_max=ft_mw.value, g0range=frs_g0fit.value, fitg0=tb_fitg0.value, defaultQ=ft_quality.value, gpmax=ft_gpmax.value) display(self.fig) # self.df = df def write_df(*args): df = self.table.get_changed_df() self.df.update(df) # self.table.df = self.df self.df['plot'] = False def save(*args): write_df() pickle.dump(self.df, open(t_save.value, 'wb')) def reset_plot(*args): df = self.table.get_changed_df() df['plot'] = False self.table.df = df def update_table(*args): self.table.df.update(self.table.get_changed_df()) self.interactive = True self.table = qgrid.show_grid(self.df, grid_options={ 'forceFitColumns': False, 'defaultColumnWidth': 70, }) box_layout = Layout(overflow_x='scroll', flex_flow='row', display='flex') btable = Box(children=[self.table], layout=box_layout) w = widgets.SelectMultiple( options=self.table.get_changed_df()['file'], value=[], # rows=10, description='Rheo Data Sets', disabled=False, layout=widgets.Layout(width='40%', height='160px'), style={'description_width': 'initial'}) items_layout = Layout(flex='1 1 auto', width='auto') box_layout = Layout(display='flex', flex_flow='row', width='75%') togPlot = [ widgets.ToggleButton(description=word, value=bool(value), layout=items_layout, button_style='info') for word, value in self.plots.items() ] plotl = Box(children=togPlot, layout=box_layout) b_plot = widgets.Button( description='plot', button_style='info', # 'success', 'info', 'warning', 'danger' or '' ) b_plot.on_click(update_plot) tb_plotfit = widgets.ToggleButton(description='plot fit', value=True, button_style='info') b_wpars = widgets.Button( description='write fit params', button_style='info', ) b_wpars.on_click(write_df) t_save = widgets.Text(value='RheoAnalysis.pkl', disabled=False) ft_quality = widgets.FloatText(value=1, min=0, max=1, step=0.2, description='Quality:', disabled=False, layout=Layout(width='15%')) b_save = widgets.Button( description='save', button_style='info', ) b_save.on_click(save) b_resetplot = widgets.Button( description='reset plot', button_style='info', ) b_resetplot.on_click(reset_plot) b_updatetable = widgets.Button( description='update', button_style='info', ) b_updatetable.on_click(update_table) # Widgets Maxwell Plot ft_mw = widgets.FloatText(value=6, description=r'MW: $\omega_{max}$', disabled=False, layout=Layout(width='15%')) # Widgets Cole-Cole Plot ft_cc = widgets.FloatText(value=50, description=r'CC: $\omega_{max}$', disabled=False, layout=Layout(width='15%')) ft_gpmax = widgets.FloatText(value=90, description=r"$G'_{max}$", disabled=False, layout=Layout(width='15%')) tb_fitg0 = widgets.ToggleButton(description=r'fit $G_0$', value=False, button_style='info') frs_g0fit = widgets.FloatRangeSlider( value=[6, 24], min=1, max=150, step=1, description=r'$\omega$ range:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.0f', ) # Widgets Flow Curve fls_fc_gpmin = widgets.FloatLogSlider( value=0.02, base=10, min=-2, # max exponent of base max=1, # min exponent of base step=0.2, # exponent step description=r'FC: GP min') fls_fc_gpmax = widgets.FloatLogSlider( value=0.2, base=10, min=-2, # max exponent of base max=1, # min exponent of base step=0.2, # exponent step description='GP max') fls_fc_etamin = widgets.FloatLogSlider( value=1e-3, base=10, min=-3, # max exponent of base max=1, # min exponent of base step=0.2, # exponent step description=r'FC: eta min') fls_fc_etamax = widgets.FloatLogSlider( value=100, base=10, min=-2, # max exponent of base max=2, # min exponent of base step=0.2, # exponent step description='eta max') self.cc_box = widgets.HBox([ft_cc, frs_g0fit, tb_fitg0, ft_gpmax]) self.mw_box = widgets.HBox([ft_mw, ft_quality]) self.fc_box = widgets.HBox( [fls_fc_gpmin, fls_fc_gpmax, fls_fc_etamin, fls_fc_etamax]) self.output = widgets.Output( layout=Layout(height='600px', width='800px', border='solid')) gui = widgets.VBox([ widgets.HBox([ b_plot, t_save, b_save, b_resetplot, tb_plotfit, b_wpars, ]), plotl, self.mw_box, self.cc_box, self.fc_box ]) main_window = widgets.VBox([btable, gui, self.output]) display(main_window)
def general(): """General settings. Args: None Returns: update_widget : A widget for general settings. Raises: Error: Example: """ # User settings user_info = Label("General settings.") values = config.read() user_name = Text(value=values['set']['user'], placeholder='user name', description='User:'******'set']['email'], placeholder='[email protected]', description='email:', disabled=False) user_institution = Text(value=values['set']['institution'], placeholder='EU-', description='Institution:', disabled=False) ms_list = data_options.eu_ms() ms = Dropdown( options=[(ms_list[m], m) for m in ms_list] + [('', '')], value=values['set']['member_state'], description='Member state:', disabled=False, ) wbox_user = VBox([user_info, user_name, user_email, user_institution, ms], layout=Layout(border='1px solid black')) # System settings sys_info = Label("System settings.") paths_info = Label("Select the personal data folder.") jupyterlab = Checkbox( value=eval(values['set']['jupyterlab']), description= 'Workin in Jupyter Lab (Uncheck for Voila and classical jupyter environment)', disabled=False, indent=False) def on_jupyterlab_change(change): config.set_value(['set', 'jupyterlab'], str(jupyterlab.value)) jupyterlab.observe(on_jupyterlab_change, 'value') path_data = Text(value=values['paths']['data'], description='Data path:') path_temp = Text(value=values['paths']['temp'], description='Temp path:', disabled=True) files_info = Label("Select where to store the parcel IDs list file from:") plimit_info = Label( "Warning: No more than 25 parcels are tested, unexpected results may occur." ) plimit = BoundedIntText(value=int(values['set']['plimit']), max=100_000_000, min=1, step=1, description='Max parcels that can be downloaded:', disabled=False) wbox_sys = VBox([ sys_info, jupyterlab, plimit_info, plimit, paths_info, path_data, path_temp, files_info ], layout=Layout(border='1px solid black')) btn_save = Button(description='Save', icon='save') progress = Output() def outlog(*text): with progress: print(*text) @btn_save.on_click def btn_save_on_click(b): progress.clear_output() config.set_value(['set', 'user'], str(user_name.value)) config.set_value(['set', 'email'], str(user_email.value)) config.set_value(['set', 'institution'], str(user_institution.value)) config.set_value(['set', 'member_state'], str(user_email.value)) config.set_value(['set', 'plimit'], str(plimit.value)) config.set_value(['paths', 'data'], str(path_data.value)) config.set_value(['paths', 'temp'], str(path_temp.value)) outlog("The new settings are saved.") wbox = VBox( [clean_temp(), wbox_user, wbox_sys, HBox([btn_save]), progress]) return wbox
def make_controls(self): button_begin = Button(icon="fast-backward", layout=Layout(width='100%')) button_prev = Button(icon="backward", layout=Layout(width='100%')) button_next = Button(icon="forward", layout=Layout(width='100%')) button_end = Button(icon="fast-forward", layout=Layout(width='100%')) #button_prop = Button(description="Propagate", layout=Layout(width='100%')) #button_train = Button(description="Train", layout=Layout(width='100%')) self.button_play = Button(icon="play", description="Play", layout=Layout(width="100%")) refresh_button = Button(icon="refresh", layout=Layout(width="25%")) self.position_text = IntText(value=0, layout=Layout(width="100%")) self.control_buttons = HBox( [ button_begin, button_prev, #button_train, self.position_text, button_next, button_end, self.button_play, refresh_button ], layout=Layout(width='100%', height="50px")) length = (len(self.dataset.train_inputs) - 1) if len(self.dataset.train_inputs) > 0 else 0 self.control_slider = IntSlider(description="Dataset index", continuous_update=False, min=0, max=max(length, 0), value=0, layout=Layout(width='100%')) self.total_text = Label(value="of 0", layout=Layout(width="100px")) self.zoom_slider = FloatSlider(description="Zoom", continuous_update=False, min=.5, max=3, value=self.net.config["svg_height"] / 780.0) ## Hook them up: button_begin.on_click(lambda button: self.goto("begin")) button_end.on_click(lambda button: self.goto("end")) button_next.on_click(lambda button: self.goto("next")) button_prev.on_click(lambda button: self.goto("prev")) self.button_play.on_click(self.toggle_play) self.control_slider.observe(self.update_slider_control, names='value') refresh_button.on_click(lambda widget: (self.update_control_slider( ), self.output.clear_output(), self.regenerate())) self.zoom_slider.observe(self.update_zoom_slider, names='value') self.position_text.observe(self.update_position_text, names='value') # Put them together: controls = VBox([ HBox([self.control_slider, self.total_text], layout=Layout(height="40px")), self.control_buttons ], layout=Layout(width='100%')) #net_page = VBox([control, self.net_svg], layout=Layout(width='95%')) controls.on_displayed(lambda widget: self.regenerate()) return controls
def __init__(self, *args, **kwargs): self.progress_callback = self.set_progress super().__init__(progress_callback=self.progress_callback, *args, **kwargs) fc = FileChooser() fc.show_only_dirs = True fc.default_path = tempfile.gettempdir() self.ms_storage_path = fc self.ms_upload = FileUpload() self.peaklist_files_button = FileUpload(description='Peaklists', accept='csv,xlsx', multiple=False) self.peaklist_files_button.observe(self.load_peaklist, names='value') self.load_ms_button = Button(description='Load MS-files') self.load_ms_button.on_click(self.search_files) self.detect_peaks_button = Button(description="Detect Peaks") self.detect_peaks_button.on_click(self.detect_peaks) self.message_box = Textarea( value='', placeholder='Please select some files and click on Run.', description='', disabled=True, layout={ 'width': '90%', 'height': '500px', 'font_family': 'monospace' }) self.run_button = Button(description="Run") self.run_button.on_click(self.run) self.run_button.style.button_color = 'lightgray' self.optimize_rt_button = Button(description="Find closest peaks") self.optimize_rt_button.on_click(self.action_optimize_rt) self.download_button = Button(description="Export") self.download_button.on_click(self.export_action) self.download_button.style.button_color = 'lightgray' self.progress_bar = Progress(min=0, max=100, layout=Layout(width='90%'), description='Progress:', bar_style='info') self.output = widgets.Output() tabs = Tab() tabs.children = [ HBox([self.ms_storage_path, self.ms_upload, self.load_ms_button]), HBox([ self.peaklist_files_button, self.detect_peaks_button, self.optimize_rt_button ]), ] tabs.set_title(0, 'MS-Files') tabs.set_title(1, 'Peaklists') self.layout = VBox([ tabs, self.message_box, HBox([self.run_button, self.download_button]), self.progress_bar ])
class jobMaintenance: ##Debug assistance debug = widgets.Output(style={'description_width': '120px'}, layout=Layout(width='90%')) def __init__(self, header, jobNumberField, buildJobFunc, buildNewJobsFunc, buildArgumentsListFunc, updateScreenFieldsFunc, callProgramFunc, program): self.existingJobs = [] self.jobCounter = 1 self.jobNumber = jobNumberField self.program = program #the buildJob function as implemented by the consuming class self.buildJob = buildJobFunc #the buildNewJobs function as implemented by the consuming class self.buildNewJobs = buildNewJobsFunc #the buildArgumentsList function as implemented by the consuming class self.buildArgumentsList = buildArgumentsListFunc #the updateScreenFields function as implemented by the consuming class self.updateScreenFields = updateScreenFieldsFunc #the callProgram function as implemented by the consuming class self.callProgram = callProgramFunc self.jobsList = widgets.SelectMultiple( description='Jobs: ', options=header, disabled=False, style={'description_width': 'initial'}, rows=10, layout=Layout(width='90%')) self.addButton = widgets.Button(description='Add', disabled=False, button_style='', tooltip='Add job') self.deleteButton = widgets.Button(description='Delete', disabled=False, button_style='', tooltip='Delete job(s)') self.selectButton = widgets.Button(description='Select', disabled=False, button_style='', tooltip='Select job for editing.') self.updateButton = widgets.Button(description='Update', disabled=False, button_style='', tooltip='Update job.') self.runAllButton = widgets.Button(description='Run All', disabled=False, button_style='', tooltip='Run all jobs') self.runProgress = widgets.IntProgress(value=0, min=0, max=10, step=1, description='Progress:', bar_style='', orientation='horizontal') # addJob() - builds the new job from the input variables and updates the job list. # @debug.capture(clear_output=True) def addJob(self, target): listedJobs = self.jobsList.options listedJobsList = list(listedJobs) newJob = self.buildJob(self.jobCounter) #converting to tuple, update jobsList, jobNumber newJobTuple = (newJob, ) listedJobsList.extend(newJobTuple) self.jobsList.options = listedJobsList self.jobCounter = self.jobCounter + 1 self.jobNumber.value = '' # deleteJob() - delete selected jobs from the job list. # @debug.capture(clear_output=True) def deleteJob(self, target): #obtain the listedJobs listedJobs = self.jobsList.options listedJobsList = list(listedJobs) #obtain the selectedJobs selectedJobs = self.jobsList.value selectedJobsList = list(selectedJobs) #remove selected jobs for i in range(len(selectedJobsList)): if (str(selectedJobsList[i]).startswith('Job#') == False): listedJobsList.remove(selectedJobsList[i]) #update self.jobsList.options = listedJobsList self.jobNumber.value = '' # selectJob() - update field values using the selected job in the job list # @debug.capture(clear_output=True) def selectJob(self, target): #obtain the selectedJobs selectedJobs = self.jobsList.value selectedJobsList = list(selectedJobs) #can only select a single job for updating. if len(selectedJobsList) == 1: self.updateScreenFields(selectedJobsList[0]) # updateJob() - update the job for the displayed job number # @debug.capture(clear_output=True) def updateJob(self, target): #obtain the listedJobs listedJobs = self.jobsList.options listedJobsList = list(listedJobs) #build updated job updatedJob = self.buildJob() updateJobNo = updatedJob['jobNumber'] for i in range(len(listedJobsList)): #skip checking the header if (str(listedJobsList[i]).startswith('Job#') == False): listedJobNo = listedJobsList[i]["jobNumber"] if listedJobNo == updateJobNo: listedJobsList[i] = updatedJob #update screen field self.jobsList.options = listedJobsList self.jobNumber.value = '' # runAllJobs() - execute all jobs in the list. # target - not used, exists to make to make the button call work. # @debug.capture(clear_output=True) def runAllJobs(self, target): #obtain the listedJobs listedJobs = self.jobsList.options listedJobsList = list(listedJobs) self.runProgress.max = len(listedJobsList) #Run each job, but not the Header row. for i in range(len(listedJobsList)): #setting progress bar to show job has started running. if (str(listedJobsList[i]).startswith('Job#') == True): self.runProgress.value = i + 1 if (str(listedJobsList[i]).startswith('Job#') == False): self.callProgram( self.program, self.buildArgumentsList(jobToProcess=listedJobsList[i]), listedJobsList[i]['outMrc']) self.runProgress.value = i + 1 # addJobs() - Adds multiple jobs, when the user has specified a range of values. # Arguments: # fieldName - name of the field that value range has been specified # values - specified values, ';' separated. # @debug.capture(clear_output=True) def addJobs(self, fieldName, values): #obtaining currently listed jobs listedJobs = self.jobsList.options listedJobsList = list(listedJobs) newJobs = self.buildNewJobs(fieldName, values) for i in range(len(newJobs)): #converting to tuple newJobTuple = (newJobs[i], ) listedJobsList.extend(newJobTuple) #Update jobsList and jobNumber self.jobsList.options = listedJobsList self.jobNumber.value = '' # buildJobWidgets() # def buildJobWidgets(self): #Add fuctions to buttons. self.addButton.on_click(self.addJob) self.deleteButton.on_click(self.deleteJob) self.selectButton.on_click(self.selectJob) self.updateButton.on_click(self.updateJob) self.runAllButton.on_click(self.runAllJobs) buttons = HBox([ self.addButton, self.deleteButton, self.selectButton, self.updateButton, self.runAllButton, self.runProgress ]) return VBox([self.debug, self.jobsList, buttons])
def __init__(self): micron_units = Label('micron') # use "option m" (Mac, for micro symbol) constWidth = '180px' tab_height = '500px' stepsize = 10 #style = {'description_width': '250px'} style = {'description_width': '25%'} layout = {'width': '400px'} name_button_layout={'width':'25%'} widget_layout = {'width': '15%'} units_button_layout ={'width':'15%'} desc_button_layout={'width':'45%'} param_name1 = Button(description='random_seed', disabled=True, layout=name_button_layout) param_name1.style.button_color = 'lightgreen' self.random_seed = IntText( value=0, step=1, style=style, layout=widget_layout) param_name2 = Button(description='immune_activation_time', disabled=True, layout=name_button_layout) param_name2.style.button_color = 'tan' self.immune_activation_time = FloatText( value=20160, step=1000, style=style, layout=widget_layout) param_name3 = Button(description='save_interval_after_therapy_start', disabled=True, layout=name_button_layout) param_name3.style.button_color = 'lightgreen' self.save_interval_after_therapy_start = FloatText( value=3.0, step=0.1, style=style, layout=widget_layout) param_name4 = Button(description='immune_o2_relative_uptake', disabled=True, layout=name_button_layout) param_name4.style.button_color = 'tan' self.immune_o2_relative_uptake = FloatText( value=0.1, step=0.01, style=style, layout=widget_layout) param_name5 = Button(description='immune_apoptosis_rate', disabled=True, layout=name_button_layout) param_name5.style.button_color = 'lightgreen' self.immune_apoptosis_rate = FloatText( value=6.944e-5, step=1e-05, style=style, layout=widget_layout) param_name6 = Button(description='immune_motility_persistence_time', disabled=True, layout=name_button_layout) param_name6.style.button_color = 'tan' self.immune_motility_persistence_time = FloatText( value=10, step=1, style=style, layout=widget_layout) param_name7 = Button(description='immune_migration_speed', disabled=True, layout=name_button_layout) param_name7.style.button_color = 'lightgreen' self.immune_migration_speed = FloatText( value=1.0, step=0.1, style=style, layout=widget_layout) param_name8 = Button(description='immune_migration_bias', disabled=True, layout=name_button_layout) param_name8.style.button_color = 'tan' self.immune_migration_bias = FloatText( value=0.5, step=0.1, style=style, layout=widget_layout) param_name9 = Button(description='immune_relative_adhesion', disabled=True, layout=name_button_layout) param_name9.style.button_color = 'lightgreen' self.immune_relative_adhesion = FloatText( value=0, step=0.01, style=style, layout=widget_layout) param_name10 = Button(description='immune_relative_repulsion', disabled=True, layout=name_button_layout) param_name10.style.button_color = 'tan' self.immune_relative_repulsion = FloatText( value=5, step=0.1, style=style, layout=widget_layout) param_name11 = Button(description='immune_kill_rate', disabled=True, layout=name_button_layout) param_name11.style.button_color = 'lightgreen' self.immune_kill_rate = FloatText( value=0.06667, step=0.01, style=style, layout=widget_layout) param_name12 = Button(description='immune_attachment_lifetime', disabled=True, layout=name_button_layout) param_name12.style.button_color = 'tan' self.immune_attachment_lifetime = FloatText( value=60.0, step=1, style=style, layout=widget_layout) param_name13 = Button(description='immune_attachment_rate', disabled=True, layout=name_button_layout) param_name13.style.button_color = 'lightgreen' self.immune_attachment_rate = FloatText( value=0.2, step=0.01, style=style, layout=widget_layout) param_name14 = Button(description='elastic_coefficient', disabled=True, layout=name_button_layout) param_name14.style.button_color = 'tan' self.elastic_coefficient = FloatText( value=0.01, step=0.001, style=style, layout=widget_layout) param_name15 = Button(description='number_of_immune_cells', disabled=True, layout=name_button_layout) param_name15.style.button_color = 'lightgreen' self.number_of_immune_cells = IntText( value=7500, step=100, style=style, layout=widget_layout) param_name16 = Button(description='initial_min_immune_distance_from_tumor', disabled=True, layout=name_button_layout) param_name16.style.button_color = 'tan' self.initial_min_immune_distance_from_tumor = FloatText( value=30, step=1, style=style, layout=widget_layout) param_name17 = Button(description='thickness_of_immune_seeding_region', disabled=True, layout=name_button_layout) param_name17.style.button_color = 'lightgreen' self.thickness_of_immune_seeding_region = FloatText( value=75, step=1, style=style, layout=widget_layout) param_name18 = Button(description='tumor_radius', disabled=True, layout=name_button_layout) param_name18.style.button_color = 'tan' self.tumor_radius = FloatText( value=250, step=10, style=style, layout=widget_layout) param_name19 = Button(description='tumor_mean_immunogenicity', disabled=True, layout=name_button_layout) param_name19.style.button_color = 'lightgreen' self.tumor_mean_immunogenicity = FloatText( value=1.0, step=0.1, style=style, layout=widget_layout) param_name20 = Button(description='tumor_immunogenicity_standard_deviation', disabled=True, layout=name_button_layout) param_name20.style.button_color = 'tan' self.tumor_immunogenicity_standard_deviation = FloatText( value=0.25, step=0.01, style=style, layout=widget_layout) param_name21 = Button(description='oncoprotein_saturation', disabled=True, layout=name_button_layout) param_name21.style.button_color = 'lightgreen' self.oncoprotein_saturation = FloatText( value=2.0, step=0.1, style=style, layout=widget_layout) param_name22 = Button(description='oncoprotein_threshold', disabled=True, layout=name_button_layout) param_name22.style.button_color = 'tan' self.oncoprotein_threshold = FloatText( value=0.5, step=0.1, style=style, layout=widget_layout) param_name23 = Button(description='max_attachment_distance', disabled=True, layout=name_button_layout) param_name23.style.button_color = 'lightgreen' self.max_attachment_distance = FloatText( value=18.0, step=1, style=style, layout=widget_layout) param_name24 = Button(description='min_attachment_distance', disabled=True, layout=name_button_layout) param_name24.style.button_color = 'tan' self.min_attachment_distance = FloatText( value=14.0, step=1, style=style, layout=widget_layout) units_button1 = Button(description='', disabled=True, layout=units_button_layout) units_button1.style.button_color = 'lightgreen' units_button2 = Button(description='min', disabled=True, layout=units_button_layout) units_button2.style.button_color = 'tan' units_button3 = Button(description='min', disabled=True, layout=units_button_layout) units_button3.style.button_color = 'lightgreen' units_button4 = Button(description='', disabled=True, layout=units_button_layout) units_button4.style.button_color = 'tan' units_button5 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button5.style.button_color = 'lightgreen' units_button6 = Button(description='min', disabled=True, layout=units_button_layout) units_button6.style.button_color = 'tan' units_button7 = Button(description='micron/min', disabled=True, layout=units_button_layout) units_button7.style.button_color = 'lightgreen' units_button8 = Button(description='min', disabled=True, layout=units_button_layout) units_button8.style.button_color = 'tan' units_button9 = Button(description='', disabled=True, layout=units_button_layout) units_button9.style.button_color = 'lightgreen' units_button10 = Button(description='', disabled=True, layout=units_button_layout) units_button10.style.button_color = 'tan' units_button11 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button11.style.button_color = 'lightgreen' units_button12 = Button(description='min', disabled=True, layout=units_button_layout) units_button12.style.button_color = 'tan' units_button13 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button13.style.button_color = 'lightgreen' units_button14 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button14.style.button_color = 'tan' units_button15 = Button(description='', disabled=True, layout=units_button_layout) units_button15.style.button_color = 'lightgreen' units_button16 = Button(description='micron', disabled=True, layout=units_button_layout) units_button16.style.button_color = 'tan' units_button17 = Button(description='micron', disabled=True, layout=units_button_layout) units_button17.style.button_color = 'lightgreen' units_button18 = Button(description='micron', disabled=True, layout=units_button_layout) units_button18.style.button_color = 'tan' units_button19 = Button(description='', disabled=True, layout=units_button_layout) units_button19.style.button_color = 'lightgreen' units_button20 = Button(description='', disabled=True, layout=units_button_layout) units_button20.style.button_color = 'tan' units_button21 = Button(description='', disabled=True, layout=units_button_layout) units_button21.style.button_color = 'lightgreen' units_button22 = Button(description='', disabled=True, layout=units_button_layout) units_button22.style.button_color = 'tan' units_button23 = Button(description='micron', disabled=True, layout=units_button_layout) units_button23.style.button_color = 'lightgreen' units_button24 = Button(description='micron', disabled=True, layout=units_button_layout) units_button24.style.button_color = 'tan' desc_button1 = Button(description='', disabled=True, layout=desc_button_layout) desc_button1.style.button_color = 'lightgreen' desc_button2 = Button(description='', disabled=True, layout=desc_button_layout) desc_button2.style.button_color = 'tan' desc_button3 = Button(description='', disabled=True, layout=desc_button_layout) desc_button3.style.button_color = 'lightgreen' desc_button4 = Button(description='', disabled=True, layout=desc_button_layout) desc_button4.style.button_color = 'tan' desc_button5 = Button(description='', disabled=True, layout=desc_button_layout) desc_button5.style.button_color = 'lightgreen' desc_button6 = Button(description='', disabled=True, layout=desc_button_layout) desc_button6.style.button_color = 'tan' desc_button7 = Button(description='', disabled=True, layout=desc_button_layout) desc_button7.style.button_color = 'lightgreen' desc_button8 = Button(description='', disabled=True, layout=desc_button_layout) desc_button8.style.button_color = 'tan' desc_button9 = Button(description='', disabled=True, layout=desc_button_layout) desc_button9.style.button_color = 'lightgreen' desc_button10 = Button(description='', disabled=True, layout=desc_button_layout) desc_button10.style.button_color = 'tan' desc_button11 = Button(description='', disabled=True, layout=desc_button_layout) desc_button11.style.button_color = 'lightgreen' desc_button12 = Button(description='', disabled=True, layout=desc_button_layout) desc_button12.style.button_color = 'tan' desc_button13 = Button(description='', disabled=True, layout=desc_button_layout) desc_button13.style.button_color = 'lightgreen' desc_button14 = Button(description='', disabled=True, layout=desc_button_layout) desc_button14.style.button_color = 'tan' desc_button15 = Button(description='', disabled=True, layout=desc_button_layout) desc_button15.style.button_color = 'lightgreen' desc_button16 = Button(description='', disabled=True, layout=desc_button_layout) desc_button16.style.button_color = 'tan' desc_button17 = Button(description='', disabled=True, layout=desc_button_layout) desc_button17.style.button_color = 'lightgreen' desc_button18 = Button(description='', disabled=True, layout=desc_button_layout) desc_button18.style.button_color = 'tan' desc_button19 = Button(description='', disabled=True, layout=desc_button_layout) desc_button19.style.button_color = 'lightgreen' desc_button20 = Button(description='', disabled=True, layout=desc_button_layout) desc_button20.style.button_color = 'tan' desc_button21 = Button(description='', disabled=True, layout=desc_button_layout) desc_button21.style.button_color = 'lightgreen' desc_button22 = Button(description='', disabled=True, layout=desc_button_layout) desc_button22.style.button_color = 'tan' desc_button23 = Button(description='', disabled=True, layout=desc_button_layout) desc_button23.style.button_color = 'lightgreen' desc_button24 = Button(description='', disabled=True, layout=desc_button_layout) desc_button24.style.button_color = 'tan' row1 = [param_name1, self.random_seed, units_button1, desc_button1] row2 = [param_name2, self.immune_activation_time, units_button2, desc_button2] row3 = [param_name3, self.save_interval_after_therapy_start, units_button3, desc_button3] row4 = [param_name4, self.immune_o2_relative_uptake, units_button4, desc_button4] row5 = [param_name5, self.immune_apoptosis_rate, units_button5, desc_button5] row6 = [param_name6, self.immune_motility_persistence_time, units_button6, desc_button6] row7 = [param_name7, self.immune_migration_speed, units_button7, desc_button7] row8 = [param_name8, self.immune_migration_bias, units_button8, desc_button8] row9 = [param_name9, self.immune_relative_adhesion, units_button9, desc_button9] row10 = [param_name10, self.immune_relative_repulsion, units_button10, desc_button10] row11 = [param_name11, self.immune_kill_rate, units_button11, desc_button11] row12 = [param_name12, self.immune_attachment_lifetime, units_button12, desc_button12] row13 = [param_name13, self.immune_attachment_rate, units_button13, desc_button13] row14 = [param_name14, self.elastic_coefficient, units_button14, desc_button14] row15 = [param_name15, self.number_of_immune_cells, units_button15, desc_button15] row16 = [param_name16, self.initial_min_immune_distance_from_tumor, units_button16, desc_button16] row17 = [param_name17, self.thickness_of_immune_seeding_region, units_button17, desc_button17] row18 = [param_name18, self.tumor_radius, units_button18, desc_button18] row19 = [param_name19, self.tumor_mean_immunogenicity, units_button19, desc_button19] row20 = [param_name20, self.tumor_immunogenicity_standard_deviation, units_button20, desc_button20] row21 = [param_name21, self.oncoprotein_saturation, units_button21, desc_button21] row22 = [param_name22, self.oncoprotein_threshold, units_button22, desc_button22] row23 = [param_name23, self.max_attachment_distance, units_button23, desc_button23] row24 = [param_name24, self.min_attachment_distance, units_button24, desc_button24] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') box1 = Box(children=row1, layout=box_layout) box2 = Box(children=row2, layout=box_layout) box3 = Box(children=row3, layout=box_layout) box4 = Box(children=row4, layout=box_layout) box5 = Box(children=row5, layout=box_layout) box6 = Box(children=row6, layout=box_layout) box7 = Box(children=row7, layout=box_layout) box8 = Box(children=row8, layout=box_layout) box9 = Box(children=row9, layout=box_layout) box10 = Box(children=row10, layout=box_layout) box11 = Box(children=row11, layout=box_layout) box12 = Box(children=row12, layout=box_layout) box13 = Box(children=row13, layout=box_layout) box14 = Box(children=row14, layout=box_layout) box15 = Box(children=row15, layout=box_layout) box16 = Box(children=row16, layout=box_layout) box17 = Box(children=row17, layout=box_layout) box18 = Box(children=row18, layout=box_layout) box19 = Box(children=row19, layout=box_layout) box20 = Box(children=row20, layout=box_layout) box21 = Box(children=row21, layout=box_layout) box22 = Box(children=row22, layout=box_layout) box23 = Box(children=row23, layout=box_layout) box24 = Box(children=row24, layout=box_layout) self.tab = VBox([ box1, box2, box3, box4, box5, box6, box7, box8, box9, box10, box11, box12, box13, box14, box15, box16, box17, box18, box19, box20, box21, box22, box23, box24, ])
def _create_result_tabs( self, res: Dict[str, NamedRelationalAlgebraFrozenSet], callbacks: Dict[str, Callable] = None, ): """Creates necessary tab pages and viewers for the specified query result `res`. Parameters ---------- res: Dict[str, NamedRelationalAlgebraFrozenSet] dictionary of query results with keys as result name and values as result for corresponding key. callbacks : Dict[str, Callable], optional dict of callback functions to display outputs in result tabs, by default None Returns ------- result_tabs: list list of tab pages to be added to tab as children. titles: list list of titles for tab pages. icons: list list of icons for tab pages. viewers: set set of viewers for all tab pages. """ result_tabs = [] titles = [] icons = [] # to be passed to each tab page to use viewers from the same factory viewer_factory = ViewerFactory() # set of all viewers for each result_tab viewers = set() def icon_changed(change): icons = [] for result_tab in result_tabs: icons.append(result_tab.icon) self._tab.title_icons = icons for name in sorted(res.keys()): result_set = res[name] result_tab = ResultTabPageWidget(name, result_set, viewer_factory, layout=Layout(height="100%")) result_tabs.append(result_tab) titles.append(name) icons.append(result_tab.icon) result_tab.observe(icon_changed, names="icon") viewers = viewers | result_tab.get_viewers() if callbacks is not None: for name, callback in callbacks.items(): output_tab = GraphOutputWidget(name, res, callback) result_tabs.append(output_tab) titles.append(name) icons.append(output_tab.icon) return result_tabs, titles, icons, viewers
def __init__(self, start, next_frame, L=8): self.next_frame = next_frame self.L = L width = int(50 * 8 / L) wide = str(7 * width + 24) + 'px' wider = str(L * width + (L - 1) * 4) + 'px' width = str(width) + 'px' height = width width = str(int(50 * 8 / L)) + 'px' layout = Layout(width=width, height=height) screen = {} for x in range(L): for y in range(L): screen[x, y] = widgets.ToggleButton(description='', button_style='', layout=layout, disabled=True) screen['text'] = widgets.ToggleButton(description='', button_style='', layout=Layout(width=wider, height=height), disabled=True) controller = {} controller['blank'] = widgets.ToggleButton(description='', button_style='', layout=layout) controller['up'] = widgets.ToggleButton(description='▲', button_style='', layout=layout) controller['down'] = widgets.ToggleButton(description='▼', button_style='', layout=layout) controller['left'] = widgets.ToggleButton(description='◀︎', button_style='', layout=layout) controller['right'] = widgets.ToggleButton(description='►', button_style='', layout=layout) controller['A'] = widgets.ToggleButton(description='A', button_style='', layout=layout) controller['B'] = widgets.ToggleButton(description='B', button_style='', layout=layout) controller['X'] = widgets.ToggleButton(description='X', button_style='', layout=layout) controller['Y'] = widgets.ToggleButton(description='Y', button_style='', layout=layout) controller['next'] = widgets.ToggleButton(description='Next', button_style='', layout=Layout(width=wide, height=height)) [b, u, d, l, r, A, B, X, Y, c] = [ controller['blank'], controller['up'], controller['down'], controller['left'], controller['right'], controller['A'], controller['B'], controller['X'], controller['Y'], controller['next'] ] interface = [] interface.append( widgets.HBox([screen[x, 0] for x in range(L)] + [b, u, b, b, b, X, b])) interface.append( widgets.HBox([screen[x, 1] for x in range(L)] + [l, b, r, b, Y, b, A])) interface.append( widgets.HBox([screen[x, 2] for x in range(L)] + [b, d, b, b, b, B, b])) interface.append(widgets.HBox([screen[x, 3] for x in range(L)] + [c])) for y in range(4, L): interface.append(widgets.HBox([screen[x, y] for x in range(L)])) interface.append(screen['text']) self.screen = screen self.controller = controller start(self) display(widgets.VBox(interface)) b.observe(self.given_blank) for button in self.controller: if button != 'blank': self.controller[button].observe(self.given_button)
def __init__(self, nb_rows, limit=50, *args, **kwargs): """ Parameters ---------- nb_rows: int total number of rows in the result set. limit: int number of rows to display in a page. """ super().__init__(*args, **kwargs) self.__nb_rows = nb_rows if nb_rows else 1 self.page = 1 self.limit = (limit if limit and limit > 0 and limit < PaginationWidget.MAX_LIMIT else PaginationWidget.DEFAULT_LIMIT) self.layout.width = "400px" if nb_rows <= limit: self.layout.visibility = "hidden" else: self.layout.visibility = "visible" nb_pages = self._get_nb_pages(self.limit) # widget to set page number self.__page_widget = BoundedIntText( value=self.page, min=1, max=nb_pages, step=1, continuous_update=True, description="page", description_tooltip="Current page", disabled=False, style={"description_width": "30px"}, layout=Layout(width="90px", max_width="90px"), ) # widget to display total number of pages. self.__label_slash = Label(value=f"/ {nb_pages}", layout=Layout(width="60px")) # widget to set limit self.__limit_widget = BoundedIntText( value=self.limit, min=1, max=PaginationWidget.MAX_LIMIT, step=1, continuous_update=True, description="rows", description_tooltip= f"Number of rows per page. Max. possible: {PaginationWidget.MAX_LIMIT}", disabled=False, style={"description_width": "30px"}, layout=Layout(width="90px", max_width="90px"), ) self.__page_widget.observe(self._page_widget_changed, names="value") self.__limit_widget.observe(self._limit_widget_changed, names="value") self.children = [ self.__page_widget, self.__label_slash, self.__limit_widget, ]
def run_widget(): roll = widgets.ToggleButtons( options=['Keep All', 'Drop Lowest Roll'], description='Roll Modifications:', style={'description_width': 'initial'}, disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['', ''], ) drop_roll = widgets.IntSlider( value=1, min=0, max=3, step=1, description='If Dropping Rolls, How Many?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) stat = widgets.ToggleButtons( options=['Keep All', 'Drop Lowest Stat', 'Replace Lowest Stat'], description='Roll Modifications:', style={'description_width': 'initial'}, disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['', ''], ) drop_stat = widgets.IntSlider( value=1, min=0, max=3, step=1, description='If Dropping Stats, How Many?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) replace_stat = widgets.IntSlider( value=18, min=1, max=20, step=1, description='If Replacing Lowest Stat, With What?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) n = widgets.Textarea(value='3', placeholder='Type something', description='Number of each Dice', disabled=False, style={'description_width': 'initial'}, layout=Layout(width='50%', height='100px')) s = widgets.Textarea(value='1,2,3,4,5,6', placeholder='Type something', description='Sides of each Dice ', disabled=False, style={ 'description_width': 'initial', 'width': '10%' }, layout=Layout(width='50%', height='100px')) name = widgets.Text(value='Roll 3d6', placeholder='Type something', description='Title of Policy ', disabled=False, style={ 'description_width': 'initial', 'width': '10%' }, layout=Layout(width='50%')) interact_manual(runRoller, n=n, s=s, roll=roll, drop_roll=drop_roll, stat=stat, drop_stat=drop_stat, replace_stat=replace_stat, name=name)
def upload_shp(path_data): # Upload l_up = Label("a. Upload .shp to the server.") accept_files = ".shp, .cpg, .dbf, .prj, .shx, .sbn, .sbx, .xml" shp_dist_folder = Text(value=f"{path_data}vector", placeholder='tmp/', description='Folder:', disabled=False) shp_select = FileUpload( description='Select files:', icon='plus', accept=accept_files, multiple=True # True to accept multiple files upload else False ) shp_clear = Button(value=False, disabled=False, button_style='info', tooltip='Clear selections.', icon='broom', layout=Layout(width='40px')) shp_upload = Button(value=False, disabled=False, button_style='info', tooltip='Upload foi reference data (.shp).', icon='fa-upload', layout=Layout(width='40px')) progress = Output() def outlog(*text): with progress: print(*text) @shp_clear.on_click def shp_clear_on_click(b): shp_select.value.clear() shp_select._counter = 0 @shp_upload.on_click def shp_upload_on_click(b): progress.clear_output() os.makedirs(shp_dist_folder.value, exist_ok=True) for key in shp_select.value: content = shp_select.value[key]['content'] with open(f'{shp_dist_folder.value}/{key}', 'wb') as f: f.write(content) outlog("All files are uploaded.") shp_select.value.clear() shp_select._counter = 0 shp_box = HBox([shp_dist_folder, shp_select, shp_clear, shp_upload]) # Import the .shp to the database l_imp = Label("""b. Import uploaded .shp to the database. Add a short name, max 15 characters for the parcels table e.g.:escat2020.""") imp_select = Dropdown(options=[ s for s in glob.glob(f'{shp_dist_folder.value}/*') if '.shp' in s ], description='Select .shp:', disabled=False) imp_refresh = Button(layout=Layout(width='35px'), icon='fa-refresh') imp_proc = Button( description='Import .shp file', value=False, disabled=False, button_style='info', tooltip='Run', icon='fa-database', ) imp_truncate = Checkbox(value=False, description='Remove old entries', disabled=False) try: with open(f"{config.get_value(['paths','temp'])}tb_prefix", 'r') as f: name_from_prfix = f.read() except Exception: name_from_prfix = None imp_tb_name = Text(value=name_from_prfix, placeholder='ms2010', description='Table name:', tooltip='A short name max 10 char.', disabled=False) def on_imp_tb_name(change): with open(f"{config.get_value(['paths','temp'])}tb_prefix", 'w+') as f: f.write(imp_tb_name.value) imp_tb_name.observe(on_imp_tb_name, 'value') @imp_proc.on_click def imp_proc_on_click(b): if imp_tb_name is not None: import subprocess progress.clear_output() # tb_name = imp_select.value.split('/')[-1].split('.')[0] tb_name = imp_tb_name.value.replace(' ', '').lower()[:15] outlog("Importing .shp to database...") command = [ 'ogr2ogr', '-f', 'PostgreSQL', 'PG:' + database.conn_str(), '-nln', tb_name, '-nlt', 'PROMOTE_TO_MULTI', '-nlt', 'GEOMETRY', imp_select.value ] if imp_truncate.value is True: command.extend(['--config', 'OGR_TRUNCATE', 'YES']) if subprocess.call(command) == 0: progress.clear_output() outlog( f"Completed. Total number of rows in table '{tb_name}':", database.exact_count(tb_name)) else: outlog("Could not import shp file.") else: outlog( "Please add a name for the parcels table (MAX 15 char e.g.: escat2020)." ) @imp_refresh.on_click def imp_refresh_on_click(b): imp_select.options = [ s for s in glob.glob(f'{shp_dist_folder.value}/*') if '.shp' in s ] imp_box = HBox( [imp_tb_name, imp_select, imp_refresh, imp_proc, imp_truncate]) return VBox([l_up, shp_box, l_imp, imp_box, progress])
def __init__(self, player): self.widget = ipywidgets.HTML( value="", placeholder='', description='', ) output = ipywidgets.Output() self.player = player def fast_backward_clicked(b): with output: self.player.begin() self.player.pause() def backward_clicked(b): with output: self.player.backward() def step_backward_clicked(b): with output: self.player.pause() self.player.step_backward() def pause_clicked(b): with output: self.player.pause() def step_forward_clicked(b): with output: self.player.pause() self.player.step_forward() def play_clicked(b): with output: self.player.play() def fast_forward_clicked(b): with output: self.player.pause() self.player.end() # self.slider_time=ipywidgets.IntSlider( # value=0, # min=0, # max=len(self.player.history), # step=1, # description="time:" # ) slider = ipywidgets.FloatSlider(value=1.0, min=0.0, max=6.0, step=1, description="Speed:") # 2puissance speed affiché ou alors nous affiché juste la valeur et pas "speed " 2** = puissance def on_value_change(change): value = int(change['new']) self.player.set_fps(2**value) slider.observe(on_value_change, names='value') play = ipywidgets.Button(description="", icon='fa-play', layout=Layout(width='35px')) fast_backward = ipywidgets.Button(description="", icon='fa-fast-backward', layout=Layout(width='35px')) backward = ipywidgets.Button(description="", icon='fa-backward', layout=Layout(width='35px')) step_backward = ipywidgets.Button(description="", icon='fa-step-backward', layout=Layout(width='35px')) pause = ipywidgets.Button(description="", icon='fa-pause', layout=Layout(width='35px')) step_forward = ipywidgets.Button(description="", icon='fa-step-forward', layout=Layout(width='35px')) fast_forward = ipywidgets.Button(description="", icon='fa-fast-forward', layout=Layout(width='35px')) play.on_click(play_clicked) fast_backward.on_click(fast_backward_clicked) backward.on_click(backward_clicked) step_backward.on_click(step_backward_clicked) pause.on_click(pause_clicked) step_forward.on_click(step_forward_clicked) fast_forward.on_click(fast_forward_clicked) self.affichage = ipywidgets.HBox([ fast_backward, backward, step_backward, pause, step_forward, play, fast_forward, slider ]) VBox.__init__( self, [self.player.view, self.player.slider_time, self.affichage]) #link((self.slider_time,'value'),(self.player,'time')) #self.widget_affichage=VBox([self.player.view,self.slider_time,self.affichage]) #self.player.time=0 self.player = player
def _init_widget(self): state = self._state widget = dict() fig = dict(x=self._create_slice_fig(), y=self._create_slice_fig(), z=self._create_slice_fig()) widget['fig'] = fig topomap_fig = dict(mag=create_topomap_fig(), grad=create_topomap_fig(), eeg=create_topomap_fig()) widget['topomap_fig'] = topomap_fig label = dict() label['axis'] = dict(x=HTML(f"<b>{state['label_text']['x']}</b>"), y=HTML(f"<b>{state['label_text']['y']}</b>"), z=HTML(f"<b>{state['label_text']['z']}</b>")) label['topomap_mag'] = HTML(f"<b>{state['label_text']['topomap_mag']}</b>") label['topomap_grad'] = HTML(f"<b>{state['label_text']['topomap_grad']}</b>") label['topomap_eeg'] = HTML(f"<b>{state['label_text']['topomap_eeg']}</b>") label['dipole_pos'] = Label('Not set') label['dipole_ori'] = Label('Not set') label['dipole_pos_'] = Label('Dipole origin:') label['dipole_ori_'] = Label('Dipole orientation:') label['status'] = Label('Status:') label['updating'] = Label('Ready.') widget['label'] = label widget['tab'] = Tab(layout=Layout(width='700')) toggle_buttons = dict( mode_selector=ToggleButtons( options=['Slice Browser', 'Set Dipole Origin', 'Set Dipole Orientation'], button_style='primary', layout=Layout(width='auto')) ) toggle_buttons['mode_selector'].observe(self._handle_view_mode_change, 'value') widget['toggle_buttons'] = toggle_buttons widget['reset_button'] = Button(description='Reset', button_style='danger', layout=Layout(width='auto')) widget['reset_button'].on_click(self._handle_reset_button_click) checkbox = dict(exact_solution=Checkbox( value=self._exact_solution, description='Exact solution (slow!)', tooltip='Calculate an exact forward projection. This is SLOW!')) checkbox['exact_solution'].observe(self._toggle_exact_solution, 'value') widget['checkbox'] = checkbox widget['amplitude_slider'] = IntSlider( value=int(self._state['dipole_amplitude'] * 1e9), min=5, max=100, step=5, continuous_update=False) widget['amplitude_slider'].observe(self._handle_amp_change, names='value') widget['label']['amplitude_slider'] = Label('Dipole amplitude in nAm') widget['quickstart_text'] = HTML( value=('<ul>' '<li>Select the desired brain slices in the ' '<b>Slice Browser.</b></li>' '<li>Choose the location of the dipole via ' '<b>Set Dipole Origin.</b></li>' '<li>Orient the dipole via ' '<b>Set Dipole Orientation.</b></li>' '<li>Adjust the <b>dipole amplitude</b> ' 'using the slider below the topographic maps.</li>' '</ul>')) widget['quickstart_accordion'] = Accordion( children=[widget['quickstart_text']]) widget['quickstart_accordion'].set_title(0, 'Quickstart') widget['preset_dropdown'] = Dropdown( options=['Select Preset…', 'Preset 1', 'Preset 2', 'Preset 3'], value='Select Preset…', layout=Layout(width='auto')) widget['preset_dropdown'].observe(self._handle_preset_selection_change, 'value') widget['title'] = HTML(value='<h2>Dipole Simulator</h2>') widget['output'] = output_widget return widget
def _create_ui(self): """Create and initialize widgets""" # ------------ # Callbacks + logic # ------------ def image_passes_filters(image_index): """Return if image should be shown.""" actual_label = int(self.dataset[image_index][1]) bo_pred_correct = bool(actual_label == self.label_to_id[self.pred_labels[image_index]]) if (bo_pred_correct and self.w_filter_correct.value) or ( not bo_pred_correct and self.w_filter_wrong.value ): return True return False def button_pressed(obj): """Next / previous image button callback.""" step = int(obj.value) self.vis_image_index += step self.vis_image_index = min( max(0, self.vis_image_index), int(len(self.pred_labels)) - 1 ) while not image_passes_filters(self.vis_image_index): self.vis_image_index += step if ( self.vis_image_index <= 0 or self.vis_image_index >= int(len(self.pred_labels)) - 1 ): break self.vis_image_index = min( max(0, self.vis_image_index), int(len(self.pred_labels)) - 1 ) self.w_image_slider.value = self.vis_image_index self.update() def slider_changed(obj): """Image slider callback. Need to wrap in try statement to avoid errors when slider value is not a number. """ try: self.vis_image_index = int(obj["new"]["value"]) self.update() except Exception: pass # ------------ # UI - image + controls (left side) # ------------ w_next_image_button = widgets.Button(description="下一张") w_next_image_button.value = "1" w_next_image_button.layout = Layout(width="80px") w_next_image_button.on_click(button_pressed) w_previous_image_button = widgets.Button(description="上一张") w_previous_image_button.value = "-1" w_previous_image_button.layout = Layout(width="80px") w_previous_image_button.on_click(button_pressed) self.w_filename = widgets.Text( value="", description="名称:", layout=Layout(width="200px") ) self.w_path = widgets.Text( value="", description="路径:", layout=Layout(width="200px") ) self.w_image_slider = IntSlider( min=0, max=len(self.pred_labels) - 1, step=1, value=self.vis_image_index, continuous_update=False, ) self.w_image_slider.observe(slider_changed) self.w_image_header = widgets.Text("", layout=Layout(width="130px")) self.w_img = widgets.Image() self.w_img.layout.width = f"{self.IM_WIDTH}px" w_header = widgets.HBox( children=[ w_previous_image_button, w_next_image_button, self.w_image_slider, self.w_filename, self.w_path, ] ) # ------------ # UI - info (right side) # ------------ w_filter_header = widgets.HTML( value="Filters (use Image +1/-1 buttons for navigation):" ) self.w_filter_correct = widgets.Checkbox( value=True, description="正确分类图像" ) self.w_filter_wrong = widgets.Checkbox( value=True, description="错误分类图像" ) w_gt_header = widgets.HTML(value="真实值:") self.w_gt_label = widgets.Text(value="") self.w_gt_label.layout.width = "360px" w_pred_header = widgets.HTML(value="预测值:") self.w_pred_labels = widgets.Textarea(value="") self.w_pred_labels.layout.height = "200px" self.w_pred_labels.layout.width = "360px" w_scores_header = widgets.HTML(value="分类得分:") self.w_scores = bqpyplot.figure() self.w_scores.layout.height = "250px" self.w_scores.layout.width = "370px" self.w_scores.fig_margin = { "top": 5, "bottom": 80, "left": 30, "right": 5, } # Combine UIs into tab widget w_info = widgets.VBox( children=[ w_filter_header, self.w_filter_correct, self.w_filter_wrong, w_gt_header, self.w_gt_label, w_pred_header, self.w_pred_labels, w_scores_header, self.w_scores, ] ) w_info.layout.padding = "20px" self.ui = widgets.Tab( children=[ widgets.VBox( children=[ w_header, widgets.HBox(children=[self.w_img, w_info]), ] ) ] ) self.ui.set_title(0, "模型结果分析系统") # Fill UI with content self.update()
def __init__(self, path=os.getcwd(), filename='', title='', select_desc='Select', load_desc='Load', change_desc='Change', show_hidden=False, select_default=False, use_dir_icons=False, show_only_dirs=False, filter_pattern=None, **kwargs): """Initialize FileChooser object.""" self._default_path = path.rstrip(os.path.sep) self._default_filename = filename self._selected_path = None self._selected_filename = None self._show_hidden = show_hidden self._select_desc = select_desc self._load_desc = load_desc self._change_desc = change_desc self._callback = None self._select_default = select_default self._use_dir_icons = use_dir_icons self._show_only_dirs = show_only_dirs self._filter_pattern = filter_pattern # Widgets self._pathlist = Dropdown(description="", layout=Layout(width='auto', grid_area='pathlist')) self._filename = Text( placeholder='output filename', layout=Layout(width='auto', grid_area='filename', display=(None, "none")[self._show_only_dirs]), disabled=self._show_only_dirs) self._dircontent = Select(rows=8, layout=Layout(width='auto', height=FC_SCROLLBOX_HEIGHT, grid_area='dircontent')) self._cancel = Button(description='Cancel', layout=Layout(width='auto', display='none')) self._select = Button(description=self._select_desc, layout=Layout(width='auto')) self._title = HTML(value=title) if title == '': self._title.layout.display = 'none' # Widget observe handlers self._pathlist.observe(self._on_pathlist_select, names='value') self._dircontent.observe(self._on_dircontent_select, names='value') self._filename.observe(self._on_filename_change, names='value') self._select.on_click(self._on_select_click) self._cancel.on_click(self._on_cancel_click) # Selected file label self._label = HTML(value=self._LBL_TEMPLATE.format( self._LBL_NOFILE, 'black'), placeholder='', description='') # Layout self._gb = GridBox( children=[self._pathlist, self._filename, self._dircontent], layout=Layout(display='none', width=FC_WIDTH, grid_gap='0px 0px', grid_template_rows='auto auto', grid_template_columns='60% 40%', grid_template_areas=''' 'pathlist {}' 'dircontent dircontent' '''.format( ('filename', 'pathlist')[self._show_only_dirs]))) buttonbar = HBox(children=[self._select, self._cancel, self._label], layout=Layout(width='auto')) # Call setter to set initial form values self._set_form_values(self._default_path, self._default_filename) # Use the defaults as the selected values if self._select_default: self._apply_selection() # Call VBox super class __init__ super().__init__(children=[ self._title, self._gb, buttonbar, ], layout=Layout(width='auto'), **kwargs)
def dsc_config(dsc_value): values = config.read() ds_db = Dropdown( options=list(values['db'].keys()), value="main", description='Database:', disabled=False, layout=Layout(width='200px') ) try: with open(normpath(join(f"{values['paths']['temp']}", 'tb_prefix')), 'r') as f: code_value = f.read().split('_')[0] except Exception: code_value = dsc_value.split('_')[0] ds_code = Combobox( value=code_value, placeholder='abc', options=[m for m in data_options.eu_ms()] + [''], description='AOI code:', ensure_option=False, disabled=False, layout=Layout(width='200px'), tooltip='Lowercase AOI code name for the dataset (5chr max).' ) ds_year = BoundedIntText( value=int(dsc_value.split('_')[1]), min=1980, max=2100, step=1, description='Dataset year:', disabled=False, layout=Layout(width='180px') ) ds_desc = Text( value=values['dataset'][dsc_value]['description'], description='Description:', disabled=False ) info_map_text = ["Set default map view options. ", "You can get automatically the dataset ", "center coordinates."] lat, lon = values['dataset'][dsc_value]['center'].split(",") map_cent_lat = FloatText( value=float(lat), description='Lat:', disabled=False, layout=Layout(width='160px') ) map_cent_lon = FloatText( value=float(lon), description='Lon:', disabled=False, layout=Layout(width='160px') ) map_zoom = BoundedIntText( value=values['dataset'][dsc_value]['zoom'], min=0, max=20, step=1, description='Zoom:', disabled=False, layout=Layout(width='140px') ) bt_get_center = Button( layout=Layout(width='40px'), icon='bullseye', tooltip='Get center point from database.' ) ds_box = HBox([ds_code, ds_year, ds_desc, ds_db]) map_box = HBox([Label("Map center: "), map_cent_lat, map_cent_lon, bt_get_center, map_zoom]) info_config = Label( """Change 'AOI code' or 'Year' value to create a new configuration set or leave the same 'AOI code' value to configure the selected one.""") db_set = values['dataset'][dsc_value]['db'] def get_tb_list(): tbls = db.tables(db_set, None, False) if tbls is None: return [] else: return tbls tb_dc = Dropdown( options=get_tb_list(), value=config.autoselect( values['dataset'][dsc_value]['tables']['dias_catalog'], get_tb_list(), False), description='DIAS catalog:', disabled=False ) tb_pr = Dropdown( options=get_tb_list(), value=config.autoselect( values['dataset'][dsc_value]['tables']['parcels'], get_tb_list(), False), description='Parcels:', disabled=False ) def get_pr_columns(): try: colms = db.table_columns(tb_pr.value, ds_db.value, None) if colms is None: return [] else: return colms except Exception: return [] tc_id = Dropdown( options=get_pr_columns(), value=config.autoselect( values['dataset'][dsc_value]['pcolumns']['parcels_id'], get_pr_columns(), False), description='Parcels ID:', disabled=False, layout=Layout(width='180px') ) tc_cn = Dropdown( options=get_pr_columns(), value=config.autoselect( values['dataset'][dsc_value]['pcolumns']['crop_names'], get_pr_columns(), False), description='Crop names:', disabled=False, layout=Layout(width='180px') ) tc_cc = Dropdown( options=get_pr_columns(), value=config.autoselect( values['dataset'][dsc_value]['pcolumns']['crop_codes'], get_pr_columns(), False), description='Crop codes:', disabled=False, layout=Layout(width='180px') ) def on_tb_pr_change(change): tc_id.options = get_pr_columns() tc_cn.options = get_pr_columns() tc_cc.options = get_pr_columns() tb_pr.observe(on_tb_pr_change, 'value') tb_s2 = Dropdown( options=get_tb_list(), value=config.autoselect( values['dataset'][dsc_value]['tables']['s2'], get_tb_list(), False), description='S2 signatures:', disabled=False ) tb_bs = Dropdown( options=get_tb_list(), value=config.autoselect( values['dataset'][dsc_value]['tables']['bs'], get_tb_list(), False), description='Backscattering:', disabled=False ) tb_6c = Dropdown( options=get_tb_list(), value=config.autoselect( values['dataset'][dsc_value]['tables']['c6'], get_tb_list(), False), description='6 day coherence:', disabled=False ) wb_save = Button( description='Save', disabled=False, icon='save' ) @bt_get_center.on_click def bt_get_center_on_click(b): import json center_json = json.loads( db_queries.getTableCentroid(tb_pr.value)['center'][0]) map_cent_lat.value = round(center_json['coordinates'][1], 2) map_cent_lon.value = round(center_json['coordinates'][0], 2) map_zoom.value = 10 @wb_save.on_click def wb_save_on_click(b): progress.clear_output() dscode = ds_code.value config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'tables', 'dias_catalog'], str(tb_dc.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'tables', 'parcels'], str(tb_pr.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'pcolumns', 'parcels_id'], str(tc_id.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'pcolumns', 'crop_names'], str(tc_cn.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'pcolumns', 'crop_codes'], str(tc_cc.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'tables', 's2'], str(tb_s2.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'tables', 'bs'], str(tb_bs.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'tables', 'c6'], str(tb_6c.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'db'], str(ds_db.value)) config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'description'], str(ds_desc.value)) config.set_value( ['dataset', f'{dscode}_{str(ds_year.value)}', 'center'], f"{map_cent_lat.value},{map_cent_lon.value}") config.set_value(['dataset', f'{dscode}_{str(ds_year.value)}', 'zoom'], str(map_zoom.value)) config.set_value(['set', 'dataset'], f'{dscode}_{str(ds_year.value)}') config.set_value(['set', 'ds_year'], str(ds_year.value)) values = config.read() ds_c = values['set']['dataset'] dsc.options = [d for d in values['dataset']] dsc.value = ds_c outlog("The configurations are saved.") db_box = HBox([VBox([Label('Tables:'), tb_pr, tb_dc, tb_s2, tb_bs, tb_6c]), VBox([Label('Columns:'), HBox([tc_id, tc_cn, tc_cc])])]) return VBox([info_config, ds_box, db_box, Label(''.join(info_map_text)), map_box, wb_save])
def __init__(self): # размерность задачи items_layout = Layout (flex = '1 1 auto', width = 'auto') self.w_title = HTML('<h3>Параметры задачи</h3>') self.w_l_dim = Label('Размерность задачи:') self.w_dim = ToggleButtons( options=['2', '3'], value = '2', #description=' ', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Плоская двухмерная задача', 'Трехмерная осесимметричная задача'], layout=items_layout ) chg.r0=1e-6 self.w_l_r0 = Label('Радиус заряда:') self.w_r0 =SelectionSlider( options=['1e-6', '1e-5', '1e-4', '1e-3', '1e-2'], value='1e-6', #description=' ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, layout=items_layout ) chg.alpha = 0 self.w_l_alpha = Label(r"Параметр регуляризации ($\alpha$):") self.w_alpha =SelectionSlider( options=['0', '1e-6', '1e-4', '1e-2', '1e-1', '0.5', '1.0'], value='0', #description=' ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, layout=items_layout ) chg.n = 100 self.w_l_n = Label('Число разбиений области:') self.w_n = SelectionSlider( options=['20', '50', '100', '200', '400', '500', '1000'], value='100', #description=' ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, layout=items_layout ) chg.minmaxxy=(0., 0, 1.,1.) self.w_l_minmaxxy = Label('Область для расчета и отображения потенциала (x, y):') self.w_minmaxx = FloatRangeSlider(value=[0.,1.], min=0, max=2.0, #description='xmin, xmax', step=0.01, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.2f', layout=items_layout) self.w_minmaxy = FloatRangeSlider(value=[0.,1.], min=0, max=2.0, #description='ymin, ymax', step=0.02, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.2f', layout=items_layout) chg.minmaxarea=(0.2, 0.2, 0.9,0.9) self.w_l_minmaxarea = Label('Область для расчета напряженности (x, y):') self.w_minmaxxarea = FloatRangeSlider(value=[0.2,0.9], min=0, max=1.0, #description='xmin, xmax', step=0.01, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.2f', layout=items_layout) self.w_minmaxyarea = FloatRangeSlider(value=[0.2,0.9], min=0, max=1.2, #description='ymin, ymax', step=0.005, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.3f', layout=items_layout) self.w_l_na = Label('Разбиений для аппроксимации электродов:') chg.na = 50 self.w_na = IntSlider( value=chg.na, min=20, max=250, step=2, #description=' ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', layout=items_layout ) chg.c = None self.l_c = Label('') self.update_label('cond', chg.c, self.l_c) chg.err = None self.l_err = Label('') self.update_label('err', chg.err, self.l_err) chg.E = None self.l_E = Label('') self.update_label('E', chg.E, self.l_E) chg.t = None self.l_t = Label('') self.update_label('t', chg.t, self.l_t) self.l_msg=HTML('<b></b>') self.l_var = Label('Вариант:') self.w_dsc = Textarea(value='', placeholder='Введите пояснения по варианту расчета', description='', disabled=False ) self.btn0 = Button(description ='Пересчитать поле', button_style='primary') self.btn01 = Button(description ='Emax/Emin', button_style='primary', disabled=True) self.out0 = Output() self.btn02 = Button(description='Сохранить', disabled=False) vb01= VBox([self.w_l_dim, self.w_dim, self.w_l_r0, self.w_r0, self.w_l_alpha, self.w_alpha, self.w_l_n, self.w_n, self.w_l_minmaxxy, self.w_minmaxx, self.w_minmaxy, self.w_l_minmaxarea, self.w_minmaxxarea, self.w_minmaxyarea], layout=Layout(width='47%')) vb02 = VBox([self.w_l_na, self.w_na, self.l_var, self.w_dsc, self.l_c, self.l_err, self.l_E , self.l_t, self.l_msg ], layout=Layout(width='47%')) hbox =HBox([vb01, vb02], layout=Layout(justify_content='space-between')) hbox2 = HBox([self.btn0, self.btn01, self.btn02]) self.layout = VBox([self.w_title, hbox, hbox2, self.out0], layout=Layout(width='100%')) # инициализация self.get_data()
def _create_title(self, title, tab_controls): """Creates title controls for this tab widget. - Adds title label - Adds download button for query result. Disabled if one of the following conditions hold: * query result contains ExplicitVBR or ExplicitVBROverlay type column * number of rows in the query result exceeds DOWNLOAD_THRESHOLD - Adds paginator if there exists no ExplicitVBR or ExplicitVBROverlay type column - Adds any controls related to column types in the result set Parameters ---------- title: str result set title. tab_controls: list list of controls related to columns in the result set. """ # initialize widgets # add title label title_label = HTML(f"<h3>{title}</h3>", layout=Layout(padding="0px 5px 5px 0px")) self._hbox_title = HBox(layout=Layout(justify_content="space-between", align_items="center")) # create download link dw = NlDownloadLink(layout=Layout( width="30px", max_width="30px", min_width="30px", margin="5px 5px 5px 0", padding="0 0 0 0", flex="0 1 0", align_self="center", )) hbox_table_info = HBox( [title_label, dw], layout=Layout(justify_content="flex-start", align_items="center"), ) if not self._columns_manager.hasVBRColumn: if self._total_nb_rows <= ResultTabPageWidget.DOWNLOAD_THRESHOLD: dw.filename = f"{title}.csv.gz" dw.mimetype = "application/gz" dw.tooltip = f"Download {dw.filename} file." def clicked(event): dw.content = gzip.compress( self._df.to_csv(index=False).encode()) dw.on_click(clicked) else: dw.disabled = True dw.tooltip = "Not available for download due to size!" # add paginator if there exist no ExplicitVBR or ExplicitVBROverlay column paginator = PaginationWidget( self._df.shape[0], layout=Layout(padding="0px 0px 0px 50px")) self._limit = paginator.limit paginator.observe(self._page_number_changed, names="page") paginator.observe(self._limit_changed, names="limit") hbox_table_info.children = hbox_table_info.children + (paginator, ) else: dw.tooltip = "Not available for download due to column type!" dw.disabled = True self._limit = self._total_nb_rows return [hbox_table_info, HBox(tab_controls)]
def interact_distributions(): from ipywidgets import FloatSlider, Label, GridBox, interactive, Layout, VBox, \ HBox, Checkbox, IntSlider, Box, Button, widgets fx0=FloatSlider(value=2, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vx0')) fy0=FloatSlider(value=3, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vy0')) fs0=FloatSlider(value=1, description=" ", min=.1, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vs0')) fd0=FloatSlider(value=.9, description=" ", min=-2., max=2., step=.1, continuous_update=False, layout=Layout(width='auto', grid_area='vd0')) fx1=FloatSlider(value=2, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vx1')) fy1=FloatSlider(value=2, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vy1')) fs1=FloatSlider(value=1, description=" ", min=.1, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vs1')) fd1=FloatSlider(value=-.3, description=" ", min=-2., max=2., step=.1, continuous_update=False, layout=Layout(width='auto', grid_area='vd1')) fdummy = FloatSlider(value=2, description= " ", min=1, max=4, step=1) l = lambda s,p, w="auto": Label(s, layout=Layout(width=w, grid_area=p)) bay = Checkbox(value=False, description='show NATURAL frontiers',disabled=False, indent=False, layout=Layout(width="80%")) resample = Button(description="resample data points") from IPython.core.display import clear_output def resample_onclick(_): global do_resample_points do_resample_points = True tmp = fdummy.value fdummy.value = tmp+(1 if tmp<3 else -1) do_resample_points = False resample.on_click(resample_onclick) w = interactive(display_distributions, x0=fx0, y0=fy0, s0=fs0, d0=fd0, x1=fx1, y1=fy1, s1=fs1, d1=fd1, show_bayesians=bay, dummy=fdummy, continuous_update=False) w.children[-1].layout=Layout(width='auto', grid_area='fig') controls = Box([bay, resample], layout=Layout(grid_area="ctr", display="flex-flow", justify_content="flex-start", flex_flow="column", align_items = 'flex-start')) gb =GridBox(children=[fx0, fy0, fs0, fd0, fx1, fy1, fs1, fd1, l("AMERICAN TRILOBYTE", "h0"), l("AFRICAN TRILOBYTE", "h1"), l("size", "lx0"),l("weight", "ly0"), l("spread", "ls0"), l("tilt", "ld0"), l("size", "lx1"),l("weight", "ly1"), l("spread", "ls1"), l("tilt", "ld1"), controls ], layout=Layout( width='100%', grid_template_rows='auto auto auto auto auto auto auto', grid_template_columns='5% 30% 5% 30% 30%', grid_template_areas=''' "h0 h0 h1 h1 ." "lx0 vx0 lx1 vx1 ." "ly0 vy0 ly1 vy1 ctr" "ls0 vs0 ls1 vs1 ctr" "ld0 vd0 ld1 vd1 ctr" "fig fig fig fig fig" ''') ) def limit_fd0(*args): fd0.max = fs0.value+fs0.value*0.5 fd0.min = -fs0.value*0.5 def limit_fd1(*args): fd1.max = fs1.value+fs1.value*0.5 fd1.min = -fs1.value*0.5 fs0.observe(limit_fd0, "value") fd0.observe(limit_fd0, "value") fs1.observe(limit_fd1, "value") fd1.observe(limit_fd1, "value") w.children[0].value=1 widget1 = VBox([gb, w.children[-1]]) display(widget1) return fx0, fy0, fs0, fd0, fx1, fy1, fs1, fd1
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # tab widget that displays each resultset in an individual tab self._tab = NlIconTab(layout=Layout(height="460px")) # viewers necessary for each resultset, can be shared among resultsets self._viewers = None
def __init__( self, origin_time: datetime = None, before: int = 60, after: int = 10, max_before: int = 600, max_after: int = 100, label: str = None, units: str = "min", auto_display: bool = False, ): """ Create new instance of QueryTime. Parameters ---------- origin_time : datetime, optional The origin time (the default is `datetime.utcnow()`) label : str, optional The description to display (the default is 'Select time ({units}) to look back') before : int, optional The default number of `units` before the `origin_time` (the default is 60) after : int, optional The default number of `units` after the `origin_time` (the default is 10) max_before : int, optional The largest value for `before` (the default is 600) max_after : int, optional The largest value for `after` (the default is 100) units : str, optional Time unit (the default is 'min') Permissable values are 'day', 'hour', 'minute', 'second' These can all be abbreviated down to initial characters ('d', 'm', etc.) auto_display : bool, optional Whether to display on instantiation (the default is False) """ self._label = "Set query time boundaries" if label is None else label self._time_unit = _parse_time_unit(units) max_before = abs(max_before) max_after = abs(max_after) before = abs(before) after = abs(after) if max_before < before: before = max_before if max_after < after: after = max_after # default to now self.origin_time = datetime.utcnow() if origin_time is None else origin_time # Calculate time offsets from origin self._query_start = self.origin_time - timedelta( 0, before * self._time_unit.value ) self._query_end = self.origin_time + timedelta(0, after * self._time_unit.value) # Create widgets self._w_origin_dt = widgets.DatePicker( description="Origin Date", disabled=False, value=self.origin_time.date() ) self._w_origin_tm = widgets.Text( description="Time (24hr)", disabled=False, value=str(self.origin_time.time()), ) range_desc = "Time Range ({}):".format(self._time_unit.name) self._w_tm_range = widgets.IntRangeSlider( value=[-before, after], min=-max_before, max=max_after, step=1, description=range_desc, disabled=False, continuous_update=True, orientation="horizontal", readout=True, readout_format="d", layout=Layout(width="80%"), style=self._label_style, ) self._w_start_time_txt = widgets.Text( value=self._query_start.isoformat(sep=" "), description="Query start time (UTC):", layout=Layout(width="50%"), style=self._label_style, ) self._w_end_time_txt = widgets.Text( value=self._query_end.isoformat(sep=" "), description="Query end time (UTC) : ", layout=Layout(width="50%"), style=self._label_style, ) self._w_tm_range.observe(self._time_range_change, names="value") self._w_origin_dt.observe(self._update_origin, names="value") self._w_origin_tm.observe(self._update_origin, names="value") if auto_display: self.display()
def getTS(self, startDate, endDate): ndays = (endDate - startDate).days + 1 if self.init: ndays += 1 currentDate = startDate delta = timedelta(days=1) self.df = pd.DataFrame(columns=[ 'datetime', 'AOD', 'DUST_PM', 'SALT_PM', 'ORG_CARB', 'BLK_CARB', 'SO4', 'PM2.5' ]) with self.out_cp: self.out_cp.clear_output() pbar = IntProgress(min=0, max=int(ndays)) pbar.description = 'Progress:' info1 = Label('0%') info2 = Label(' ') display( VBox([ HBox([pbar, info1]), HBox([info2], layout=Layout(justify_content='center')) ])) progVal = 0 if self.init: info2.value = 'Initializing NASA Earth Data Connection..' self.initSession() self.init = False pbar.value += 1 progVal += 1 info1.value = '{:.1f}%'.format( (float(progVal) / float(ndays)) * 100.0) self.lonlatToIndex(self.plon, self.plat) while currentDate <= endDate: url = self.getUrlMERRA(currentDate) info2.value = 'Accessing data for {}'.format(currentDate) dataset = open_url(url, session=self.session) aod = np.squeeze(dataset['TOTEXTTAU'][:, self.ilat, self.ilon]) dust_pm = np.squeeze( dataset['DUSMASS25'][:, self.ilat, self.ilon]) * 1000000000.0 salt_pm = np.squeeze( dataset['SSSMASS25'][:, self.ilat, self.ilon]) * 1000000000.0 org_carb = np.squeeze( dataset['OCSMASS'][:, self.ilat, self.ilon]) * 1000000000.0 blk_carb = np.squeeze( dataset['BCSMASS'][:, self.ilat, self.ilon]) * 1000000000.0 so4 = np.squeeze(dataset['SO4SMASS'][:, self.ilat, self.ilon]) * 1000000000.0 pm25 = (1.375 * so4 + 1.6 * org_carb + blk_carb + dust_pm + salt_pm) dt = pd.date_range(currentDate, periods=24, freq='H') vardict = { 'datetime': dt, 'AOD': aod, 'DUST_PM': dust_pm, 'SALT_PM': salt_pm, 'ORG_CARB': org_carb, 'BLK_CARB': blk_carb, 'SO4': so4, 'PM2.5': pm25 } df_add = pd.DataFrame(vardict) self.df = pd.concat([self.df, df_add]) currentDate += delta progVal += 1 info1.value = '{:.1f}%'.format( (float(progVal) / float(ndays)) * 100.0) pbar.value += 1 self.stateChange = False