def update(self, val): self.out.clear_output(wait=True) plot = self.plot if self.vectors is not False: plot -= self.vectors coord = self.coord_select.value value = self.coord_slider.value x, y, z = None, None, None if coord == 'x': x = value if coord == 'y': y = value if coord == 'z': z = value field = self.get_field self.coord_slider.min, \ self.coord_slider.max, \ self.coord_slider.step, \ _ = self.coord_min_max(field) coor, vect = field.get_coord_and_vect(field.mesh.plane(x=x, y=y, z=z)) colors = df.plot3d.get_colors(vect) self.vectors = k3d.vectors(coor, vect, colors=colors) plot += self.vectors
def vectors(coordinates, vectors, colors=[], plot=None, **kwargs): coordinates = coordinates.astype(np.float32) # to avoid k3d warning vectors = vectors.astype(np.float32) # to avoid k3d warning if plot is None: plot = k3d.plot() plot.display() plot += k3d.vectors(coordinates, vectors, colors=colors, **kwargs) return plot
def vectors_plot(self): plot = k3d.plot() plot.camera_auto_fit = False plot.grid_auto_fit = False field = self.get_field coord, vect = field.get_coord_and_vect(field.mesh.coordinates) colors = df.plot3d.get_colors(vect) vectors = k3d.vectors(coord, vect, colors=colors) plot += vectors plot.display() return vectors
def show_points(points, colors=[], normals=None, point_size=0.1, line_width=0.00001): plot = k3d.plot(grid_visible=False, axes_helper=0) if normals is not None: normal_vectors = k3d.vectors(points, normals, line_width=line_width, use_head=False) plot += normal_vectors point_cloud = k3d.points(points, colors=colors, point_size=point_size, shader='flat') plot += point_cloud plot.display() return None
XYZ = np.vstack([xyz, xyz1, xyz2, xyz3]).astype(np.float32) return XYZ def distance(a, b): return np.sqrt(np.sum((a - b)**2, axis=1)) ### FIRST DRAWING cubic_system = cubic(0, 0, 0, 3, 3, 3) red_point = k3d.points(cubic_system[0], point_size=0.2, color=0xff0000) system = k3d.points(cubic_system[1:], point_size=0.2, color=0) a_vec = k3d.vectors(red_point.positions, cubic_system[3], head_size=1.5, labels=['a']) b_vec = k3d.vectors(red_point.positions, cubic_system[9], head_size=1.5, labels=['b']) c_vec = k3d.vectors(red_point.positions, cubic_system[1], head_size=1.5, labels=['c']) ab_vec = k3d.vectors(red_point.positions, cubic_system[3] + 2 * cubic_system[9], head_size=1.5, labels=['a+2b']) plot1 = k3d.plot()
def __init__( self, lcs: LocalCoordinateSystem, plot: k3d.Plot = None, name: str = None, color: int = RGB_BLACK, show_origin=True, show_trace=True, show_vectors=True, vector_scale=2.5, ): """Create a `CoordinateSystemVisualizerK3D`. Parameters ---------- lcs : Coordinate system that should be visualized plot : A k3d plotting widget. name : Name of the coordinate system color : The RGB color of the coordinate system (affects trace and label) as a 24 bit integer value. show_origin : If `True`, the origin of the coordinate system will be highlighted in the color passed as another parameter show_trace : If `True`, the trace of a time dependent coordinate system will be visualized in the color passed as another parameter show_vectors : If `True`, the the coordinate axes of the coordinate system are visualized """ coordinates, orientation = _get_coordinates_and_orientation(lcs) self._lcs = lcs self._color = color self._vector_scale = vector_scale self._vectors = k3d.vectors( origins=[coordinates for _ in range(3)], vectors=orientation.transpose() * self._vector_scale, line_width=0.05, head_size=3.0, colors=[[RGB_RED, RGB_RED], [RGB_GREEN, RGB_GREEN], [RGB_BLUE, RGB_BLUE]], labels=[], label_size=1.5, name=name if name is None else f"{name} (vectors)", ) self._vectors.visible = show_vectors self._label = None if name is not None: self._label = k3d.text( text=name, position=coordinates + 0.05, color=self._color, size=1, label_box=False, name=name if name is None else f"{name} (text)", ) self._trace = k3d.line( _get_unitless_coordinates(lcs), # type: ignore shader="thick", width=0.1, # change with .set_trait("width", value) color=color, name=name if name is None else f"{name} (line)", ) self._trace.visible = show_trace self.origin = platonic.Octahedron(size=0.1).mesh self.origin.color = color self.origin.model_matrix = _create_model_matrix(coordinates, orientation) self.origin.visible = show_origin if plot is not None: plot += self._vectors plot += self._trace plot += self.origin if self._label is not None: plot += self._label
def plot_regions_3d( atlas, regions_to_plot=[["HVC", "Nuclei"]], downsample_pct=1, polygon_simplification=0, additional_volumes=[], verbose=False, height=1024, ): """ plots brain regions on top of brain """ # collect data brain_data = np.swapaxes(atlas.voxel_data.loc["Brain", "voxels"], 0, 2) # get axis boundaries bounds = np.array([ atlas.xmin, atlas.xmax, atlas.ymin, atlas.ymax, atlas.zmin, atlas.zmax ]).astype("int") # the zero point in voxels, relative to y sinus zero_point = utils.um_to_vox( [0, 0, 0], atlas.voxel_data.loc["Brain", "affine"], atlas.um_mult, atlas.y_sinus_um_transform, ) # downsample if downsample_pct < 1: brain_data = scipy.ndimage.zoom(brain_data, downsample_pct) # make a volume plot of the brain brain_volume = k3d.volume( brain_data, color_range=[0, 1], color_map=k3d.basic_color_maps.Binary, samples=128, alpha_coef=0.25, bounds=bounds, compression_level=9, ) addl_vols = [] for vol in additional_volumes: bg_image_data = atlas.voxel_data.loc[vol, "voxels"] affine = atlas.voxel_data.loc[vol, "affine"] xm, ym, zm = utils.vox_to_um([0, 0, 0], affine, atlas.um_mult, atlas.y_sinus_um_transform) xma, yma, zma = utils.vox_to_um( list(np.shape(bg_image_data)), affine, atlas.um_mult, atlas.y_sinus_um_transform, ) img_bg_extent = np.concatenate( np.array([[xm, xma], [ym, yma], [zm, zma]])) bg_image_data = np.uint8( utils.norm01(np.swapaxes(bg_image_data, 0, 2)) * 256) addl_vol = k3d.volume( bg_image_data, color_range=[70, 100], color_map=k3d.matplotlib_color_maps.Greys, samples=128, alpha_coef=10.0, bounds=img_bg_extent, compression_level=9, ) addl_vols.append(addl_vol) # set atlas a region for y sinus atlas.region_vox.loc["y_sinus"] = [ "y_sinus", "y_sinus", np.nan, np.nan, np.nan ] atlas.region_vox.loc["y_sinus", "coords_vox"] = zero_point color_pal = atlas.label_cmap.colors # loop through regions regs = [] for ri, (reg, type_) in enumerate(tqdm(regions_to_plot, leave=False)): color = (np.array(color_pal[ri % len(color_pal)]) * 255).astype("int") # get voxel_data lab = atlas.brain_labels[atlas.brain_labels.type_ == type_].loc[ reg, "label"] vox_data = np.swapaxes( np.array(atlas.voxel_data.loc[type_, "voxels"] == lab), 0, 2) """addl_vol = k3d.volume( vox_data, color_range=[0, 1], color_map=k3d.matplotlib_color_maps.Greys, samples=128, alpha_coef=10.0, bounds=bounds, compression_level=9, ) addl_vols.append(addl_vol)""" # convert to vtk format vtk_dat = vox2vtk(vox_data, zero_point=zero_point) # simplify polygon if polygon_simplification > 0: vtk_dat = vtk_reduce(vtk_dat, polygon_simplification=polygon_simplification, verbose=verbose) # shape of voxel data xs, ys, zs = vox_data.shape region_bounds = [ 0, (bounds[1] - bounds[0]) / zs, 0, (bounds[3] - bounds[2]) / ys, 0, (bounds[5] - bounds[4]) / xs, ] # print(np.shape(vox_data), region_bounds, np.sum(vox_data)) # create mesh plot region = k3d.vtk_poly_data( vtk_dat.GetOutput(), color=utils.rgb2hex(color[0], color[1], color[2]), bounds=region_bounds, ) regs.append(region) origins = [-5000, 0, 0, 0, -5000, 0, 0, 0, -5000] vectors = [10000, 0, 0, 0, 10000, 0, 0, 0, 10000] colors = [0xFF0000, 0xFF0000, 0x00FF00, 0x00FF00, 0x0000FF, 0x0000FF] vec = k3d.vectors(origins, vectors, colors=colors, line_width=100, use_head=True, head_size=1000) plot = k3d.plot(height=height, background_color=0xFEFEFE) plot += brain_volume for vol in addl_vols: plot += vol # plot regions for region in regs: plot += region plot += vec plot.display() plot.camera_auto_fit = False # plot.grid_visible = False # camera loc, center or rocation, angle (?) plot.camera = [-22977, 18052, 8696, 0, 0, 0, 0.14, -0.16, 0.997] widget_controllers(atlas, vec, plot, bounds, regions_to_plot) return plot, vec
def _process_series(self, series): self._init_cyclers() self._fig.auto_rendering = False # clear data for o in self._fig.objects: self._fig.remove_class(o) for ii, s in enumerate(series): if s.is_3Dline and s.is_point: x, y, z, _ = s.get_data() positions = np.vstack([x, y, z]).T.astype(np.float32) a = dict(point_size=0.2, color=self._convert_to_int(next(self._cl))) line_kw = self._kwargs.get("line_kw", dict()) plt_points = k3d.points(positions=positions, **merge({}, a, line_kw)) plt_points.shader = "mesh" self._fig += plt_points elif s.is_3Dline: x, y, z, param = s.get_data() # K3D doesn't like masked arrays, so filled them with NaN x, y, z = [ np.ma.filled(t) if isinstance(t, np.ma.core.MaskedArray) else t for t in [x, y, z] ] vertices = np.vstack([x, y, z]).T.astype(np.float32) # keyword arguments for the line object a = dict( width=0.1, name=s.label if self._kwargs.get("show_label", False) else None, color=self._convert_to_int(next(self._cl)), shader="mesh", ) if self._use_cm: a["attribute"] = (param.astype(np.float32), ) a["color_map"] = next(self._cm) a["color_range"] = [s.start, s.end] line_kw = self._kwargs.get("line_kw", dict()) line = k3d.line(vertices, **merge({}, a, line_kw)) self._fig += line elif (s.is_3Dsurface and (not s.is_complex)) or (s.is_3Dsurface and s.is_complex and (s.real or s.imag or s.abs)): x, y, z = s.get_data() # K3D doesn't like masked arrays, so filled them with NaN x, y, z = [ np.ma.filled(t) if isinstance(t, np.ma.core.MaskedArray) else t for t in [x, y, z] ] # TODO: # Can I use get_vertices_indices also for non parametric surfaces? if s.is_parametric: vertices, indices = get_vertices_indices(x, y, z) vertices = vertices.astype(np.float32) else: x = x.flatten() y = y.flatten() z = z.flatten() vertices = np.vstack([x, y, z]).T.astype(np.float32) indices = Triangulation(x, y).triangles.astype(np.uint32) self._high_aspect_ratio(x, y, z) a = dict( name=s.label if self._kwargs.get("show_label", False) else None, side="double", flat_shading=False, wireframe=False, color=self._convert_to_int(next(self._cl)), ) if self._use_cm: a["color_map"] = next(self._cm) a["attribute"] = z.astype(np.float32) surface_kw = self._kwargs.get("surface_kw", dict()) surf = k3d.mesh(vertices, indices, **merge({}, a, surface_kw)) self._fig += surf elif s.is_3Dvector and self._kwargs.get("streamlines", False): xx, yy, zz, uu, vv, ww = s.get_data() # K3D doesn't like masked arrays, so filled them with NaN xx, yy, zz, uu, vv, ww = [ np.ma.filled(t) if isinstance(t, np.ma.core.MaskedArray) else t for t in [xx, yy, zz, uu, vv, ww] ] magnitude = np.sqrt(uu**2 + vv**2 + ww**2) min_mag = min(magnitude.flatten()) max_mag = max(magnitude.flatten()) import vtk from vtk.util import numpy_support vector_field = np.array( [uu.flatten(), vv.flatten(), ww.flatten()]).T vtk_vector_field = numpy_support.numpy_to_vtk( num_array=vector_field, deep=True, array_type=vtk.VTK_FLOAT) vtk_vector_field.SetName("vector_field") points = vtk.vtkPoints() points.SetNumberOfPoints(s.n2 * s.n1 * s.n3) for i, (x, y, z) in enumerate( zip(xx.flatten(), yy.flatten(), zz.flatten())): points.SetPoint(i, [x, y, z]) grid = vtk.vtkStructuredGrid() grid.SetDimensions([s.n2, s.n1, s.n3]) grid.SetPoints(points) grid.GetPointData().SetVectors(vtk_vector_field) stream_kw = self._kwargs.get("stream_kw", dict()) starts = stream_kw.pop("starts", None) max_prop = stream_kw.pop("max_prop", 500) streamer = vtk.vtkStreamTracer() streamer.SetInputData(grid) streamer.SetMaximumPropagation(max_prop) if starts is None: seeds_points = get_seeds_points(xx, yy, zz, uu, vv, ww) seeds = vtk.vtkPolyData() points = vtk.vtkPoints() for p in seeds_points: points.InsertNextPoint(p) seeds.SetPoints(points) streamer.SetSourceData(seeds) streamer.SetIntegrationDirectionToForward() elif isinstance(starts, dict): if not all([t in starts.keys() for t in ["x", "y", "z"]]): raise KeyError( "``starts`` must contains the following keys: " + "'x', 'y', 'z', whose values are going to be " + "lists of coordinates.") seeds_points = np.array( [starts["x"], starts["y"], starts["z"]]).T seeds = vtk.vtkPolyData() points = vtk.vtkPoints() for p in seeds_points: points.InsertNextPoint(p) seeds.SetPoints(points) streamer.SetSourceData(seeds) streamer.SetIntegrationDirectionToBoth() else: npoints = stream_kw.get("npoints", 200) radius = stream_kw.get("radius", None) center = 0, 0, 0 if not radius: xmin, xmax = min(xx[0, :, 0]), max(xx[0, :, 0]) ymin, ymax = min(yy[:, 0, 0]), max(yy[:, 0, 0]) zmin, zmax = min(zz[0, 0, :]), max(zz[0, 0, :]) radius = max([ abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin) ]) center = (xmax - xmin) / 2, (ymax - ymin) / 2, ( zmax - zmin) / 2 seeds = vtk.vtkPointSource() seeds.SetRadius(radius) seeds.SetCenter(*center) seeds.SetNumberOfPoints(npoints) streamer.SetSourceConnection(seeds.GetOutputPort()) streamer.SetIntegrationDirectionToBoth() streamer.SetComputeVorticity(0) streamer.SetIntegrator(vtk.vtkRungeKutta4()) streamer.Update() streamline = streamer.GetOutput() streamlines_points = numpy_support.vtk_to_numpy( streamline.GetPoints().GetData()) streamlines_velocity = numpy_support.vtk_to_numpy( streamline.GetPointData().GetArray("vector_field")) streamlines_speed = np.linalg.norm(streamlines_velocity, axis=1) vtkLines = streamline.GetLines() vtkLines.InitTraversal() point_list = vtk.vtkIdList() lines = [] lines_attributes = [] while vtkLines.GetNextCell(point_list): start_id = point_list.GetId(0) end_id = point_list.GetId(point_list.GetNumberOfIds() - 1) l = [] v = [] for i in range(start_id, end_id): l.append(streamlines_points[i]) v.append(streamlines_speed[i]) lines.append(np.array(l)) lines_attributes.append(np.array(v)) count = sum([len(l) for l in lines]) vertices = np.nan * np.zeros((count + (len(lines) - 1), 3)) attributes = np.zeros(count + (len(lines) - 1)) c = 0 for k, (l, a) in enumerate(zip(lines, lines_attributes)): vertices[c:c + len(l), :] = l attributes[c:c + len(l)] = a if k < len(lines) - 1: c = c + len(l) + 1 skw = dict(width=0.1, shader="mesh", compression_level=9) if self._use_cm and ("color" not in stream_kw.keys()): skw["color_map"] = next(self._cm) skw["color_range"] = [min_mag, max_mag] skw["attribute"] = attributes else: col = stream_kw.pop("color", next(self._cl)) if not isinstance(col, int): col = self._convert_to_int(col) stream_kw["color"] = col self._fig += k3d.line(vertices.astype(np.float32), **merge({}, skw, stream_kw)) elif s.is_3Dvector: xx, yy, zz, uu, vv, ww = s.get_data() # K3D doesn't like masked arrays, so filled them with NaN xx, yy, zz, uu, vv, ww = [ np.ma.filled(t) if isinstance(t, np.ma.core.MaskedArray) else t for t in [xx, yy, zz, uu, vv, ww] ] xx, yy, zz, uu, vv, ww = [ t.flatten().astype(np.float32) for t in [xx, yy, zz, uu, vv, ww] ] # default values qkw = dict(scale=1) # user provided values quiver_kw = self._kwargs.get("quiver_kw", dict()) qkw = merge(qkw, quiver_kw) scale = qkw["scale"] magnitude = np.sqrt(uu**2 + vv**2 + ww**2) vectors = np.array((uu, vv, ww)).T * scale origins = np.array((xx, yy, zz)).T if self._use_cm and ("color" not in quiver_kw.keys()): colormap = next(self._cm) colors = k3d.helpers.map_colors(magnitude, colormap, []) self._handles[ii] = [qkw, colormap] else: col = quiver_kw.get("color", next(self._cl)) if not isinstance(col, int): col = self._convert_to_int(col) colors = col * np.ones(len(magnitude)) self._handles[ii] = [qkw, None] vec_colors = np.zeros(2 * len(colors)) for i, c in enumerate(colors): vec_colors[2 * i] = c vec_colors[2 * i + 1] = c vec_colors = vec_colors.astype(np.uint32) vec = k3d.vectors( origins=origins - vectors / 2, vectors=vectors, colors=vec_colors, ) self._fig += vec elif s.is_complex and s.is_3Dsurface and ( not s.is_domain_coloring): x, y, mag_arg, colors, colorscale = s.get_data() mag, arg = mag_arg[:, :, 0], mag_arg[:, :, 1] x, y, z = [t.flatten() for t in [x, y, mag]] vertices = np.vstack([x, y, z]).T.astype(np.float32) indices = Triangulation(x, y).triangles.astype(np.uint32) self._high_aspect_ratio(x, y, z) a = dict( name=s.label if self._kwargs.get("show_label", False) else None, side="double", flat_shading=False, wireframe=False, color=self._convert_to_int(next(self._cl)), color_range=[-np.pi, np.pi], ) if self._use_cm: colors = colors.reshape((-1, 3)) a["colors"] = [self._rgb_to_int(c) for c in colors] r = [] loc = np.linspace(0, 1, colorscale.shape[0]) colorscale = colorscale / 255 for l, c in zip(loc, colorscale): r.append(l) r += list(c) a["color_map"] = r a["color_range"] = [-np.pi, np.pi] surface_kw = self._kwargs.get("surface_kw", dict()) surf = k3d.mesh(vertices, indices, **merge({}, a, surface_kw)) self._fig += surf else: raise NotImplementedError( "{} is not supported by {}\n".format( type(s), type(self).__name__) + "K3D-Jupyter only supports 3D plots.") xl = self.xlabel if self.xlabel else "x" yl = self.ylabel if self.ylabel else "y" zl = self.zlabel if self.zlabel else "z" self._fig.axes = [xl, yl, zl] if self.title: self._fig += k3d.text2d(self.title, position=[0.025, 0.015], color=0, size=1, label_box=False) self._fig.auto_rendering = True
def __init__( self, lcs, plot: k3d.Plot = None, name: str = None, color: int = RGB_BLACK, show_origin=True, show_trace=True, show_vectors=True, ): """Create a `CoordinateSystemVisualizerK3D`. Parameters ---------- lcs : weldx.transformations.LocalCoordinateSystem Coordinate system that should be visualized plot : k3d.Plot A k3d plotting widget. name : str Name of the coordinate system color : int The RGB color of the coordinate system (affects trace and label) as a 24 bit integer value. show_origin : bool If `True`, the origin of the coordinate system will be highlighted in the color passed as another parameter show_trace : If `True`, the trace of a time dependent coordinate system will be visualized in the color passed as another parameter show_vectors : bool If `True`, the the coordinate axes of the coordinate system are visualized """ coordinates, orientation = self._get_coordinates_and_orientation(lcs) self._lcs = lcs self._color = color self._vectors = k3d.vectors( origins=[coordinates for _ in range(3)], vectors=orientation.transpose(), colors=[[RGB_RED, RGB_RED], [RGB_GREEN, RGB_GREEN], [RGB_BLUE, RGB_BLUE]], labels=[], label_size=1.5, ) self._vectors.visible = show_vectors self._label = None if name is not None: self._label = k3d.text( text=name, position=coordinates + 0.05, color=self._color, size=1, label_box=False, ) self._trace = k3d.line( np.array(lcs.coordinates.values, dtype="float32"), shader="simple", width=0.05, color=color, ) self._trace.visible = show_trace self.origin = platonic.Octahedron(size=0.1).mesh self.origin.color = color self.origin.model_matrix = self._create_model_matrix( coordinates, orientation) self.origin.visible = show_origin if plot is not None: plot += self._vectors plot += self._trace plot += self.origin if self._label is not None: plot += self._label
def display_sharpness(mesh=None, plot_meshvert=True, samples=None, samples_distances=None, sharp_vert=None, sharp_curves=None, directions=None, directions_width=0.0025, samples_color=0x0000ff, samples_psize=0.002, mesh_color=0xbbbbbb, meshvert_color=0x666666, meshvert_psize=0.0025, sharpvert_color=0xff0000, sharpvert_psize=0.0025, sharpcurve_color=None, sharpcurve_width=0.0025, as_image=False, plot_height=768, cmap=k3d.colormaps.matplotlib_color_maps.coolwarm_r): plot = k3d.plot(height=plot_height) if None is not mesh: k3d_mesh = k3d.mesh(mesh.vertices, mesh.faces, color=mesh_color) plot += k3d_mesh if plot_meshvert: k3d_points = k3d.points(mesh.vertices, point_size=meshvert_psize, color=meshvert_color) plot += k3d_points k3d_points.shader = 'flat' if None is not samples: colors = None if None is not samples_distances: max_dist = 0.5 colors = k3d.helpers.map_colors(samples_distances, cmap, [0, max_dist]).astype(np.uint32) k3d_points = k3d.points(samples, point_size=samples_psize, colors=colors) else: k3d_points = k3d.points(samples, point_size=samples_psize, color=samples_color) plot += k3d_points k3d_points.shader = 'flat' if None is not directions: vectors = k3d.vectors(samples, directions * samples_distances[..., np.newaxis], use_head=False, line_width=directions_width) print(vectors) plot += vectors if None is not sharp_vert: k3d_points = k3d.points(sharp_vert, point_size=sharpvert_psize, color=sharpvert_color) plot += k3d_points k3d_points.shader = 'flat' if None is not sharp_curves: if None is not sharpcurve_color: color = sharpcurve_color else: import randomcolor rand_color = randomcolor.RandomColor() for i, vert_ind in enumerate(sharp_curves): sharp_points_curve = mesh.vertices[vert_ind] if None is sharpcurve_color: color = rand_color.generate(hue='red')[0] color = int('0x' + color[1:], 16) plt_line = k3d.line(sharp_points_curve, shader='mesh', width=sharpcurve_width, color=color) plot += plt_line plot.grid_visible = False plot.display() if as_image: plot.fetch_screenshot() return Image(data=b64decode(plot.screenshot))