def __init__(self, data, dimensions, **kwargs): GluePlotly.__init__(self, data, dimensions, **kwargs) self.DefaultLayoutTitles("", self.dimensions[0], ' '.join([self.dimensions[i] for i in range(1,len(self.dimensions))])) self.DefaultLayoutScales("linear","linear"); self.options['line_width'] = IntText(description = 'Lines width:', value = 1) self.options['line_width'].observe(lambda v:self.UpdateTraces({'line.width':v['new']}), names='value') self.options['marker_size'] = IntText(description = 'Markers size:', value = 3) self.options['marker_size'].observe(lambda v:self.UpdateTraces({'marker.size':v['new']}), names='value') self.updateRender()
def _make_button_export_image(self): slider_factor = IntSlider(value=4, min=1, max=10, description='scale') checkbox_antialias = Checkbox(value=True, description='antialias') checkbox_trim = Checkbox(value=False, description='trim') checkbox_transparent = Checkbox(value=False, description='transparent') filename_text = Text(value='Screenshot', description='Filename') delay_text = FloatText(value=1, description='delay (s)', tooltip='hello') start_text, stop_text, step_text = (IntText(value=0, description='start'), IntText(value=self._view.count, description='stop'), IntText(value=1, description='step')) start_text.layout.max_width = stop_text.layout.max_width = step_text.layout.max_width \ = filename_text.layout.max_width = delay_text.layout.max_width = default.DEFAULT_TEXT_WIDTH button_movie_images = Button(description='Export Images') def download_image(filename): self._view.download_image(factor=slider_factor.value, antialias=checkbox_antialias.value, trim=checkbox_trim.value, transparent=checkbox_transparent.value, filename=filename) @button_movie_images.on_click def on_click_images(button_movie_images): for i in range(start_text.value, stop_text.value, step_text.value): self._view.frame = i time.sleep(delay_text.value) download_image(filename=filename_text.value + str(i)) time.sleep(delay_text.value) vbox = VBox([ button_movie_images, start_text, stop_text, step_text, delay_text, filename_text, slider_factor, checkbox_antialias, checkbox_trim, checkbox_transparent, ]) form_items = _relayout(vbox, make_form_item_layout()) form = Box(form_items, layout=_make_box_layout()) # form = _relayout_master(vbox) return form
def display_widget(waveforms, plot_params, location, mode, *args): """ This function creates and displays the widget for selecting the waveform or cluster index to be displayed and the widget that displays the waveforms or mean waveforms for the clusters across multiple channels for this index. Inputs: waveforms: Numpy array containing the waveforms; in the form of (N_events x N_electrodes x N_spike_time_range_steps ) plot_params: see above mapping: Mapping attribute in the h5 data params: see above mode: 'waveforms' for displaying individual waveforms by index, 'clusters' for displaying the mean waveform of a cluster """ if mode[0] == 'waveforms': #Widget for selecting waveform or cluster index selectionWidget = IntText(min=0, max=len(waveforms), step=1, value=0, description="Waveforms to be displayed", continuous_update=True) #Widget for plotting selected waveforms or mean waveforms widget = interact(plot_waveforms, index=selectionWidget, waveforms=fixed(waveforms), plot_params=fixed(plot_params), location=fixed(location)) elif mode[0] == 'clusters': #Widget for selecting waveform or cluster index selectionWidget = IntText( min=0, max=len(waveforms), step=1, value=0, description="Cluster for which the waveforms to be displayed", continuous_update=True) #Widget for plotting selected waveforms or mean waveforms widget = interact(plot_mean_cluster_waveforms, cluster=selectionWidget, clusters=fixed(args[0]), waveforms=fixed(waveforms), plot_params=fixed(plot_params), location=fixed(location), mode=mode[1]) else: raise ValueError( 'Please select a valid mode for display ("waveforms" or "clusters")' ) display(selectionWidget) display(widget)
def DefaultMargins(self, l=50, r=0, b=50, t=30): self.margins['left'] = IntText(description='Left:', value=l) self.margins['left'].observe( lambda v: self.UpdateLayout({'margin.l': v['new']}), names='value') self.margins['right'] = IntText(description='Right:', value=r) self.margins['right'].observe( lambda v: self.UpdateLayout({'margin.r': v['new']}), names='value') self.margins['bottom'] = IntText(description='Bottom:', value=b) self.margins['bottom'].observe( lambda v: self.UpdateLayout({'margin.b': v['new']}), names='value') self.margins['top'] = IntText(description='Top:', value=t) self.margins['top'].observe( lambda v: self.UpdateLayout({'margin.t': v['new']}), names='value')
def __init__(self, data, dimensions, **kwargs): GluePlotly.__init__(self, data, dimensions, **kwargs) self.DefaultLayoutTitles("", self.dimensions[0], self.dimensions[1]) self.DefaultLayoutScales("linear","linear"); self.options['line_width'] = IntText(description = 'Lines width:', value = 1) self.options['line_width'].observe(lambda v:self.UpdateTraces({'line.width':v['new']}), names='value') self.options['marker_size'] = IntText(description = 'Markers size:', value = 3) self.options['marker_size'].observe(lambda v:self.UpdateTraces({'marker.size':v['new'],'selected.marker.size':v['new'],'unselected.marker.size':v['new']}), names='value') self.options['ncontours'] = IntText(description = '# Contours:', value = 1) self.options['ncontours'].observe(lambda v:self.UpdateTraces({'ncontours':v['new']}), names='value') self.options['nbins'] = IntText(description = 'Number of Bins', value = 40) self.options['nbins'].observe(lambda v:self.updateRender(), names='value') self.updateRender()
def __init__(self, layer_state): self.state = layer_state self.widget_visible = Checkbox(description='visible', value=self.state.visible) link((self.state, 'visible'), (self.widget_visible, 'value')) self.widget_color = ColorPicker(description='color') link((self.state, 'color'), (self.widget_color, 'value'), color2hex) self.widget_linewidth = IntText(description='line width') link((self.state, 'linewidth'), (self.widget_linewidth, 'value')) self.widget_attribute = LinkedDropdown(self.state, 'attribute', label='attribute') if self.state.v_min is None: self.state.v_min = 0 self.widget_v_min = FloatText(description='vmin') link((self.state, 'v_min'), (self.widget_v_min, 'value')) if self.state.v_max is None: self.state.v_max = 1 self.widget_v_max = FloatText(description='vmax') link((self.state, 'v_max'), (self.widget_v_max, 'value')) self.widget_percentile = LinkedDropdown(self.state, 'percentile', label='percentile') super().__init__([self.widget_visible, self.widget_color, self.widget_linewidth, self.widget_attribute, self.widget_v_min, self.widget_v_max, self.widget_percentile])
def test_widget_utils(): box = HBox() i0 = IntText() i0._ngl_name = 'i0' i1 = IntText() i1._ngl_name = 'i1' box.children = [i0, i1] assert i0 is widget_utils.get_widget_by_name(box, 'i0') assert i1 is widget_utils.get_widget_by_name(box, 'i1') box.children = [i1, i0] assert i0 is widget_utils.get_widget_by_name(box, 'i0') assert i1 is widget_utils.get_widget_by_name(box, 'i1') nt.assert_equal(widget_utils.get_widget_by_name(box, 'i100'), None)
def __init__(self, grid_item=ImageButton, image_width=150, image_height=150, n_rows=3, n_cols=3, display_label=False): self.image_width = image_width self.image_height = image_height self.n_rows = n_rows self.n_cols = n_cols self._screen_im_number = IntText(value=n_rows * n_cols, description='screen_image_number', disabled=False) self._labels = [grid_item(display_label=display_label, image_width='%dpx' % self.image_width, image_height='%dpx' % self.image_height) for _ in range(self._screen_im_number.value)] self.callback = None gap = 40 if display_label else 15 centered_settings = { 'grid_template_columns': " ".join(["%dpx" % (self.image_width + gap) for i in range(self.n_cols)]), 'grid_template_rows': " ".join(["%dpx" % (self.image_height + gap) for i in range(self.n_rows)]), 'justify_content': 'center', 'align_content': 'space-around' } super().__init__(children=self._labels, layout=Layout(**centered_settings))
def interact_plot_inversion(self, maxIter=30): interact( self.plot_inversion, mode=RadioButtons( description="mode", options=["Run", "Explore"], value="Run" ), maxIter=IntText(value=maxIter), m0=FloatSlider( min=-2, max=2, step=0.05, value=0.0, continuous_update=False ), mref=FloatSlider( min=-2, max=2, step=0.05, value=0.0, continuous_update=False ), percentage=FloatText(value=self.percentage), floor=FloatText(value=self.floor), chifact=FloatText(value=1.0), beta0_ratio=FloatText(value=100), coolingFactor=FloatSlider( min=0.1, max=10, step=1, value=2, continuous_update=False ), coolingRate=IntSlider( min=1, max=10, step=1, value=1, continuous_update=False ), alpha_s=FloatText(value=1e-10), alpha_x=FloatText(value=0), target=False, option=ToggleButtons(options=["misfit", "tikhonov"], value="misfit"), i_iteration=IntSlider( min=0, max=maxIter, step=1, value=0, continuous_update=False ), )
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.net.dataset.train_inputs) - 1) if len(self.net.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%')) if self.net.config["dashboard.dataset"] == "Train": length = len(self.net.dataset.train_inputs) else: length = len(self.net.dataset.test_inputs) self.total_text = Label(value="of %s" % length, layout=Layout(width="100px")) self.zoom_slider = FloatSlider(description="Zoom", continuous_update=False, min=0, max=1.0, style={"description_width": 'initial'}, layout=Layout(width="65%"), value=self.net.config["svg_scale"] if self.net.config["svg_scale"] is not None else 0.5) ## 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 tradeoffs_setup(lock=True): box1 = IntText(value = 20, description='Euler steps') if lock: box2 = BoundedFloatText(value = 2.2, description='predict value', max=6) else: box2 = BoundedFloatText(value = 2.2, description='predict value') return box1, box2
def __init__(self, data, dimensions, **kwargs): GluePlotly.__init__(self, data, dimensions, **kwargs) self.options['title'] = Text(description='Title:', value="") self.options['title'].observe( lambda v: self.UpdateLayout({'title': v['new']}), names='value') self.options['xaxis'] = Text(description='Xaxis Title:', value=self.dimensions[0]) self.options['xaxis'].observe( lambda v: self.UpdateLayout({'scene.xaxis.title': v['new']}), names='value') self.options['yaxis'] = Text(description='Yaxis Title:', value=self.dimensions[1]) self.options['yaxis'].observe( lambda v: self.UpdateLayout({'scene.yaxis.title': v['new']}), names='value') self.options['zaxis'] = Text(description='Zaxis Title:', value=self.dimensions[2]) self.options['zaxis'].observe( lambda v: self.UpdateLayout({'scene.zaxis.title': v['new']}), names='value') self.options['marker_size'] = IntText(description='Markers size:', value=3) self.options['marker_size'].observe( lambda v: self.UpdateTraces({'marker.size': v['new']}), names='value') self.updateRender()
def __init__(self, net, width="95%", height="550px", play_rate=0.5): self._ignore_layer_updates = False self.player = _Player(self, play_rate) self.player.start() self.net = net r = random.randint(1, 1000000) self.class_id = "picture-dashboard-%s-%s" % (self.net.name, r) self._width = width self._height = height ## Global widgets: style = {"description_width": "initial"} self.feature_columns = IntText(description="Feature columns:", value=self.net.config["dashboard.features.columns"], min=0, max=1024, style=style) self.feature_scale = FloatText(description="Feature scale:", value=self.net.config["dashboard.features.scale"], min=0.1, max=10, style=style) self.feature_columns.observe(self.regenerate, names='value') self.feature_scale.observe(self.regenerate, names='value') ## Hack to center SVG as justify-content is broken: self.net_svg = HTML(value="""<p style="text-align:center">%s</p>""" % ("",), layout=Layout( width=self._width, overflow_x='auto', overflow_y="auto", justify_content="center")) # Make controls first: self.output = Output() controls = self.make_controls() config = self.make_config() super().__init__([config, controls, self.net_svg, self.output])
def interact_plot_inversion(self, n_beta=81): interact( self.plot_inversion, mode=RadioButtons( description="mode", options=["Run", "Explore"], value="Run" ), mref=FloatSlider( min=-2, max=2, step=0.05, value=0.0, continuous_update=False ), percentage=FloatText(value=self.percentage), floor=FloatText(value=self.floor), beta_min=FloatText(value=1e-3), beta_max=FloatText(value=1e5), n_beta=IntText(value=n_beta, min=10, max=100), alpha_s=FloatText(value=1.0), alpha_x=FloatText(value=0), option=ToggleButtons(options=["misfit", "tikhonov"], value="tikhonov"), data_option=ToggleButtons( options=["obs/pred", "misfit"], value="obs/pred", description="data" ), scale=ToggleButtons(options=["linear", "log"], value="log"), i_beta=IntSlider( min=0, max=n_beta - 1, step=1, value=0, continuous_update=False ), chifact=FloatText(value=1.0), )
def _make_slider_input(self, label, description, min_val, max_val): 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 process(opt, key): if isinstance(opt, str): return Text(opt, description=key.replace("_", "-")) if isinstance(opt, float): return FloatText(opt, description=key.replace("_", "-")) if isinstance(opt, int): return IntText(opt, description=key.replace("_", "-")) return opt
def app(self): self._out = Output(layout=Layout(width="{}px".format(self.width+2), height="{}px".format(self.height+2), border='1px solid black')) sld_frame = IntSlider(description="Frame", min=0, max=self.num_frames-1, step=1, value=self.active_frame, layout=Layout(width="{}px".format(self.width))) btn_play = Play(description="Animate", min=0, max=self.num_frames-1, step=1, value=self.active_frame, interval=200) btn_fwrd = Button(description="▶▶", layout=Layout(width="auto")) btn_revs = Button(description="◀◀", layout=Layout(width="auto")) drd_model = Dropdown(description="Model", options=list(range(self.num_models)), value=self.active_model) drd_style = Dropdown(description="Style", options=['sticks', 'ballsticks', 'vanderwaals', 'default'], value='default') int_delay = IntText(description="Delay (ms)", value=100, layout=Layout(max_width="150px")) int_step = BoundedIntText(description="Step", value=1, min=1, max=self.num_frames, layout=Layout(max_width="150px")) ui = VBox([HBox([drd_model, drd_style]), self._out, HBox([VBox([int_step, int_delay]), VBox([sld_frame, HBox([btn_revs, btn_play, btn_fwrd])], layout=Layout(align_items='center'))])], layout=Layout(align_items='center')) def frame_fwrd(btn): if (sld_frame.value < sld_frame.max): sld_frame.value += 1 def frame_revs(btn): if (sld_frame.value > sld_frame.min): sld_frame.value -= 1 def frame_change(model, frame, style): with self._out: self.update(model=model, frame=frame, style=style) btn_fwrd.on_click(frame_fwrd) btn_revs.on_click(frame_revs) jslink((btn_play, "value"), (sld_frame, "value")) jslink((int_delay, "value"), (btn_play, "interval")) jslink((int_step, "value"), (btn_play, "step")) interactive_output(frame_change, {'model': drd_model, 'style': drd_style, 'frame': sld_frame}) IPython.display.display(ui)
def _build_procesing_panel(self, processing_info): """ Build up the processing panel for filtering data. Parameters ---------- processing_info: dict Processing information that contains name and parameters. Returns ------- """ self._processing_parameters = processing_info parameter_list = [] # Add the title to the top of the processing area. title = Label('Process: ' + processing_info['name'], style={'font-weight': 'bold', 'font-size': '1.5em'}) title.layout.width = '100%' parameter_list.append(title) # Add all the parameters for parameter in self._processing_parameters.get('parameters'): if isinstance(parameter[1], (int, float, str, list, tuple)): label = Label(parameter[0]) label.layout.width = '50%' # TODO: This needs to be cleaned up / generalized. if isinstance(parameter[1], int): ft = IntText(value=parameter[1]) elif isinstance(parameter[1], float): ft = FloatText(value=parameter[1]) else: ft = Text(value=str(parameter[1])) ft.layout.width = '50%' box = HBox((label, ft )) parameter_list.append(box) # Add the Cancel and Process buttons cancel_button = Button(description='Cancel', value='Cancel') cancel_button.button_style = 'danger' cancel_button.on_click(self._processing_cancel_button_callback) process_button = Button(description='Process', value='Process') process_button.button_style = 'success' process_button.on_click(self._processing_process_button_callback) parameter_list.append(HBox((process_button, cancel_button))) # Add them all to the VBox self._processing_vbox.children = tuple(parameter_list)
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 _counter_nb(items, tot=None): from ipywidgets import IntProgress, IntText from IPython.display import display if tot is not None: g = IntText(value=0, description='total = %d' % tot) f = IntProgress(min=0, max=tot) display(f) g.desription = 'hi' else: g = IntText(value=0) f = None display(g) for ii, item in enumerate(items): if f: f.value += 1 g.value += 1 yield item
def __init__(self, data, dimensions, **kwargs): GluePlotly.__init__(self, data, dimensions, **kwargs) self.DefaultLayoutTitles("", "", "") self.options['grouping_limit'] = IntText(description = 'Group limiy', value = 12) self.options['grouping_limit'].observe(lambda v:self.updateRender(), names='value') cl_options = list(cl.scales['8']['qual'].keys()) cl_options.append(GlueParallelCategoriesPlotly.default_color) self.options['colorscale'] = Dropdown(description = 'Color Palette:', value = GlueParallelCategoriesPlotly.default_color, options = cl_options) self.options['colorscale'].observe(lambda v:self.updateRender(), names='value') self.DefaultLegend('h', 0.01, -0.05); self.updateRender()
def __init__(self, displayer: Callable[[Figure, Selection], Callable[[int, Any], None]], resolution: int = None, fig_kw={}, children=(), toolbar=(), **ka): from ipywidgets import BoundedIntText, IntText, Label def select(bounds_): i = self.level + 1 w_level.active = False w_level.max = i w_level.value = i setlevel(i, (resolution, bounds_)) w_level.active = True def show_running(b): w_running.icon = 'pause' if b else 'play' def show_precision(p): w_precision.value = p self.select = select self.show_precision = show_precision self.show_running = show_running def setlevel(i, new=None): self.level = i w_precision.value = display(i, new) board.canvas.draw_idle() # global design and widget definitions w_running = SimpleButton(icon='') w_level = BoundedIntText(0, min=0, max=0, layout=dict(width='1.6cm', padding='0cm')) w_level.active = True w_precision = IntText(0, disabled=True, layout=dict(width='1.6cm', padding='0cm')) super().__init__(children, toolbar=(w_running, Label('level:'), w_level, Label('precision:'), w_precision, *toolbar)) self.board = board = self.mpl_figure(**fig_kw) display = displayer(board, select) # callbacks w_running.on_click(lambda b: self.setrunning()) w_level.observe( (lambda c: (setlevel(c.new) if w_level.active else None)), 'value') super(app, self).__init__(display, **ka)
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'} layout = {'width': '400px'} self.tumor_radius = FloatText(description='tumor_radius', step=0.02, style=style, layout=layout) self.oncoprotein_mean = FloatText(description='oncoprotein_mean', step=0.02, style=style, layout=layout) self.oncoprotein_sd = FloatText(description='oncoprotein_sd', step=0.02, style=style, layout=layout) self.oncoprotein_min = FloatText(description='oncoprotein_min', step=0.02, style=style, layout=layout) self.oncoprotein_max = FloatText(description='oncoprotein_max', step=0.02, style=style, layout=layout) self.random_seed = IntText(description='random_seed', step=1, style=style, layout=layout) self.tab = VBox([ HBox([self.tumor_radius, Label('micron')]), HBox([self.oncoprotein_mean, Label('')]), HBox([self.oncoprotein_sd, Label('')]), HBox([self.oncoprotein_min, Label('')]), HBox([self.oncoprotein_max, Label('')]), HBox([self.random_seed, Label('')]), ])
def __init__(self, candidate_labels, propositions): # internal vars self.header = '<p style="font-size: 150%;font-weight: 300;line-height: 1.39;margin: 0 0 12.5px;">{} <a target="_blank" href="{}">source</a></p>' self.candidate_labels = candidate_labels self.propositions = propositions self.choice = None self.clicked = False self.confusion_matrix = np.zeros((len(candidate_labels), len(candidate_labels)), dtype=np.int) # candidate buttons buttons = [Button(description=label) for label in self.candidate_labels] for b in buttons: b.on_click(self.on_button_clicked) hbox1 = HBox() hbox1.children = buttons self.buttons = buttons # scorebox and new_question button and confusion matrix self.scorebox = IntText(description='score', value=0, disabled=True) self.number = IntText(description='questions', value=0, disabled=True) new_question = Button(description='nouvelle question !') new_question.on_click(self.create_new_question) confusion_matrix_button = Button(description='afficher matrice de confusion') confusion_matrix_button.on_click(self.show_confusion_matrix) hbox2 = HBox() hbox2.children = [self.scorebox, self.number, new_question, confusion_matrix_button] # proposition box self.html = HTML() # general layout vbox = VBox() vbox.children = [hbox1, hbox2, self.html] self.box = vbox # generate first question self.create_new_question()
def __init__(self, data, dimensions, **kwargs): GluePlotly.__init__(self, data, dimensions, **kwargs) self.DefaultLayoutTitles("", self.dimensions[0], self.dimensions[1]) z_id = self.dimensions[2] self.max_color = max(self.data[z_id].flatten()) self.min_color = min(self.data[z_id].flatten()) color_options = [ 'Greys', 'YlGnBu', 'Greens', 'YlOrRd', 'Bluered', 'RdBu', 'Reds', 'Blues', 'Picnic', 'Rainbow', 'Portland', 'Jet', 'Hot', 'Blackbody', 'Earth', 'Electric', 'Viridis', 'Cividis' ] self.options['line_width'] = IntText(description='Lines width:', value=1) self.options['line_width'].observe( lambda v: self.UpdateTraces({'line.width': v['new']}), names='value') self.options['marker_size'] = IntText(description='Markers size:', value=3) self.options['marker_size'].observe( lambda v: self.UpdateTraces({'marker.size': v['new']}), names='value') self.options['color_range_min'] = FloatText(description='Color min:', value=self.min_color) self.options['color_range_min'].observe( lambda v: self.UpdateTraces({'zmin': v['new']}), names='value') self.options['color_range_max'] = FloatText(description='Color max:', value=self.max_color) self.options['color_range_max'].observe( lambda v: self.UpdateTraces({'zmax': v['new']}), names='value') self.options['color_scale'] = Dropdown(description='Color scale:', value='Greys', options=color_options) self.options['color_scale'].observe( lambda v: self.UpdateTraces({'colorscale': v['new']}), names='value') self.updateRender()
def _widget(self): """ Create IPython widget for display within a notebook """ try: return self._cached_widget except AttributeError: pass if self._gateway.asynchronous: return None try: from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML except ImportError: self._cached_widget = None return None try: self._internal_client = self.get_client(set_as_default=False) except Exception: return None layout = Layout(width="150px") title = HTML("<h2>GatewayCluster</h2>") status = HTML(self._widget_status(), layout=Layout(min_width="150px")) request = IntText(0, description="Workers", layout=layout) scale = Button(description="Scale", layout=layout) @scale.on_click def scale_cb(b): with log_errors(): self.scale(request.value) elements = [title, HBox([status, request, scale])] if self.dashboard_link is not None: link = HTML( '<p><b>Dashboard: </b><a href="{0}" target="_blank">{0}' "</a></p>\n".format(self.dashboard_link)) elements.append(link) self._cached_widget = box = VBox(elements) self._internal_client.loop.add_callback(self._widget_updater, status) return box
def __init__(self, image_width=150, image_height=150, n_rows=3, n_cols=3): self._screen_im_number = IntText(value=n_rows * n_cols, description='screen_image_number', disabled=False) self.image_width = image_width self.image_height = image_height self.n_rows = n_rows self.n_cols = n_cols self._navi = Navi() self._save_btn = Button(description="Save", layout=Layout(width='auto')) self._none_checkbox = Checkbox(description="Select none", indent=False, layout=Layout(width='100px')) self._controls_box = HBox( [self._navi, self._save_btn, self._none_checkbox], layout=Layout(display='flex', justify_content='center', flex_flow='wrap', align_items='center')) self._grid_box = CaptureGrid(image_width=image_width, image_height=image_height, n_rows=n_rows, n_cols=n_cols, display_label=False) self._grid_label = HTML() self._labels_box = VBox(children=[self._grid_label, self._grid_box], layout=Layout(display='flex', justify_content='center', flex_wrap='wrap', align_items='center')) super().__init__(header=None, left_sidebar=None, center=self._labels_box, right_sidebar=None, footer=self._controls_box, pane_widths=(2, 8, 0), pane_heights=(1, 4, 1))
def interact_with_plot_all_outputs(sa_dict, demo=False, manual=True): """ This function adds the ability to interactively adjust all of the plotting.make_plot() arguments. Parameters ---------- sa_dict : dict a dictionary with all the sensitivity analysis results. demo : bool, optional plot only few outcomes for demo purpose. Returns ------- Interactive widgets to control plot """ min_val_box = BoundedFloatText(value=0.01, min=0, max=1, description='Min value:') top_box = IntText(value=20, description='Show top:') stacks = Checkbox( description='Show stacked plots:', value=True, ) error_bars = Checkbox(description='Show error bars:', value=True) log_axis = Checkbox(description='Use log axis:', value=True) # get a list of all the parameter options key = sa_dict.keys()[0] param_options = list(sa_dict[key][0].Parameter.values) highlighted = SelectMultiple(description="Choose parameters to highlight", options=param_options, value=[]) return interact(plot_all_outputs, sa_dict=fixed(sa_dict), demo=fixed(demo), min_val=min_val_box, top=top_box, stacked=stacks, error_bars=error_bars, log_axis=log_axis, highlighted_parameters=highlighted, __manual=manual)
def test_player_link_to_ipywidgets(): traj = pt.datafiles.load_tz2() view = nv.show_pytraj(traj) int_text = IntText(2) float_text = BoundedFloatText(40, min=10) HBox([int_text, float_text]) link((int_text, 'value'), (view.player, 'step')) link((float_text, 'value'), (view.player, 'delay')) nt.assert_equal(view.player.step, 2) nt.assert_equal(view.player.delay, 40) float_text.value = 100 nt.assert_equal(view.player.delay, 100) float_text.value = 0.00 # we set min=10 nt.assert_equal(view.player.delay, 10)
def _widget(self): """ Create IPython widget for display within a notebook """ try: return self._cached_widget except AttributeError: pass from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML client = self._dask_client() layout = Layout(width='150px') title = HTML('<h2>YarnCluster</h2>') status = HTML(self._widget_status(), layout=Layout(min_width='150px')) request = IntText(0, description='Workers', layout=layout) scale = Button(description='Scale', layout=layout) @scale.on_click def scale_cb(b): with log_errors(): self.scale(request.value) elements = [title, HBox([status, request, scale])] if self.dashboard_link is not None: link = HTML('<p><b>Dashboard: </b><a href="%s" target="_blank">%s' '</a></p>\n' % (self.dashboard_link, self.dashboard_link)) elements.append(link) self._cached_widget = box = VBox(elements) def update(): status.value = self._widget_status() pc = PeriodicCallback(update, 500, io_loop=client.loop) pc.start() return box