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()
def showSolution3D(S, start, goal): from vedo import Text3D, Cube, Line, Grid, merge, show pts, cubes, txts = [], [], [] pts = [(x, -y) for y, x in S[0]] for y, line in enumerate(Z): for x, c in enumerate(line): if c: cubes.append(Cube([x, -y, 0])) path = Line(pts).lw(6).c('tomato') walls = merge(cubes).clean().flat().texture('wood1') sy, sx = S[1].shape gradient = np.flip(S[1], axis=0).ravel() grd = Grid(pos=((sx - 1) / 2, -(sy - 1) / 2, -0.49), sx=sx, sy=sy, resx=sx, resy=sy) grd.lw(0).wireframe(False).cmap('gist_earth_r', gradient, on='cells') grd.addScalarBar(title='Gradient', horizontal=True, c='k', nlabels=2) txts.append(__doc__) txts.append(Text3D('Start', pos=[start[1] - 1, -start[0] + 1.5, 1], c='k')) txts.append(Text3D('Goal!', pos=[goal[1] - 2, -goal[0] - 2.7, 1], c='k')) show(path, walls, grd, txts, axes=0, zoom=1.2)
"""Mesh a line contour with quads of variable resolution""" from vedo import Spline, Grid, show import numpy as np shape = Spline( [ [0.0, 0.0], [1.0, 0.0], [1.1, 4.0], [1.0, 1.5], [0.2, 5.0], [-1., 3.0], [0.4, 2.7], [-1., 2.4], ], closed=True, ).color('red4').lineWidth(5) xcoords = np.arange(-2.0, 2.5, 0.075) ycoords = np.arange(-0.5, 5.5, 0.075) xcoords += np.cos(xcoords + 0.6) * 0.75 # make quads shrink and stretch ycoords += np.sin(ycoords + 0.5) * 0.75 # to refine mesh resolution grd = Grid(sx=xcoords, sy=ycoords) # create a gridded plane msh = shape.tomesh(grid=grd, quads=True) show(shape, msh, __doc__, axes=1)
# --------------------------------------------------------------- Z = np.zeros((n+2, n+2), [('U', np.double), ('V', np.double)]) U, V = Z['U'], Z['V'] u, v = U[1:-1, 1:-1], V[1:-1, 1:-1] r = 20 u[...] = 1.0 U[n//2-r:n//2+r, n//2-r:n//2+r] = 0.50 V[n//2-r:n//2+r, n//2-r:n//2+r] = 0.25 u += 0.05*np.random.uniform(-1, 1, (n, n)) v += 0.05*np.random.uniform(-1, 1, (n, n)) sy, sx = V.shape grd = Grid(sx=sx, sy=sy, resx=sx, resy=sy) grd.lineWidth(0).wireframe(False).lighting(ambient=0.5) formula = r'(u,v)=(D_u\cdot\Delta u -u v v+F(1-u), D_v\cdot\Delta v +u v v -(F+k)v)' ltx = Latex(formula, s=15, pos=(0,-sy/1.9,0)) print('Du, Dv, F, k, name =', Du, Dv, F, k, name) settings.useDepthPeeling = False for step in range(Nsteps): for i in range(25): Lu = ( U[0:-2, 1:-1] + U[1:-1, 0:-2] - 4*U[1:-1, 1:-1] + U[1:-1, 2:] + U[2: , 1:-1]) Lv = ( V[0:-2, 1:-1] + V[1:-1, 0:-2] - 4*V[1:-1, 1:-1] + V[1:-1, 2:] + V[2: , 1:-1]) uvv = u*v*v
"""A simple quiver plot""" from vedo import Grid, show from vedo.pyplot import quiver # create displacements pts1 = Grid(sx=1.0, sy=1.0).points() pts2 = Grid(sx=1.2, sy=1.2).rotateZ(4).points() qp = quiver( pts1, # points pts2 - pts1, # associated vectors c='r', ) show(qp, __doc__, axes=1).close()
for s in range(1, Nsp): ListVel.append((Rb * random.uniform(-1, 1), Rb * random.uniform(-1, 1))) Vel = np.array(ListVel) # Create the spheres Spheres = [ Sphere(pos=(Pos[0][0], Pos[0][1], 0), r=Radius[0], c="red", res=12).phong() ] for s in range(1, Nsp): a = Sphere(pos=(Pos[s][0], Pos[s][1], 0), r=Radius[s], c="blue", res=6).phong() Spheres.append(a) # vp += a vp += Spheres vp += Grid(sx=screen_w, sy=screen_w) # Auxiliary variables Id = np.identity(Nsp) Dij = (Radius + Radius[:, np.newaxis])**2 # Matrix Dij=(Ri+Rj)**2 # The main loop pb = ProgressBar(0, 2000, c="r") for i in pb.range(): # Update all positions np.add(Pos, Vel * Dt, Pos) # Fast version of Pos = Pos + Vel*Dt # Impose the bouncing at the walls if Pos[0, 0] <= -Lb0: Pos[0, 0] = -Lb0 Vel[0, 0] = -Vel[0, 0]
Du, Dv, F, k, name = 0.16, 0.08, 0.035, 0.060, 'Zebrafish' # --------------------------------------------------------------- Z = np.zeros((n + 2, n + 2), [('U', np.double), ('V', np.double)]) U, V = Z['U'], Z['V'] u, v = U[1:-1, 1:-1], V[1:-1, 1:-1] r = 20 u[...] = 1.0 U[n // 2 - r:n // 2 + r, n // 2 - r:n // 2 + r] = 0.50 V[n // 2 - r:n // 2 + r, n // 2 - r:n // 2 + r] = 0.25 u += 0.05 * np.random.uniform(-1, 1, (n, n)) v += 0.05 * np.random.uniform(-1, 1, (n, n)) sy, sx = V.shape grd = Grid(sx=sx, sy=sy, resx=sx, resy=sy) grd.lineWidth(0).wireframe(False).lighting(ambient=0.5) formula = r'(u,v)=(D_u\cdot\Delta u -u v v+F(1-u), D_v\cdot\Delta v +u v v -(F+k)v)' ltx = Latex(formula, s=15, pos=(0, -sy / 1.9, 0)) print('Du, Dv, F, k, name =', Du, Dv, F, k, name) settings.useDepthPeeling = False for step in range(Nsteps): for i in range(25): Lu = (U[0:-2, 1:-1] + U[1:-1, 0:-2] - 4 * U[1:-1, 1:-1] + U[1:-1, 2:] + U[2:, 1:-1]) Lv = (V[0:-2, 1:-1] + V[1:-1, 0:-2] - 4 * V[1:-1, 1:-1] + V[1:-1, 2:] + V[2:, 1:-1]) uvv = u * v * v u += Du * Lu - uvv + F * (1 - u) v += Dv * Lv + uvv - (F + k) * v
import vtk from vedo import Grid, Tensors, show domain = Grid(resx=5, resy=5, c='gray') # Generate random attributes on a plane ag = vtk.vtkRandomAttributeGenerator() ag.SetInputData(domain.polydata()) ag.GenerateAllDataOn() ag.Update() ts = Tensors(ag.GetOutput(), scale=0.1) #ts.printInfo() show(domain, ts).close()
"""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))
"""The butterfly effect with cylindrical mirrors and a laser""" # Original idea from "The Action Lab": https://www.youtube.com/watch?v=kBow0kTVn3s # from vedo import Plotter, Grid, Cylinder, merge from optics_base import Ray, Mirror, Detector # see file ./optics_base.py grid = Grid(resx=3, resy=4) # pick a few points in space to place cylinders pts = grid.points().tolist() + grid.cellCenters().tolist() # Create the mirror by merging many (y-scaled) cylinders into a single mesh object cyls = [ Cylinder(p, r=0.065, height=0.2, res=720).scale([1, 1.5, 1]) for p in pts ] mirror = Mirror(merge(cyls)).color("silver") # Create a detector surface as a thin cylinder surrounding the mirror sd = Cylinder(r=1, height=0.3, cap=False).cutWithPlane([0, -0.95, 0], normal='y') detector = Detector(sd) def slider(widget, event): ### callback to shift the beam along x dx = widget.GetRepresentation().GetValue() ray = Ray([dx, -1.2, -0.1], direction=(0, 1, 0.02)) ray.maxiterations = 1000 # max nr. of reflections ray.trace([mirror, detector]) # cumpute trajectory detector.count().cmap("Reds", on='cells', vmax=10) line = ray.asLine().lineWidth(4).c('green5') if plt.actors[-1].name == "Line": plt.pop() # remove the last Line plt.add(line) # add the new one
"""Simulation of an optical system with lenses and mirrors of arbitrary shapes and orientations (points mark the exit locations of photons, many from total internal reflections)""" from vedo import Grid, Sphere, Cube, Cone, Points, show from optics_base import Lens, Ray, Mirror, Screen # see file ./optics_base.py import numpy as np # Create meshes as ordinary vedo objects sm = Sphere(r=8).z(-8.1) sp = Sphere(r=8).z(+8.1) shape1 = Sphere(r=0.9, res=53).cutWithPlane().cap().rotateY(-90).pos(0, 0, 0.5) shape2 = Cube(side=2).triangulate().boolean('-', sm).boolean("-", sp).z(3) shape3 = Cone().rotateY(-90).z(6) shape4 = Cube().scale([1.7, 1, 0.2]).rotateY(70).pos(-0.3, 0, 8) shape5 = Sphere(r=2).boolean("intersect", Sphere(r=2).z(3.5)).rotateX(10).pos(0.8, 0, 7.5) shape6 = Grid(resx=1, resy=1).rotateY(-60).rotateX(30).pos(0, -1, 11) # Build lenses (with their refractive indices), and mirrors, using those meshes lens1 = Lens(shape1, ref_index=1.35).c("blue9") # constant refr. index lens2 = Lens(shape2, ref_index="glass").c("blue7") lens3 = Lens(shape3, ref_index="glass").c("green9") lens4 = Lens(shape4, ref_index="glass").c("purple9").lineWidth(1) lens5 = Lens(shape5, ref_index="glass").c("orange9") mirror = Mirror(shape6) screen = Screen(4, 4).rotateY(20).pos(1, 0, 12) elements = [lens1, lens2, lens3, lens4, lens5, mirror, screen] # Generate photons and trace them through the optical elements lines = [] source = Grid(resx=20, resy=20).points() # a numpy array for pt in source:
"""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 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')
u1, u2 = TrialFunctions(V) v1, v2 = TestFunctions(V) a1 = u1 * v1 - Constant(0.5 * dt) * u2 * v1 L1 = un1 * v1 + Constant(0.5 * dt) * un2 * v1 a2 = u2 * v2 + Constant(0.5 * c**2 * dt) * inner(grad(u1), grad(v2)) L2 = un2 * v2 - Constant(0.5 * c**2 * dt) * inner(grad(un1), grad(v2)) a = (a1 + a2) * dx L = (L1 + L2) * dx uh = Function(V) ############################################################ from vedo.dolfin import plot from vedo import Grid #build a thin gray frame to avoid camera jumping around frame = Grid(pos=[0.5, 0, 0]).c('gray').alpha(0.1) for i in range(nt): solve(a == L, uh, [bc1, bc2]) uk1, uk2 = uh.split() un.assign(uh) # # plot(uk1, warpYfactor=.0) # exit() if not i % 4: plot( uk1, frame, at=0,