def __init__(self, grid, color_map, title, bounding_box, codim, U, vmins, vmaxs, separate_colorbars, size): render_size = (300, 300) self.renderer = [ Renderer(u, grid, render_size, color_map, title, bounding_box=bounding_box, codim=codim, vmin=vmin, vmax=vmax) for u, vmin, vmax in zip(U, vmins, vmaxs) ] bar_size = (100, render_size[1]) if not separate_colorbars: self.colorbars = [ ColorBarRenderer(render_size=bar_size, vmin=vmins[0], vmax=vmaxs[0], color_map=color_map) ] self.r_hbox_items = self.renderer + self.colorbars else: self.r_hbox_items = [] self.colorbars = [] for vmin, vmax, renderer in zip(vmins, vmaxs, self.renderer): cr = ColorBarRenderer(render_size=bar_size, vmin=vmin, vmax=vmax, color_map=color_map) self.r_hbox_items.append(widgets.HBox([renderer, cr])) self.colorbars.append(cr) layout = Layout(display='flex', flex_flow='row wrap', align_items='stretch', justify_content='flex-start') children = [widgets.Box(self.r_hbox_items, layout=layout)] if size > 1: def _goto_idx(idx): for c in self.renderer: c.goto(idx) play = Play(min=0, max=size - 1, step=1, value=0, description='Timestep:') interact(idx=play).widget(_goto_idx) slider = IntSlider(min=0, max=size - 1, step=1, value=0, description='Timestep:') widgets.jslink((play, 'value'), (slider, 'value')) controls = widgets.HBox([play, slider]) children.append(controls) super().__init__(children=children)
def test_embed_data_two_widgets(self): feature_track = pileup.Track( viz="features", label="myFeatures", source=pileup.sources.GA4GHFeatureJson('{}')) variant_track = pileup.Track( viz="variants", label="myVariants", source=pileup.sources.GA4GHVariantJson('{}')) w1 = pileup.PileupViewer(chrom="chr17", start=1, stop=250, reference="hg19", tracks=[feature_track]) w2 = pileup.PileupViewer(chrom="chr17", start=1, stop=250, reference="hg19", tracks=[variant_track]) jslink((w1, 'reference'), (w2, 'reference')) state = dependency_state([w1, w2], drop_defaults=True) data = embed_data(views=[w1, w2], drop_defaults=True, state=state) state = data['manager_state']['state'] views = data['view_specs'] assert len(views) == 2 model_names = [s['model_name'] for s in state.values()] widget_names = list( filter(lambda x: x == 'PileupViewerModel', model_names)) assert len(widget_names) == 2
def show_obs_plot_widget(data, display_fn): from IPython import display from ipywidgets import widgets text_wid = widgets.IntText(value=0, placeholder='Frame number', description='Frame number:', disabled=False) slider_wid = widgets.IntSlider(value=0, min=0, max=len(data), step=1, description='Frames:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') widgets.jslink((text_wid, 'value'), (slider_wid, 'value')) output_widget = widgets.Output(layout={'height': '250px'}) def on_value_change(change): frame_idx = change['new'] display_fn(frame_idx) slider_wid.observe(on_value_change, names='value') frame_box = widgets.HBox([output_widget]) control_box = widgets.HBox([text_wid, slider_wid]) # Controls main_box = widgets.VBox([frame_box, control_box]) display.display(main_box) display_fn(0)
def show_in_notebook(self, fps=5, figsize=(8, 8), cmap="viridis"): # Prepare widgets play = widgets.Play(value=0, min=0, max=len(self.states) - 1, step=1, interval=int(1000 / fps), description="Press play", disabled=False) slider = widgets.IntSlider(min=0, value=0, max=len(self.states) - 1, step=1) widgets.jslink((play, 'value'), (slider, 'value')) # Visualize frames and widgets @interact(i=play) def show(i): plt.figure(figsize=figsize) plt.axis('off') plt.imshow(self.states[i], cmap=cmap) # Display on the notebook display(slider)
def __init__(self, grid, color_map, title, bounding_box, codim, U, vmins, vmaxs, separate_colorbars, size): render_size = (400, 400) self.renderer = [ Renderer(u, grid, render_size, color_map, title, bounding_box=bounding_box, codim=codim, vmin=vmin, vmax=vmax) for u, vmin, vmax in zip(U, vmins, vmaxs) ] bar_size = (100, render_size[1]) if not separate_colorbars: self.colorbars = [ ColorBarRenderer(render_size=bar_size, vmin=vmins[0], vmax=vmaxs[0], color_map=color_map) ] self.r_hbox_items = self.renderer + self.colorbars else: self.r_hbox_items = self.renderer self.colorbars = [] for i, (vmin, vmax) in enumerate(zip(vmins, vmaxs)): cr = ColorBarRenderer(render_size=bar_size, vmin=vmin, vmax=vmax, color_map=color_map) self.r_hbox_items.insert(2 * i + 1, cr) self.colorbars.append(cr) children = [ widgets.HBox(self.r_hbox_items, layout=Layout(overflow='auto', overflow_x='auto')) ] if size > 1: def _goto_idx(idx): for c in self.renderer: c.goto(idx) play = Play(min=0, max=size - 1, step=1, value=0, description='Timestep:') interact(idx=play).widget(_goto_idx) slider = IntSlider(min=0, max=size - 1, step=1, value=0, description='Timestep:') widgets.jslink((play, 'value'), (slider, 'value')) controls = widgets.HBox([play, slider]) children.append(controls) super().__init__(children=children)
def browse_images_orig_prep(img_orig_py, img_prep_py, size, slice_ID, fig, ax1, ax2, image_data): # function for slider def view_image_1(slider_1): ax1.imshow(img_orig_py[:,:,slider_1], cmap=plt.cm.gray, origin='lower',interpolation=None) ax1.set_title(image_data["image_name_root"] + "_orig.mha") ax1.axis('off') #display(fig) ax2.imshow(img_prep_py[:,:,slider_1], cmap=plt.cm.gray, origin='lower',interpolation=None) ax2.set_title(image_data["image_name_root"] + "_prep.mha") ax2.axis('off') display(fig) # link function and sliders (created inside the interactive command) slider = interactive(view_image_1, slider_1 = widgets.IntSlider(min=0, max=size[2]-1, value=slice_ID, step=1, continuous_update=False, # avoids intermediate image display readout=False, layout=Layout(width='450px'), description='Slice n.') ) # show images before start interacting slider.update() # slice number scrolling text = widgets.BoundedIntText(description="", # BoundedIntText to avoid that displayed text goes outside of the range min=0, max=size[2]-1, value=slice_ID, step=1, continuous_update=False, layout=Layout(width='50px')) # link slider and text widgets.jslink((slider.children[:-1][0], 'value'), (text, 'value')) # layout slider_box = HBox(slider.children[:-1]) widget_box = HBox([slider_box, text]) whole_box = VBox([widget_box, slider.children[-1] ]) return whole_box
def show_stamp_widget(masked_stamps): from IPython import display from ipywidgets import widgets text_wid = widgets.IntText(value=0, placeholder='Frame number', description='Frame number:', disabled=False) slider_wid = widgets.IntSlider(value=0, min=0, max=len(masked_stamps), step=1, description='Frames:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') widgets.jslink((text_wid, 'value'), (slider_wid, 'value')) output_widget = widgets.Output(layout={'height': '250px'}) def show_stamp(i): fig = make_sigma_aperture_plot(masked_stamps[i]) # fig.set_size_inches(9, 2.5) fig.suptitle(f'Frame {i:03d}', fontsize=14, y=1.06) fig.axes[1].grid(False) fig.axes[1].set_yticklabels([]) fig.axes[1].set_facecolor('#bbbbbb') with output_widget: display.clear_output() display.display(fig) def on_value_change(change): frame_idx = change['new'] show_stamp(frame_idx) slider_wid.observe(on_value_change, names='value') frame_box = widgets.HBox([output_widget]) control_box = widgets.HBox([text_wid, slider_wid]) # Controls main_box = widgets.VBox([frame_box, control_box]) display.display(main_box) show_stamp(0)
def make_buttons(input_widget, inverse=False): button_layout = {'width': '20px'} factor = 0.5 if inverse else 2.0 double_btn = Button(description="", button_style='warning', layout=button_layout) half_btn = Button(description="", button_style='success', layout=button_layout) def double_value(_): input_widget.value *= factor def half_value(_): input_widget.value /= factor widgets.jslink((double_btn, 'disabled'), (input_widget, 'disabled')) widgets.jslink((half_btn, 'disabled'), (input_widget, 'disabled')) double_btn.on_click(double_value) half_btn.on_click(half_value) return [half_btn, double_btn]
def replay_episode(self,fps = 5): # Prepare widgets play = widgets.Play( value=0, min=0, max=len(self.frame_cache) - 1, step=1, interval=int(1000/fps), description="Press play", disabled=False ) slider = widgets.IntSlider(min = 0,value = 0,max = len(self.frame_cache) - 1,step = 1) widgets.jslink((play, 'value'), (slider, 'value')) # Visualize frames and widgets @interact(i = play) def show(i): img = Image.fromarray(self.frame_cache[i]) return img display(slider)
def __init__(self, *args, slider=True, **kwargs): super(IterFigure, self).__init__(*args, **kwargs) self.idx = 0 self._btn_first = widgets.Button(description='First') self._btn_prev = widgets.Button(description='Prev') self._int_box = widgets.BoundedIntText(value=0, min=0, max=1) self._btn_next = widgets.Button(description='Next') self._btn_last = widgets.Button(description='Last') self._btn_random = widgets.Button(description='Random') self._int_box.observe(self.handle_int_box, names='value') self._btn_first.on_click(self.on_first) self._btn_prev.on_click(self.on_prev) self._btn_next.on_click(self.on_next) self._btn_last.on_click(self.on_last) self._btn_random.on_click(self.on_random) self.btn_hbox = widgets.HBox() self.btn_hbox.children = [ self._btn_first, self._btn_prev, self._int_box, self._btn_next, self._btn_last, self._btn_random ] if slider: self._slider = widgets.IntSlider(value=0, min=0, max=1, layout=dict(width='99%'), readout=False) widgets.jslink((self._int_box, 'value'), (self._slider, 'value')) self.vbox = widgets.VBox() self.vbox.children = [self.btn_hbox, self._slider] self.box = self.vbox else: self.box = self.btn_hbox
def replay(self, interval=0.5): # Prepare widgets play = widgets.Play( value=0, min=0, max=len(self.board_stack) - 1, step=1, interval=interval * 1000, description="Press play", disabled=False, ) slider = widgets.IntSlider( min=0, value=0, max=len(self.board_stack) - 1, step=1 ) widgets.jslink((play, "value"), (slider, "value")) # Visualize frames and widgets @interact(i=play) def show(i): return self.board_stack[i] display(slider)
def test_embed_data_two_widgets(self): w1 = pileup.Variants(json="{}", build='hg19', contig='chr1', start=1, stop=20) w2 = pileup.Features(json="{}", build='hg19', contig='chr1', start=1, stop=20) jslink((w1, 'start'), (w2, 'start')) state = dependency_state([w1, w2], drop_defaults=True) data = embed_data(views=[w1, w2], drop_defaults=True, state=state) state = data['manager_state']['state'] views = data['view_specs'] assert len(views) == 2 model_names = [s['model_name'] for s in state.values()] assert 'VariantModel' in model_names assert 'FeatureModel' in model_names
def interact(obj): tab = widgets.Tab() base_style = widgets.ButtonStyle() selected_style = widgets.ButtonStyle(button_color='#DDFFDD', font_weight='bold') if isinstance(obj, hl.Table): glob = widgets.Button(description='globals', layout=widgets.Layout(width='150px', height='30px')) rows = widgets.Button(description='rows', layout=widgets.Layout(width='150px', height='200px')) rows.style = selected_style globals_frames = [] globals_frames.append( widgets.HTML( f'<p><big>Global fields, with one value in the dataset.</big></p>\n' f'<p>Commonly used methods:</p>\n' f'<ul>' f'<li>{html_link("annotate_globals", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.annotate_globals")}: ' f'add new global fields.</li>' f'</ul>')) append_struct_frames(obj.globals.dtype, globals_frames) row_frames = [] row_frames.append( widgets.HTML( f'<p><big>Row fields, with one record per row of the table.</big></p>\n' f'<p>Commonly used methods:</p>\n' f'<ul>' f'<li>{html_link("annotate", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.annotate")}: ' f'add new fields.</li>' f'<li>{html_link("filter", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.filter")}: ' f'filter rows of the table.</li>' f'<li>{html_link("aggregate", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.aggregate")}: ' f'aggregate over rows to produce a single value.</li>' f'</ul>')) if len(obj.key) > 0: row_frames.append( widgets.HTML(f'<p><big>Key: {list(obj.key)}<big><p>')) append_struct_frames(obj.row.dtype, row_frames) tab.children = [ widgets.VBox(frames) for frames in [globals_frames, row_frames] ] tab.set_title(0, 'globals') tab.set_title(1, 'row') tab.selected_index = 1 box = widgets.VBox([glob, rows]) buttons = [glob, rows] else: assert isinstance(obj, hl.MatrixTable) glob = widgets.Button(description='globals', layout=widgets.Layout(width='65px', height='30px')) cols = widgets.Button(description='cols', layout=widgets.Layout(width='200px', height='30px')) rows = widgets.Button(description='rows', layout=widgets.Layout(width='65px', height='200px')) entries = widgets.Button(description='entries', layout=widgets.Layout(width='200px', height='200px')) entries.style = selected_style globals_frames = [] globals_frames.append( widgets.HTML( f'<p><big>Global fields, with one value in the dataset.</big></p>\n' f'<p>Commonly used methods:</p>\n' f'<ul>' f'<li>{html_link("annotate_globals()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_globals")}: ' f'add new global fields.</li>' f'</ul>')) append_struct_frames(obj.globals.dtype, globals_frames) row_frames = [] row_frames.append( widgets.HTML( f'<p><big>Row fields, with one record per row in the dataset.</big></p>\n' f'<p>Commonly used methods:</p>\n' f'<ul>' f'<li>{html_link("annotate_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_rows")}: ' f'add new row fields. This method supports {html_link("aggregation", "https://hail.is/docs/0.2/aggregators.html")}, ' f'aggregating over entries to compute one result per row, e.g. computing the mean depth per variant.</li>' f'<li>{html_link("filter_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_rows")}: ' f'filter rows in the matrix table.</li>' f'<li>{html_link("aggregate_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_rows")}: ' f'aggregate over rows (not including entries or columns) to produce a single value, e.g. counting the number of loss-of-function variants.</li>' f'<li>{html_link("rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.rows")}: ' f'return the rows as a Hail {html_link("Table", "https://hail.is/docs/0.2/hail.Table.html")}.</li>' f'</ul>')) if len(obj.row_key) > 0: row_frames.append( widgets.HTML(f'<p><big>Row key: {list(obj.row_key)}<big><p>')) append_struct_frames(obj.row.dtype, row_frames) col_frames = [] col_frames.append( widgets.HTML( f'<p><big>Column fields, with one record per column in the dataset.</big></p>\n' f'<p>Commonly used methods:</p>\n' f'<ul>' f'<li>{html_link("annotate_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_cols")}: ' f'add new column fields. This method supports {html_link("aggregation", "https://hail.is/docs/0.2/aggregators.html")}, ' f'aggregating over entries to compute one result per column, e.g. computing the mean depth per sample.</li>' f'<li>{html_link("filter_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_cols")}: ' f'filter columns in the matrix table.</li>' f'<li>{html_link("aggregate_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_cols")}: ' f'aggregate over columns (not including entries or rows) to produce a single value, e.g. counting the number of samples with case status.</li>' f'<li>{html_link("cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.cols")}: ' f'return the columns as a Hail {html_link("Table", "https://hail.is/docs/0.2/hail.Table.html")}.' f'</li>' f'</ul>')) if len(obj.col_key) > 0: col_frames.append( widgets.HTML( f'<p><big>Column key: {list(obj.col_key)}<big><p>')) append_struct_frames(obj.col.dtype, col_frames) entry_frames = [] entry_frames.append( widgets.HTML( f'<p><big>Entry fields, with one record per (row, column) pair in the dataset.</big></p>\n' f'<p>Commonly used methods:</p>\n' f'<ul>' f'<li>{html_link("annotate_entries()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_entries")}: ' f'add new entry fields.</li>' f'<li>{html_link("filter_entries()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_entries")}: ' f'filter entries in the matrix table, removing them from downstream operations, like aggregations.</li>' f'<li>{html_link("aggregate_entries", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_entries")}: ' f'aggregate over entries to produce a single value, e.g. computing mean depth across an entire dataset.</li>' f'</ul>')) append_struct_frames(obj.entry.dtype, entry_frames) tab.children = [ widgets.VBox(frames) for frames in [globals_frames, row_frames, col_frames, entry_frames] ] tab.set_title(0, 'globals') tab.set_title(1, 'row') tab.set_title(2, 'col') tab.set_title(3, 'entry') tab.selected_index = 3 box = widgets.VBox( [widgets.HBox([glob, cols]), widgets.HBox([rows, entries])]) buttons = [glob, rows, cols, entries] selection_handler = widgets.IntText(tab.selected_index) button_idx = dict(zip(buttons, range(len(buttons)))) def handle_selection(x): if x['name'] == 'value' and x['type'] == 'change': buttons[x['old']].style = base_style selection = x['new'] buttons[selection].style = selected_style tab.selected_index = selection selection_handler.observe(handle_selection) widgets.jslink((tab, 'selected_index'), (selection_handler, 'value')) def button_action(b): selection_handler.value = button_idx[b] for button in button_idx: button.on_click(button_action) display(box, tab)
def createLink(self, a, b): link = widgets.jslink((a, 'value'), (b, 'value')) return link
def _set_widgets(self): min_v = [] max_v = [] if self._link: n_links = 1 else: n_links = self._num_dsets for i in range(n_links): try: min_v.append( (self.vmin[i] - np.fabs(self.vmax[i] - self.vmin[i]), self.vmin[i])) except TypeError: min_v.append((0, -1)) try: max_v.append( (self.vmax[i] + np.fabs(self.vmax[i] - self.vmin[i]), self.vmax[i])) except TypeError: max_v.append((1000, 11000)) self.val_sliders = [ widgets.FloatRangeSlider(value=[min_v[i][-1], max_v[i][-1]], min=min_v[i][0], max=max_v[i][0], step=self.mag[i], description='Range:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='0.4f', layout=Layout(width='100%')) for i in range(n_links) ] self.cmap_sel = [ widgets.Dropdown(options=self.cmaps, value=self.cmaps[0], description='CMap:', disabled=False, layout=Layout(width='200px')) for i in range(n_links) ] self.t_step = widgets.BoundedFloatText(value=0, min=0, max=10000, step=1, disabled=False, description=self.step_variable, layout=Layout(width='200px', height='30px')) self.t_step.observe(self._tstep_observer, names='value') for n in range(n_links): self.val_sliders[n].observe(self._clim_observer, names='value') self.cmap_sel[n].observe(self._cmap_observer, names='value') self.val_sliders[n].num = n self.cmap_sel[n].num = n if n_links > 1: self.val_sliders[n].description = 'Range #{}:'.format(n + 1) self.cmap_sel[n].description = 'CMap #{}:'.format(n + 1) if self._link and n > 0: _ = widgets.jslink((self.val_sliders[0], 'value'), (self.val_sliders[n], 'value'))
def browse_images(moving_py, mask_py, ax_i, fig, moving_root, last_value, sliceID): # The code in this function has to be separate. If code directly into show_segmented_images, when using widgets, they update the last image # function for slider def view_image(slider): # get slice of moving image slice_moving_py = moving_py[:,:,slider] # get slice in mask slice_mask_py = mask_py[:,:,slider] slice_mask_masked = np.ma.masked_where(slice_mask_py == 0, slice_mask_py) # show both ax_i.imshow(slice_moving_py, cmap=plt.cm.gray, origin='lower',interpolation=None) ren = ax_i.imshow(slice_mask_masked, 'jet' , interpolation=None, origin='lower', alpha=1, vmin=0, vmax=100) ax_i.set_title(moving_root) ax_i.axis('off') # colorbar cbar_ax = fig.add_axes([0.08, 0.4, 0.01, 0.2]) #[left, bottom, width, height] fig.colorbar(ren, cax=cbar_ax, orientation='vertical', shrink=0.60, ticks=[0, 20, 40, 60, 80, 100]) cbar_ax.set_title('[ms]') # The following two lines are to avoid this warning in the notebook: # Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. # To be fixed in following releases import warnings warnings.filterwarnings("ignore") # display display(fig) # link sliders and its function slider_image = interactive(view_image, slider = widgets.IntSlider(min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, # avoids intermediate image display readout=False, layout=Layout(width='250px'), description='Slice n.')) # show figures before start interacting slider_image.update() # slice number scrolling text = widgets.BoundedIntText(description="", # BoundedIntText to avoid that displayed text goes outside of the range min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, layout=Layout(width='50px')) # link slider and text widgets.jslink((slider_image.children[:-1][0], 'value'), (text, 'value')) # layout slider_box = HBox(slider_image.children[:-1]) widget_box = HBox([slider_box, text]) whole_box = VBox([widget_box, slider_image.children[-1] ]) return whole_box
def visualize_tracker(tracker: "Tracker", sequence: "Sequence"): from IPython.display import display from ipywidgets import widgets from vot.utilities.draw import ImageDrawHandle def encode_image(handle): with io.BytesIO() as output: handle.snapshot.save(output, format="PNG") return output.getvalue() handle = ImageDrawHandle(sequence.frame(0).image()) button_restart = widgets.Button(description='Restart') button_next = widgets.Button(description='Next') button_play = widgets.Button(description='Run') frame = widgets.Label(value="") frame.layout.display = "none" frame2 = widgets.Label(value="") image = widgets.Image(value=encode_image(handle), format="png", width=sequence.size[0] * 2, height=sequence.size[1] * 2) state = dict(frame=0, auto=False, alive=True, region=None) condition = Condition() buttons = widgets.HBox(children=(frame, button_restart, button_next, button_play, frame2)) image.value = encode_image(handle) def run(): runtime = tracker.runtime() while state["alive"]: if state["frame"] == 0: state["region"], _, _ = runtime.initialize(sequence.frame(0), sequence.groundtruth(0)) else: state["region"], _, _ = runtime.update(sequence.frame(state["frame"])) update_image() with condition: condition.wait() if state["frame"] == sequence.length: state["alive"] = False continue state["frame"] = state["frame"] + 1 def update_image(): handle.image(sequence.frame(state["frame"]).image()) handle.style(color="green").region(sequence.frame(state["frame"]).groundtruth()) if state["region"]: handle.style(color="red").region(state["region"]) image.value = encode_image(handle) frame.value = "Frame: " + str(state["frame"] - 1) def on_click(button): if button == button_next: with condition: state["auto"] = False condition.notify() if button == button_restart: with condition: state["frame"] = 0 condition.notify() if button == button_play: with condition: state["auto"] = not state["auto"] button.description = "Stop" if state["auto"] else "Run" condition.notify() button_next.on_click(on_click) button_restart.on_click(on_click) button_play.on_click(on_click) widgets.jslink((frame, "value"), (frame2, "value")) def on_update(_): with condition: if state["auto"]: condition.notify() frame2.observe(on_update, names=("value", )) thread = Thread(target=run) display(widgets.Box([widgets.VBox(children=(image, buttons))])) thread.start()
def play_publisher(publisher, step=1, speed=1.0, skip=None, timestamps=None): """ Interactive widget for playing back messages from a publisher. Parameters ---------- publisher: object Any object with a ``publish`` method that accepts an ``idx`` parameter and publishes a message corresponding to that index. step: int, default 1 Difference in indexes between consecutive messages, e.g. if ``step=2`` every second message will be published. speed: float, default 1.0 Playback speed. skip: int, optional Number of messages to skip with the forward and backward buttons. timestamps: array_like, datetime64 dtype, optional Timestamps of publisher messages that determine time difference between messages and total number of messages. The time difference is calculated as the mean difference between the timestamps, i.e. it assumes that the timestamps are more or less regular. If not provided, the publisher must have a ``timestamps`` attribute which will be used instead. """ from IPython.core.display import display from ipywidgets import widgets if timestamps is None: timestamps = np.asarray(publisher.timestamps) interval = np.mean(np.diff(timestamps.astype(float) / 1e6)) / speed # position bar s_idx = widgets.IntSlider(min=0, max=len(timestamps) - 1, value=0, description="Index") # forward button def button_plus(name): s_idx.value += skip or step if s_idx.value < s_idx.max else 0 forward = widgets.Button(description="►►", layout=widgets.Layout(width="50px")) forward.on_click(button_plus) # backward button def button_minus(name): s_idx.value -= skip or step if s_idx.value < s_idx.max else 0 backward = widgets.Button(description="◄◄", layout=widgets.Layout(width="50px")) backward.on_click(button_minus) # play button play = widgets.Play( interval=int(interval * step), value=0, min=s_idx.min, max=s_idx.max, step=step, description="Press play", disabled=False, ) widgets.jslink((play, "value"), (s_idx, "value")) # layout ui = widgets.HBox([s_idx, backward, play, forward]) out = widgets.interactive_output(publisher.publish, {"idx": s_idx}) display(ui, out)
aladin.add_table(table) # ## Linked Aladin Lite Views # # In[ ]: from ipywidgets import Layout, Box, widgets a = ipyal.Aladin(layout=Layout(width='33.33%'), target='09 14 42.373 +00 29 43.26', fov=0.3) b = ipyal.Aladin(layout=Layout(width='33.33%'), survey='P/DSS2/red') c = ipyal.Aladin(layout=Layout(width='33.33%'), survey='P/2MASS/color') # synchronize target between 3 widgets widgets.jslink((a, 'target'), (b, 'target')) widgets.jslink((b, 'target'), (c, 'target')) # synchronize FoV (zoom level) between 3 widgets widgets.jslink((a, 'fov'), (b, 'fov')) widgets.jslink((b, 'fov'), (c, 'fov')) items = [a, b, c] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', border='solid', width='100%') box = Box(children=items, layout=box_layout) box
def plot(vtkfile_path, color_attribute_name, color_map=get_cmap('viridis')): ''' Generate a k3d Plot and associated controls for VTK data from file :param vtkfile_path: the path to load vtk data from. Can be a single .vtu or a collection :param color_attribute_name: which data array from vtk to use for plot coloring :param color_map: a Matplotlib Colormap object or a K3D array((step, r, g, b)) :return: the generated Plot object ''' if isinstance(color_map, Colormap): color_map = [(x, *color_map(x)[:3]) for x in np.linspace(0, 1, 256)] data = read_vtkfile(vtkfile_path) size = len(data) # getbounds: (xmin, xmax, ymin, ymax, zmin, zmax) all_bounds = np.stack([p[1].GetBounds() for p in data]) combined_bounds = np.array([ np.min(all_bounds[:, 0]), np.min(all_bounds[:, 2]), np.min(all_bounds[:, 4]), np.max(all_bounds[:, 1]), np.max(all_bounds[:, 3]), np.max(all_bounds[:, 5]) ]) vtkplot = VTKPlot(data, color_attribute_name=color_attribute_name, grid_auto_fit=False, camera_auto_fit=False, color_map=color_map, grid=combined_bounds) # display needs to have been called before changing camera/grid_visible vtkplot.display() # could be replaced with testing if the widget is'ready' time.sleep(0.5) vtkplot.grid_visible = False try: vtkplot.menu_visibility = False except AttributeError: pass # k3d < 2.5.6 # guesstimate fov_angle = 30 absx = np.abs(combined_bounds[0] - combined_bounds[3]) c_dist = np.sin((90 - fov_angle) * np.pi / 180) * absx / (2 * np.sin(fov_angle * np.pi / 180)) xhalf = (combined_bounds[0] + combined_bounds[3]) / 2 yhalf = (combined_bounds[1] + combined_bounds[4]) / 2 zhalf = (combined_bounds[2] + combined_bounds[5]) / 2 # camera[posx, posy, posz, targetx, targety, targetz, upx, upy, upz] vtkplot.camera = (xhalf, yhalf, zhalf + c_dist, xhalf, yhalf, zhalf, 0, 1, 0) if size > 1: play = Play(min=0, max=size - 1, step=1, value=0, description='Timestep:') interact(idx=play).widget(vtkplot._goto_idx) slider = IntSlider(min=0, max=size - 1, step=1, value=0, description='Timestep:') interact(idx=slider).widget(vtkplot._goto_idx) widgets.jslink((play, 'value'), (slider, 'value')) hbox = widgets.HBox([play, slider]) IPython.display.display(hbox) return vtkplot
top = widgets.FloatSlider(min=-10, max=10, value=1, description='top') right = widgets.FloatSlider(min=-10, max=10, value=1, description='right') fine = widgets.IntSlider(min = 20, max = 100, value=50, description='Fine') Hticks = widgets.IntSlider(min = 2, max = 50, value=10, description='Hticks') Vticks = widgets.IntSlider(min = 2, max = 50, value=10, description='Vticks') function = widgets.Text( value = 'z**2' , description='w : ') frame = widgets.FloatSlider(min=0, max=100, value=100, step = 5, description='anim') play = widgets.Play(min= 0, max = 100, step = 5) widgets.jslink((play, 'value'), (frame, 'value')) interactive_plot = widgets.interactive(rect.updateFunc, w = function, left = left, right = right, top= top, bottom = bottom, fine = fine, Hticks = Hticks, Vticks = Vticks, frame = frame ) w1 = VBox([ left, right])
def browse_images(moving_py, mask_py, ax_i, fig, moving_root, last_value, sliceID): # The code in this function has to be separate. If code directly into show_segmented_images, when using widgets, they update the last image # function for slider def view_image(slider): # get slice of moving image slice_moving_py = moving_py[:, :, slider] # get slice in mask slice_mask_py = mask_py[:, :, slider] slice_mask_masked = np.ma.masked_where(slice_mask_py == 0, slice_mask_py) # show both ax_i.imshow(slice_moving_py, cmap=plt.cm.gray, origin='lower', interpolation=None) ax_i.imshow(slice_mask_masked, 'hsv', interpolation=None, origin='lower', alpha=1, vmin=0, vmax=100) ax_i.set_title(moving_root) ax_i.axis('off') display(fig) # link sliders and its function slider_image = interactive( view_image, slider=widgets.IntSlider( min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, # avoids intermediate image display readout=False, layout=Layout(width='180px'), description='Slice n.')) # show figures before start interacting slider_image.update() # slice number scrolling text = widgets.BoundedIntText( description= "", # BoundedIntText to avoid that displayed text goes outside of the range min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, layout=Layout(width='50px')) # link slider and text widgets.jslink((slider_image.children[:-1][0], 'value'), (text, 'value')) # layout slider_box = HBox(slider_image.children[:-1]) widget_box = HBox([slider_box, text]) whole_box = VBox([widget_box, slider_image.children[-1]]) return whole_box
columns=4, # define ncol and nrow of a sheet column_headers=False, row_headers=False # define headers ) sheet # %% # change value and return a cell obj # cell(row, column, value=0.0, ... ) cell_a = ipysheet.cell(0, 1, 1, label_left='a') cell_b = ipysheet.cell(1, 1, 2, label_left='b') cell_sum = ipysheet.cell(2, 1, 3, label_left='sum', read_only=True) # %% # create a slider linked to cell a slider = widgets.FloatSlider(min=-10, max=10, description='a') widgets.jslink( (cell_a, 'value'), (slider, 'value' )) # jslink(attr1, attr2) -> Link; type(attr1)=tuple:(<widegt, name>) # %% # changes in a or b should trigger this function def calculate(change): cell_sum.value = cell_a.value + cell_b.value cell_a.observe(calculate, 'value') cell_b.observe(calculate, 'value') widgets.VBox([sheet, slider]) # %% '''