def __init__(self, name): self.dirname = os.path.join(name, "") odtfile = max(glob.iglob("{}*.odt".format(self.dirname)), key=os.path.getctime) self.dt = oommfodt.OOMMFodt(odtfile).df self.time = self.dt["t"].as_matrix() / 1e-12 self.slider = ipywidgets.IntSlider( value=self.time[0], min=self.time[0], max=self.time[-1], step=self.time[1] - self.time[0], description="t (ps):", readout=True, layout=ipywidgets.Layout(width="100%"), continuous_update=False) self.select = ipywidgets.Select(options=list(self.dt.columns.values), description="Output:") self.play = ipywidgets.Play(value=self.time[0], min=self.time[0], max=self.time[-1], step=self.time[1] - self.time[0]) ipywidgets.jslink((self.play, "value"), (self.slider, "value")) self.slider.observe(self.update_output_slider) self.select.observe(self.update_output_slider) self.out = ipywidgets.Output(layout=ipywidgets.Layout(width="300%")) self.update_output_slider(None)
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 animation(self, t, v, interval, duration, a_step=10, a_interval=100, a_duration=10): xs = LinearScale() ys = LinearScale() line = Lines(x=t[:interval], y=v[:, :interval], scales={'x': xs, 'y': ys}) xax = Axis(scale=xs, label='x', grid_lines='solid') yax = Axis(scale=ys, orientation='vertical', tick_format='0.2f', label='y', grid_lines='solid') fig = Figure(marks=[line], axes=[xax, yax], animation_duration=a_duration) def on_value_change(change): line.x = t[change['new']:interval + change['new']] line.y = v[:, change['new']:interval + change['new']] play = widgets.Play( interval=a_interval, value=0, min=0, max=duration, step=a_step, description="Press play", disabled=False ) slider = widgets.IntSlider(min=0, max=duration) widgets.jslink((play, 'value'), (slider, 'value')) slider.observe(on_value_change, names='value') return play, slider, fig
def animate_list(lst, play=False, navigation=True, interval=200): slider = widgets.IntSlider(min=0, max=len(lst) - 1, step=1, value=0) if navigation: prev_button = widgets.Button( description='Prev', disabled=False, ) next_button = widgets.Button( description='Next', disabled=False, ) def increment_value(arg): slider.value += 1 def decrement_value(arg): slider.value -= 1 prev_button.on_click(decrement_value) next_button.on_click(increment_value) if play: play_widget = widgets.Play(interval=interval) widgets.jslink((play_widget, 'value'), (slider, 'value')) if play or navigation: if play and navigation: display(widgets.HBox([play_widget, prev_button, next_button])) elif play: display(play_widjet) elif navigation: display(widgets.HBox([prev_button, next_button])) return interact(step_slice, lst=fixed(lst), step=slider)
def setup(self): nsteps = self.dataset._widgets.nsteps self.label = widgets.Label(self.dataset._widgets.current_time_fmt) self.label.layout = widgets.Layout(width='150px') self.slider = widgets.IntSlider(value=0, min=0, max=nsteps - 1, readout=False) self.slider.layout = widgets.Layout(width='auto', flex='3 1 0%') self.slider.observe(self._update_step, names='value') self.play = widgets.Play(value=0, min=0, max=nsteps - 1, interval=100) self.play_speed = widgets.IntSlider(value=30, min=0, max=50, readout=False) self.play_speed.layout = widgets.Layout(width='auto', flex='1 1 0%') self.play_speed.observe(self._update_play_speed, names='value') widgets.jslink((self.play, 'value'), (self.slider, 'value')) return widgets.HBox( [ self.play, widgets.Label('slow/fast: '), self.play_speed, widgets.Label('steps: '), self.slider, self.label, ], layout=widgets.Layout(width='100%'), )
def images( pathstring="kh_*.h5", directory="/home/dominik/FUW/Semestr3/PrezentacjaNiestabilności/pyro2/backup2", interval=2000, figsize=(20, 20), ): p = pathlib.Path(directory) frames = sorted(list(p.glob(pathstring)))[::1] plotfile_name = str(frames[0]) sims = [io.read(str(frame)) for frame in frames] fig = plt.figure(figsize=figsize, dpi=200, facecolor='w') slider = ipywidgets.IntSlider(min=1, max=len(frames) - 1, step=1, continuous_update=True) play = ipywidgets.Play(min=1, max=len(frames) - 1, interval=interval) display(play) ipywidgets.jslink((play, 'value'), (slider, 'value')) def interactive(i): sims[i].dovis() plt.show() return ipywidgets.interactive(interactive, i=slider)
def show_vibs(calc, amplitude=1): import traitlets import nglview import ipywidgets as widgets from ipywidgets import Layout, HBox, VBox trajs = [] freqs, modes = calc.get_vibrational_modes() freq_list = [ '-%.2f' % (f.real * 1000) if np.iscomplexobj(f) else '%.2f' % (f * 1000) for f in freqs ] for n, mode in enumerate(modes): trajs.append( [a.positions for a in form_traj(calc.atoms, mode, amplitude)]) v = nglview.show_asetraj([calc.atoms]) v.clear_representations() v.add_spacefill(radius_type='vdw', radius_scale=0.5, roughness=1, metalness=0) v._set_size('450px', '300px') v.camera = 'orthographic' v.parameters = dict(clipDist=0, sampleLevel=1) select = widgets.Select(options=freq_list, value=freq_list[-1], layout=Layout(width='100px', height='270px'), disabled=False) play = widgets.Play(value=0, min=-10, max=10, step=1, _repeat=True, description="Press play", disabled=False) slider = widgets.IntSlider( value=0, min=-10, max=10, ) class FnScope: traj = trajs[-1] def handle_slider_change(change): v.set_coordinates({0: FnScope.traj[change.new]}) def handle_select_change(change): FnScope.traj = trajs[change.new] slider.observe(handle_slider_change, names='value') select.observe(handle_select_change, names='index') traitlets.link((play, 'value'), (slider, 'value')) vib_viewer = HBox([VBox([v, HBox([play, slider])]), select]) display(vib_viewer)
def __init__(self, image_fnames): self.display_w = 400 self.display_h = 400 self.fnames = image_fnames self.index = 0 self.data = [] for fname in self.fnames: with open(fname, "rb") as f: self.data.append(f.read()) self.label = ipywidgets.Label(value=self.fnames[self.index]) self.image = ipywidgets.Image(value=self.data[self.index], width=self.display_w, height=self.display_h, format="png") self.check = ipywidgets.Checkbox(value=False, description='Show absolute file path', disabled=False, indent=False) self.slider = ipywidgets.IntSlider() self.play = ipywidgets.Play(value=0, min=0, max=len(self.data)-1, step=1, interval=500) ipywidgets.jslink((self.play, "min"), (self.slider, "min")) ipywidgets.jslink((self.play, "max"), (self.slider, "max")) ipywidgets.jslink((self.play, "value"), (self.slider, "value"))
def __init__(self, *args, min=0, max=100, value=100, step=1, interval=500, label="Value", continuous_update=True, **kwargs): # initialise the hbox widget super().__init__([ widgets.Label(label + ": "), widgets.Play(min=min, max=max, value=value, interval=interval), widgets.IntSlider( min=min, max=max, value=value, step=step, continuous_update=continuous_update, ), ]) for trait in ("min", "max", "value", "step"): # first the two control elements: widgets.link((self.children[1], trait), (self.children[2], trait)) # then link the latter with self: widgets.link((self.children[2], trait), (self, trait)) widgets.link((self.children[1], "interval"), (self, "interval"))
def showSlice(filePath): image = sitk.ReadImage(filePath) img = sitk.GetArrayFromImage(image) zSlice = img[1, :, :] pl = figure(plot_width=400, plot_height=400, x_range=(0, 10), y_range=(0, 10)) slicer = pl.image(image=[zSlice], x=[0], y=[0], dw=[10], dh=[10]) def update(z): zSlicer = img[z, :, :] slicer.data_source.data['image'] = [zSlicer] push_notebook() show(pl, notebook_handle=True) play = widgets.Play(value=50, min=0, max=154, step=1, description="Press play", disabled=False) slider = widgets.IntSlider() widgets.jslink((play, 'value'), (slider, 'value')) interact(update, z=play) display(slider)
def animate_glyphs(scatter, sequence_length=None, add=True, interval=200): """Animate scatter or quiver by adding a slider and play button. :param scatter: scatter or quiver object :param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly, you can tell us what it should be :param add: if True, add the widgets to the container, else return a HBox with the slider and play button :param interval: interval in msec between each frame :return: """ if sequence_length is None: # get all non-None arrays values = [getattr(scatter, name) for name in "x y z vx vy vz".split()] values = [k for k in values if k is not None] # sort them such that the higest dim is first values.sort(key=lambda key: -len(key.shape)) sequence_length = values[0].shape[ 0] # assume this defines the sequence length fig = gcf() fig.animation = interval fig.animation_exponent = 1. play = ipywidgets.Play(min=0, max=sequence_length, interval=interval, value=0, step=1) slider = ipywidgets.IntSlider(min=0, max=play.max - 1) ipywidgets.jslink((play, 'value'), (slider, 'value')) ipywidgets.jslink((slider, 'value'), (scatter, 'sequence_index')) control = ipywidgets.HBox([play, slider]) if add: current.container.children += (control, ) else: return control
def __init__( self, first, last, ): play = widgets.Play( # interval=10, value=0, min=first, max=last, step=1, description="Press play", disabled=False, continuous_updata=1, ) slider = widgets.IntSlider() widgets.jslink((play, "value"), (slider, "value")) hbox = widgets.HBox([play, slider]) display(hbox) fig, ax = plt.subplots(1, 1, figsize=(9, 6)) while True: print(play.value) time.sleep(2) ax.plot(play.value) fig.canvas.draw_idle()
def _create_play_bar(self, num_iterations: int) -> widgets.Widget: """Create play bar widget over iterations. Args: num_iterations (int): length of the play bar Returns: widgets.Widget: play bar widget """ play = widgets.Play( value=1, min=1, max=num_iterations, step=1, interval=400, disabled=False, ) slider = widgets.IntSlider(1, 1, num_iterations) # Linking slider and play bar values in javascript widgets.jslink((play, "value"), (slider, "value")) self.widgets["iteration"] = slider return widgets.HBox([play, slider])
def SlideShower(folder, frame_duration=800): slides = list([open(os.path.join(folder,s), 'rb').read() for s in natural_sort(os.listdir(folder))]) x, y = _get_png_info(slides[0]) img = widgets.Image(value=slides[0], width=x, height=y) def on_frame(change): n = change['new'] img.value = slides[n] play = widgets.Play( value=0, min=0, max=len(slides), step=1, interval=frame_duration, disabled=False ) slider = widgets.IntSlider( value=0, min=0, max=len(slides)-1, step=1 ) slider.observe(on_frame, names='value') widgets.jslink((play, 'value'), (slider, 'value')) box = widgets.VBox([img, widgets.HBox([play, slider])]) return box
def AnimateList(lst, play=False, interval=200): slider = widgets.IntSlider(min=0, max=len(lst) - 1, step=1, value=0) if play: play_widjet = widgets.Play(interval=interval) widgets.jslink((play_widjet, 'value'), (slider, 'value')) display(play_widjet) return interact(StepSlice, lst=fixed(lst), step=slider)
def joint_player(self): # no player for static view static = True for a in self.arg: if not a.static: static = False if static: return # compute timeline timeline = [] for v in self.arg: p = v.ctrl.widgets["player"] if p.timeline is not None: timeline = timeline + p.timeline timeline = list(set(timeline)) timeline.sort() self.timeline = timeline # init widgets self.player = widgets.Play(value=0, min=0, max=len(timeline) - 1, interval=150) self.slider = widgets.SelectionSlider(value=timeline[0], options=timeline) self.speed = widgets.Dropdown( options=[("1", 250), ("2", 200), ("3", 150), ("4", 100), ("5", 50)], value=150, description="Speed:", layout=widgets.Layout( width="100px" ), style={ "description_width": "45px" } ) def on_slider_change(change): t = change.new self.player.value = self.timeline.index(t) for v in self.arg: p = v.ctrl.widgets["player"] if p.slider is not None and t in p.slider.options: p.slider.value = t self.slider.observe(on_slider_change, names="value") def on_player_change(change): t = self.timeline[change.new] self.slider.value = t for v in self.arg: p = v.ctrl.widgets["player"] if p.slider is not None and t in p.slider.options: p.slider.value = t self.player.observe(on_player_change, names="value") widgets.link((self.speed, "value"), (self.player, "interval"))
def __init__(self, simulation, emitter): self.simulation = simulation self.hmap = simulation.hmap self.emitter = emitter self.coords = np.array( [self.hmap.hmap[i].coords for i in range(self.hmap.n**2)]) self.colors = [ 'green' if self.hmap.hmap[i].state == 'terrain' else 'steelblue' for i in range(self.hmap.n**2) ] ax_x = Axis(label="x", scale=bqplot.LinearScale(min=0, max=2)) ax_y = Axis(label="y", scale=bqplot.LinearScale(min=0, max=2), orientation="vertical", side="left") self.grid_scat = plt.scatter(x=self.coords[:, 0], y=self.coords[:, 1], colors=self.colors, default_size=3, default_opacities=[.3], marker='rectangle') self.particles_scat = plt.scatter( x=[p.x for p in simulation.particles], y=[p.y for p in simulation.particles]) self.fig = plt.Figure(marks=[self.grid_scat, self.particles_scat], axes=[ax_x, ax_y], animation_duration=100, padding_x=.05, padding_y=.05) self.out = widgets.Output() def on_value_change(change): t = change['new'] if t == 1: self.simulation.reset() self.emitter.reset() self.hmap.reset() self.out.clear_output() self.particles_scat.x = [p.x for p in self.simulation.particles] self.particles_scat.y = [p.y for p in self.simulation.particles] self.simulation.update_particles() p = self.emitter.emit() if p: self.simulation.add_particle(p) self.slider = widgets.IntSlider(min=0, max=1000, step=1, continuous_update=True) self.play = widgets.Play(min=1, max=1000, interval=150) self.slider.observe(on_value_change, 'value') widgets.jslink((self.play, 'value'), (self.slider, 'value'))
def animation_control(object, sequence_length=None, add=True, interval=200): """Animate scatter, quiver or mesh by adding a slider and play button. :param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to control multiple. :param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly, you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance documented in :any:`scatter` or :any:`plot_mesh`. :param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you want to customise the layout of the widgets yourself. :param interval: interval in msec between each frame :return: If add is False, if returns the ipywidgets.HBox object containing the controls """ if isinstance(object, (list, tuple)): objects = object else: objects = [object] del object if sequence_length is None: # get all non-None arrays sequence_lengths = [] for object in objects: sequence_lengths_previous = list(sequence_lengths) values = [getattr(object, name) for name in "x y z vx vy vz".split() if hasattr(object, name)] values = [k for k in values if k is not None] # sort them such that the higest dim is first values.sort(key=lambda key: -len(key.shape)) try: sequence_length = values[0].shape[0] # assume this defines the sequence length if isinstance(object, ipv.Mesh): # for a mesh, it does not make sense to have less than 1 dimension if len(values[0].shape) >= 2: # if just 1d, it is most likely not an animation sequence_lengths.append(sequence_length) else: sequence_lengths.append(sequence_length) except IndexError: # scalars get ignored pass if hasattr(object, 'color'): color = object.color if color is not None: shape = color.shape if len(shape) == 3: # would be the case for for (frame, point_index, color_index) sequence_lengths.append(shape[0]) # TODO: maybe support arrays of string type of form (frame, point_index) if len(sequence_lengths) == len(sequence_lengths_previous): raise ValueError('no frame dimension found for object: {}'.format(object)) sequence_length = max(sequence_lengths) fig = gcf() fig.animation = interval fig.animation_exponent = 1. play = ipywidgets.Play(min=0, max=sequence_length - 1, interval=interval, value=0, step=1) slider = ipywidgets.FloatSlider(min=0, max=play.max, step=1) ipywidgets.jslink((play, 'value'), (slider, 'value')) for object in objects: ipywidgets.jslink((slider, 'value'), (object, 'sequence_index')) control = ipywidgets.HBox([play, slider]) if add: current.container.children += (control,) else: return control
def interactive_plot(num_frames=-1): max_frames = x.shape[0] - 1 if (num_frames == -1) or (num_frames > max_frames): num_frames = max_frames s = t[:, np.newaxis, np.newaxis] if anomalous == False: #print('not anomalous') data = x / np.sqrt(s) else: #print('anomalous') data = x / np.sqrt(s * np.log(s)) def update(s): fig, ax = plt.subplots() for d in range(part.dim): q = np.histogram(data[s, :, d], density=True) h = q[1] dh = np.diff(h) / 2 h = h[:-1] + dh hnew = np.linspace(h.min(), h.max(), 300) v = InterpolatedUnivariateSpline(h, q[0])(hnew) if anomalous == False: #print('not anomalous') n = norm_pdf(hnew, mu=0, var=2 * D) else: #print('anomalous') n = norm_pdf(hnew, mu=0, var=2 * D) ax.plot(hnew, v) ax.plot(hnew, n) l = widgets.Layout(width='150px') step_text = widgets.BoundedIntText(min=2, max=num_frames, value=0, layout=l) step_slider = widgets.IntSlider(min=2, max=num_frames, value=0, readout=False, continuous_update=False, layout=l) widgets.jslink((step_text, 'value'), (step_slider, 'value')) play_button = widgets.Play(min=2, max=num_frames, step=1, interval=50, layout=l) widgets.jslink((step_text, 'value'), (play_button, 'value')) img = widgets.interactive_output(update, {'s': step_text}) display( widgets.HBox( [widgets.VBox([step_text, step_slider, play_button]), img]))
def unit_player(self): # no player for static view if self.arg.static: return # compute timeline layer, legend, profile = self.arg.get() temp_path = self.arg.temp_path file_list = self.arg.file_list timeline = [t.split(".")[0] for t in self.arg.file_list] timeline = [parser.parse(t) for t in timeline] self.timeline = timeline # init widgets self.player = widgets.Play(value=0, min=0, max=len(timeline) - 1, interval=150) self.slider = widgets.SelectionSlider(value=timeline[0], options=timeline) self.speed = widgets.Dropdown( options=[("1", 250), ("2", 200), ("3", 150), ("4", 100), ("5", 50)], value=150, description="Speed:", layout=widgets.Layout( width="100px" ), style={ "description_width": "45px" } ) # slider change event def on_slider_change(change): i = self.timeline.index(change.new) self.player.value = i # regarding change on player img = os.path.join(temp_path, file_list[i]) layer.url = View.Layer.read_image(img) self.slider.observe(on_slider_change, names="value") # player change event def on_player_change(change): t = self.timeline[change.new] self.slider.value = t # regarding change on slider img = os.path.join(temp_path, file_list[change.new]) layer.url = View.Layer.read_image(img) self.player.observe(on_player_change, names="value") # speed change event widgets.link((self.speed, "value"), (self.player, "interval"))
def __init__(self, name): self.dirname = os.path.join(name, "") odtfile = max(glob.iglob("{}*.odt".format(self.dirname)), key=os.path.getctime) self.omffiles = sorted(glob.iglob("{}*.omf".format(self.dirname)), key=os.path.getctime) last_omf_file = max(glob.iglob("{}*.omf".format(self.dirname)), key=os.path.getctime) self.last_field = df.read_oommf_file(last_omf_file) self.dt = oommfodt.OOMMFodt(odtfile).df self.stage = self.dt["stage"].as_matrix() self.slider = ipywidgets.IntSlider( value=self.stage[0], min=self.stage[0], max=self.stage[-1], step=self.stage[1] - self.stage[0], description="Stage:", readout=True, layout=ipywidgets.Layout(width="80%"), continuous_update=False) self.slice_slider = ipywidgets.FloatSlider( value=0, min=0, max=1, step=0.01, description="Point:", readout=True, layout=ipywidgets.Layout(width="75.5%"), continuous_update=False) self.play = ipywidgets.Play(value=self.stage[0], min=self.stage[0], max=self.stage[-1], step=self.stage[1] - self.stage[0]) self.select = ipywidgets.RadioButtons(options=["x", "y", "z"], description="Slice:") ipywidgets.jslink((self.play, "value"), (self.slider, "value")) self.slider.observe(self.update_plot) self.slice_slider.observe(self.update_plot) self.select.observe(self.update_plot) self.out = ipywidgets.Output(layout=ipywidgets.Layout(width="300%")) self.update_plot(None)
def animation_control(object, sequence_length=None, add=True, interval=200): """Animate scatter, quiver or mesh by adding a slider and play button. :param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to control multiple. :param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly, you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance documented in :any:`scatter` or :any:`plot_mesh`. :param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you want to customise the layout of the widgets yourself. :param interval: interval in msec between each frame :return: If add is False, if returns the ipywidgets.HBox object containing the controls """ if isinstance(object, (list, tuple)): objects = object else: objects = [object] del object if sequence_length is None: # get all non-None arrays sequence_lengths = [] for object in objects: values = [ getattr(object, name) for name in "x y z vx vy vz".split() if hasattr(object, name) ] values = [k for k in values if k is not None] # sort them such that the higest dim is first values.sort(key=lambda key: -len(key.shape)) sequence_length = values[0].shape[ 0] # assume this defines the sequence length sequence_lengths.append(sequence_length) sequence_length = max(sequence_lengths) fig = gcf() fig.animation = interval fig.animation_exponent = 1. play = ipywidgets.Play(min=0, max=sequence_length - 1, interval=interval, value=0, step=1) slider = ipywidgets.FloatSlider(min=0, max=play.max, step=1) ipywidgets.jslink((play, 'value'), (slider, 'value')) for object in objects: ipywidgets.jslink((slider, 'value'), (object, 'sequence_index')) control = ipywidgets.HBox([play, slider]) if add: current.container.children += (control, ) else: return control
def __get_play_widget(function): # type: (typing.Any) -> typing.Any """ Generate play widget. :param function: Function to associate with Play. :return: Play widget. """ play = widgets.interactive(function, i=widgets.Play(value=0, min=0, max=500, step=1, interval=5000, description="Press play", disabled=False)) return play
def __init__(self, file, file_count): self.temp_data = load(file)['arrays'] self.frame = widgets.IntSlider( min=0, max=file_count, step=1, value=0, description='frame', layout=widgets.Layout(width='500px'), continuous_update=False, ) self.play_button = widgets.Play( min=0, max=file_count, step=1, disabled=False, ) self.link = widgets.jslink( (self.frame, 'value'), (self.play_button, 'value'), ) self.delay_box = widgets.FloatText( value=0.2, description='Delay', disabled=False, layout=widgets.Layout(width='240px', display='flex'), ) self.save_figure = widgets.Text( value='', placeholder='example.pdf', description='Save figure', disabled=False, layout=widgets.Layout(width='240px', display='flex'), ) self.save_all_plots = widgets.ToggleButton( value=False, description='Save all plots!', disabled=False, tooltip='Saves the corresponding plots for all the' + ' frames in the presently set styling.', icon='', ) self.particles = {} for array_name in self.temp_data.keys(): self.particles[array_name] = ParticleArrayWidgets( self.temp_data[array_name], )
def animate_list(lst, play=False, navigation=True, interval=200): """ Wrapper function that creates a widget with navigation over a list of visualization objects Args: lst: list of static visualization objects to navigate over play: if True, widget will contain basic audio like playbar navigation: if True, widget will contain prev and next buttons interval: if play=True, interval will set the delay between frame change (in ms) Returns: ipywidgets.interact object navigating over lst """ slider = widgets.IntSlider(min=0, max=len(lst) - 1, step=1, value=0) if navigation: prev_button = widgets.Button( description='Prev', disabled=False, ) next_button = widgets.Button( description='Next', disabled=False, ) def increment_value(arg): slider.value += 1 def decrement_value(arg): slider.value -= 1 prev_button.on_click(decrement_value) next_button.on_click(increment_value) if play: play_widget = widgets.Play(interval=interval) widgets.jslink((play_widget, 'value'), (slider, 'value')) if play or navigation: if play and navigation: display(widgets.HBox([play_widget, prev_button, next_button])) elif play: display(play_widget) elif navigation: display(widgets.HBox([prev_button, next_button])) return interact(step_slice, lst=fixed(lst), step=slider)
def animated_frames(animation_segments, animation_vertices): import matplotlib.pyplot as plt import numpy as np import os import ipywidgets from ipywidgets import interact, IntSlider from IPython.display import display plt.close() fig, ax = plt.subplots() title = ax.set_title("Iteration 0") def update(f: int = 0): ax.cla() frame_segments = animation_segments[f].T # frame_segments = animation_segments[f] frame_vertices = animation_vertices[f] if frame_vertices.size > 0: scatterplot = ax.scatter(frame_vertices[:, 0], frame_vertices[:, 1]) # TODO optimize the line below - done? lines = ax.scatter(frame_segments[0], frame_segments[1], 0.1, 'k') # lines = [ax.plot(segment[:, 0], segment[:, 1]) for segment in frame_segments] ax.axis('equal') title = ax.set_title(f"Iteration {f}/{len(animation_segments) - 1}") fig.canvas.draw() # fig.savefig(f"{folder}/{f:06}.png") plt.show() play = ipywidgets.Play(interval=200, value=0, min=0, max=len(animation_segments) - 1, step=1, description="Press play", disabled=False) slider = IntSlider(min=0, max=len(animation_segments) - 1, step=1) # w = interactive() link = ipywidgets.jslink((play, 'value'), (slider, 'value')) display(slider) # ipywidgets.HBox([play, slider]) # 1.png return interact(update, f=play)
def __init__(self, fpath, vis_fx=None, dtypes=("pcd", "image", "conf"), sleep=500): # Parse args self.fpath = fpath self.subdirs = [x for x in fpath.iterdir()] imgs = [] for sdir in self.subdirs: imgs += [ x.stem for x in self.fpath.glob(f"{str(sdir.stem)}/pcd/*.pcd") ] self.imgs = sorted(imgs) self.dtypes = dtypes self.vis_fx = vis_fx # Create all widgets self.selected = widgets.Text(value=imgs[0], layout={'width': '30%'}) self.play = widgets.Play(value=0, min=0, max=len(imgs) - 1, step=1, interval=sleep, disabled=False, continuous_update=False) self.slider = widgets.IntSlider( min=0, max=len(imgs) - 1, value=0, continuous_update=False, ) self.play.observe(self.change) self.slider.observe(self.change) widgets.jslink((self.play, "value"), (self.slider, "value")) vbox = widgets.VBox([self.selected, self.slider, self.play]) display(vbox) # Matplotlib 'canvas' init if self.vis_fx is not None: self.main_fig = plt.figure(figsize=(6, 6)) self.fig = self.main_fig.add_subplot(111) # Initial setup self.change({"name": "value"})
def pos_timelapse(arr,pos=0): """ Assumes the first column is 'pos' and the second column is time steps """ idx = arr['pos']==pos fig = plt.figure(f"position {pos}") im = plt.imshow(arr[idx][0]['image']) def on_value_change(change): i = change['new'] im.set_data(arr[idx][i]['image']) fig.canvas.draw() slider = widgets.IntSlider(min=0, max=np.sum(idx)-1, step=1, continuous_update=True) play = widgets.Play(min=0,max=np.sum(idx)-1, interval=200,_repeat=True,_playing=True,step=1) slider.observe(on_value_change, 'value') widgets.jslink((play, 'value'), (slider, 'value')) return widgets.HBox([play,slider])
def plot_solution(view): line_para = [] size = view['size'][0] xx, sol = view.apply(main, 1)[0] x_sc, y_sc = LinearScale(), LinearScale() ax_x = Axis(label='x', scale=x_sc, grid_lines='solid') ax_y = Axis(label='solution', scale=y_sc, orientation='vertical', grid_lines='solid') for i in range(size): line_para.append(Lines(x=xx[i], y=sol[0][i], scales={'x': x_sc, 'y': y_sc})) play = widgets.Play( value=0, min=0, max=100, step=1, description="Press play", disabled=False, continuous_update=False ) iteration = widgets.IntSlider(continuous_update=False) widgets.jslink((play, 'value'), (iteration, 'value')) def update_ite(iteration): import time for i in range(size): line_para[i].y=sol[iteration][i] time.sleep(.1) def change_overlap(overlap): xx[:], sol[:] = view.apply(main, overlap)[0] iteration.value = 0 update_ite(0) for i in range(size): line_para[i].x=xx[i] line_para[i].y=sol[0][i] widgets.interact(update_ite, iteration=iteration); overlap = widgets.IntSlider(value=1, min=0, max=20, step=1, continuous_update=False) widgets.interact(change_overlap, overlap=overlap) fig_para = Figure(axes=[ax_x, ax_y], marks=line_para, animation_duration=100) return widgets.VBox([widgets.HBox([play, iteration, overlap]), fig_para])
def make_controls(self): self.playbutton = ipy.Play(value=0, min=0, max=self.traj.num_frames - 1) self.slider = ipy.IntSlider(value_selects='framenum', value=0, description='Frame:', min=0, max=len(self.traj) - 1, readout=False) self.readout = ipy.HTML(value='/%d' % (self.traj.num_frames - 1)) self.annotation = ipy.HTML() traitlets.link((self.playbutton, 'value'), (self.slider, 'value')) traitlets.link((self.slider, 'value'), (self, 'current_frame')) return VBox( (self.annotation, HBox( (self.playbutton, self.slider, self.readout))))