def setup_play_level(level, on_update, interval=1000, min=1, max=8): play = Play(interval=interval, min=min, max=max, step=1) progress = IntProgress(min=min, max=max, step=1) link((play, 'value'), (progress, 'value')) play.observe(on_update, 'value') canvas_dimensions = level.get_canvas_dimensions() layout = Layout(width=f'{canvas_dimensions[0]}px') return play, progress, layout
def __init__(self, storage, setup): self.storage = storage self.setup = setup self.nans = None self.play = Play() self.step_slider = IntSlider() self.fps_slider = IntSlider(min=100, max=1000, description="1000/fps") self.plots = {} for var in setup.output_vars: self.plots[var] = Output() self.ims = {} self.reinit()
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 nb_play_movie(data,interval=30,shape = None,**kwargs): ''' Play a movie from the notebook ''' from ipywidgets import Play,jslink,HBox,IntSlider from IPython.display import display i = _handle_sparse(data[0],shape = shape) im = plt.imshow(i.squeeze(),**kwargs) slider = IntSlider(0,min = 0,max = data.shape[0]-1,step = 1,description='Frame') play = Play(interval=interval, value=0, min=0, max=data.shape[0]-1, step=1, description="Press play", disabled=False) jslink((play, 'value'), (slider, 'value')) display(HBox([play, slider])) def updateImage(change): i = _handle_sparse(data[change['new']],shape=shape) im.set_data(i.squeeze()) slider.observe(updateImage, names='value') return dict(fig = plt.gcf(), ax=plt.gca(), im= im, update = updateImage)
def show(): max_depth = 5 depth = IntSlider(value=1, min=1, max=max_depth, continuous_update=False) play = Play(interval=1000, value=1, min=1, max=max_depth, step=1) jslink((play, 'value'), (depth, 'value')) output = interactive_output(plot, dict(depth=depth)) display(play, output)
def show(): max_ = max_iter * n_scenes i = IntSlider(value=0, min=0, max=max_, continuous_update=False) play = Play(interval=2000, value=0, min=0, max=max_, step=1) jslink((play, 'value'), (i, 'value')) output = interactive_output(plot, dict(i=i)) display(play, output)
def show_result(lim=20): """Display filter result.""" global error x, m, data, error = _load() fig = Figure(lim=lim) fig.hline.opacities = [0.75] estline = fig.add_line([], [], 'go') def run(i, tail=True, sleep=0): if i == 0: fig.clear_tail() xi = x[:, i] mi = m[:, i] di = data[i] fig.update(xi, tail=tail, data=di) estline.x = [mi[0]] estline.y = [mi[1]] time.sleep(sleep) play = Play(value=0, min=0, max=1000, step=1) playbar = IntSlider(value=0, min=0, max=1000) jslink((play, 'value'), (playbar, 'value')) w = interactive(run, i=play, tail=True, sleep=_spd_sld()) display(HBox((fig.fig, VBox([w, playbar]))))
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 show(): max_ = sum([(len(movement) - 1) * n_scenes for movement in history]) + n_intro - 1 i = IntSlider(value=0, min=0, max=max_, continuous_update=False) play = Play(interval=1000, value=0, min=0, max=max_, step=1) jslink((play, 'value'), (i, 'value')) output = interactive_output(plot, dict(i=i)) display(play, output)
def create_video_player(fps: int, number_of_frames: int) -> Play: return Play(value=0, min=0, max=number_of_frames, step=1, interval=1000 / fps, description='Press play', disabled=False)
def __init__(self, storage, setup): self.storage = storage self.setup = setup self.nans = None self.play = Play() self.step_slider = IntSlider() self.fps_slider = IntSlider(min=100, max=1000, description="1000/fps") self.plots = {} self.plots_box = Box( children=tuple(self.plots.values()), layout=Layout(display='flex', flex_flow='column') ) self.reinit({})
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 __init__(self, storage, setup): self.storage = storage self.setup = setup self.nans = None self.play = Play() self.step_slider = IntSlider() self.fps_slider = IntSlider(min=100, max=1000, description="1000/fps") self.product_select = Select() self.plots_box = Box() self.slider = {} self.lines = {'x': [{}, {}], 'y': [{}, {}]} for xy in ('x', 'y'): self.slider[xy] = IntRangeSlider(min=0, max=1, description=f'spectrum_{xy}', orientation='horizontal' if xy == 'x' else 'vertical') self.reinit({})
def show(): value = 1 value_min = 1 value_max = reputation random_state = IntSlider(value=value, min=value_min, max=value_max, continuous_update=False) play = Play(interval=1000, value=value, min=value_min, max=value_max) jslink((play, 'value'), (random_state, 'value')) controller = HBox([play, random_state]) output = interactive_output(plot, dict(random_state=random_state)) display(controller, output)
def build(self): self.geomap.observe(self.plot_yearly_income_per_province, "selected") play_button = Play(min=1995, max=2001, interval=1000, layout=Layout(width="100%")) self.year_slider.observe(self.update_income, "value") jslink((play_button, "value"), (self.year_slider, "value")) map_figure = self.create_map_figure() lineplot_figure = self.create_lineplot_figure() return VBox([ HBox([play_button, self.year_slider]), map_figure, lineplot_figure ])
def configure_controllers(self): from ipywidgets import (IntSlider, interactive, Play, VBox, HBox, Label, jslink) super().configure_controllers() # orientation self.controllers["orientation"] = interactive( self.set_orientation, orientation=self.brain.orientation, ) # smoothing self.sliders["smoothing"] = IntSlider( value=self.brain._data['smoothing_steps'], min=self.brain.default_smoothing_range[0], max=self.brain.default_smoothing_range[1], continuous_update=False ) self.controllers["smoothing"] = VBox([ Label(value='Smoothing steps'), interactive( self.brain.set_data_smoothing, n_steps=self.sliders["smoothing"] ) ]) # time slider max_time = len(self.brain._data['time']) - 1 if max_time >= 1: time_player = Play( value=self.brain._data['time_idx'], min=0, max=max_time, continuous_update=False ) time_slider = IntSlider( min=0, max=max_time, ) jslink((time_player, 'value'), (time_slider, 'value')) time_slider.observe(self.set_time_point, 'value') self.controllers["time"] = VBox([ HBox([ Label(value='Select time point'), time_player, ]), time_slider, ]) self.sliders["time"] = time_slider
def _frame_folder(self, nframes): playable = bool(nframes <= 1) flims = dict(min=0, max=nframes - 1, step=1, value=0) control = Button(description=' Animate', icon='play') content = _ListDict([('playing', Play(disabled=playable, **flims)), ('scn_frame', IntSlider(description='Frame', **flims))]) def _scn_frame(c): for scn in self.active(): scn.frame_idx = c.new content['scn_frame'].observe(_scn_frame, names='value') content['playing'].active = False jslink((content['playing'], 'value'), (content['scn_frame'], 'value')) folder = Folder(control, content) return folder
def __init__(self, storage, setup): self.storage = storage self.setup = setup self.play = Play(interval=1000) self.step_slider = IntSlider(continuous_update=False, description='t/dt:') self.product_select = Dropdown() self.plots_box = Box() self.slider = {} self.lines = {'X': [{}, {}], 'Z': [{}, {}]} for xz in ('X', 'Z'): self.slider[xz] = IntRangeSlider( min=0, max=1, description=f'{xz}', continuous_update=False, orientation='horizontal' if xz == 'X' else 'vertical') self.reinit({})
class DemoViewer: def __init__(self, storage, setup): self.storage = storage self.setup = setup self.nans = None self.play = Play() self.step_slider = IntSlider() self.fps_slider = IntSlider(min=100, max=1000, description="1000/fps") self.plots = {} self.plots_box = Box( children=tuple(self.plots.values()), layout=Layout(display='flex', flex_flow='column') ) self.reinit({}) def clear(self): self.plots_box.children = () def reinit(self, products): self.products = products self.plots.clear() for var in products.keys(): self.plots[var] = Output() self.ims = {} self.axs = {} self.nans = np.full((self.setup.grid[0], self.setup.grid[1]), np.nan) # TODO: np.nan for key in self.plots.keys(): with self.plots[key]: clear_output() _, ax = plt.subplots(1, 1) product = self.products[key] self.ims[key], self.axs[key] = plotter.image(ax, self.nans, self.setup.size, label=f"{product.description} [{product.unit}]", # cmap=self.clims[key][2], # TODO: Reds, Blues, YlGnBu... scale=product.scale ) self.ims[key].set_clim(vmin=product.range[0], vmax=product.range[1]) plt.show() self.plots_box.children = tuple(self.plots.values()) n_steps = len(self.setup.steps) self.step_slider.max = n_steps - 1 self.play.max = n_steps - 1 self.play.value = 0 self.step_slider.value = 0 self.replot(step=0) def handle_replot(self, bunch): self.replot(bunch.new) def replot(self, step): for key in self.plots.keys(): try: data = self.storage.load(self.setup.steps[step], key) except self.storage.Exception: data = self.nans plotter.image_update(self.ims[key], self.axs[key], data) for key in self.plots.keys(): with self.plots[key]: clear_output(wait=True) display(self.ims[key].figure) def box(self): jslink((self.play, 'value'), (self.step_slider, 'value')) jslink((self.play, 'interval'), (self.fps_slider, 'value')) self.play.observe(self.handle_replot, 'value') return VBox([ Box([self.play, self.step_slider, self.fps_slider]), self.plots_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
def _create_controls( self, time: types_timeindex, show_data_labels: bool, show_labels: bool, show_origins: bool, show_traces: bool, show_vectors: bool, show_wireframe: bool, ): """Create the control panel. Parameters ---------- time : pandas.DatetimeIndex, pandas.TimedeltaIndex, List[pandas.Timestamp], or \ LocalCoordinateSystem The time steps that should be plotted initially show_data_labels : bool If `True`, the data labels will be shown initially show_labels : bool If `True`, the coordinate system labels will be shown initially show_origins : bool If `True`, the coordinate systems' origins will be shown initially show_traces : bool If `True`, the coordinate systems' traces will be shown initially show_vectors : bool If `True`, the coordinate systems' axis vectors will be shown initially show_wireframe : bool If `True`, spatial data containing mesh data will be drawn as wireframe """ num_times = 1 disable_time_widgets = True lo = Layout(width="200px") # create widgets if time is not None: num_times = len(time) disable_time_widgets = False play = Play( min=0, max=num_times - 1, value=self._current_time_index, step=1, ) time_slider = IntSlider( min=0, max=num_times - 1, value=self._current_time_index, description="Time:", ) reference_dropdown = Dropdown( options=self._csm.coordinate_system_names, value=self._current_reference_system, description="Reference:", disabled=False, ) data_dropdown = Dropdown( options=SpatialDataVisualizer.visualization_methods, value="auto", description="data repr.:", disabled=False, layout=lo, ) lo = Layout(width="200px") vectors_cb = Checkbox(value=show_vectors, description="show vectors", layout=lo) origin_cb = Checkbox(value=show_origins, description="show origins", layout=lo) traces_cb = Checkbox(value=show_traces, description="show traces", layout=lo) labels_cb = Checkbox(value=show_labels, description="show labels", layout=lo) wf_cb = Checkbox(value=show_wireframe, description="show wireframe", layout=lo) data_labels_cb = Checkbox( value=show_data_labels, description="show data labels", layout=lo ) jslink((play, "value"), (time_slider, "value")) play.disabled = disable_time_widgets time_slider.disabled = disable_time_widgets # callback functions def _reference_callback(change): self.update_reference_system(change["new"]) def _time_callback(change): self.update_time_index(change["new"]) def _vectors_callback(change): self.show_vectors(change["new"]) def _origins_callback(change): self.show_origins(change["new"]) def _traces_callback(change): self.show_traces(change["new"]) def _labels_callback(change): self.show_labels(change["new"]) def _data_callback(change): self.set_data_visualization_method(change["new"]) def _data_labels_callback(change): self.show_data_labels(change["new"]) def _wireframe_callback(change): self.show_wireframes(change["new"]) # register callbacks time_slider.observe(_time_callback, names="value") reference_dropdown.observe(_reference_callback, names="value") vectors_cb.observe(_vectors_callback, names="value") origin_cb.observe(_origins_callback, names="value") traces_cb.observe(_traces_callback, names="value") labels_cb.observe(_labels_callback, names="value") data_dropdown.observe(_data_callback, names="value") data_labels_cb.observe(_data_labels_callback, names="value") wf_cb.observe(_wireframe_callback, names="value") # create control panel row_1 = HBox([time_slider, play, reference_dropdown]) row_2 = HBox([vectors_cb, origin_cb, traces_cb, labels_cb]) if len(self._data_vis) > 0: row_3 = HBox([data_dropdown, wf_cb, data_labels_cb]) return VBox([row_1, row_2, row_3]) return VBox([row_1, row_2])
nation_line.visible = False wealth_scat.observe(hover_changed, 'hovered_point') # %% [markdown] # On the slider value `callback` (a function that is triggered everytime the `value` of the slider is changed) we change the `x`, `y` and `size` co-ordinates of the `Scatter`. We also update the `text` of the `Label` to reflect the current year. # %% {"collapsed": true} def year_changed(change): wealth_scat.x, wealth_scat.y, wealth_scat.size = get_data( year_slider.value) year_label.text = [str(year_slider.value)] year_slider.observe(year_changed, 'value') # %% [markdown] # #### Add an animation button # %% {"collapsed": true} play_button = Play(min=1800, max=2008, interval=time_interval) jslink((play_button, 'value'), (year_slider, 'value')) # %% [markdown] # #### Displaying the GUI # %% {"scrolled": false} VBox([HBox([play_button, year_slider]), fig])
def __init__(self, volume=None, default_directory=os.getcwd(), title='', enhancement_steps=1000, **kwargs): def on_chosen_path_change(old_path, new_path): self.dataset = FolderDataset(new_path) # TODO: If the path doesn't contain images, display a warning # A widget for changing the image folder self.pathchooser = PathChooser( chosen_path_desc='Image folder:', default_directory=default_directory, on_chosen_path_change=on_chosen_path_change, ) self.pathchooser.layout.margin = '0 0 10px 0' # The number of increments of the min/max slider self.enhancement_steps = enhancement_steps self.scales = { 'x': LinearScale(), 'y': LinearScale(), } # The currently displayed image will be in bytes at `self.image_plot.image.value` self.image_plot = BQImage( image=IPyImage(), scales=self.scales, ) self.figure = Figure( marks=[self.image_plot], padding_x=0, padding_y=0, animation_duration=1000, fig_margin={ 'top': 0, 'right': 0, 'bottom': 0, 'left': 0, }, layout=Layout( grid_area='figure', margin='0', width='320px', height='320px', ), ) # Custom toolbar toolbar_width = '100%' toolbar_margin = '0px 0 2px 0' self.pan_zoom = PanZoom(scales={ 'x': [self.scales['x']], 'y': [self.scales['y']], }, ) self.save_button = Button( description='Save Image', tooltip='Save Image', icon='save', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.save_button.on_click(self.save_current_image) self.hide_button = Button( description='Hide Image', tooltip='Hide Image', icon='eye-slash', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, )) self.hide_button.on_click(self.hide_current_image) self.pan_zoom_toggle_button = ToggleButton( description='Pan / Zoom', tooltip='Pan/Zoom', icon='arrows', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.pan_zoom_toggle_button.observe(self.on_pan_zoom_toggle, names='value') self.reset_pan_zoom_button = Button( description='Undo Zoom', tooltip='Reset pan/zoom', icon='refresh', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.reset_pan_zoom_button.on_click(self.reset_pan_zoom) self.reset_enhancements_button = Button( description='Un-Enhance', tooltip='Reset enhancements', icon='ban', layout=Layout( width=toolbar_width, # flex='1 1 auto', margin=toolbar_margin, ), ) self.reset_enhancements_button.on_click(self.reset_enhancements) self.mini_map = IPyImage(layout=Layout( grid_area='mini-map', margin='0', )) self.mini_map.width = 180 self.mini_map.height = 180 # PERFORMANCE CONCERN # Ideally instead of four observations, this would observe 'scales' on `self.pan_zoom` # However, it doesn't fire updates # Ref: https://github.com/bloomberg/bqplot/issues/800 self.image_plot.scales['x'].observe(self.on_pan_zoom_change('x_min'), names='min') self.image_plot.scales['x'].observe(self.on_pan_zoom_change('x_max'), names='max') self.image_plot.scales['y'].observe(self.on_pan_zoom_change('y_min'), names='min') self.image_plot.scales['y'].observe(self.on_pan_zoom_change('y_max'), names='max') self.plane_toggle = ToggleButtons( options=['yz', 'xz', 'xy'], description='', disabled=False, button_style='', tooltips=[ 'Step in x direction', 'Step in y direction', 'Step in z direction' ], layout=Layout( width='200px', # flex='1 1 auto', margin='7px 0 auto auto', ), ) self.plane_toggle.style.button_width = 'auto' self.plane_toggle.observe(self.on_plane_change, names='value') self.toolbar = VBox( children=[ self.save_button, self.hide_button, self.pan_zoom_toggle_button, self.reset_pan_zoom_button, self.reset_enhancements_button, ], layout=Layout( grid_area='toolbar', margin='0', ), ) # Image enhancements self.min_max_slider = FloatRangeSlider( value=[0, 255], min=0, max=255, step=255 / self.enhancement_steps, description='Min/Max:', orientation='horizontal', readout=True, readout_format='.1f', continuous_update=True, layout=Layout( grid_area='min-max-slider', margin='10px 0 10px -10px', width='100%', ), ) self.min_max_slider.observe(self.on_min_max_change, names='value') self.index_slider = IntSlider( value=0, min=0, max=1, step=1, description='Index:', orientation='horizontal', readout=True, readout_format='d', continuous_update=True, layout=Layout( grid_area='index-slider', margin='8px -20px 10px -36px', width='100%', ), ) self.index_slider.observe(self.on_image_index_change, names='value') # Animation self.play = Play( value=self.index_slider.value, min=self.index_slider.min, max=self.index_slider.max, step=self.index_slider.step, ) jslink((self.play, 'value'), (self.index_slider, 'value')) # Keep 'max' in sync as well self.index_slider.observe(self.on_index_slider_max_change, names='max') self.bottom_bar = HBox( children=[ self.play, self.index_slider, self.plane_toggle, ], layout=Layout( grid_area='bottom-bar', margin=f'10px -20px 0 0', # overflow='hidden', )) # Layout self.gridbox = GridBox(children=[ self.figure, self.toolbar, self.mini_map, self.min_max_slider, self.bottom_bar, ], ) # Initially hidden without data self.gridbox.layout.display = 'none' self._dataset = None if volume is not None: self.dataset = VolumeDataset(volume) # Hide pathchooser when using a volume self.pathchooser.layout.display = 'none' # Call VBox super class __init__ super().__init__( children=[ self.pathchooser, self.gridbox, ], layout=Layout(width='auto'), **kwargs, )
def show_m(): multipoly = [] multycent = [] geom = spatial_utils.transform_geometry(info_data) poly = geom['geom'][0]['coordinates'][0] # poly = spatial_utils.swap_xy(geom['coordinates'][0])[0] multipoly.append(poly) centroid = spatial_utils.centroid(poly) multycent.append(centroid) centroid = spatial_utils.centroid(multycent) m = Map(center=centroid, zoom=16, basemap=basemaps.OpenStreetMap.Mapnik) polygon = Polygon(locations=multipoly, name='Parcel polygon', color="yellow", fill_color=None) m.add_layer(polygon) basemap2 = basemap_to_tiles(basemaps.Esri.WorldImagery) poly_text = HTML() poly_text.value = f"""Parcel ID: {pid}<br> Crop name: {crop_name}<br> Area: {area:.2f} sqm<br> Coordinates: {centroid} """ poly_text.placeholder = "HTML" poly_text.description = "" # Popup with a given location on the map: poly_popup = Popup(child=poly_text, close_button=False, auto_close=False, close_on_escape_key=False) m.add_layer(poly_popup) polygon.popup = poly_popup # Popup associated to a layer # Layers control show_poly = Checkbox(value=True, description='Polygon', indent=False, layout=Layout(width='140px')) show_sat = Checkbox(value=False, description='High res basemap', indent=False, layout=Layout(width='140px')) def polygon_changed(b): try: if show_poly.value is True: m.add_layer(polygon) else: m.remove_layer(polygon) except Exception: pass show_poly.observe(polygon_changed) def show_sat_changed(b): try: if show_sat.value is True: m.add_layer(basemap2) else: m.remove_layer(basemap2) except Exception: pass show_sat.observe(show_sat_changed) try: df = raster_utils.create_df(ci_path, pid, ci_band.value) geotiff = normpath( join(ci_path, f"{df['imgs'][0]}.{ci_band.value[0]}.tif")) bounds = raster_utils.bounds(geotiff) images = {} for i, row in df.iterrows(): str_date = str(row['date'].date()).replace('-', '') img_tc = normpath( join(ci_path, f"{('').join(ci_band.value)}_{str_date}.png")) # Create false color image if it does not exist # Merge bands (images path, export image path, bands list) if not isfile(img_tc): imgs_path = normpath(join(ci_path, row['imgs'])) raster_utils.merge_bands(imgs_path, img_tc, ci_band.value) if bool(config.get_value(['set', 'jupyterlab'])) is True: jlab_path = os.getcwd().replace(os.path.expanduser("~"), '') image_path = normpath(join(f'files{jlab_path}', img_tc)) else: image_path = img_tc # print('image_path: ', image_path) images[i] = ImageOverlay(url=image_path, name=str_date, bounds=(bounds)) # Time slider slider = IntSlider(value=1, min=1, max=len(images), step=1, description=str(df['date'][0].date()), continuous_update=False, orientation='horizontal', readout=True, readout_format='d') show_chip = Checkbox(value=True, description='Chip image', indent=False, layout=Layout(width='140px')) def on_ci_band_change(change): pass ci_band.observe(on_ci_band_change, 'value') def show_chip_changed(b): try: if show_chip.value is True: m.add_layer(images[slider.value - 1]) else: m.remove_layer(images[slider.value - 1]) except Exception: pass show_chip.observe(show_chip_changed) # Slider control play = Play( value=1, min=1, max=len(images), step=1, interval=1000, description="Press play", ) def slider_changed(b): if show_chip.value is True: try: m.substitute_layer(images[b['old'] - 1], images[b['new'] - 1]) except Exception: pass slider.description = str(df['date'][slider.value - 1].date()) slider.observe(slider_changed) jslink((play, 'value'), (slider, 'value')) time_box = HBox([slider, play]) time_control = WidgetControl(widget=time_box, position='bottomleft') m.add_control(time_control) m.add_layer(images[0]) map_options = VBox([show_poly, show_chip, show_sat]) except Exception as err: map_options = VBox([show_poly, show_sat]) print(err) layers_control = WidgetControl(widget=map_options, position='topright', max_width=150) m.add_control(layers_control) return m
def show(): step = IntSlider(value=1, min=1, max=x.size) play = Play(interval=200, value=1, min=1, max=x.size, step=1) jslink((play, 'value'), (step, 'value')) output = interactive_output(plot, dict(step=step)) display(play, output)
def __init__(self): # Stores the respective line number and variable changes for each # exection step self._tracer = TimeTravelTracer() self._current_state = None self._debugger = None self._code_output = HTML() self._var_output = Output() self._watchpoint_output = Output() self._breakpoint_output = Output() self._diff_slider = IntSlider( min=1, readout=False, layout=Layout(width="99%"), tooltip="Execution timeline", ) self._diff_slider.observe(self._handle_diff_slider, names="value") self._autoplay = Play( tooltip="Automatic playback of the execution", layout=Layout(height="30px"), ) self._auto_link = jsdlink((self._autoplay, "value"), (self._diff_slider, "value")) self._speed_slider = IntSlider(description="Delay (ms)", min=100, max=1000, step=100, value=500) self._speed_link = jsdlink((self._speed_slider, "value"), (self._autoplay, "interval")) self._reverse_autoplay = ToggleButton( value=False, icon="history", tooltip="Reverse autoplay", layout=Layout(width="40px"), ) self._reverse_autoplay.observe(self._handle_reverse_button) self._watchpoint_input = Text( layout=Layout(width="150px"), placeholder="Watch expression", ) self._add_watchpoint = Button( icon="plus", tooltip="Add an expression or variable to watch", layout=Layout(width="50px"), ) self._add_watchpoint.on_click(self.watch_command) self._watchpoint_dropdown = Dropdown(layout=Layout(width="150px"), ) self._remove_watchpoint = Button( icon="trash", tooltip="Remove a watchpoint", layout=Layout(width="50px"), ) self._remove_watchpoint.on_click(self.unwatch_command) self._breakpoint_layout = GridspecLayout(3, 1) self._add_breakpoint = Button( icon="plus", tooltip="Add a breakpoint", name="breakpoint_button", layout=Layout(width="40px"), ) self._add_breakpoint.on_click(self._handle_breakpoint) self._disable_breakpoint_button = Button( icon="eye-slash", tooltip="Disable breakpoint", layout=Layout(width="50px"), ) self._disable_breakpoint_button.on_click(self.disable_command) self._remove_breakpoint_button = Button( icon="trash", tooltip="Remove breakpoint", layout=Layout(width="50px"), ) self._remove_breakpoint_button.on_click(self.delete_command) self._breakpoint_dropdown = Dropdown(layout=Layout(width="70px")) self._function_dropdown = Dropdown(layout=Layout(width="200px")) self._function_dropdown.disabled = True self._breakpoint_type = Dropdown( options=["Line", "Function", "Conditional"], value="Line", layout=Layout(width="100px"), ) self._breakpoint_type.observe(self._handle_breakpoint_type, names="value") self._condition_input = Text(placeholder="Enter condition", layout=Layout(width="200px")) self._condition_input.disabled = True self._line_input = Text( placeholder="Line Number", name="line_input", layout=Layout(width="100px"), ) self._breakpoint_layout = VBox([ HBox([ self._add_breakpoint, self._breakpoint_type, self._function_dropdown, self._line_input, self._condition_input, self._breakpoint_dropdown, self._remove_breakpoint_button, self._disable_breakpoint_button, ]), self._breakpoint_output, ]) self._search_input = Text(placeholder="Search...") self._search_input.observe(self._handle_search_input, names="value") self._search_results = Output() self._search_layout = VBox([ self._search_input, self._search_results, ]) # Remove shadows from scrolling style = """ <style> .jupyter-widgets-output-area .output_scroll { border-radius: unset !important; -webkit-box-shadow: unset !important; box-shadow: unset !important; } </style> """ display(HTML(style)) for key, item in self._BUTTONS.items(): self.register_button(key, **item) self._code_layout = GridspecLayout(4, 4, grid_gap="20px") self._code_layout[0:4, 0:3] = HBox( [self._code_output], layout=Layout(height="500px", overflow_y="scroll", border="2px solid black"), ) self._code_layout[0:2, 3] = self._var_output self._code_layout[2:4, 3] = VBox([ HBox([self._add_watchpoint, self._watchpoint_input]), HBox([self._remove_watchpoint, self._watchpoint_dropdown]), self._watchpoint_output, ]) self._code_nav_layout = VBox([ HBox([ *self.get_buttons(), self._autoplay, self._reverse_autoplay, self._speed_slider, ]), self._diff_slider, self._code_layout, ]) self._main_layout = Tab( [ self._code_nav_layout, self._breakpoint_layout, self._search_layout, ], layout=Layout(height="650px"), ) self._main_layout.set_title(0, "Code") self._main_layout.set_title(1, "Breakpoints") self._main_layout.set_title(2, "Search") display(self._main_layout)
def __init__(self, df: pd.DataFrame, box_col: str = 'box', img_col: str = 'image', text_cols: Union[str, List[str]] = None, text_fmts: Union[Callable, List[Callable]] = None, style_col: str = None): """ :param pd.DataFrame df: `DataFrame` with images and boxes :param str box_col: column in the dataframe that contains boxes :param str img_col: column in the dataframe that contains image paths :param Union[str, List[str]] text_cols: (optional) the column(s) in the dataframe to use for creating the text that is shown on top of a box. When multiple columns are give, the text will be created by a comma-separated list of the contents of the given columns. :param Unions[Callable, List[Callable]] text_fmts: (optional) a callable, or list of callables, that takes the corresponding value from the `text_cols` column(s) as an input and returns the string to print for that value. :param str style_col: the column containing a dict of style attributes. Available attributes are: - `stroke_width`: the stroke width of a box (default 2) - `stroke_color`: the stroke color of a box (default 'red') - `fill_color`: the fill color of a box (default '#00000000') - `hover_fill`: the fill color of a box when it is hovered on (default '#00000088') - `hover_stroke`: the stroke color of a box when it is hovered on (default 'blue') - `active_fill`: the fill color of a box when it is clicked on (default '#ffffff22') - `active_stroke`: the stroke color of a box when it is clicked on (default 'green') - `font_family`: the font family to use for box text (default 'arial'). NOTE: exported text will always be Arial. - `font_size`: the font size in points (default 10) """ if text_cols is None: text_cols = [] if isinstance(text_cols, str): text_cols = [text_cols] if text_fmts is None: text_fmts = [None] * len(text_cols) if isinstance(text_fmts, Callable): text_fmts = [text_fmts] self.text_cols = text_cols self.text_fmts = text_fmts df2 = df.copy() def row2text(row): txts = row[text_cols] return ', '.join([ fmt(txt) if fmt is not None else str(txt) for txt, fmt in zip(txts, self.text_fmts) ]) if style_col is None: style_col = '_dfim_style' df2[style_col] = [DEFAULT_STYLE] * len(df2) else: df2[style_col] = df2[style_col].apply(lambda s: { k: s[k] if k in s else DEFAULT_STYLE[k] for k in DEFAULT_STYLE }) df2['box_text'] = df2.apply(lambda row: row2text(row), axis=1) df2['box_dict'] = df2.apply( lambda row: dict(index=row.name, box=row[box_col], text=row['box_text'], style=row[style_col]) if (box_col in row.index and row[box_col] is not None) else None, axis=1) self.df_img = df2.groupby(img_col).agg(list).reset_index() self.df = df self.img_col = img_col self.box_col = box_col # SELECTION widget self.idx_wgt = BoundedIntText(value=0, min=0, max=len(self.df_img) - 1, step=1, description='Choose index', disabled=False) self.drop_wgt = Dropdown(options=self.df_img[img_col], description='or image', value=None, disabled=False) self.drop_wgt.observe(self.drop_changed, names='value') self.idx_wgt.observe(self.idx_changed, names='value') self.imsel_wgt = VBox([self.idx_wgt, self.drop_wgt]) self.imsel_wgt.layout = Layout(margin='auto') # IMAGE PANE self.img_title = HTML(placeholder='(Image path)') self.img_title.layout = Layout(margin='auto') self.imbox_wgt = ImBoxWidget() self.imbox_wgt.layout = Layout(margin='1em auto') self.imbox_wgt.observe(self.box_changed, names='active_box') self.imbox_wgt.observe(self.img_changed, names='img') # DETAILS PANE self.crop_wgt = CropBoxWidget() self.crop_wgt.layout = Layout(margin='0 1em') self.detail_wgt = DetailsWidget() self.detail_wgt.layout = Layout(margin='auto') self.detail_pane = HBox([self.crop_wgt, self.detail_wgt]) self.detail_pane.layout = Layout(margin='1em auto') # PLAY widget self.play_btns = Play(interval=100, value=0, min=0, max=len(self.df_img) - 1, step=1, description="Play", disabled=False) self.play_slider = widgets.IntSlider(value=0, min=0, max=len(self.df_img) - 1, step=1) widgets.jslink((self.play_btns, 'value'), (self.idx_wgt, 'value')) widgets.jslink((self.play_btns, 'value'), (self.play_slider, 'value')) self.play_wgt = widgets.HBox([self.play_btns, self.play_slider]) self.play_wgt.layout = Layout(margin='auto') # IMAGE EXPORT widget self.imexp_dest = Text(description='Output file', value='output/output.png') self.imexp_btn = Button(description='Export') self.imexp_btn.on_click(self.export_img) self.imexp_wgt = HBox([self.imexp_dest, self.imexp_btn]) # VIDEO EXPORT widget self.videxp_dest = Text(description='Output file', value='output/output.mp4') self.videxp_start = BoundedIntText(value=0, min=0, max=len(self.df_img) - 1, step=1, description='From index', disabled=False) self.videxp_start.observe(self.vididx_changed, names='value') self.videxp_end = BoundedIntText(value=0, min=0, max=len(self.df_img) - 1, step=1, description='Until index', disabled=False) self.videxp_end.observe(self.vididx_changed, names='value') self.videxp_fps = FloatText(value=30, description='FPS') self.videxp_btn = Button(description='Export') self.videxp_btn.on_click(self.export_vid) self.videxp_wgt = VBox([ HBox([self.videxp_start, self.videxp_end]), HBox([self.videxp_dest, self.videxp_fps]), self.videxp_btn ]) self.exp_wgt = Tab(children=[self.imexp_wgt, self.videxp_wgt]) self.exp_wgt.set_title(0, 'Export image') self.exp_wgt.set_title(1, 'Export video') self.exp_wgt.layout = Layout(margin='0 1em') super().__init__([ self.imsel_wgt, VBox([ self.img_title, self.imbox_wgt, self.play_wgt, self.detail_pane ]), self.exp_wgt ]) self.idx_changed({'new': 0})
class DemoViewer: def __init__(self, storage, setup): self.storage = storage self.setup = setup self.nans = None self.play = Play() self.step_slider = IntSlider() self.fps_slider = IntSlider(min=100, max=1000, description="1000/fps") self.product_select = Select() self.plots_box = Box() self.slider = {} self.lines = {'x': [{}, {}], 'y': [{}, {}]} for xy in ('x', 'y'): self.slider[xy] = IntRangeSlider(min=0, max=1, description=f'spectrum_{xy}', orientation='horizontal' if xy == 'x' else 'vertical') self.reinit({}) def clear(self): self.plots_box.children = () def reinit(self, products): self.products = products self.product_select.options = [key for key, val in products.items() if len(val.shape) == 2] self.plots = {} for var in products.keys(): self.plots[var] = Output() self.ims = {} self.axs = {} self.figs = {} for j, xy in enumerate(('x', 'y')): self.slider[xy].max = self.setup.grid[j] self.nans = np.full((self.setup.grid[0], self.setup.grid[1]), np.nan) # TODO: np.nan for key in self.plots.keys(): with self.plots[key]: clear_output() product = self.products[key] if len(product.shape) == 2: data=self.nans domain_size_in_metres=self.setup.size cmap='YlGnBu' fig, ax = plt.subplots(1, 1) label = f"{product.description} [{product.unit}]" scale = product.scale ax.set_xlabel('X [m]') ax.set_ylabel('Z [m]') im = ax.imshow(_transform(data), origin='lower', extent=(0, domain_size_in_metres[0], 0, domain_size_in_metres[1]), cmap=cmap, norm=matplotlib.colors.LogNorm() if scale == 'log' and np.isfinite( data).all() else None ) plt.colorbar(im, ax=ax).set_label(label) im.set_clim(vmin=product.range[0], vmax=product.range[1]) x = self.slider['x'].value[0] * self.setup.size[0] / self.setup.grid[0] y = self.slider['y'].value[0] * self.setup.size[1] / self.setup.grid[1] self.lines['x'][0][key] = ax.axvline(x=x, color='red') self.lines['y'][0][key] = ax.axhline(y=y, color='red') x = self.slider['x'].value[1] * self.setup.size[0]/self.setup.grid[0] y = self.slider['y'].value[1] * self.setup.size[1]/self.setup.grid[1] self.lines['x'][1][key] = ax.axvline(x=x, color='red') self.lines['y'][1][key] = ax.axhline(y=y, color='red') elif len(product.shape) == 3: fig, ax = plt.subplots(1, 1) ax.set_xlim(np.amin(self.setup.v_bins), np.amax(self.setup.v_bins)) ax.set_ylim(0, 10) ax.set_xlabel("TODO [TODO]") ax.set_ylabel("TODO [TODO]") ax.set_xscale('log') ax.grid(True) im = ax.step(self.setup.v_bins[:-1], np.full_like(self.setup.v_bins[:-1], np.nan)) im = im[0] else: raise NotImplementedError() self.figs[key], self.ims[key], self.axs[key] = fig, im, ax plt.show() self.plot_box = Box() if len(products.keys()) > 0: self.plots_box.children = ( HBox(children=(self.slider['y'], VBox((self.slider['x'], self.plot_box)))), self.plots['Particles Size Spectrum'] ) n_steps = len(self.setup.steps) self.step_slider.max = n_steps - 1 self.play.max = n_steps - 1 self.play.value = 0 self.step_slider.value = 0 self.replot() def replot(self, _=None): if self.product_select.value in self.plots: self.plot_box.children = [self.plots[self.product_select.value]] step = self.step_slider.value for key in self.plots.keys(): try: data = self.storage.load(self.setup.steps[step], key) except self.storage.Exception: data = self.nans if len(self.products[key].shape) == 2: self.ims[key].set_data(_transform(data)) self.axs[key].set_title(f"min:{np.amin(data):.4g} max:{np.amax(data):.4g} std:{np.std(data):.4g}") self.lines['x'][0][key].set_xdata(x=self.slider['x'].value[0] * self.setup.size[0]/self.setup.grid[0]) self.lines['y'][0][key].set_ydata(y=self.slider['y'].value[0] * self.setup.size[1]/self.setup.grid[1]) self.lines['x'][1][key].set_xdata(x=self.slider['x'].value[1] * self.setup.size[0]/self.setup.grid[0]) self.lines['y'][1][key].set_ydata(y=self.slider['y'].value[1] * self.setup.size[1]/self.setup.grid[1]) elif len(self.products[key].shape) == 3: xrange = slice(*self.slider['x'].value) yrange = slice(*self.slider['y'].value) data = data[xrange, yrange, :] data = np.mean(np.mean(data, axis=0), axis=0) self.ims[key].set_ydata(data) amax = np.amax(data) if np.isfinite(amax): self.axs[key].set_ylim((0, amax)) else: raise NotImplementedError() for key in self.plots.keys(): with self.plots[key]: clear_output(wait=True) display(self.figs[key]) def box(self): jslink((self.play, 'value'), (self.step_slider, 'value')) jslink((self.play, 'interval'), (self.fps_slider, 'value')) self.play.observe(self.replot, 'value') self.product_select.observe(self.replot, 'value') for xy in ('x', 'y'): self.slider[xy].observe(self.replot, 'value') return VBox([ Box([self.play, self.step_slider, self.fps_slider]), self.product_select, self.plots_box ])
def _tool_bar_add_play_button(self, name, desc, func, shortcut=None): widget = Play(interval=500) self._layout_add_widget(self._tool_bar_layout, widget) self.actions[name] = widget return _IpyWidget(widget)
step=step, description=description) def _spd_sld(value=0, min=0.01, max=0.3, step=0.01, description=r'slowness'): """Create a slider for dt (controls the speed).""" return FloatSlider(value=value, min=min, max=max, step=step, description=description) dsct = DynamicPlotter(discrete, [1, 1], observe=_observe, i=Play(), sigma=_sigma_sld(), gamma=_sigma_sld(description=r'\(\gamma\)'), sleep=_spd_sld(value=0.5, max=1)) cnts = DynamicPlotter(continuous, [0, 1], observe=_observe, fig=Figure(lim=3), i=Play(), sigma=_sigma_sld(), gamma=_sigma_sld(description=r'\(\gamma\)'), dt=fixed(0.05), sleep=_spd_sld()) def do_filter(init_guess=[0, 1],