def on_select_to_plot(self, change): """Call-back function for plotting a 3D visualisaiton of the segmentation""" #if the selected file has changed, import image, segmentation and global mask and plot if change['new'] != change['old']: print('new: ' + str(change['new'])) print('old: ' + str(change['old'])) image = skimage.io.imread(self.folder_name + '/' + self.select_file_to_plot.value, plugin='tifffile') image2 = skimage.io.imread( self.folder_name + '/' + os.path.splitext(self.select_file_to_plot.value)[0] + '_label.tif', plugin='tifffile') image3 = skimage.io.imread( self.folder_name + '/' + os.path.splitext(self.select_file_to_plot.value)[0] + '_region.tif', plugin='tifffile') #create ipyvolume figure ipv.figure() volume_image = ipv.volshow(image[0, :, :, :, 1], extent=[[0, 1024], [0, 1024], [-20, 20]], level=[0.3, 0.2, 0.2], opacity=[0.2, 0, 0]) volume_seg = ipv.plot_isosurface(np.swapaxes(image2 > 0, 0, 2), level=0.5, controls=True, color='green', extent=[[0, 1024], [0, 1024], [-20, 20]]) volume_reg = ipv.volshow(image3, extent=[[0, 1024], [0, 1024], [-20, 20]], level=[0.3, 0.2, 1], opacity=[0.0, 0, 0.5]) volume_reg.brightness = 10 volume_image.brightness = 10 volume_image.opacity = 100 ipv.xyzlim(0, 1024) ipv.zlim(-500, 500) ipv.style.background_color('black') #create additional controls to show/hide segmentation color = ColorPicker(description='Segmentation color') visible = ipw.Checkbox() jslink((volume_seg, 'color'), (color, 'value')) jslink((volume_seg, 'visible'), (visible, 'value')) ipv.show() with self.out: clear_output(wait=True) display(VBox([ipv.gcc(), color, visible])) viewer = napari.Viewer(ndisplay=3) viewer.add_image(image, colormap='red') viewer.add_image(image2, colormap='green', blending='additive') viewer.add_image(image3, colormap='blue', blending='additive')
def __init__(self, *args, **kwargs): self.figure = ipv.figure(animation_exponent=1.) self.figure.selector = '' super(IpyvolumeBaseView, self).__init__(*args, **kwargs) # FIXME: hack for the movie maker to have access to the figure self.state.figure = self.figure # note that for ipyvolume, we use axis in the order x, z, y in order to have # the z axis of glue pointing up def attribute_to_label(attribute): return 'null' if attribute is None else attribute.label dlink((self.state, 'x_att'), (self.figure, 'xlabel'), attribute_to_label) dlink((self.state, 'y_att'), (self.figure, 'zlabel'), attribute_to_label) dlink((self.state, 'z_att'), (self.figure, 'ylabel'), attribute_to_label) self.state.add_callback('x_min', self.limits_to_scales) self.state.add_callback('x_max', self.limits_to_scales) self.state.add_callback('y_min', self.limits_to_scales) self.state.add_callback('y_max', self.limits_to_scales) if hasattr(self.state, 'z_min'): self.state.add_callback('z_min', self.limits_to_scales) self.state.add_callback('z_max', self.limits_to_scales) self.state.add_callback('visible_axes', self._update_axes_visibility) self._figure_widget = ipv.gcc() self.create_layout()
def complete(final_solution: Solution, correct_solution: Solution = None) -> None: """ Will print result in 3D world :return: Noting """ # init of plot-output #1 figure = plot.figure() axes = figure.add_subplot(111, projection='3d') for part in final_solution.partitions: color = random.choice(list_of_colors) marker = random.choice(list_of_marker) for p in part: axes.scatter(p.x, p.y, p.z, marker=marker, c=color) axes.set_xlabel("X Achse") axes.set_ylabel("Y Achse") axes.set_zlabel("Z Achse") plot.show() # init 3D view ipv.current.containers.clear() ipv.current.figures.clear() extra_figures = list() # create correct solution if correct_solution is not None: figure_correct = ipv.figure("correct") ipv.pylab.xyzlim(-1, 11) for part in correct_solution.partitions: marker = random.choice(list_of_IPYVmarker) color = random.choice(list_of_colors) ipv.scatter(*convert.partition_to_IpyVolume(part), marker=marker, color=color) extra_figures.append(figure_correct) figure_result = ipv.figure("result") container = ipv.gcc() ipv.current.container = widgets.HBox(container.children) ipv.current.containers["result"] = ipv.current.container # crate computed solution for part in final_solution.partitions: marker = random.choice(list_of_IPYVmarker) color = random.choice(list_of_colors) ipv.scatter(*convert.partition_to_IpyVolume(part), marker=marker, color=color) ipv.pylab.xyzlim(-1, 11) ipv.current.container.children = list( ipv.current.container.children) + extra_figures ipv.show() # save in a separate file ipv.save("example.html") # destroy 3D views ipv.clear()
def _add_title(self): u"""Add title to the current figure.""" if self._title is None: title = self._subject_id.capitalize() else: title = self._title title_w = widgets.HTML('<p style="color: %s">' % self._foreground + '<b>%s</b></p>' % title) hboxes = (widgets.HBox(f_row) for f_row in self._figures) ipv.gcc().children = (title_w, *hboxes)
def __init__(self, brain): if brain.data['time'] is None: raise ValueError('Brain class instance does not have time data.') self._brain = brain time = brain.data['time'] time_idx = brain.data['time_idx'] overlays = tuple(brain.overlays.values()) control = ipv.animation_control(overlays, len(time), add=False, interval=500) slider = control.children[1] slider.readout = False slider.value = time_idx label = widgets.Label(self._get_label(time[time_idx])) # hadler for changing of selected time moment def slider_handler(change): k = brain.data['k'] b = brain.data['b'] lut = brain.data['lut'] time_idx_new = int(change.new) for v in brain.views: for h in brain.hemis: act_data = brain.data[h + '_array'][:, time_idx_new] smooth_mat = brain.data[h + '_smooth_mat'] act_data = smooth_mat.dot(act_data) act_data = k * act_data + b act_data = np.clip(act_data, 0, 1) act_color_new = lut(act_data) brain.overlays[h + '_' + v].color = act_color_new # change label value label.value = self._get_label(time[time_idx_new]) slider.observe(slider_handler, names='value') control = widgets.HBox((*control.children, label)) ipv.gcc().children += (control,)
def __init__(self, *args, **kwargs): super(IpyvolumeBaseView, self).__init__(*args, **kwargs) self.state = self._state_cls() self.figure = ipv.figure(animation_exponent=1.) self.figure.on_selection(self.on_selection) self.create_tab() self.state.add_callback('x_min', self.limits_to_scales) self.state.add_callback('x_max', self.limits_to_scales) self.state.add_callback('y_min', self.limits_to_scales) self.state.add_callback('y_max', self.limits_to_scales) self.output_widget = widgets.Output() self.main_widget = widgets.VBox( children=[self.tab, ipv.gcc(), self.output_widget])
def quickvolshow( data, lighting=False, data_min=None, data_max=None, max_shape=256, level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, extent=None, memorder='C', **kwargs ): """Visualize a 3d array using volume rendering. :param data: 3d numpy array :param lighting: boolean, to use lighting or not, if set to false, lighting parameters will be overriden :param data_min: minimum value to consider for data, if None, computed using np.nanmin :param data_max: maximum value to consider for data, if None, computed using np.nanmax :param int max_shape: maximum shape for the 3d cube, if larger, the data is reduced by skipping/slicing (data[::N]), set to None to disable. :param extent: list of [[xmin, xmax], [ymin, ymax], [zmin, zmax]] values that define the bounds of the volume, otherwise the viewport is used :param level: level(s) for the where the opacity in the volume peaks, maximum sequence of length 3 :param opacity: opacity(ies) for each level, scalar or sequence of max length 3 :param level_width: width of the (gaussian) bumps where the opacity peaks, scalar or sequence of max length 3 :param kwargs: extra argument passed to Volume and default transfer function :return: """ ipv.figure() ipv.volshow( data, lighting=lighting, data_min=data_min, data_max=data_max, max_shape=max_shape, level=level, opacity=opacity, level_width=level_width, extent=extent, memorder=memorder, **kwargs ) return ipv.gcc()
def projection_3d(self): # Initialise Figure if not self.figure3d: self.fig3d = ipv.figure(width=config.plot.width, height=config.plot.height, animation=0, lighting=False) max_size = 0.0 dx = {"x": 0, "y": 0, "z": 0} for ax in dx.keys(): dx[ax] = np.ediff1d(self.minmax[ax]) max_size = np.amax(list(dx.values())) # Make plot outline if aspect ratio is to be conserved if self.aspect == "equal": arrays = dict() for ax, s in dx.items(): diff = max_size - s arrays[ax] = [ self.minmax[ax][0] - 0.5 * diff, self.minmax[ax][1] + 0.5 * diff ] outl_x, outl_y, outl_z = np.meshgrid(arrays["x"], arrays["y"], arrays["z"], indexing="ij") self.outline = ipv.plot_wireframe(outl_x, outl_y, outl_z, color="black") # Try to guess marker size perc_size = 100.0 * self.size / max_size self.scatter3d = ipv.scatter(x=self.det_pos[:, 0], y=self.det_pos[:, 1], z=self.det_pos[:, 2], marker="square_2d", size=perc_size) self.figure3d = True self.figurewidget.clear_output() self.box.children = tuple([self.figurewidget, ipv.gcc(), self.vbox]) return
def __init__(self, *args, **kwargs): self.state = self._state_cls() self.figure = ipv.figure(animation_exponent=1.) self.figure.selector = '' super(IpyvolumeBaseView, self).__init__(*args, **kwargs) self.create_tab() self.state.add_callback('x_min', self.limits_to_scales) self.state.add_callback('x_max', self.limits_to_scales) self.state.add_callback('y_min', self.limits_to_scales) self.state.add_callback('y_max', self.limits_to_scales) if hasattr(self.state, 'z_min'): self.state.add_callback('z_min', self.limits_to_scales) self.state.add_callback('z_max', self.limits_to_scales) self.output_widget = widgets.Output() self.main_widget = widgets.VBox( children=[self.widget_toolbar, widgets.HBox([ipv.gcc(), self.tab])])
def __init__(self, *args, **kwargs): self.figure = ipv.figure(animation_exponent=1.) self.figure.selector = '' super(IpyvolumeBaseView, self).__init__(*args, **kwargs) # FIXME: hack for the movie maker to have access to the figure self.state.figure = self.figure self.state.add_callback('x_min', self.limits_to_scales) self.state.add_callback('x_max', self.limits_to_scales) self.state.add_callback('y_min', self.limits_to_scales) self.state.add_callback('y_max', self.limits_to_scales) if hasattr(self.state, 'z_min'): self.state.add_callback('z_min', self.limits_to_scales) self.state.add_callback('z_max', self.limits_to_scales) self.state.add_callback('visible_axes', self._update_axes_visibility) self._figure_widget = ipv.gcc() self.create_layout()
def quickscatter(x, y, z, **kwargs): import ipyvolume as ipv ipv.figure() ipv.scatter(x, y, z, **kwargs) return ipv.gcc()
def __init__(self, scipp_obj_dict=None, axes=None, masks=None, cmap=None, log=None, vmin=None, vmax=None, color=None, aspect=None): super().__init__(scipp_obj_dict=scipp_obj_dict, axes=axes, masks=masks, cmap=cmap, log=log, vmin=vmin, vmax=vmax, color=color, aspect=aspect, button_options=['X', 'Y', 'Z']) self.cube = None self.members.update({"surfaces": {}, "wireframes": {}}) # Initialise Figure and VBox objects self.fig = ipv.figure(width=config.plot.width, height=config.plot.height, animation=0) self.scalar_map = cm.ScalarMappable( norm=self.params["values"][self.name]["norm"], cmap=self.params["values"][self.name]["cmap"]) self.permutations = {"x": ["y", "z"], "y": ["x", "z"], "z": ["x", "y"]} # Store min/max for each dimension for invisible scatter self.xminmax = dict() for dim, var in self.slider_x[self.name].items(): self.xminmax[dim] = [var.values[0], var.values[-1]] self.set_axes_range() self.wireframes = dict() self.surfaces = dict() # #==================================================================== # wframes = self.get_outlines() # meshes = self.get_meshes() # surf_args = dict.fromkeys(self.permutations) # wfrm_args = dict.fromkeys(self.permutations) # # print(wframes) # for xyz, perm in self.permutations.items(): # print(xyz, perm) # key = self.button_axis_to_dim[xyz] # wfrm_args[xyz] = np.ones_like(wframes[xyz][perm[0]]) * \ # self.slider_x[key].values[self.slider[key].value] # surf_args[xyz] = np.ones_like(meshes[xyz][perm[0]]) * \ # self.slider_x[key].values[self.slider[key].value] # for p in perm: # wfrm_args[p] = wframes[xyz][p] # surf_args[p] = meshes[xyz][p] # self.wireframes[xyz] = ipv.plot_wireframe(**wfrm_args, # color="red") # self.surfaces[xyz] = ipv.plot_surface(**surf_args, color="red") # #==================================================================== self.mouse_events = dict() self.last_changed_slider_dim = None for dim, sl in self.slider.items(): self.mouse_events[dim] = Event(source=sl, watched_events=['mouseup']) self.mouse_events[dim].on_dom_event(self.update_surface) # Call update_slice once to make the initial image self.update_axes() self.box = [ipv.gcc()] + self.vbox self.box = widgets.VBox(self.box) self.box.layout.align_items = 'center' self.members["fig"] = self.fig return
def get_globe(topofile, df, size=None, key=None): """Return an ipywidget with an interactive globe. Arguments: topofile: filename of a TopoJSON file to render. This file is expected to have its major regions arranged as a list in ['objects']['areas']['geometries']. df: dataframe where each row will be turned into an animation frame and columns are expected to match the major regions in the topofile. size: in integer pixels key: string key to pass to ipyvolume, allows replacement of earlier charts """ with open(topofile, 'r') as fid: topo = json.loads(fid.read()) (width, height) = (size, size) if size is not None else (500, 500) ipv.pylab.clear() fig = ipv.figure(width=width, height=height, key=key, controls=True) # Make a simple globe x, y, z = np.array([[0.], [0.], [0.]]) ipv.scatter(x, y, z, size=100, color='blue', marker="sphere") # draw raised outlines for each area animate = [] for area in topo['objects']['areas']['geometries']: name = area['id'] if name not in df.columns: continue lines = _extract_lines(topo, name=name) x = [] y = [] z = [] triangles = [] data = df.loc[:, name].fillna(0.0) for (year, row) in df.iterrows(): x_t = [0] y_t = [0] z_t = [0] tri_t = [] offset = 1 total = row.get('Total', row.get('World', 1.0)) val = row.get(name, 0.0) radius = 1.01 + (((val / total) * 0.15) if total > 0.0 else 0.0) for line in lines: xyz = [ _latlon2xyz(lat, lon, radius=radius) for (lon, lat) in line ] x1, y1, z1 = [list(t) for t in zip(*xyz)] x_t.extend(x1 + [0]) y_t.extend(y1 + [0]) z_t.extend(z1 + [0]) for _ in range(0, len(x1)): tri_t.append([0, offset, offset + 1]) offset += 1 offset += 1 x.append(x_t) y.append(y_t) z.append(z_t) triangles.append(tri_t) color = ui.color.webcolor_to_hex(ui.color.get_region_color(name)) s = ipv.scatter(x=-np.array(x), y=np.array(z), z=np.array(y), color=color, size=0.5, connected=True, marker='sphere') s.material.visible = False animate.append(s) s = ipv.pylab.plot_trisurf(-np.array(x), np.array(z), np.array(y), color=color, triangles=triangles) animate.append(s) ipv.animation_control(animate, interval=100) ipv.xyzlim(-1, 1) ipv.style.box_on() ipv.style.axes_off() return ipv.gcc()
def __init__(self, brain): self._brain = brain self._input_fmin = None self._input_fmid = None self._input_fmax = None self._btn_upd_mesh = None self._colors = None if brain.data['center'] is None: dt_min = brain.data['fmin'] dt_max = brain.data['fmax'] else: dt_min = -brain.data['fmax'] dt_max = brain.data['fmax'] self._lut = brain.data['lut'] self._cbar_data = np.linspace(0, 1, self._lut.N) cbar_ticks = np.linspace(dt_min, dt_max, self._lut.N) color = np.array((self._cbar_data, self._cbar_data)) cbar_w = 500 cbar_fig_margin = {'top': 15, 'bottom': 15, 'left': 5, 'right': 5} self._update_colors() x_sc, col_sc = LinearScale(), ColorScale(colors=self._colors) ax_x = Axis(scale=x_sc) heat = HeatMap(x=cbar_ticks, color=color, scales={'x': x_sc, 'color': col_sc}) self._add_inputs() fig_layout = widgets.Layout(width='%dpx' % cbar_w, height='60px') cbar_fig = Figure(axes=[ax_x], marks=[heat], fig_margin=cbar_fig_margin, layout=fig_layout) def on_update(but_event): u"""Update button click event handler.""" val_min = self._input_fmin.value val_mid = self._input_fmid.value val_max = self._input_fmax.value center = brain.data['center'] time_idx = brain.data['time_idx'] time_arr = brain.data['time'] if not val_min < val_mid < val_max: raise ValueError('Incorrect relationship between' + ' fmin, fmid, fmax. Given values ' + '{0}, {1}, {2}' .format(val_min, val_mid, val_max)) if center is None: # 'hot' or another linear color map dt_min = val_min dt_max = val_max else: # 'mne' or another divergent color map dt_min = -val_max dt_max = val_max self._lut = self._brain.update_lut(fmin=val_min, fmid=val_mid, fmax=val_max) k = 1 / (dt_max - dt_min) b = 1 - k * dt_max self._brain.data['k'] = k self._brain.data['b'] = b for v in brain.views: for h in brain.hemis: if (time_arr is None) or (time_idx is None): act_data = brain.data[h + '_array'] else: act_data = brain.data[h + '_array'][:, time_idx] smooth_mat = brain.data[h + '_smooth_mat'] act_data = smooth_mat.dot(act_data) act_data = k * act_data + b act_data = np.clip(act_data, 0, 1) act_color_new = self._lut(act_data) brain.overlays[h + '_' + v].color = act_color_new self._update_colors() x_sc, col_sc = LinearScale(), ColorScale(colors=self._colors) ax_x = Axis(scale=x_sc) heat = HeatMap(x=cbar_ticks, color=color, scales={'x': x_sc, 'color': col_sc}) cbar_fig.axes = [ax_x] cbar_fig.marks = [heat] self._btn_upd_mesh.on_click(on_update) info_widget = widgets.VBox((cbar_fig, self._input_fmin, self._input_fmid, self._input_fmax, self._btn_upd_mesh)) ipv.gcc().children += (info_widget,)
def get_frizzle_chart(df, ylabel, size=None, key=None, color=None): """Returns a 3D Frizz chart, one frizzle strip per column in the dataframe. Arguments: df: the DataFrame to graph. ylabel: text label to place on the Y axis. size: in integer pixels key: string key to pass to ipyvolume, allows replacement of earlier charts color: base color to generate a gradient from (if None, a default color will be used) Returns: an ipywidget """ (width, height) = (size, size) if size is not None else (500, 500) fig = ipv.figure(width=width, height=height, key=key, controls=True) if isinstance(color, str): color = ui.color.webcolor_to_rgb(color) if not color: color = (128, 128, 128) # Draw a strip of triangles for each region, tracing the dataframe values for (z, region) in enumerate(df.columns): years = list(df.index) nyears = len(years) year = years.pop(0) X = [year, year] y = df.loc[year, region] Y = [y, y] Z = [float(z), float(z) + 1.0] U = [0.0, 0.0] V = [0.0, 1.0] triangles = [] offset = 2 for (idx, year) in enumerate(years, 1): X.extend([year, year]) y = df.loc[year, region] Y.extend([y, y * 0.97]) Z.extend([float(z), float(z) + 0.95]) u = float(idx) / nyears U.extend([u, u]) V.extend([0.0, 1.0]) triangles.extend([[offset - 2, offset - 1, offset + 1], [offset - 2, offset, offset + 1]]) offset += 2 img = PIL.Image.new(mode='RGB', size=(1000, 100), color=color) draw = PIL.ImageDraw.Draw(img) font = PIL.ImageFont.truetype( os.path.join('data', 'fonts', 'Roboto-Medium.ttf'), 85) draw.text(xy=(40, 0), text=region, fill=(255, 250, 250), font=font) ipv.pylab.plot_trisurf(np.array(X), np.array(Y), np.array(Z), triangles=triangles, u=U, v=V, texture=img.transpose( PIL.Image.FLIP_TOP_BOTTOM)) ipv.style.box_on() ipv.pylab.xlabel('Year') first_year = df.index[0] last_year = df.index[-1] ipv.pylab.xlim(first_year - 2, last_year + 2) ipv.pylab.ylabel(ylabel) ipv.pylab.zlabel('Region') nregions = len(df.columns) ipv.pylab.zlim(-0.5, nregions + 0.5) ipv.pylab.view(10.0, 10.0, 3.0) ipv.pylab.view(-24.46, 73.7, 2.32) return ipv.gcc()
def quickscatter(x, y, z, **kwargs): ipv.figure() ipv.scatter(x, y, z, **kwargs) return ipv.gcc()
def scatter(points, labels=None, labels_gt=None, colors=None, cmap=cm.RdBu, reorder_colors=True, normals=None, width=800, height=600, axeslim='auto', aspect_ratio_preserve=True, point_size_value=0.5, vector_size_value=0.5, title=None): if normals is not None: assert len(points) == len( normals ), "Length incorrect. These are not normals of points, may be." points = points.astype(np.float32) x = points[:, 0] y = points[:, 1] z = points[:, 2] # draw ipv.figure(width=width, height=height) set_axes_lims(points, axeslim=axeslim, aspect_ratio_preserve=aspect_ratio_preserve) is_multilabels = isinstance(labels, (list, tuple)) if is_multilabels: colors_by_labels = [] for vl in labels: colors_by_labels.append( calc_colors_by_labels(vl, cmap=cmap, reorder_colors=reorder_colors)) else: colors_by_labels = calc_colors_by_labels(labels, cmap=cmap, reorder_colors=reorder_colors) colors_rgb = colors if colors_by_labels is None and colors_rgb is None: current_colors = 'red' elif colors_rgb is not None: current_colors = colors_rgb elif is_multilabels: current_colors = colors_by_labels[0] else: current_colors = colors_by_labels sc = ipv.scatter(x, y, z, size=point_size_value, marker="sphere", color=current_colors) point_size = FloatSlider(min=0, max=2, step=0.02, description='Point size') jslink((sc, 'size'), (point_size, 'value')) w_switch_colors = get_color_switch_widget(colors_by_labels, colors_rgb, sc) sc_errors, point_size_errors = draw_error_points(points, labels, labels_gt) container = ipv.gcc() fig = container.children[0] widget_list = [fig, point_size] if point_size_errors is not None: widget_list.append(point_size_errors) if w_switch_colors is not None: widget_list.append(w_switch_colors) # vertex normals if normals is not None: u = normals[:, 0] v = normals[:, 1] w = normals[:, 2] quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color='green') vector_size = FloatSlider(min=0, max=5, step=0.1, description='Nomals size') jslink((quiver, 'size'), (vector_size, 'value')) widget_list.append(vector_size) if title is not None: widget_list = [Label(title)] + widget_list return display_widgets(widget_list)
def quickquiver(x, y, z, u, v, w, **kwargs): ipv.figure() ipv.quiver(x, y, z, u, v, w, **kwargs) return ipv.gcc()
def show_mesh(verts, triangles, face_colors=None, face_labels=None, face_cmap=cm.RdBu, face_reorder_colors=True, vertex_colors=None, vertex_labels=None, vertex_cmap=cm.RdBu, vertex_reorder_colors=True, vertex_normals=None, point_size_value=0.5, vector_size_value=0.5, width=800, height=600, axeslim='auto', aspect_ratio_preserve=True, verbose=0): """ vertex_normals - normals of vertices. """ if vertex_normals is not None: assert len(verts) == len( vertex_normals ), "Length incorrect. These are not normals of points, may be." x = verts[:, 0] y = verts[:, 1] z = verts[:, 2] ipv.figure(width=width, height=height) set_axes_lims(verts, axeslim=axeslim, aspect_ratio_preserve=aspect_ratio_preserve) # faces if face_labels is not None: face_color_dict = calc_colors_dict_by_labels( face_labels, cmap=face_cmap, reorder_colors=face_reorder_colors) for label in face_color_dict.keys(): triangles_set = triangles[face_labels == label] color = face_color_dict[label] _ = ipv.plot_trisurf(x, y, z, triangles=triangles_set, color=color) else: if face_colors is None: face_colors = '#f0f0f0' _ = ipv.plot_trisurf(x, y, z, triangles=triangles, color=face_colors) # vertices is_multilabels = isinstance(vertex_labels, (list, tuple)) if is_multilabels: vertex_colors_by_labels = [] for vl in vertex_labels: vertex_colors_by_labels.append( calc_colors_by_labels(vl, cmap=vertex_cmap, reorder_colors=vertex_reorder_colors)) else: vertex_colors_by_labels = calc_colors_by_labels( vertex_labels, cmap=vertex_cmap, reorder_colors=vertex_reorder_colors) vertex_colors_rgb = vertex_colors if vertex_colors_by_labels is None and vertex_colors_rgb is None: vertex_current_colors = 'red' elif vertex_colors_rgb is not None: vertex_current_colors = vertex_colors_rgb elif is_multilabels: vertex_current_colors = vertex_colors_by_labels[0] else: vertex_current_colors = vertex_colors_by_labels sc = ipv.scatter(x, y, z, size=point_size_value, marker='sphere', color=vertex_current_colors) point_size = FloatSlider(min=0, max=2, step=0.1, description='Vertex size') jslink((sc, 'size'), (point_size, 'value')) w_switch_vertex_colors = get_color_switch_widget(vertex_colors_by_labels, vertex_colors_rgb, sc) widget_list = [ipv.gcc(), point_size] # vertex normals if vertex_normals is not None: u = vertex_normals[:, 0] v = vertex_normals[:, 1] w = vertex_normals[:, 2] quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color='green') vector_size = FloatSlider(min=0, max=5, step=0.1, description='Nomals size') jslink((quiver, 'size'), (vector_size, 'value')) widget_list.append(vector_size) if w_switch_vertex_colors is not None: widget_list.append(w_switch_vertex_colors) return display_widgets(widget_list)
def scatter_normals( points, normals, labels=None, labels_gt=None, with_normals_errors_only=False, width=800, height=600, cmap=cm.RdBu, cmap_normals=cm.cool, aspect_ratio_preserve=True, axeslim='auto', reorder_colors=True, point_size_value=0.2, vector_size_value=1.0, title=None, ): assert len(points) == len( normals), "Length incorrect. These are not normals of points, may be." points = points.astype(np.float32) normals = normals.astype(np.float32) x = points[:, 0] y = points[:, 1] z = points[:, 2] u = normals[:, 0] v = normals[:, 1] w = normals[:, 2] if labels is None: labels = np.ones(shape=len(points), dtype=np.int) # draw ipv.figure(width=width, height=height) if axeslim == 'auto': if aspect_ratio_preserve: bounds = np.array([(v.min(), v.max()) for v in [x, y, z]]).T widths = bounds[1] - bounds[0] max_width = widths.max() pads = (max_width - widths) / 2 pads = np.vstack([-pads, pads]) axeslim = (bounds + pads).T ipv.xlim(axeslim[0][0], axeslim[0][1]) ipv.ylim(axeslim[1][0], axeslim[1][1]) ipv.zlim(axeslim[2][0], axeslim[2][1]) else: ipv.xlim(x.min(), x.max()) ipv.ylim(y.min(), y.max()) ipv.zlim(z.min(), z.max()) else: ipv.xlim(-axeslim, axeslim) ipv.ylim(-axeslim, axeslim) ipv.zlim(-axeslim, axeslim) # calc point colors colors_seg = cmap(np.linspace(0, 1, labels.max() + 1)) if reorder_colors: colors_seg = reorder_contrast(colors_seg) colors = np.array([colors_seg[label - 1][:3] for label in labels]) sc = ipv.scatter(x, y, z, size=point_size_value, marker="sphere", color=colors) colors_seg = cmap_normals(np.linspace(0, 1, labels.max() + 1)) if reorder_colors: colors_seg = reorder_contrast(colors_seg) colors_normals = np.array([colors_seg[label - 1][:3] for label in labels]) if labels_gt is None: quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color=colors_normals) else: if not with_normals_errors_only: quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color=colors_normals) # accuracy assert len(labels_gt) == len(labels) accuracy = (labels_gt == labels).sum() / len(labels) print("Accuracy: {}".format(accuracy)) # draw errors points_error = points[(labels_gt != labels)] x = points_error[:, 0] y = points_error[:, 1] z = points_error[:, 2] # normals with errors normals_error = normals[(labels_gt != labels)] u = normals_error[:, 0] v = normals_error[:, 1] w = normals_error[:, 2] sc2 = ipv.scatter(x, y, z, size=point_size_value, marker="sphere", color='red') point_size2 = FloatSlider(min=0, max=2, step=0.02, description='Error point size') jslink((sc2, 'size'), (point_size2, 'value')) if with_normals_errors_only: quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color=colors_normals) point_size = FloatSlider(min=0, max=2, step=0.1, description='Point size') vector_size = FloatSlider(min=0, max=5, step=0.1, description='Vector size') jslink((sc, 'size'), (point_size, 'value')) jslink((quiver, 'size'), (vector_size, 'value')) if labels_gt is not None: widget_list = [ipv.gcc(), point_size, point_size2, vector_size] else: widget_list = [ipv.gcc(), point_size, vector_size] if title is not None: widget_list = [Label(title)] + widget_list return display_widgets(widget_list)
def viz_swarm(swarm, paramLabels=False): swarmDF, particleHistory = viz_prep(swarm) particleHistoryCopy = copy.deepcopy(particleHistory) nParticles = swarm.nParticles nAnimationFrames = list( swarmDF['nEvals'])[0] # max( sortedBarHeightsDF['nEvals'] ) particleXYZ = np.zeros((nAnimationFrames, nParticles, 3)) lastKnownLocation = {} # TODO: bestIterationNTrees # particleSizes[ iFrame, iParticle ] = particleHistoryCopy[iParticle]['bestIterationNTrees'].pop(0).copy() for iFrame in range(nAnimationFrames): for iParticle in range(nParticles): if iParticle in particleHistoryCopy.keys(): # particle exists in the particleHistory and it has parameters for the current frame if len(particleHistoryCopy[iParticle]): particleXYZ[iFrame, iParticle, :] = particleHistoryCopy[ iParticle].pop(0).copy() lastKnownLocation[iParticle] = particleXYZ[ iFrame, iParticle, :].copy() else: # particle exists but it's params have all been popped off -- use its last known location if iParticle in lastKnownLocation.keys(): particleXYZ[iFrame, iParticle, :] = lastKnownLocation[ iParticle].copy() else: # particle does not exist in the particleHistory if iParticle in lastKnownLocation.keys(): # particle has no params in current frame, attempting to use last known location particleXYZ[ iFrame, iParticle, :] = lastKnownLocation[iParticle].copy() else: print('particle never ran should we even display it') assert (False) # using initial params #particleXYZ[iFrame, iParticle, : ] = initialParticleParams[iParticle].copy() #lastKnownLocation[iParticle] = particleXYZ[iFrame, iParticle, : ].copy() ipvFig = ipv.figure(width=ipvPlotWidth, height=ipvPlotHeight) scatterPlots = ipv.scatter(particleXYZ[:, :, 0], particleXYZ[:, :, 1], particleXYZ[:, :, 2], marker='sphere', size=5, color=swarm.particleColorStack) xyzLabelsButton = widgets.Button(description="x, y, z labels") paramNamesLabelsButton = widgets.Button(description="parameter labels") ipv.animation_control([scatterPlots], interval=400) ipv.xlim(swarm.paramRanges[0][1] - .5, swarm.paramRanges[0][2] + .5) ipv.ylim(swarm.paramRanges[1][1] - .1, swarm.paramRanges[1][2] + .1) ipv.zlim(swarm.paramRanges[2][1] - .1, swarm.paramRanges[2][2] + .1) container = ipv.gcc() container.layout.align_items = 'center' comboBox = append_label_buttons(swarm, ipvFig, container) display(comboBox)
def quickquiver(x, y, z, u, v, w, **kwargs): import ipyvolume as ipv ipv.figure() ipv.quiver(x, y, z, u, v, w, **kwargs) return ipv.gcc()
def visualize_objects(self, train_idxs=None, test_idxs=None, max_time_steps=None, train_sim=False, test_sim=True, train_marker_size=4, test_marker_size=6): """ train_idxs - numpy array из индексов объектов (sat_id) тренировочной выборки, которые надо визуализировать. Если None - берем все объекты test_idxs - numpy array из индексов объектов (sat_id) тренировочной выборки, которые надо визуализировать. Если None - берем train_idxs max_time_steps - максимальное количество измерений для одного объекта (sat_id) train_sim - если False - используем реальные данные (колонки без приставки sim) test_sim - если False - используем реальные (предсказанные) данные (для этого в датафрейм нужно добавить приставки колонки с предсказаниями без приставки sim, как в трейне) """ ipv.clear() if train_idxs is None: train_idxs = np.array(self.train_data['sat_id'].unique()) if test_idxs is None: test_idxs = train_idxs if max_time_steps is None: max_time_steps_train = self.train_data.groupby( 'sat_id').count()['epoch'].max() max_time_steps_test = self.test_data.groupby( 'sat_id').count()['epoch'].max() max_time_steps = max(max_time_steps_train, max_time_steps_test) ## подготовка трейна и теста stream_train = self._prepare_stream('train', train_idxs, max_time_steps, train_sim) stream_test = self._prepare_stream('test', test_idxs, max_time_steps, test_sim) ## визуализация stream = np.dstack([stream_train[:, :, :], stream_test[:, :, :]]) selected = stream_train.shape[2] + test_idxs self.q = ipv.quiver(*stream[:, :, :], color="green", color_selected='red', size=train_marker_size, size_selected=test_marker_size, selected=selected) ## Чтобы можно было менять размеры и цвета size = FloatSlider(min=1, max=15, step=0.2) size_selected = FloatSlider(min=1, max=15, step=0.2) color = ColorPicker() color_selected = ColorPicker() jslink((self.q, 'size'), (size, 'value')) jslink((self.q, 'size_selected'), (size_selected, 'value')) jslink((self.q, 'color'), (color, 'value')) jslink((self.q, 'color_selected'), (color_selected, 'value')) # ipv.style.use('seaborn-darkgrid') ipv.animation_control(self.q, interval=75) ipv.show( [VBox([ipv.gcc(), size, size_selected, color, color_selected])])
v, w, size=5, size_selected=8, selected=selected) from ipywidgets import FloatSlider, ColorPicker, VBox, jslink size = FloatSlider(min=0, max=30, step=0.1) size_selected = FloatSlider(min=0, max=30, step=0.1) color = ColorPicker() color_selected = ColorPicker() jslink((quiver, 'size'), (size, 'value')) jslink((quiver, 'size_selected'), (size_selected, 'value')) jslink((quiver, 'color'), (color, 'value')) jslink((quiver, 'color_selected'), (color_selected, 'value')) VBox([ipv.gcc(), size, size_selected, color, color_selected]) #%% # Import dependencies import plotly import plotly.graph_objs as go # output_file("myfile.html") # Configure Plotly to be rendered inline in the notebook. # plotly.offline.init_notebook_mode() # Configure the trace. trace = go.Scatter3d( x=[1, 2, 3, 5], # <-- Put your data instead y=[4, 5, 6, 6], # <-- Put your data instead