def draw_shapes(self): sb = self.source.bounds() x1, x2, y1, y2, z1, z2 = sb maxb = max(x2 - x1, y2 - y1) grid0 = Grid(self.source.centerOfMass(), sx=maxb, sy=maxb, resx=40, resy=40) T = self.morphed_source.getTransform() grid1 = grid0.alpha(0.3).wireframe(0).clone().applyTransform( T) # warp the grid arrows = Arrows(self.ptsource, self.pttarget, alpha=0.5, s=3).c("k") lines = Lines(self.source, self.target).c('db') mlines = Lines(self.morphed_source, self.target).c('db') show(grid0, self.source, self.target, lines, arrows, __doc__, at=0, N=2) show(grid1, self.morphed_source, self.target, mlines, f"morphed source (green) vs target (red)\nNDF = {2*self.npts}", at=1, interactive=True).close()
for t_interval in range(int(T / output_int)): for it in range(output_int): t = t_interval * output_int + it #print('\r', "t=", t, end='') #print("t=", t) take_step(d_X, N) print('\r', "t=", t, end='') out_X = d_X.copy_to_host() pol = arr_pol_to_float3(out_X[:, 3:5]) coords_t.append(out_X[:, :3]) pol_t.append(pol) #print('\r', "DONE", t, end='') ####################################################################### from vedo import Box, Spheres, Arrows, show, interactive world = Box(pos=(1, 1, 0), size=(10, 10, 4), alpha=1).wireframe() for t in range(len(coords_t)): cells = Spheres(coords_t[t], c='b', r=0.4) polarities = Arrows(startPoints=coords_t[t], endPoints=coords_t[t] + pol_t[t], c='tomato') show(world, cells, polarities, interactive=0, viewup='z') interactive()
def get_neurons_synapses( self, scene_store, neurons, alpha=1, pre=False, post=False, colorby="synapse_type", draw_patches=False, draw_arrows=True, ): """ THIS METHODS GETS CALLED BY SCENE, self referes to the instance of Scene not to this class. Renders neurons and adds them to the scene. :param neurons: list of names of neurons :param alpha: float in range 0,1 - neurons transparency :param pre: bool, if True the presynaptic sites of each neuron are rendered :param post: bool, if True the postsynaptic sites on each neuron are rendered :param colorby: str, criteria to use to color the neurons. Accepts values like synapse_type, type, individual etc. :param draw_patches: bool, default True. If true dark patches are used to show the location of post synapses :param draw_arrows: bool, default True. If true arrows are used to show the location of post synapses """ col_names = ["x", "z", "y"] # used to correctly position synapses on .obj files neurons = self._check_neuron_argument(neurons) spheres_data, actors = [], [] for neuron in neurons: if pre: if colorby == "synapse_type": color = self.pre_synapses_color else: color = self.get_neuron_color(neuron, colorby=colorby) data = self.synapses_data.loc[self.synapses_data.pre == neuron] if not len(data): print(f"No pre- synapses found for neuron {neuron}") else: data = data[["x", "y", "z"]] data["y"] = -data["y"] spheres_data.append(( data, dict( color=color, verbose=False, alpha=alpha, radius=self.synapses_radius, res=24, col_names=col_names, ), )) if post: if colorby == "synapse_type": color = self.post_synapses_color else: color = self.get_neuron_color(neuron, colorby=colorby) rows = [ i for i, row in self.synapses_data.iterrows() if neuron in row.posts ] data = self.synapses_data.iloc[rows] if not len(data): print(f"No post- synapses found for neuron {neuron}") else: data = data[["x", "y", "z"]] data["y"] = -data["y"] """ Post synaptic locations are shown as darkening of patches of a neuron's mesh and or as a 3d arrow point toward the neuron. """ spheres_data.append(( data, dict( color="black", verbose=False, alpha=0, radius=self.synapses_radius * 4, res=24, col_names=col_names, ), )) # Get mesh points for neuron the synapses belong to if neuron not in scene_store.keys(): neuron_file = [ f for f in self.neurons_files if neuron in f ][0] neuron_act = load_mesh_from_file(neuron_file, c=color) else: neuron_act, as_skeleton = scene_store[neuron] # Draw post synapses as dark patches if draw_patches: if as_skeleton: print( "Can't display post synapses as dark spots when neron is rendered in skeleton mode" ) else: # Get faces that are inside the synapses spheres and color them darker raise NotImplementedError("This needs some fixing") # neuron_points = neuron_act.cellCenters() # inside_points = spheres.insidePoints( # neuron_points, returnIds=True # ) # n_cells = neuron_act.polydata().GetNumberOfCells() # scals = np.zeros((n_cells)) # scals[inside_points] = 1 # colors = [ # neuron_act.c() # if s == 0 # else getColor("blackboard") # for s in scals # ] # neuron_act.cellIndividualColors(colors) # Draw post synapses as arrow if draw_arrows: points1 = [[x, y, z] for x, y, z in zip( data[col_names[0]].values, data[col_names[1]].values, data[col_names[2]].values, )] points2 = [neuron_act.closestPoint(p) for p in points1] # shift point1 to make arrows longer def dist(p1, p2): return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2) def get_point(p1, p2, d, u): alpha = (1 / d) * u x = (1 - alpha) * p1[0] + alpha * p2[0] y = (1 - alpha) * p1[1] + alpha * p2[1] z = (1 - alpha) * p1[2] + alpha * p2[2] return [x, y, z] dists = [ dist(p1, p2) for p1, p2 in zip(points1, points2) ] points0 = [ get_point(p1, p2, d, -0.5) for p1, p2, d in zip(points1, points2, dists) ] arrows = Arrows(points0, endPoints=points2, c=color, s=4) # ! aasduaisdbasiudbuia actors.append(arrows) return spheres_data, actors
"""Read structured grid data and show the associated vector and scalar fields """ from vedo import load, datadir, Arrows, show g = load(datadir+'structgrid.vts').printInfo() coords = g.points() vects = g.getPointArray('Momentum')/600 # printInfo gives the list print('numpy array shapes are:', coords.shape, vects.shape) # build arrows from starting points to endpoints, with colormap arrows = Arrows(coords-vects, coords+vects, c='hot_r') g.pointColors('Density').lineWidth(0.1).alpha(0.3) #g.color('grey').alpha(0.3) show(g, arrows, __doc__, axes=9) # axes type 9 is a simple box
mesh = trimesh.load(plyfile) points = mesh.bounding_box_oriented.sample_volume(count=30) # find the closest point on the mesh to each random point closest_points, distances, triangle_id = mesh.nearest.on_surface(points) #print('Distance from point to surface of mesh:\n{}'.format(distances)) # create a PointCloud object out of each (n,3) list of points cloud_original = trimesh.points.PointCloud(points) cloud_close = trimesh.points.PointCloud(closest_points) # create a unique color for each point cloud_colors = np.array([trimesh.visual.random_color() for i in points]) # set the colors on the random point and its nearest point to be the same cloud_original.vertices_color = cloud_colors cloud_close.vertices_color = cloud_colors arrs = Arrows(cloud_original.vertices, cloud_close.vertices, c='w') ## create a scene containing the mesh and two sets of points show(mesh, cloud_original, cloud_close, arrs, __doc__, bg='bb', axes=1, viewup='z').close()
sources = [(5, 8, 5), (8, 5, 5), (5, 2, 5)] deltas = [(1, 1, 0.2), (1, 0, -0.8), (1, -1, 0.2)] apos = Points(positions, r=2) # for p in apos.points(): ####### Uncomment to fix some points. # if abs(p[2]-5) > 4.999: # differences btw RBF and thinplate # sources.append(p) # will become much smaller. # deltas.append(np.zeros(3)) sources = np.array(sources) deltas = np.array(deltas) src = Points(sources, c="r", r=12) trs = Points(sources + deltas, c="v", r=12) arr = Arrows(sources, sources + deltas) ################################################# Thin Plate Splines warped = apos.clone().thinPlateSpline(sources, sources + deltas) warped.alpha(0.4).color("lg").pointSize(10) allarr = Arrows(apos.points(), warped.points()) set1 = [apos, warped, src, trs, arr, __doc__] plt1 = show([set1, allarr], N=2, bg='bb') # returns the Plotter class ################################################# RBF from scipy.interpolate import Rbf x, y, z = sources[:, 0], sources[:, 1], sources[:, 2] dx, dy, dz = deltas[:, 0], deltas[:, 1], deltas[:, 2]
end_points = np.array([section.pos_target]) if section.pos2 is not None: start_points = np.concatenate((start_points, [section.pos2])) end_points = np.concatenate(([section.pos2], [section.pos_target])) if section.pos3 is not None: start_points = np.concatenate((start_points, [section.pos3])) end_points = np.concatenate( ([section.pos2], [section.pos3], [section.pos_target])) lines = Lines(startPoints=start_points, endPoints=end_points, c='green', lw=5) # Add some arrows to represent the vectors at the start and end positions scalar = 150 arrows = Arrows(startPoints=np.array([section.pos1, section.pos_target]), endPoints=np.array([ section.pos1 + scalar * section.vec1, section.pos_target + scalar * section.vec_target ]), s=0.5, res=24) # generate a mesh of the generated section from the survey # use the 'circle' method to construct a cylinder with constant radius mesh = we.mesh.WellMesh( survey=survey, method='circle', n_verts=24, ) # plot the results we.visual.plot( [mesh.mesh],
def visualize_log_data(): parser = config_parser() args = parser.parse_args() if args.run_dir == "newest": run_folders = os.listdir('../runs') if len(run_folders) == 0: raise ValueError('There is no run in the runs directory') newest = 0 run_dir = "" for run_folder in run_folders: timestamp = os.path.getmtime(os.path.join('../runs', run_folder)) if timestamp > newest: newest = timestamp run_dir = os.path.join('../runs', run_folder) else: run_dir = args.run_dir if args.epoch == 0: try: filenames = os.listdir(os.path.join(run_dir, 'vedo_data')) except: raise ValueError("There seems to be no vedo data generated for the specified run since the path ", os.path.join(run_dir, 'vedo_data'), ' was not found') if len(filenames) == 0: raise ValueError('No epoch in the vedo_data folder') epoch = 0 for filename in filenames: file_epoch = int(re.findall(r'\d+', filename)[0]) if file_epoch > epoch: epoch = file_epoch else: epoch = args.epoch ats = [] images = [] print('Using run ' + run_dir + ' and epoch ' + str(epoch)) for image_index in range(args.number_images): try: densities_samples_warps = np.load( os.path.join(run_dir, 'vedo_data', "densities_samples_warps_epoch_" + str(epoch) + '_image_' + str(image_index) + '.npz')) densities, densities_samples, warps, warps_samples = densities_samples_warps['densities'], \ densities_samples_warps['samples_density'], \ densities_samples_warps['warps'], \ densities_samples_warps['samples_warp'] if args.mode == "density": max_density = np.max(densities) if max_density == 0: print('Every density for image ', image_index, ' is 0 so your images are probably white and this visualization has spheres of radius 0') normalized_densities = densities / max_density radii = normalized_densities * 0.05 ats.append(image_index) images.append(Spheres(densities_samples, r=radii, c="lb", res=8)) elif args.mode == "warp": ats.append(image_index) images.append([Arrows(warps_samples, warps_samples + warps, s=0.3), Spheres(warps_samples, r=0.01, res=8)]) except FileNotFoundError as err: print('Skipping the iteration with image index ', image_index, ' because the file for that image ' 'was not found: ', err) show(images, at=ats, axes=2)
Any point on the mesh close to a source landmark will be moved to a place close to the corresponding target landmark. The points in between are interpolated using Bookstein's algorithm.""" from vedo import Grid, merge, Points, Arrows, show import numpy as np #np.random.seed(2) grids = [] for i in range(5): gr = Grid([0, 0, i / 8], resx=12, resy=12) grids.append(gr) mesh = merge(grids) # merge grids into a single object idxs = np.random.randint(0, mesh.N(), 10) # pick 10 indices pts = mesh.points()[idxs] ptsource, pttarget = [], [] for pt in pts: ptold = pt + np.random.randn(3) * 0.02 ptsource.append(ptold) ptnew = ptold + [0, 0, np.random.randn(1) * 0.1] # move in z pttarget.append(ptnew) warped = mesh.warp(ptsource, pttarget) warped.color("b4").lc('light blue').wireframe(False).lw(1) apts = Points(ptsource, r=10, c="r") arrs = Arrows(ptsource, pttarget, c='k') show(warped, apts, arrs, __doc__, axes=1, viewup="z").close()
out_X = np.copy(X) pol = arr_pol_to_float3(out_X[:, 3:5]) coords_t.append(out_X[:, :3]) pol_t.append(pol) ############################################################################### # View as an interactive time sequence with a slider max_time = len(coords_t) vp = Plotter(interactive=False) coord_acts = [] pol_acts = [] for t in range(len(coords_t)): coords = Spheres(coords_t[t], c='b', r=0.4).off() polarities = Arrows(startPoints=coords_t[t], endPoints=coords_t[t] + pol_t[t], c='t').off() vp += [coords, polarities] coord_acts.append(coords) pol_acts.append(polarities) def set_time(widget, event): new_time = int(floor(widget.GetRepresentation().GetValue())) for t in range(0, max_time): if t == new_time: coord_acts[t].on() pol_acts[t].on() else: coord_acts[t].off() pol_acts[t].off()