def print_matrix(m: Union[np.ndarray, BaseGraph, Circuit]) -> 'Label': """Returns a Label() Jupyter widget that displays a pretty latex representation of the given matrix. Instead of a matrix, can also give a Circuit or Graph. """ from ipywidgets import Label if isinstance(m, BaseGraph) or isinstance(m, Circuit): m = m.to_matrix() return Label(matrix_to_latex(m))
def _make_slider_input(self, label, description, min_val, max_val) -> HBox: label_widget = Label(description) slider = widgets.IntSlider(continuous_update=True, min=min_val, max=max_val, readout=False) self._input[label] = IntText(continuous_update=True, layout={"width": "80px"}) widgets.link((self._input[label], "value"), (slider, "value")) return HBox([label_widget, slider, self._input[label]])
def __init__(self, attr, func, **kwargs): self._attr = attr self.f = func self.label = Label(value=attr) widget = kwargs.get('ui', None) if widget is None: widget = FloatSlider(min=0, max=1, step=0.01) kwargs['ui'] = widget self.box = HBox([self.label, widget]) super().__init__(func=self.filter, **kwargs)
def setup_toposim_widgets(self): self.toposim_labels = { 'kf': Label(value='River incision coefficient'), 'g': Label(value='River transport coefficient'), 'kd': Label(value='Hillslope diffusivity'), 'p': Label(value='Flow partition exponent'), 'u': Label(value='Plateau uplift rate') } self.toposim_widgets = { 'kf': FloatSlider(value=1e-4, min=5e-5, max=3e-4, step=1e-5, readout_format='.1e'), 'g': FloatSlider(value=1., min=0.5, max=1.5, step=0.1, readout_format='.1f'), 'kd': FloatSlider( value=0.02, min=0., max=0.1, step=0.01, ), 'p': FloatSlider(value=1., min=0., max=10., step=0.2, readout_format='.1f'), 'u': FloatSlider(value=0., min=0., max=1e-3, step=1e-5, readout_format='.1e') }
def __init__(self): self.mp4_zip_file = "cells_mp4.zip" self.mp4_file = "cells.mp4" self.instructions = Label("After a simulation completes, generate a video of cells (from SVG files). Does not work for cached results yet.") self.feedback = Label(" ") # self.feedback.value = "Converting all svg to jpg..." self.gen_button = Button( description='Generate video', button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Generate a MP4 video of cells', ) self.gen_button.disabled = True self.gen_button.on_click(self.gen_button_cb) fps_style = {'description_width': '35%'} fps_layout = {'width': '85px'} # tooltip='frames per sec', -- tooltip not available for *Text ! self.fps = BoundedIntText(description="fps=", value=5, min=1, max=30, step=1, style=fps_style, layout=fps_layout) size_style = {'description_width': '50%'} size_layout = {'width': '150px'} self.size = BoundedIntText(description="w,h(pixels)=", value=500, min=250, max=1500, step=10, disabled=False, tooltip='width, height of video', style=size_style, layout=size_layout) self.video = HTML( value="", placeholder='', description='', layout= Layout(visibility='hidden') ) if (hublib_flag): self.download_mp4_button = Download(self.mp4_zip_file, style='success', icon='cloud-download', tooltip='Download mp4 (you need to allow pop-ups in your browser)') self.download_mp4_button.w.disabled = True self.tab = VBox([self.instructions, HBox([ self.gen_button, self.fps, self.size, self.feedback, self.download_mp4_button.w]), self.video]) else: self.tab = VBox([self.instructions, HBox([self.gen_button, self.fps, self.size, self.feedback]), self.video])
def build_ui(self): widget_dark_mode() disable_widget_scroll() ui = VBox([ Label("Plot Controls"), self.build_ui_knobs(), self.build_ui_controls() ]) self.ui = ui return ui
def generate_widgets(self): self.button_eem_integration.on_click( self.regional_integration_interact) integration_items = [ ipywidgets.Box([ Label(value='Excitation wavelength range: ', style={'description_width': 'initial'}), self.ex_boundary_left, Label(value='to', style={'description_width': 'initial'}), self.ex_boundary_right ]), ipywidgets.Box([ Label(value='Emission wavelength range: ', style={'description_width': 'initial'}), self.em_boundary_left, Label(value='to', style={'description_width': 'initial'}), self.em_boundary_right ]), self.integration_form, self.button_eem_integration ] return integration_items
def __init__(self, title, function, length, play_rate=0.5): self.player = _Player(self, play_rate) self.player.start() self.title = title self.function = function self.length = length self.output = Output() self.position_text = IntText(value=0, layout=Layout(width="100%")) self.total_text = Label(value="of %s" % self.length, layout=Layout(width="100px")) controls = self.make_controls() super().__init__([controls, self.output])
def _number_box(self): """ See comments for the special character box above. """ explanation = Label('Check to include 1 to 3 numbers ' 'in the password:'******'description_width': '0px'}) link((check, 'value'), (self.model, 'include_numbers')) container = HBox(description='Number checkbox', children=[explanation, check]) return container
def run_and_display(A): # Create input text boxes and buttons for users gna_hh = FloatText(value=0, layout=Layout(width='100px')) gk_hh = FloatText(value=0, layout=Layout(width='100px')) gl_hh = FloatText(value=2.0e-5, layout=Layout(width='100px')) cur_inj = FloatText(value=1, layout=Layout(width='100px')) run_button = Button(description="Run Model", button_style='info') clear_button = Button(description="Clear Output", button_style='warning') # Use a form to hold the Labels and Input Boxes form_items = [ Box([Label(value='Leak Channel (gl_hh)', layout=Layout(width='195px')), gl_hh]), Box([Label(value='Sodium Channel (gnabar_hh)', layout=Layout(width='195px')), gna_hh]), Box([Label(value='Potassium Channel (gkbar_hh)', layout=Layout(width='195px')), gk_hh]), Box([Label(value='Current Injection Amplitude (nA)', layout=Layout(width='195px')), cur_inj]), ] # Define the parameters of the form_items form = Box(form_items, layout=Layout( display='flex', flex_flow='column', align_items='initial', width='295px' )) # Display form and buttons display(form, HBox([run_button, clear_button])) #display(HBox([f])) plt.figure # Define functions that run when the user clicks a button def run_button_clicked(b): t,v=run_simulation(gl_hh.value, gna_hh.value, gk_hh.value, cur_inj.value) plt.plot(t,v) plt.show() def clear_button_clicked(b): clear_output() run_button.on_click(run_button_clicked) clear_button.on_click(clear_button_clicked)
def widget_box(): source = int(config.get_value(['set', 'data_source'])) sources = RadioButtons(options=[ ("JRC RESTful API.", 0), ("Direct access to database and object storage.", 1) ], value=source, layout={'width': 'max-content'}) sources_box = Box([Label(value="Data sources:"), sources]) info_api = Label("RESTful API Settings.") info_direct = Label("Direct access settings") view_options = VBox([info_direct]) if source == 0: view_options.children = [info_api, rest_api()] elif source == 1: view_options.children = [info_direct, direct()] def on_source_change(change): view_options.children = [] if sources.value == 0: view_options.children = [info_api, rest_api()] elif sources.value == 1: view_options.children = [info_direct, direct()] config.update(['set', 'data_source'], str(sources.value)) sources.observe(on_source_change, 'value') wbox_sources = VBox([sources_box, view_options], layout=Layout(border='1px solid black')) info_general = Label(value="General settings:") wbox = VBox([wbox_sources, info_general, settings.widget_box()]) return wbox
def proc(): l_connec = Label("1. Connect to database and object storage.") l_create = Label("2. Create the essential CbM tables. The parcels table name will be added as prefix.") l_upload = Label("3. Upload .shp, with all the required files (.shp, .cpg, .dbf, .prj, .shx).") l_carddb = Label("4. Add CARD metadata to databse tabel 'xx_dias_catalogue'.") l_extrac = Label("5. Run parcel extraction routines.") path_data = f"{config.get_value(['paths', 'temp'])}proc/" # Connect db_select = Dropdown( options=[db for db in config.get_value(['db'])], description='Configure:', disabled=True, layout=Layout(width='140px') ) db_config = Button( value=False, disabled=False, button_style='info', tooltip='Configure db connection.', icon='cogs', layout=Layout(width='40px') ) db_box = HBox([db_select, db_config]) db_conf_box = HBox([]) @db_config.on_click def db_config_on_click(b): if db_conf_box.children == (): db_conf_box.children = [settings.direct_conn()] else: db_conf_box.children = () wbox = VBox([l_connec, VBox([db_box, db_conf_box]), l_create, proc_func.create_tables(), l_upload, proc_func.upload_shp(path_data), l_carddb, proc_card2db.dias_cat(), l_extrac, proc_func.extraction()]) return wbox
def configure_controllers(self): from ipywidgets import (IntSlider, interactive, Play, VBox, HBox, Label, jslink) super().configure_controllers() # orientation self.controllers["orientation"] = interactive( self.set_orientation, orientation=self.time_viewer.orientation, ) # smoothing self.sliders["smoothing"] = IntSlider( value=self.brain._data['smoothing_steps'], min=self.time_viewer.default_smoothing_range[0], max=self.time_viewer.default_smoothing_range[1], continuous_update=False) self.controllers["smoothing"] = VBox([ Label(value='Smoothing steps'), interactive(self.brain.set_data_smoothing, n_steps=self.sliders["smoothing"]) ]) # time slider max_time = len(self.brain._data['time']) - 1 if max_time >= 1: time_player = Play(value=self.brain._data['time_idx'], min=0, max=max_time, continuous_update=False) time_slider = IntSlider( min=0, max=max_time, ) jslink((time_player, 'value'), (time_slider, 'value')) time_slider.observe(self.set_time_point, 'value') self.controllers["time"] = VBox([ HBox([ Label(value='Select time point'), time_player, ]), time_slider, ]) self.sliders["time"] = time_slider
def __init__(self, title: str, max: Union[int, float], min: Union[int, float] = 0, **klsargs) -> None: self.data = self.CLASS(min=min, max=max, layout=self.left_layout, description=title, **klsargs) self.label = Label(value='Starting', layout=self.right_layout) self.hbox = HBox([self.data, self.label], layout=self.box_layout)
def __create_loss_tab_for_skeleton(self, index: int) -> HBox: joint_loss_labels: List[Label] = [ Label(value='test') for _ in range(self.joint_set.number_of_joints) ] joint_names: VBox = VBox( children=[Label(value=name) for name in self.joint_set.names]) joint_losses: VBox = VBox(children=joint_loss_labels) self.joint_loss_labels.append(joint_loss_labels) statistics_labels: VBox = VBox(children=[ Label(value='All losses:'), Label(value='Joint with min loss:'), Label(value='Joint with max loss:') ]) skeleton_values: VBox = VBox(children=[ self.all_joint_loss_labels[index], self.min_joint_loss_name_labels[index], self.max_joint_loss_name_labels[index] ]) return HBox(children=[ joint_names, joint_losses, statistics_labels, skeleton_values ])
def __init__(self, name=None): self.editable = name is None self.checkbox = Checkbox(value=True, layout=_checkbox_layout, indent=False) self.true_name = self.summary = self.last_textfield = None if self.editable: self.text_field = Text(layout=_label_layout) else: self.text_field = Label(value=name, layout=_label_layout) self.remove_button = Button( description='Remove', disabled=False, button_style= 'danger', # 'success', 'info', 'warning', 'danger' or '' layout=_remove_layout, ) self.additional_info = Label("", layout=_additional_info_layout) self.ambiguity_dropdown = None
def __init__(self, obj): self.value = obj children = [] for p in get_properties(obj): val = getattr(obj, p.name).__call__() children.append(Label(p.prop_label)) children.append(ExplorableValue(val)) #children.append(Label("?")) super(ExplorerProperties, self).__init__( (GridBox(children, layout=Layout(grid_template_columns='25% 75%')),), layout=Layout(border='1px solid red') )
def showWords(self, filters): rows = [self.title] for type_name in filters.keys(): rows.append(Label(value=type_name + ':')) # only show single word selections = ToggleButtonsMultiSelectionInBox( options=[word for word in filters[type_name].to_list() if ' ' not in word]) self.to_we_ext_filters[type_name] = selections rows.append(selections) rows += (self.addSeparator()) rows += [self.addPreviousNext(self.show_previous, self.show_next)] return rows
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='tumor_radius', disabled=True, layout=name_button_layout) param_name1.style.button_color = 'lightgreen' self.tumor_radius = FloatText( value=750, step=10, style=style, layout=widget_layout) param_name2 = Button(description='enable_pH_effects', disabled=True, layout=name_button_layout) param_name2.style.button_color = 'tan' self.enable_pH_effects = Checkbox( value=False, disabled=True, style=style, layout=widget_layout) units_button1 = Button(description='micron', disabled=True, layout=units_button_layout) units_button1.style.button_color = 'lightgreen' units_button2 = Button(description='', disabled=True, layout=units_button_layout) units_button2.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 in this version)', disabled=True, layout=desc_button_layout) desc_button2.style.button_color = 'tan' row1 = [param_name1, self.tumor_radius, units_button1, desc_button1] row2 = [param_name2, self.enable_pH_effects, units_button2, desc_button2] 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) self.tab = VBox([ box1, box2, ])
def four_plot_widget(): # generate the 6 necessary sliders S_m = widgets.IntSlider(value=20, min=0, max=100, step=5) S_b = widgets.IntSlider(value=200, min=0, max=1000, step=50) D_m = widgets.IntSlider(value=-20, min=-100, max=0, step=5) D_b = widgets.IntSlider(value=1800, min=1000, max=2000, step=50) World_Price = widgets.IntSlider(value=400, min=0, max=1000, step=50) Tariff = widgets.IntSlider(value=400, min=0, max=1000, step=50) # generate the widget out = interactive_output(all_four_plots, {"S_m":S_m, "S_b":S_b, "D_m":D_m, "D_b":D_b, "World_Price":World_Price, "Tariff":Tariff}) labels = ["Supply Slope", "Supply Intercept", "Demand Slope", "Demand Intercept", "World Price", "Tariff"] sliders = [S_m, S_b, D_m, D_b, World_Price, Tariff] pre_boxes = [[Label(l) for l in labels[0:3]], sliders[0:3], [Label(l) for l in labels[3:]], sliders[3:]] vboxes = [VBox(box) for box in pre_boxes] ui = HBox(vboxes) # display the widget display(ui, out)
def _special_char_box(self): """ The amount of space provided as a description in a ToggleButtons or a RadioButton. This makes a compound widget that has a longer description over some buttons. Note that the linking to the model is handled here so that the calling code, __init__ does not need to know about the details of this widget. """ explanation1 = Label('Select one of the groups of special characters ' 'below.') explanation2 = Label('From 1 to 3 special characters will be included.') special = ToggleButtons(options=SPECIAL_GROUPS) special.layout.margin = '0 0 0 20px' link((special, 'value'), (self.model, 'special_character_groups')) container = VBox(description='Special character', children=[explanation1, explanation2, special]) container.layout.align_items = 'flex-start' return container
def __init__(self, ref, attr, func, widget=None): self._attr = None self.monitored = None self.func = func self.widget = widget if widget is not None else FloatSlider( min=0, max=1, step=0.01) self.value = self.widget.value self.label = Label() super().__init__(ref) self.attr = attr self.widget.observe(self.update, names='value') self.update(None)
def display_for_input(self) -> 'OptionsForm': """Displays the widgets to take user inputs.""" from IPython.display import display from ipywidgets import GridBox from ipywidgets import Label from ipywidgets import Layout from ipywidgets import Text widgets = [] for entry in self.entries: text_label = Label(value=entry.label) text_input = entry.input if entry.input else Text( value=entry.default if entry.default else '') text_help = Label(value=entry.help) entry.input = text_input widgets.append(text_label) widgets.append(text_input) widgets.append(text_help) grid = GridBox(widgets, layout=Layout(grid_template_columns='1fr 2fr 6fr')) display(grid) self.display_actions() return self
def __init__(self, label, width, value='INDU Index'): ''' Summary: A text box with a label on top. Args: label (str): the label on top of the text box. width (int): the width of the text box and the label. init_value (str): the initial value in the text box. ''' self.label = Label(value=label, layout=Layout(width='{w}px'.format(w=width))) self.text = Text(value=value, layout=Layout(width='{w}px'.format(w=width))) super().__init__(children=[self.label, self.text], layout=Layout(margin='0 0 10px 0'))
def __get_widgets(self, chromosomes, frame=None): if frame is None: frame = HTML() widgets = OrderedDict([ ("chromosomes_list", Dropdown(options=chromosomes)), ("left_button", Button(icon="arrow-left")), ("right_button", Button(icon="arrow-right")), ("zoom_out_button", Button(icon="search-minus")), ("zoom_in_button", Button(icon="search-plus")), ("range_textbox", Text(placeholder="genome range like: 'chr1:10000-20000'")), ("go_button", Button(description="Go")), ("range_slider", IntRangeSlider(continuous_update=False, readout=False, layout=Layout(width='90%'))), ("range_min_label", Label("", layout=Layout(width='2%'))), ("range_max_label", Label("", layout=Layout(width='20%'))), ("auto_check_box", Checkbox(value=True, description="Auto Range", layout=Layout(width='120px'), style={'description_width': 'initial'})), ("track_min_val_float_text", FloatText(value=0, description="track's min value:", step=0.5, disabled=True, layout=Layout(width='30%'), style={'description_width': 'initial'})), ("track_max_val_float_text", FloatText(value=10, description="track's max value:", step=0.5, disabled=True, layout=Layout(width='30%'), style={'description_width': 'initial'})), ("frame", frame) ]) return widgets
def __init__( self, training_length=None, update_interval=100, ): self._training_length = training_length self._status_template = None self._update_interval = update_interval self._recent_timing = [] self.desc_total = Label("Total:") self.desc_total.layout.width = "100px" self.pbar_total = FloatProgress(min=0, max=1.0, bar_style="success") self.text_total = Label("0%") self.desc_total.layout.padding = "5px" self.text_total.layout.padding = "5px" display(HBox([self.desc_total, self.pbar_total, self.text_total])) self.desc_epoch = Label("This epoch:") self.desc_epoch.layout.width = "100px" self.pbar_epoch = FloatProgress(min=0, max=1.0) self.text_epoch = Label("0%") self.desc_epoch.layout.padding = "5px" self.text_epoch.layout.padding = "5px" display(HBox([self.desc_epoch, self.pbar_epoch, self.text_epoch])) self.epoch_report = Label("") self.time_report = Label("") self.epoch_report.layout.padding = "5px" self.time_report.layout.padding = "5px" display(VBox([self.epoch_report, self.time_report]))
def __init__(self, pred_skeletons: np.ndarray, gt_skeletons: np.ndarray, joint_set: JointSet, loss: Callable[[np.ndarray, np.ndarray], np.ndarray], loss_precision: int = 3, video_player: Optional[Play] = None): if video_player is not None: self.is_video: bool = True self.pred_skeletons: np.ndarray = np.swapaxes(pred_skeletons, 0, 1) self.gt_skeletons: np.ndarray = np.swapaxes(gt_skeletons, 0, 1) # Fields related to playing videos self.video_player = video_player self.min_loss_frame_index: int = 0 self.max_loss_frame_index: int = 0 else: self.is_video: bool = False self.pred_skeletons: np.ndarray = np.swapaxes( pred_skeletons[np.newaxis], 0, 1) self.gt_skeletons: np.ndarray = np.swapaxes( gt_skeletons[np.newaxis], 0, 1) self.loss_precision: int = loss_precision self.loss_value_format: str = '{:.' + str(self.loss_precision) + 'f}' self.joint_set: JointSet = joint_set self.number_of_skeletons: int = self.pred_skeletons.shape[0] # Joint loss related fields self.joint_losses: np.ndarray = loss(self.pred_skeletons, self.gt_skeletons) self.min_joint_loss_indices = np.argmin(self.joint_losses, axis=-1) self.max_joint_loss_indices = np.argmax(self.joint_losses, axis=-1) # Joint loss related labels self.joint_loss_labels: List[List[Label]] = [] self.all_joint_loss_labels: List[Label] = [ Label(value='test') for _ in range(self.number_of_skeletons) ] self.min_joint_loss_name_labels: List[Label] = [ Label(value='test') for _ in range(self.number_of_skeletons) ] self.max_joint_loss_name_labels: List[Label] = [ Label(value='test') for _ in range(self.number_of_skeletons) ] # Skeleton loss related fields self.skeleton_losses = np.sum(self.joint_losses, axis=-1) self.all_losses = np.sum(self.skeleton_losses, axis=0) self.min_skeleton_loss_indices = np.argmin(self.skeleton_losses, axis=0) + 1 self.max_skeleton_loss_indices = np.argmax(self.skeleton_losses, axis=0) + 1 # Skeleton loss related labels self.skeleton_loss_labels: List[Label] = [ Label(value='test') for _ in range(self.number_of_skeletons) ] self.all_loss_label: Label = Label(value='test') self.min_loss_index_label: Label = Label(value='test') self.max_loss_index_label: Label = Label(value='test')
def button_creator(client_list): client_items = [Button(layout=item_layout, description=str(client), button_style='info') for client in client_list] box_1 = HBox(client_items[0:9]) box_2 = HBox(client_items[9:18]) box_3 = HBox(client_items[18:27]) box_4 = HBox(client_items[27:36]) box_5 = HBox(client_items[36:45]) box_6 = HBox(client_items[45:54]) boxes = [Label('Choose client:'),box_1, box_2,box_3,box_4,box_5,box_6] for button in client_items: button.on_click(on_client_clicked) client_updates=VBox(boxes) return(client_updates)
def setup_jupyter(self): """ Sets up elements on the page for use with a Jupyter notebook. """ self._label = Label('Move the cursor over the cell and use the left and right arrow keys to navigate') self._hbox = HBox() self._html = HTML('<h3>Label position?</h3>') self._inner = VBox() self._vbox = VBox([self._html, self._inner, self._label]) self._event = Event(source=self._vbox, watched_events=['keydown']) self._event.on_dom_event(self.handle_event) return self
def __create_frame_jump_buttons( self, statistics_labels_column: List[Label], statistics_values_column: List[Label]) -> List[Button]: jump_buttons: List[Button] = [] if self.is_video: self.min_loss_frame_index: int = np.argmin(self.all_losses) min_loss_jump_button: Button = Button(description='Min loss frame') min_loss_jump_button.on_click(self.__jump_to_min_loss_frame) self.max_loss_frame_index: int = np.argmax(self.all_losses) max_loss_jump_button: Button = Button(description='Max loss frame') max_loss_jump_button.on_click(self.__jump_to_max_loss_frame) statistics_labels_column.append( Label(value='Min loss frame index:')) statistics_labels_column.append( Label(value='Max loss frame index:')) statistics_values_column.append( Label(value=str(self.min_loss_frame_index))) statistics_values_column.append( Label(value=str(self.max_loss_frame_index))) jump_buttons.append(min_loss_jump_button) jump_buttons.append(max_loss_jump_button) return jump_buttons