def makeGrid(shape, N): rmax = 2.0 # line length agrid, pts = [], [] for th in np.linspace(0, np.pi, N, endpoint=True): lats = [] for ph in np.linspace(0, 2 * np.pi, N, endpoint=True): p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * rmax intersections = shape.intersectWithLine([0, 0, 0], p) if len(intersections): value = mag(intersections[0]) lats.append(value - rbias) pts.append(intersections[0]) else: lats.append(rmax - rbias) pts.append(p) agrid.append(lats) agrid = np.array(agrid) actor = Points(pts, c="k", alpha=0.4, r=1) return agrid, actor
for colony in colonies: newcells = [] for cell in colony.cells: if cell.dieAt(t): continue if cell.divideAt(t): newc = cell.split() # make daughter cell plt += Line(cell.pos, newc.pos, c="k", lw=3, alpha=0.5) newcells.append(newc) newcells.append(cell) colony.cells = newcells pts = [c.pos for c in newcells] # draw all points at once plt += Points(pts, c=colony.color, r=5, alpha=0.80) # nucleus plt += Points(pts, c=colony.color, r=15, alpha=0.05) # halo msg += str(len(colony.cells)) + "," pb.print(msg + str(int(t))) plt.show(resetcam=0) if plt.escaped: exit(0) # if ESC is hit during the loop # draw the oriented ellipsoid that contains 50% of the cells for colony in colonies: pts = [c.pos for c in colony.cells] a = pcaEllipsoid(pts, pvalue=0.5) a.color(colony.color).alpha(0.3) a.legend("1/rate=" + str(colony.cells[0].tdiv) + "h") plt += a
"""Voronoi tessellation of a pointcloud on a grid""" from vedo import dataurl, Points, Grid, voronoi, show pts0 = Points(dataurl + 'rios.xyz').color('k') pts1 = pts0.clone().smoothLloyd2D() grid = Grid([14500, 61700], sx=22000, sy=24000, resx=30, resy=30).ps(1) allpts = pts1.points().tolist() + grid.points().tolist() msh = voronoi(allpts, method='scipy') msh.lw(0.1).wireframe(False).cmap('terrain_r', 'VoronoiID', on='cells') centers = Points(msh.cellCenters(), c='k') show(msh, pts0, __doc__, axes=dict(digits=3))
def f4(x, y, z, x1, y1, z1, c): x1[c] = 0.5 * x[c] + 1 / 4.0 y1[c] = 0.5 * y[c] + 1.0 / 4 z1[c] = 0.5 * z[c] + np.sqrt(3) / 4 functions = [f1, f2, f3, f4] probabilities = [1 / 4.0] * 4 assert len(functions) == len(probabilities) X, Y, Z = x, y, z for i in range(20): # pick indices for each function to be applied r = np.random.choice(len(probabilities), size=N, p=probabilities) for i, f in enumerate(functions): f(x, y, z, x1, y1, z1, r == i) x, x1 = x1, x y, y1 = y1, y z, z1 = z1, z if i > 0: X, Y, Z = np.hstack([X, x]), np.hstack([Y, y]), np.hstack([Z, z]) # how much memory are we using, how many points there are print("used mem, Npts=", 3 * X.nbytes // 1024**2, "MB", X.shape[0]) from vedo import Points Points([X, Y, Z], c="tomato").show(axes=1)
"""delaunay2D() and cellCenters() functions""" from vedo import Plotter, delaunay2D, Points, datadir vp = Plotter(shape=(1, 2), interactive=0) d0 = vp.load(datadir + "250.vtk").rotateY(-90).legend("original mesh") coords = d0.points() # get the coordinates of the mesh vertices # Build a mesh starting from points in space # (points must be projectable on the XY plane) d1 = delaunay2D(coords, mode='fit') d1.color("r").wireframe(True).legend("delaunay mesh") cents = d1.cellCenters() ap = Points(cents).legend("cell centers") vp.show(d0, d1, __doc__, at=0) # NB: d0 and d1 are slightly different vp.show(d1, ap, at=1, interactive=1)
def display_point_cloud(point_cloud, label): point_vedo = Points(point_cloud[['X', 'Y', 'Z']]) labels = label cmap = get_cmap('Spectral') point_vedo.cmap(cmap, labels) show(point_vedo, axes=True)
""" MAGIC-LAT estimate """ latEst = magicLAT(vertices, faces, TrIdx, TrCoord, TrVal, EDGE_THRESHOLD) magicDE = metrics.deltaE(TstVal, latEst[TstIdx], MINLAT, MAXLAT) x.append(m) y.append(magicDE) if magicDE > maxDE: maxDE = magicDE ymax = math.ceil(magicDE / 10) * 10 with open(meanFile, 'a') as fid: fid.write('\n') fid.write('{:<20}{:<20.6f}'.format(m, magicDE)) verPoints = Points(TrCoord, r=5).cmap('rainbow_r', TrVal, vmin=MINLAT, vmax=MAXLAT).addScalarBar() estPoints = Points(vertices, r=5).cmap('rainbow_r', latEst, vmin=MINLAT, vmax=MAXLAT).addScalarBar() coloredMesh = Mesh([vertices, faces]) coloredMesh.interpolateDataFrom(estPoints, N=1).cmap('rainbow_r', vmin=MINLAT, vmax=MAXLAT).addScalarBar() # dEPoints = Points(np.array(dE), r=5).c('black') vplt0 = Plotter(N=1, bg='black',
''' Voronoi in 3D with Voro++ library. ''' from vedo import voronoi3D, Points, show import numpy as np #from vedo import settings #settings.voro_path = '/g/sharpeba/software/bin' N = 2000 nuclei = np.random.rand(N, 3) - (0.5, 0.5, 0.5) ncl = Points(nuclei).clean(0.1) # clean makes points evenly spaced nuclei = ncl.points() mesh = voronoi3D(nuclei, tol=.001) #print(len(mesh.info['cells']), mesh.info['volumes']) pts_inside = mesh.insidePoints(nuclei) inpts = Points(pts_inside, r=50, c='r', alpha=0.2) show(mesh, inpts)
for i in range(6): g.addChild(i) # add one child node to node i for i in range(3): g.addChild(i) for i in range(3): g.addChild(i) for i in range(7, 9): g.addChild(i) for i in range(3): g.addChild(12) # add 3 children to node 12 g.build() dgraph = g.unpack(0).lineWidth(4) # get the graph lines nodes = dgraph.points() # get the 3d points of the nodes pts = Points(nodes, r=12).c('red').alpha(0.5) v1 = ['node' + str(n) for n in range(len(nodes))] v2 = [sin(x) for x in range(len(nodes))] labs1 = pts.labels(v1, scale=.04, italic=True).addPos(.05, 0.04, 0).c('green') labs2 = pts.labels(v2, scale=.04, precision=3).addPos(.05, -.04, 0).c('red') # Interpolate the node value to color the edges: dgraph.clean().pointColors(v2, cmap='viridis').addScalarBar() # This would colorize the edges directly with solid color based on the v3 array: # v3 = [sin(x) for x in range(dgraph.NCells())] # dgraph.cellColors(v3, cmap='jet').addScalarBar() show(pts, dgraph, labs1, labs2, __doc__, axes=9)
vp = Plotter(shape=[2, 2], axes=3, interactive=0) shape1 = Sphere(alpha=0.2) shape2 = vp.load(datadir + "icosahedron.vtk").normalize().lineWidth(1) agrid1, actorpts1 = makeGrid(shape1, N) vp.show(shape1, actorpts1, at=0) agrid2, actorpts2 = makeGrid(shape2, N) vp.show(shape2, actorpts2, at=1) vp.camera.Zoom(1.2) vp.interactive = False clm1 = pyshtools.SHGrid.from_array(agrid1).expand() clm2 = pyshtools.SHGrid.from_array(agrid2).expand() # clm1.plot_spectrum2d() # plot the value of the sph harm. coefficients # clm2.plot_spectrum2d() for t in np.arange(0, 1, 0.005): act21 = Points(morph(clm2, clm1, t, lmax), c="r", r=4) act12 = Points(morph(clm1, clm2, t, lmax), c="g", r=4) vp.show(act21, at=2, resetcam=0) vp.show(act12, at=3) vp.camera.Azimuth(2) vp.show(interactive=1)
# Generate photons and trace them through the optical elements lines = [] source = Grid(resx=20, resy=20).points() # a numpy array for pt in source: λ = np.random.uniform(low=450, high=750) * 1e-09 # nanometers ray = Ray(pt, direction=(0, 0, 1), wave_length=λ) line = ray.trace(elements).asLine(min_hits=4, cmap_amplitudes="Blues") # vedo.Line lines.append(line) lines = list(filter( None, lines)) # remove possible None to add a scalar bar to lines[0] lines[0].addScalarBar("Ampl.") # Grab the coords of photons exiting the conic lens3 (hits_type==-1) cone_hits = Points(lens3.hits[lens3.hits_type == -1], r=8, c="green1") # Show everything show( __doc__, elements, lines, lens5.boundaries().lw(2), cone_hits, azimuth=-90, elevation=-89, zoom=2, size=(1500, 700), bg='k2', bg2='k9', axes=dict(
# extract the columns into separate vectors: g0, g1, g2, g3, g4 = data.T # unpack genes n0, n1, n2, n3, n4 = names # now create and show histograms of the gene expressions h0 = histogram(g0, xtitle=n0, c=0) h1 = histogram(g1, xtitle=n1, c=1) h2 = histogram(g2, xtitle=n2, c=2) h3 = histogram(g3, xtitle=n3, c=3, logscale=True) h4 = histogram(g4, xtitle=n4, c=4) # this is where you choose what variables to show as 3D points pts = np.c_[g4, g2, g3] # form an array of 3d points from the columns pts_1 = pts[g0 > 0] # select only points that have g0>0 p1 = Points(pts_1, r=4, c='red') # create the vedo object print("after selection nr. of points is", len(pts_1)) pts_2 = pts[(g0 < 0) & (g1 > .5)] # select excluded points that have g1>0.5 p2 = Points(pts_2, r=8, c='green') # create the vedo object axes = (p1 + p2).buildAxes(xtitle='gene4', ytitle='gene2', ztitle='gene3', c='k') # Show the two clouds superposed on a new plotter window: show( [h0, h1, h2, h3, h4, (p1, p2, axes, __doc__)], shape="1/5", # 1 spaces above and 5 below sharecam=0,
mapIdx = [i for i in range(n)] mapCoord = [vertices[i] for i in mapIdx] # Map the LAT samples to nearest mesh vertices allLatIdx, allLatCoord, allLatVal = utils.mapSamps(mapIdx, mapCoord, OrigLatCoords, OrigLatVals) M = len(allLatIdx) # For colorbar ranges MINLAT = math.floor(min(allLatVal) / 10) * 10 MAXLAT = math.ceil(max(allLatVal) / 10) * 10 allPoints = Points(allLatCoord, r=10).cmap('gist_rainbow', allLatVal, vmin=MINLAT, vmax=MAXLAT).addScalarBar(c='white') vplt = Plotter(N=1, axes=0, interactive=True) for i in range(M): idx = allLatIdx[i] coord = allLatCoord[i] val = allLatVal[i] # plot current point as larger than the others testPoint = Point(coord, r=20).cmap('gist_rainbow', [val], vmin=MINLAT, vmax=MAXLAT).addScalarBar(c='white') vplt.show(mesh, allPoints, testPoint,
sin(state[2]) * cosa + M2 * L2 * state[3] * state[3] * sina - (M1 + M2) * G * sin(state[0])) / den1 dydx[2] = state[3] den2 = (L2 / L1) * den1 dydx[3] = (-M2 * L2 * state[3] * state[3] * sina * cosa + (M1 + M2) * G * sin(state[0]) * cosa - (M1 + M2) * L1 * state[1] * state[1] * sina - (M1 + M2) * G * sin(state[2])) / den2 return dydx t = np.arange(0.0, 10.0, dt) state = np.radians([th1, w1, th2, w2]) y = integrate.odeint(derivs, state, t) P1 = np.dstack([L1 * sin(y[:, 0]), -L1 * cos(y[:, 0])]).squeeze() P2 = P1 + np.dstack([L2 * sin(y[:, 2]), -L2 * cos(y[:, 2])]).squeeze() ax = Axes(xrange=(-2, 2), yrange=(-2, 1), htitle=__doc__) pb = ProgressBar(0, len(t), c="b") for i in pb.range(): j = max(i - 5, 0) k = max(i - 10, 0) l1 = Line([[0, 0], P1[i], P2[i]]).lw(7).c("blue2") l2 = Line([[0, 0], P1[j], P2[j]]).lw(6).c("blue2", 0.3) l3 = Line([[0, 0], P1[k], P2[k]]).lw(5).c("blue2", 0.1) pt = Points([P1[i], P2[i], P1[j], P2[j], P1[k], P2[k]], r=8).c("blue2", 0.2) show(l1, l2, l3, pt, ax, interactive=False, size=(900, 700), zoom=1.4) pb.print()
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() ################################# if __name__ == "__main__": # make up a source random cloud pts_s = np.random.randn(25, 2) pts_t = pts_s + np.sin(2 * pts_s) / 5 # and distort it mr = Morpher() mr.source = Points(pts_s, r=20, c="g", alpha=0.5) mr.target = Points(pts_t, r=10, c="r", alpha=1.0) mr.bound = 2 # limits the x and y shift mr.npts = 6 # allow move only a subset of points (implicitly sets the NDF of the fit) mr.sigma = 1. # stiffness of the mesh (1=max stiffness) mr.morph() #now mr.msource contains the modified/morphed source. mr.draw_shapes()
"""Generate 3 random sets of points and align them using Procrustes method. """ from __future__ import division, print_function from random import uniform as u from vedo import Plotter, procrustesAlignment, Points vp = Plotter(shape=[1, 2], axes=2, sharecam=0) N = 15 # number of points x = 1.0 # add some randomness pts1 = [(u(0, x), u(0, x), u(0, x) + i) for i in range(N)] pts2 = [(u(0, x) + 3, u(0, x) + i / 2 + 2, u(0, x) + i + 1) for i in range(N)] pts3 = [(u(0, x) + 4, u(0, x) + i / 4 - 3, u(0, x) + i - 2) for i in range(N)] vpts1 = Points(pts1, c="r").legend("set1") vpts2 = Points(pts2, c="g").legend("set2") vpts3 = Points(pts3, c="b").legend("set3") vp.show(vpts1, vpts2, vpts3, __doc__, at=0) # find best alignment among the n sets of Points, # return an Assembly object formed by the aligned sets aligned = procrustesAlignment([vpts1, vpts2, vpts3]) # print(aligned.info['transform']) vp.show(aligned, at=1, interactive=1)
Example shows how to share the same vtkCamera between different Plotter windows. """ from vedo import Plotter, Points, Arrows, show, Text2D import numpy as np ls = np.linspace(0, 10, 8) X, Y, Z = np.meshgrid(ls, ls, ls) xr, yr, zr = X.ravel(), Y.ravel(), Z.ravel() positions = np.vstack([xr, yr, zr]) 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)
"""Generate a denser point cloud. The new points are created in such a way that all points in any local neighborhood are within a target distance of one another""" from vedo import Points, printc, show import numpy as np npts = 50 # nr. of points coords = np.random.rand(npts, 3) # range is [0, 1] scals = np.abs(coords[:, 1]) # let the scalar be the y of the point itself pts = Points(coords, r=9) pts.pointdata["scals"] = scals densecloud = pts.densify(0.1, closest=10, niter=1) # return a new pointcloud.Points printc('nr. points increased', pts.N(), '\rightarrow ', densecloud.N(), c='lg') show([(pts, __doc__), densecloud], N=2, axes=1).close()
"""Voronoi convex tiling of the plane from a set of random points""" from vedo import Points, voronoi, show import numpy as np points = np.random.random((500, 2)) pts = Points(points).clean(0.02) # impose a min distance of 2% vor = voronoi(pts, pad=0.01) vor.cmap('Set3', "VoronoiID", on='cells').wireframe(False) # lab = vor.labels("VoronoiID", cells=True, scale=0.01) lab = None show(pts, vor, lab, __doc__, zoom=1.3)
def update(evt): global t t += 0.005 P_ = np.zeros((n, 3)) cos_t = 1.5 * np.cos(2 * np.pi * t) sin_t = 1.5 * np.sin(2 * np.pi * t) for i in range(n): x, y = P[i] f = intensity[i] * 50 dx = noise4(scale * x, scale * y, cos_t, sin_t, 2) * f dy = noise4(100 + scale * x, 200 + scale * y, cos_t, sin_t, 2) * f P_[i] = [x + dx, y + dy, np.sqrt(dx * dx + dy * dy) / 2] pts.points(P_) plt.render() pts = Points([X, Y], r=3).alpha(0.8) cir = Circle(pos=(width / 2, height / 2, -5), r=radius * 1.05) txt1 = Text2D("\Lambda L I E N L I F E", s=2.8, pos="top-center") txt2 = Text2D("Original idea by Necessary Disorder", s=0.9, pos="bottom-center") plt = Plotter() plt.show(pts, cir, txt1, txt2, elevation=-35, zoom=1.2, interactive=False) plt.addCallback("timer", update) plt.timerCallback("create") interactive()
th = np.deg2rad(90 - lat) ph = np.deg2rad(long) p = spher2cart(agrid_reco[j][i], th, ph) ll.append((lat, long)) radii = agrid_reco.T.ravel() n = 200j lnmin, lnmax = np.array(ll).min(axis=0), np.array(ll).max(axis=0) grid = np.mgrid[lnmax[0]:lnmin[0]:n, lnmin[1]:lnmax[1]:n] grid_x, grid_y = grid agrid_reco_finer = griddata(ll, radii, (grid_x, grid_y), method='cubic') pts2 = [] for i, long in enumerate( np.linspace(0, 360, num=agrid_reco_finer.shape[1], endpoint=False)): for j, lat in enumerate( np.linspace(90, -90, num=agrid_reco_finer.shape[0], endpoint=True)): th = np.deg2rad(90 - lat) ph = np.deg2rad(long) p = spher2cart(agrid_reco_finer[j][i], th, ph) pts2.append(p) mesh2 = Points(pts2, r=2, c="r", alpha=0.5) mesh2.clean(0.01) # impose point separation of 1% of the bounding box size show(mesh2, 'Spherical harmonics\nexpansion of order ' + str(lmax), at=1, interactive=True)
# G = networkx.gnm_random_graph(n=20, m=35) # for i, j in G.edges(): g.addEdge(j,i) ##################### Manually create nodes and edges for i in range(6): g.addChild(i) # add one child node to node i for i in range(3): g.addChild(i) for i in range(3): g.addChild(i) for i in range(7,9): g.addChild(i) for i in range(3): g.addChild(12) # add 3 children to node 12 g.addEdge(1,16) ##################### build and draw graph = g.build().unpack(0).lineWidth(4) # get the vedo 3d graph lines nodes = graph.points() # get the 3d points of the nodes pts = Points(nodes, r=10).lighting('off') v1 = ['node'+str(n) for n in range(len(nodes))] v2 = [sin(x) for x in range(len(nodes))] labs1 = pts.labels(v1, scale=.04, italic=True).addPos(.05,0.04,0).c('green') labs2 = pts.labels(v2, scale=.04, precision=3).addPos(.05,-.04,0).c('red') # Interpolate the node value to color the edges: graph.cmap('viridis', v2).addScalarBar3D(c='k').addPos(.3,0,0) pts.cmap('viridis', v2) # This would colorize the edges directly with solid color based on a v3 array: # v3 = [sin(x) for x in range(graph.NCells())] # graph.cmap('jet', v3).addScalarBar() show(pts, graph, labs1, labs2, __doc__, axes=9)
"""Customizing axes style (40+ control parameters!) Title font: """ from vedo import Box, Lines, Points, Spline, show, settings settings.defaultFont = 'Theemim' # an invisible box: world = Box(pos=(2.7, 0, 0), size=(12, 10, 8), alpha=0) # a dummy spline with its shadow on the xy plane pts = Points([(-2, -3.2, -1.5), (3, -1.2, -2), (7, 3, 4)], r=12) spl = Spline(pts, res=50).addShadow(z=-4) # make spline and add its shadow at z=-4 lns = Lines(spl, spl.shadow) # join spline points with its own shadow # make a dictionary of axes options axes_opts = dict( xtitle= 'My variable \Omega^\lowerxi_lm in units of \mum^3', # latex-style syntax ytitle='This is my highly\ncustomized y-axis', ztitle= 'z in units of Å', # many unicode chars are supported (type: vedo -r fonts) yValuesAndLabels=[(-3.2, 'Mark^a_-3.2'), (-1.2, 'Carmen^b_-1.2'), (3, 'John^c_3')], textScale=1.3, # make all text 30% bigger numberOfDivisions=5, # approximate number of divisions on longest axis axesLineWidth=2, gridLineWidth=1, zxGrid2=True, # show zx plane on opposite side of the bounding box yzGrid2=True, # show yz plane on opposite side of the bounding box
"""Thin Plate Spline transformations describe a nonlinear warp transform defined by a set of source and target landmarks. 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 Mesh, Points, show, dataurl import numpy as np np.random.seed(1) mesh = Mesh(dataurl + "shuttle.obj").c('silver') # pick 4 random points indxs = np.random.randint(0, mesh.N(), 4) pts = mesh.points()[indxs] # and move them randomly by a little ptsource, pttarget = [], [] for ptold in pts: ptnew = ptold + np.random.rand(3) * 0.2 ptsource.append(ptold) pttarget.append(ptnew) # print(ptold,'->',ptnew) warped = mesh.clone().thinPlateSpline(ptsource, pttarget).color("b", 0.4) apts = Points(ptsource, r=15, c="r") show(mesh, warped, apts, __doc__, viewup="z", axes=1)
"""Plot streamlines of the 2D field: u(x,y) = -1 - x\^2 + y v(x,y) = 1 + x - y\^2 """ from vedo import Points, show from vedo.pyplot import streamplot import numpy as np # a grid with a vector field (U,V): X, Y = np.mgrid[-5:5 :15j, -4:4 :15j] U = -1 - X**2 + Y V = 1 + X - Y**2 # optionally, pick some random points as seeds: prob_pts = np.random.rand(200, 2)*8 - [4,4] sp = streamplot(X,Y, U,V, lw=0.001, # line width in abs. units direction='forward', # 'both' or 'backward' probes=prob_pts, ) pts = Points(prob_pts, r=5, c='white') show(sp, pts, __doc__, axes=1, bg='bb')
latNN[i] = mapLAT[i] updatedFaces = magicLAT.updateFaces(vertices, faces, latNN, TrCoord, EDGE_THRESHOLD) latEst = magicLAT.magicLAT(vertices, faces, TrIdx, TrCoord, TrVal, EDGE_THRESHOLD) mesh = Mesh([vertices, faces]) # mesh.backColor('white').lineColor('black').lineWidth(0.25) mesh.c('grey') size = (100, 800) fontSize = 35 verPoints = Points(vertices, r=10, c='white') origLatPoints = Points(OrigLatCoords, r=10).cmap('gist_rainbow', OrigLatVals, vmin=MINLAT, vmax=MAXLAT).addScalarBar( c='white', title='LAT (ms) ', titleFontSize=fontSize, size=size) allLatPoints = Points(allLatCoord, r=10).cmap('gist_rainbow', allLatVal, vmin=MINLAT, vmax=MAXLAT).addScalarBar( c='white', title='LAT (ms) ', titleFontSize=fontSize,