def _appearance_tab(self): """Defining the appearance tab.""" # 1. Supercell def change_supercell(_=None): self.supercell = [ _supercell[0].value, _supercell[1].value, _supercell[2].value ] _supercell = [ ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}), ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}), ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}), ] for elem in _supercell: elem.observe(change_supercell, names='value') supercell_selector = ipw.HBox([ipw.HTML(description="Super cell:")] + _supercell) # 2. Choose background color. background_color = ipw.ColorPicker(description="Background") link((background_color, 'value'), (self._viewer, 'background')) background_color.value = 'white' # 3. Center button. center_button = ipw.Button(description="Center") center_button.on_click(lambda c: self._viewer.center()) return ipw.VBox([supercell_selector, background_color, center_button])
def new(self, result_callback, value=None): if value is None: tp, fp, fn = 0, 0, 0 else: tp, fp, fn = value.tp, value.fp, value.fn tp_widget = widgets.BoundedIntText(description='true (+)', value=tp, min=0, max=100, layout=widgets.Layout(width='auto')) fp_widget = widgets.BoundedIntText(description='false (+)', value=fp, min=0, max=100, layout=widgets.Layout(width='auto')) fn_widget = widgets.BoundedIntText(description='false (-)', value=fn, min=0, max=100, layout=widgets.Layout(width='auto')) submit_btn = widgets.Button(description='Submit', layout=widgets.Layout(width='auto'), button_style='danger') def on_submit(unused): result_callback( DetectorValidationInputCellFactory.ValResult( tp=tp_widget.value, fp=fp_widget.value, fn=fn_widget.value)) submit_btn.on_click(on_submit) return widgets.HBox([tp_widget, fp_widget, fn_widget, submit_btn])
def create_navigator_2d(self): import ipywidgets as ipyw x_min, y_min = 0, 0 x_max, y_max = self.signal.axes_manager.navigation_shape x_max -= 1 y_max -= 1 x_text = ipyw.BoundedIntText(value=self.indices[0], description="x", min=x_min, max=x_max, layout=ipyw.Layout(flex='0 1 auto', width='auto')) y_text = ipyw.BoundedIntText(value=self.indices[1], description="y", min=y_min, max=y_max, layout=ipyw.Layout(flex='0 1 auto', width='auto')) randomize = ipyw.Button(description="Randomize", layout=ipyw.Layout(flex='0 1 auto', width='auto')) container = ipyw.HBox((x_text, y_text, randomize)) def on_index_change(change): self.indices = (x_text.value, y_text.value) self.replot_image() def on_randomize(change): from random import randint x = randint(x_min, x_max) y = randint(y_min, y_max) x_text.value = x y_text.value = y x_text.observe(on_index_change, names='value') y_text.observe(on_index_change, names='value') randomize.on_click(on_randomize) return container
def generate_display_compute(photographes, type_seance): display( HTML('''<style> .widget-label { min-width: 20ex !important; } .slide-container { min-width: 30ex !important; } div.p-Widget { min-width: 50ex !important; } </style>''')) print('Photographes') display(pd.DataFrame(photographes).fillna(False)) interact(lambda x: None, x=widgets.BoundedIntText(value=1, description='Parametres:', disabled=True)) create_slider('seance_adjacenteA', 'seance_adjacente', 1) create_slider('seance_adjacente_2A', 'seance_adjacente_2', 1) create_slider('type_favoriA', 'type_favori', 1) interact(lambda x: None, x=widgets.BoundedIntText(value=2, description='Parametres:', disabled=True)) create_slider('seance_adjacenteB', 'seance_adjacente', 1) create_slider('seance_adjacente_2B', 'seance_adjacente_2', 1) create_slider('type_favoriB', 'type_favori', 1) button = widgets.Button(description="Run") display(button) button.on_click(lambda b: on_button_clicked(b, photographes, type_seance))
def __init__(self, color, alpha): self._x_box = ipywidgets.BoundedIntText(description="x", min=0) self._y_box = ipywidgets.BoundedIntText(description="y", min=0) self._w_box = ipywidgets.BoundedIntText(description="width", min=0) self._h_box = ipywidgets.BoundedIntText(description="height", min=0) self._update_extents_lock = threading.Lock() for b in self._x_box, self._y_box, self._w_box, self._h_box: b.observe(self._box_value_changed, "value") # Color input boxes rgb = mpl.colors.to_rgb(color) style = ("<style>.chan_{} input {{background-color: " "rgba({}, {}, {}, {}) !important}}</style>").format( id(self), *[r * 255 for r in rgb], alpha) self._style_html = ipywidgets.HTML(style) super().__init__([ self._style_html, ipywidgets.VBox([self._x_box, self._y_box]), ipywidgets.VBox([self._w_box, self._h_box]) ]) self.add_class("chan_{}".format(id(self)))
def __init__(self, iquery): self._iquery = iquery self._level = widgets.Dropdown(options=['sentence', 'token'], value='sentence', description='Partition:', disabled=False, style=ROOT_LEVEL_STYLE) self._window_size = widgets.BoundedIntText( value=1, min=1, max=1000, step=1, description='Window Size:', disabled=False, layout={'width': '10em'}, style={'description_width': 'initial'}) self._window_step = widgets.BoundedIntText( value=1, min=1, max=1000, step=1, description='Window Step:', disabled=False, layout={'width': '10em'}, style={'description_width': 'initial'}) self._hbox = widgets.HBox( [self._level, self._window_size, self._window_step])
def manualOp(*args): if len(args) == 2: # matrice augmentée A = np.matrix(args[0]).astype(float) m = A.shape[0] b = args[1] #b=[b[i] for i in range(m)] if type(b[0]) == list: b = np.matrix(b).astype(float) A = np.concatenate((A, b), axis=1) else: b = [b[i] for i in range(m)] A = [A[i] + [b[i]] for i in range(0, m)] else: A = np.matrix(args[0]).astype(float) m = A.shape[0] A = np.array(A) #just in case it's not j = widgets.BoundedIntText(value=1, min=1, max=m, step=1, description='Ligne j:', disabled=False) i = widgets.BoundedIntText(value=1, min=1, max=m, step=1, description='Ligne i:', disabled=False) r = widgets.RadioButtons(options=['Eij', 'Ei(alpha)', 'Eij(alpha)'], description='Opération:', disabled=False) alpha = widgets.Text(value='1', description='Coeff. alpha:', disabled=False) print( "Régler les paramètres et cliquer sur RUN INTERACT pour effectuer votre opération" ) def f(r, i, j, alpha): m = np.concatenate((A, b), axis=1) MatriceList = [A] RhSList = [b] if alpha == 0: print('Le coefficient alpha doit être non-nul!') if r == 'Eij': m = Eij(m, i - 1, j - 1) if r == 'Ei(alpha)': m = Ealpha(m, i.value - 1, eval(alpha)) if r == 'Eij(alpha)': m = Eijalpha(m, i - 1, j - 1, eval(alpha)) MatriceList.append(m[:, 0:len(A[0])]) RhSList.append(m[:, len(A[0]):]) printEquMatricesAug(MatriceList, RhSList) interact_manual(f, r=r, i=i, j=j, alpha=alpha)
def __init__(self): self.inpt= { # just the default to start with "wind": 3, "solar": 500, "albedo": 0.25, "airt": 15, "sfc": "grass (dry)", "rs": 40, "vp": 10, "smd": 10 } self.rblist = [500.0, -30.0, 300.0, 200.0] self.eblist = [300.0, 100.0, 150.0, 200.0] # Polynomial fit to Graham Russell's smd fit for cereals # yfit = a*x**3+b*x+c where x is smd in mm self.smdfit = [1.27791987e-04, -9.56796959e-02, 3.95338027e+01] self.mod = Model(self.inpt) self.tlist = self.mod.tlist self.vw = View(self.rblist, self.eblist, self.tlist) self.sfcs = ["grass (dry)","bare soil (dry)","cereals (dry)", "conifers (dry)","upland (dry)","grass (wet)", "bare soil (wet)", "cereals (wet)","conifers (wet)", "upland (wet)", "water"] self.bit_wind = widgets.BoundedIntText(value = self.inpt["wind"], min=1, max=15, step=1, description="u ($m \ s^{-1}$)", width=50) self.bit_solar = widgets.BoundedIntText(value = self.inpt["solar"], min=1, max=1000, step=10, description="solar ($W m^{-2}$)", width=50) self.bit_vp = widgets.BoundedIntText(value =self.inpt["vp"], min=1, max=40, step=1, description="vp (mbar)", width=50) self.dd_surface = widgets.Dropdown(value =self.inpt["sfc"], options=self.sfcs, description="surface", width=50) self.bit_smd = widgets.BoundedIntText(value=self.inpt["smd"], min=1, max=180, step=5, description="smd (mm)", width=50) self.bit_airt = widgets.BoundedIntText(value=self.inpt["airt"], min=-5, max=40, step=1, description="air T (oC)", width=50) self.txt_rs = widgets.Text(description="rs") self.txt_rh = widgets.Text(description="RH (%)") self.txt_le = widgets.Text(description="LE") self.txt_ra = widgets.Text(description="ra") # First time round to populate output boxes self.rblist, self.eblist, self.tlist, self.olist = self.mod.calculateLE(self.inpt) self.txt_rs.value = str('{0:.0f}'.format(self.olist[0])) self.txt_rh.value = str('{0:.1f}'.format(self.olist[1])) self.txt_le.value = str('{0:.1f}'.format(self.olist[2])) self.txt_ra.value = str('{0:.0f}'.format(self.olist[3])) self.bit_wind.observe(self.bit_wind_eventhandler, names='value') self.bit_solar.observe(self.bit_solar_eventhandler, names='value') self.bit_vp.observe(self.bit_vp_eventhandler, names='value') self.dd_surface.observe(self.dd_surface_eventhandler, names='value') self.bit_smd.observe(self.bit_smd_eventhandler, names='value') self.bit_airt.observe(self.bit_airt_eventhandler, names='value') self.h0 = widgets.HBox(children=[self.dd_surface, self.bit_smd]) self.h1 = widgets.HBox(children=[self.bit_solar, self.bit_wind]) self.h2 = widgets.HBox(children=[self.bit_airt, self.bit_vp, self.txt_rh]) self.h3 = widgets.HBox(children=[self.txt_ra, self.txt_rs, self.txt_le])
def __init__(self, values=None, infos=""): self.name = "restart" self.infos = w.HTML(value=infos) self.widgets = { "activated": w.Checkbox(description="activated", value=False, disabled=True), "freq": w.BoundedIntText(description="Saving frequency", value=50, min=0, max=1000000, disabled=False), "kgeneration": w.HBox([ w.BoundedIntText(description="Restart generation", value=0, min=0, max=1000000, disabled=True), w.Checkbox(description=" ", value=False, disabled=True) ]), "seed": w.HBox([ w.BoundedIntText(description="Restart Seed", value=0, min=0, max=1000000, disabled=True), w.Checkbox(description=" ", value=False, disabled=True) ]), "same_seed": w.Checkbox(description="Restart with the same seed", value=True, disabled=True), } def run_activate(value): for key in ["kgeneration", "seed"]: self.widgets[key].children[1].disabled = not value self.widgets["same_seed"].disabled = not value def activate_seed(value): self.widgets["seed"].children[ 0].disabled = not self.widgets["seed"].children[1].value def activate_kgeneration(value): self.widgets["kgeneration"].children[ 0].disabled = not self.widgets["kgeneration"].children[1].value w.interactive(run_activate, value=self.widgets["activated"]) w.interactive(activate_seed, value=self.widgets["seed"].children[1]) w.interactive(activate_kgeneration, value=self.widgets["kgeneration"].children[1]) if values: self.set_values(values)
def manualEch(*args): """Method which allows the user to perform the Gauss elimination method on the given input matrix, eventually extended by the right-hand side vector. :param args: :type args: :return: :rtype: """ if len(args) == 2: # matrice augmentée A = np.array(args[0]).astype(float) m = A.shape[0] b = args[1] if type(b[0]) is list: b = np.array(b).astype(float) A = np.concatenate((A, b), axis=1) else: b = [b[i] for i in range(m)] A = [A[i] + [b[i]] for i in range(m)] else: A = np.array(args[0]).astype(float) m = A.shape[0] j = widgets.BoundedIntText(value=1, min=1, max=m, step=1, description='Ligne j:', disabled=False) i = widgets.BoundedIntText(value=1, min=1, max=m, step=1, description='Ligne i:', disabled=False) r = widgets.RadioButtons( options=['Eij', 'Ei(alpha)', 'Eij(alpha)', 'Revert'], description='Opération:', disabled=False) alpha = widgets.Text(value='1', description='Coeff. alpha:', disabled=False) print("Régler les paramètres et évaluer la cellule suivante") print("Répéter cela jusqu'à obtenir une forme échelonnée réduite") display(r) display(i) display(j) display(alpha) return i, j, r, alpha
def _appearance_tab(self): """Defining the appearance tab.""" # 1. Supercell def change_supercell(_=None): self.supercell = [ _supercell[0].value, _supercell[1].value, _supercell[2].value, ] _supercell = [ ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}), ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}), ipw.BoundedIntText(value=1, min=1, layout={"width": "30px"}), ] for elem in _supercell: elem.observe(change_supercell, names="value") supercell_selector = ipw.HBox([ipw.HTML(description="Super cell:")] + _supercell) # 2. Choose background color. background_color = ipw.ColorPicker(description="Background") link((background_color, "value"), (self._viewer, "background")) background_color.value = "white" # 3. Camera switcher camera_type = ipw.ToggleButtons( options={ "Orthographic": "orthographic", "Perspective": "perspective" }, description="Camera type:", value=self._viewer.camera, layout={"align_self": "flex-start"}, style={"button_width": "115.5px"}, orientation="vertical", ) def change_camera(change): self._viewer.camera = change["new"] camera_type.observe(change_camera, names="value") # 4. Center button. center_button = ipw.Button(description="Center molecule") center_button.on_click(lambda c: self._viewer.center()) return ipw.VBox( [supercell_selector, background_color, camera_type, center_button])
def select_train_paramter(): ### Training epochs ################### int_train_epochs = widgets.BoundedIntText(min=1, max=4096, step=1, value=params['train_epochs']) def on_int_train_epochs_change(change): params['train_epochs'] = change.new int_train_epochs.observe(on_int_train_epochs_change, 'value') ### Steps per epoch ################### int_train_steps_per_epoch = widgets.BoundedIntText( min=1, max=4096, step=1, value=params['train_steps_per_epoch']) def on_train_steps_per_epoch_change(change): params['train_steps_per_epoch'] = change.new int_train_steps_per_epoch.observe(on_train_steps_per_epoch_change, 'value') ### Batch size ############## dd_train_batch_size = widgets.Dropdown( options=[4, 8, 16, 32, 64, 128, 256], value=params['train_batch_size']) def on_dd_train_batch_size_change(change): params['train_batch_size'] = change.new dd_train_batch_size.observe(on_dd_train_batch_size_change, 'value') ### Combine ############## train_parameter = widgets.VBox([ widgets.HBox([ widgets.Label('#Epochs', layout={'width': '100px'}), int_train_epochs ]), widgets.HBox([ widgets.Label('#Steps / epoch', layout={'width': '100px'}), int_train_steps_per_epoch ]), widgets.HBox([ widgets.Label('Batch size', layout={'width': '100px'}), dd_train_batch_size ]), ]) display(train_parameter)
def __init__(self): self.map_out = widgets.Output() self.bottom_lat = widgets.BoundedIntText(min=-90, max=90, description='Bottom Lat:') self.top_lat = widgets.BoundedIntText(min=-90, max=90, value=10, description='Top Lat:') self.left_lon = widgets.BoundedIntText(min=-180, max=180, description='Left Lon:') self.right_lon = widgets.BoundedIntText(min=-180, max=180, value=10, description='Right Lon:') self.update_area_minmax() hplot_area_selection = widgets.VBox([self.bottom_lat, self.left_lon, self.top_lat, self.right_lon]) area_on_map_out = widgets.interactive_output(self.show_area, {'left': self.left_lon, 'bottom': self.bottom_lat, 'top': self.top_lat, 'right': self.right_lon}) self.main_vbox = widgets.VBox([hplot_area_selection, self.map_out])
def generate_min_value_widget(self, ge_df, expectation_type, min_value=None, column=None, **expectation_kwargs): expectation_state = self.get_expectation_state(expectation_type, column) or { 'kwargs': {} } min_value_widget = expectation_state['kwargs'].get('min_value') max_value_widget = expectation_state['kwargs'].get('max_value') if expectation_type == 'expect_column_unique_value_count_to_be_between': if min_value_widget: min_value_widget.value = min_value or int(-9e300) else: min_value_widget = widgets.BoundedIntText( value=min_value or 0, min=0, description='min_value: ', disabled=False) if not max_value_widget: max_value_widget = widgets.BoundedIntText( description='max_value: ', value=int(9e300), max=int(9e300), disabled=False) @debug_view.capture(clear_output=True) def on_min_value_change(change): expectation_state = self.get_expectation_state( expectation_type, column) ge_expectation_kwargs = self.expectation_kwarg_widgets_to_ge_kwargs( expectation_state['kwargs']) new_result = getattr(ge_df, expectation_type)(include_config=True, **ge_expectation_kwargs) min_value_widget.observe(on_min_value_change, names='value') max_dl = widgets.link((max_value_widget, 'value'), (min_value_widget, 'max')) expectation_state['kwargs']['min_value'] = min_value_widget expectation_state['kwargs']['max_value'] = max_value_widget self.set_expectation_state(expectation_type, expectation_state, column) return min_value_widget
def helical_or_step(mode, param): if mode == 'Helical': excluded_parameters = ['shift', 'slide', 'rise', 'tilt', 'roll', 'twist'] input_options['HelicalParameters']['is_helical'] = True else: excluded_parameters = ['x_displacement', 'y_displacement', 'h_rise', 'inclination', 'tip', 'h_twist'] input_options['HelicalParameters']['is_helical'] = False for k in param: if k == 'is_helical' or k in excluded_parameters: continue param_dict[k] = [] default = [param[k]['default'][0], param[k]['default'][1], param[k]['default'][2]] # [beginning point, end point, number of steps] # Set angles if k in ['inclination', 'tip', 'h_twist', 'roll', 'tilt', 'twist', 'buckle', 'propeller', 'opening']: param_dict[k].append(widgets.FloatRangeSlider(value=[default[0], default[1]], min=-180, max=180, step=0.01, readout_format='.2f')) # Set distances else: # h_rise, x-displacement, y-displacement, rise, slide, shift, stretch, shear, stagger # limit maxium and minimum distance values to be between -20 and 20 and 0.01 Angstrom step size param_dict[k].append(widgets.FloatRangeSlider(value=[default[0], default[1]], min=-20, max=20, step=0.01, readout_format='.3f')) # Add the number of steps widgets param_dict[k].append(widgets.BoundedIntText(value=default[2], min=1, max=1000, step=1, description='Steps')) help_box = widgets.Button(description='?', tooltip=param[k]['long_glossory'], layout=widgets.Layout(width='3%')) box = widgets.HBox([help_box, widgets.Label(param[k]['glossory'], layout={'width': '200px'}), param_dict[k][0], param_dict[k][1]]) display(box) # Add widgets for helical parameter k to the widgets dictionary input_options['HelicalParameters'][k] = [param_dict[k][0], param_dict[k][1]]
def get_rawdocument_selector(info, callback): id_selector = widgets.BoundedIntText(value=0, step=1, min=0, max=1000000000, description='Document', style=style) set_layout(id_selector) try: id_selector.value = info.get('document_id', vocab_selector.value) except: pass def update_info(document_id): info['document_id'] = document_id def on_id_selector_change(change): document_id = change['new'] update_info(document_id) callback() id_selector.observe(on_id_selector_change, names='value') update_info(id_selector.value) return id_selector
def __init__(self, callback, value, min_value, max_value, step, description, dict_id='', description_width='150px', layout_width='300px'): def on_value_change(change): callback({self._dict_id: change['new']}) self._dict_id = dict_id self._text_box = ipw.BoundedIntText( value=value, min=min_value, max=max_value, step=step, description=description, continuous_update=False, style={'description_width': description_width}, layout={'width': layout_width}, disabled=False) self._text_box.observe(on_value_change, names='value')
def interact_feature_hist(tX, y, cur_feature_names): def plot_feature_hist(feature_ind, drop_nan): indices_class_pos = np.where(y == 1) indices_class_neg = np.where(y == -1) tX_pos = tX[indices_class_pos, feature_ind] tX_neg = tX[indices_class_neg, feature_ind] if drop_nan: tX_pos = tX_pos[tX_pos != -999] tX_neg = tX_neg[tX_neg != -999] plt.figure(figsize=(15, 6), dpi=80) plt.subplot(1, 2, 1) plt.title(cur_feature_names[feature_ind] + f" (Feature #{feature_ind})") plt.hist(tX_pos.T, bins=100, color="r", label="+1") plt.hist(tX_neg.T, bins=100, color="b", label="-1") plt.legend() plt.subplot(1, 2, 2) plt.title(cur_feature_names[feature_ind] + f" (Feature #{feature_ind})") plt.hist(tX_neg.T, bins=100, color="b", label="-1") plt.hist(tX_pos.T, bins=100, color="r", label="+1") plt.legend() interact(plot_feature_hist, feature_ind=widgets.BoundedIntText(value=0, min=0, max=tX.shape[1] - 1, step=1, description='Feature index:', disabled=False), drop_nan=widgets.Checkbox(value=False, description='Drop missing values', disabled=False) ) plt.show()
def _widget_factory(field: FormField): kwargs = { 'description': field.label, 'description_tooltip': field.description } if isinstance(field, IntegerField): widget = ipywidgets.BoundedIntText(value=field.default, min=field.min, max=field.max, **kwargs) elif isinstance(field, DecimalField): widget = ipywidgets.BoundedFloatText(value=field.default, min=field.min, max=field.max, **kwargs) elif isinstance(field, TextField): widget = ipywidgets.Text(placeholder=field.default, **kwargs) elif isinstance(field, BooleanField): widget = ipywidgets.Checkbox(value=field.default, **kwargs) elif isinstance(field, ChoiceField): kwargs.update(options=field.choices) if field.multiple: widget = ipywidgets.SelectMultiple(value=[field.default], **kwargs) elif len(field.choices) <= 5: widget = ipywidgets.RadioButtons(value=field.default, **kwargs) else: widget = ipywidgets.Dropdown(value=field.default, **kwargs) elif isinstance(field, FileField): widget = ipywidgets.FileUpload(accept=field.media_type or field.extension, **kwargs) else: raise TypeError(type(field)) widget.field_name = field.name return widget
def init_elements(self): self.title = ipw.HTML("<h3>Numerical Parameters</h3>") self.maxiter_inner_slider = ipw.IntSlider( min=0, max=100, value=self.params.maxiter_inner, description=r'maxiter_inner' ) self.maxiter_outer_slider = ipw.IntSlider( min=0, max=100, value=self.params.maxiter_outer, description=r'maxiter_outer' ) self.tol_abs_picker = ipw.BoundedFloatText( min=0, max=10, value = self.params.tol_abs, description = 'Tol_Abs' ) self.tol_rel_picker = ipw.BoundedFloatText( min=0, max=10, value = self.params.tol_rel, description = 'Tol_Rel' ) self.num_scatters_spinner = ipw.BoundedIntText( description='# of scatters', min=0, max=10 ) self.gmres_checkbox = ipw.Checkbox( description='Full RTE w/ GMRES' )
def __init__(self, cluster_name='*****@*****.**', remote_path='/N/slate/kadu/', max_job_per_server=500, ssh_connection=None): self.cluster_name = widgets.Text( value=cluster_name, description='SSH Con: ', disabled=True, style=style, ) self.remote_path = widgets.Text( value=remote_path, description='Remote Path: ', style=style, ) self.max_job_per_server = widgets.BoundedIntText( value=max_job_per_server, min=1, max=500, step=1, description='Maximum Job limit: ', style=style, ) self.ssh_connection = ssh_connection self.server_progress = None self.attributes_widgets = widgets.HBox( [self.cluster_name, self.remote_path, self.max_job_per_server])
def display_columns(df): """ Display the columns of df in a SelectMultiple widget and print the code representing the list of selected columns. """ dt = list(df.dtypes.items()) column_display = [f"{c} ({str(t)})" for c, t in dt] column = [c for c, t in dt] w = widgets.SelectMultiple(options=list(zip(column_display, column))) h = widgets.BoundedIntText(value=5, min=1, max=len(df)) def print_columns(columns=None, head=5): if columns is None: return else: inner = map(lambda t: '"' + str(t) + '"', columns) print(f"cols_selected = [{', '.join(inner)}]") print() if len(columns) == 0: return try: display(df[list(columns)].head(head).style) except AttributeError: pass return interactive(print_columns, columns=w, head=h)
def interactive_plot(): if part.dim != 2: print('only works in 2D') return l = widgets.Layout(width='150px') step_text = widgets.BoundedIntText(min=0, max=part.num_frames - 1, value=0, layout=l) step_slider = widgets.IntSlider(min=0, max=part.num_frames - 1, value=0, readout=False, continuous_update=False, layout=l) play_button = widgets.Play(min=0, max=part.num_frames - 1, step=1, interval=500, layout=l) widgets.jslink((step_text, 'value'), (step_slider, 'value')) widgets.jslink((step_text, 'value'), (play_button, 'value')) img = widgets.interactive_output(draw, {'s': step_text}) wid = widgets.HBox( [widgets.VBox([step_text, step_slider, play_button]), img]) display(wid)
def create_navigator_1d(self): import ipywidgets as ipyw x_min, x_max = 0, self.signal.axes_manager.navigation_size - 1 x_text = ipyw.BoundedIntText( value=self.indices[0], description="Coordinate", min=x_min, max=x_max, layout=ipyw.Layout(flex="0 1 auto", width="auto"), ) randomize = ipyw.Button(description="Randomize", layout=ipyw.Layout(flex="0 1 auto", width="auto")) container = ipyw.HBox((x_text, randomize)) def on_index_change(change): self.indices = (x_text.value, ) self.replot_image() def on_randomize(change): from random import randint x = randint(x_min, x_max) x_text.value = x x_text.observe(on_index_change, names="value") randomize.on_click(on_randomize) return container
def _on_change_layers(self, change): self.ok_button = widgets.Button(description="OK") if change["new"] > change["old"]: description = "Insert before which layer?" min_loc = 1 max_loc = len(self.model.structure) - 2 + 1 self.ok_button.on_click(self._increase_layers) elif change["new"] < change["old"]: min_loc = 1 max_loc = (len(self.model.structure) - 2 - (change["old"] - change["new"]) + 1) description = "Remove from which layer?" self.ok_button.on_click(self._decrease_layers) else: return self._varying_layers = True self.w_layers.disabled = True self.do_fit_button.disabled = True self.to_code_button.disabled = True self.save_model_button.disabled = True self.load_model_button.disabled = True self._location = widgets.BoundedIntText( value=min_loc, description=description, min=min_loc, max=max_loc, style={"description_width": "initial"}, ) self.cancel_button = widgets.Button(description="Cancel") self.cancel_button.on_click(self._cancel_layers) self.view_redraw = time.time()
def document_tab(self): ''' Creates tab relating to searching for a working document ''' doc_option_widget = widgets.Dropdown( options=['Investigation', 'Assay', 'Study', 'Data File'], value='Investigation', description='Search Type:', ) #calls a function that handles updates in the drop down menu doc_option_widget.observe(self.change_made_doc_option) self.doc_option_selected = doc_option_widget.value doc_id_search_widget = widgets.BoundedIntText(value=1, description='ID number:', disabled=False, min=1, max=sys.maxsize) #calls a function that handles updates in the int box doc_id_search_widget.observe(self.change_made_ID) self.search_doc_id = doc_id_search_widget.value doc_select_widget_list = [doc_option_widget, doc_id_search_widget] #Formats the widgets into a column doc_select_widgets_container = widgets.VBox( [doc_select_widget_list[0], doc_select_widget_list[1]]) return doc_select_widgets_container
def initialise_notebook(self): ''' initialises the checkboxes for the jupyter notebook ''' style = {'description_width': 'initial'} layout = Layout(flex='2 1 auto', width='auto') a = widgets.Text(placeholder='/path/to/simulation/data', description='Simulation Base Directory:', disabled=False, layout=layout, style=style) b = widgets.Text(placeholder='/path/to/output/directory', description='Output Directory:', disabled=False, layout=layout, style=style) c = widgets.Text(placeholder='Free_energy_summary.csv', description='Free energy file:', disabled=False, layout=layout, style=style) d = widgets.BoundedIntText(value=0, min=0, max=1000000, step=1, description='Number of frames to discard', layout=layout, style=style) e = widgets.Checkbox(False, description='Plot Overlap matrices', layout=layout, style=style) f = widgets.Checkbox( False, description='Subsample data according to statistical inefficiency', layout=layout, style=style) g = widgets.Checkbox(False, description='Generate Network analysis notebook', layout=layout, style=style) ui = widgets.VBox([a, b, c, d, e, f, g], layout=Layout(display='flex', flex_flow='column', align_items='stretch', border='solid', width='100%')) def _func(a, b, c, d, e, f, g): print((a, b, c, d, e, f, g)) self._out = widgets.interactive_output(_func, { 'a': a, 'b': b, 'c': c, 'd': d, 'e': e, 'f': f, 'g': g }) return ui
def select_n2v_parameter(): ### N2V neighbor radius ################### int_n2v_neighborhood_radius = widgets.BoundedIntText(min=1, max=4096, step=1, value=params['n2v_neighborhood_radius']) def on_n2v_neighborhood_radius_change(change): params['n2v_neighborhood_radius'] = change.new int_n2v_neighborhood_radius.observe(on_n2v_neighborhood_radius_change, 'value') ### N2V perc pixel ################### float_n2v_perc_pix = widgets.BoundedFloatText(min=0, max=100, step=0.001, value=params['n2v_perc_pix']) def on_n2v_perc_pix_change(change): params['n2v_perc_pix'] = change.new float_n2v_perc_pix.observe(on_n2v_perc_pix_change, 'value') text_n2v_name = widgets.Text(value=params['name']) def on_text_n2v_name_change(change): params['name'] = change.new text_n2v_name.observe(on_text_n2v_name_change, 'value') ### Combine ############## n2v_parameter = widgets.VBox([ widgets.HBox([widgets.Label('Neighborhood radius', layout={'width':'200px'}), int_n2v_neighborhood_radius]), widgets.HBox([widgets.Label('Percent pixel manipulation', layout={'width':'200px'}), float_n2v_perc_pix]), widgets.HBox([widgets.Label('Model name', layout={'width':'200px'}), text_n2v_name]), ]) display(n2v_parameter)
def __init__(self, map): lonlat = LonLatInput( model=map.center, layout=widgets.Layout(width="initial"), style={"description_width": "initial"}, ) widgets.link((map, "center"), (lonlat, "model")) zoom_label = widgets.Label( value="Zoom:", layout=widgets.Layout(width="initial") ) zoom = widgets.BoundedIntText( value=map.zoom, layout=widgets.Layout(width="3em"), min=map.min_zoom, max=map.max_zoom, step=1, ) widgets.link((map, "zoom"), (zoom, "value")) widgets.link((map, "min_zoom"), (zoom, "min")) widgets.link((map, "max_zoom"), (zoom, "max")) super(PositionController, self).__init__(children=(lonlat, zoom_label, zoom)) self.layout.overflow = "hidden" self.layout.flex = "0 0 auto" self.layout.padding = "2px 0"
def properties(): size = widgets.Text(placeholder='e.g. 2^10 or 1024', description='Size n=', style=style_default, layout=widgets.Layout(width='350px')) polynomial_modulus = widgets.Text( placeholder='e.g. 1033 (int representation)', description='(optional) pol. modulus Q=', style=style_default, layout=widgets.Layout(width='350px', display='none')) is_multilevel = widgets.Checkbox(value=False, description='Multilevel') dimension = widgets.BoundedIntText(value=INITIAL_DIM, min=1, description='Dimension s:', style=style_default, layout=widgets.Layout(width='160px')) interlacing = widgets.BoundedIntText(value=1, min=1, description='Interlacing d:', style=style_default, layout=widgets.Layout(width='160px'), disabled=True) properties_wrapper = widgets.Accordion([ widgets.HBox([ widgets.VBox([size, polynomial_modulus], layout=widgets.Layout(width='370px')), is_multilevel, widgets.VBox([dimension, interlacing], layout=widgets.Layout(width='180px')) ], layout=widgets.Layout(align_items='center', justify_content='space-around')) ]) properties_wrapper.set_title(0, 'Basic Lattice properties') return BaseGUIElement(size=size, is_multilevel=is_multilevel, dimension=dimension, interlacing=interlacing, main=properties_wrapper, polynomial_modulus=polynomial_modulus, _callbacks={ 'dimension': change_dimension, 'interlacing': change_interlacing, 'is_multilevel': change_multilevel })