from __future__ import division, print_function from plotter import vtkPlotter import numpy as np vp = vtkPlotter() # generate 4 random sets of N points in space N = 2000 f = 0.6 noise1 = np.random.rand(N, 3) * f + np.array([1, 1, 0]) noise2 = np.random.rand(N, 3) * f + np.array([1, 0, 1.2]) noise3 = np.random.rand(N, 3) * f + np.array([0, 1, 1]) noise4 = np.random.randn(N, 3) * f / 8 + np.array([1, 1, 1]) noise4 = vp.removeOutliers(noise4, 0.05) # merge points to lose their identity pts = noise1.tolist() + noise2.tolist() + noise3.tolist() + noise4.tolist() # find back their identity through clustering vp.cluster(pts, radius=0.1) # returns and stores a vtkAssembly vp.show()
from __future__ import division, print_function from plotter import vtkPlotter, ProgressBar vp = vtkPlotter(title='Spring in viscous medium', verbose=0, axes=3) l_rest = 0.1 # spring x position at rest x0 = 0.85 # initial x-coordinate of the block k = 25 # spring constant m = 20 # block mass b = 0.5 # viscosity friction (proportional to velocity) dt = 0.1 # time step #initial conditions v = vp.vector(0, 0, 0.2) x = vp.vector(x0, 0, 0) xr = vp.vector(l_rest, 0, 0) sx0 = vp.vector(-0.8, 0, 0) offx = vp.vector(0, 0.3, 0) vp.box(pos=(0, -0.1, 0), length=2.0, width=0.02, height=0.5) #surface vp.box(pos=(-.82, .15, 0), length=.04, width=0.50, height=0.3) #wall block = vp.cube(pos=x, length=0.2, c='t') spring = vp.helix(sx0, x, r=.06, thickness=.01, texture='metal1') pb = ProgressBar(0, 500, c='r') for i in pb.range(): F = -k * (x - xr) - b * v # Force and friction a = F / m # acceleration v = v + a * dt # velocity x = x + v * dt + 1 / 2 * a * dt**2 # position
v_eu,v_rk = np.array(v), np.array(v) t = 0 pb = ProgressBar(0, Nsteps, c='blue', ETA=0) for i in pb.range(): y_eu, v_eu = euler(y_eu, v_eu, t, dt) y_rk, v_rk = rk4( y_rk, v_rk, t, dt) t += dt positions_eu.append(y_eu) # store result of integration positions_rk.append(y_rk) pb.print('Integrate: RK-4 and Euler') #################################################### # Visualize the result #################################################### vp = vtkPlotter(verbose=0, axes=2) # choose axes type nr.2 vp.ytitle = 'u(x,t)' vp.ztitle = '' # will not draw z axis for i in x: vp.point([i, 0, 0], c='green', r=6) pts_actors_eu = vp.actors # save a copy of the actors list pts_actors_eu[0].legend = 'Euler method' vp.actors=[] # clean up the list for i in x: vp.point([i, 0, 0], c='red', r=6) pts_actors_rk = vp.actors # save a copy of the actors list pts_actors_rk[0].legend = 'Runge-Kutta4' # merge the two lists and set it as the current vtkPlotter actors vp.actors = pts_actors_eu + pts_actors_rk
#!/usr/bin/env python # # Example of drawing objects on different windows and/or subwindows # within the same window # # We split the main window in a 25 subwindows and draw something # in specific windows numbers # Then open an independent window and draw on a shape # import plotter # this is one instance of the class vtkPlotter with 5 raws and 5 columns vp1 = plotter.vtkPlotter(shape=(5, 5), title='many windows', axes=0) # set a different background color for a specific subwindow (the last one) vp1.renderers[24].SetBackground(.8, .9, .9) # don't hold script execution after the show() is called vp1.interactive = False # load the actors and give them a name a = vp1.load('data/shapes/airboat.vtk', legend='some legend') b = vp1.load('data/shapes/alfa147.vtk', c='red') c = vp1.load('data/shapes/atc.ply') vp1.show(at=10, actors=[a, b]) vp1.show(at=11, actors=a) vp1.show(at=12, actors=b) vp1.show(at=15, actors=[b, c]) vp1.show(at=24, actors=c)
#!/usr/bin/env python # from __future__ import division, print_function from random import uniform as u, gauss import plotter import math ######################################################################################### # # Check for more examples in directory examples/ # ######################################################################################### # Declare an instance of the class vp = plotter.vtkPlotter(title='first example') # vp.help() # shows a help message # Load a vtk file as a vtkActor and visualize it. # The tridimensional shape corresponds to the outer shape of the embryonic mouse limb # at about 11 days of gestation. # Choose a tomato color for the internal surface, and no transparency. vp.load('data/270.vtk', c='b', bc='tomato', alpha=1) # c=(R,G,B), #hex, letter or name vp.show() # picks what is automatically stored in vp.actors list # Press Esc to close the window and exit python session, or q to continue ######################################################################################### # Load a vtk file as a vtkActor and visualize it in wireframe style. act = vp.load('data/290.vtk', wire=1) vp.axes = False # do not draw cartesian axes vp.show() # picks what is automatically stored in vp.actors #vp.show(act) # same: store act in vp.actors and draws act only
################################################################# from __future__ import division, print_function import numpy as np import plotter vp = plotter.vtkPlotter(size=(800,800), verbose=0, projection=1) p1 = [0,0,0] p2 = [0,0,1] vers = [.5,1,-2] rpoint = [0,0,0] ## point not working in vtk?? currently ignored ####################################################### actor = vp.helix(p1, p2, r=.1, thickness=.01, c='r') #actor = vp.arrow(p1, p2, c='r') #actor = vp.line(p1, p2, lw=2, c='r') #actor = vp.cylinder([p1, p2], r=.03, c='r') #actor = vp.cone(p1, r=.1, c='r') ####################################################### #for i, c in enumerate(actor.coordinates()) : # if c[2]>.9999: print(i, c) #vp.show(actor, interactive=1) vp.arrow(rpoint, np.array(rpoint)+vers, c='g', alpha=.1)#dont change for i in vp.arange(0,360, 10): vp.rotate(actor, 10, vers, rpoint) ## rotate by 10 deg around vers # startPoint, endPoint = actor.orientation() ### get base and tip # vp.points([startPoint, endPoint], c='b')
gamma = .1 # some friction Dt = 0.03 # time step # Create the initial positions and velocitites (0,0) of the bobs bob_x = [0] bob_y = [0] x_dot = [0] * (N + 1) #velocities y_dot = [0] * (N + 1) for k in range(1, N + 1): alpha = np.pi / 5 * k / 10 bob_x.append(bob_x[k - 1] + np.cos(alpha) + np.random.normal(0, .1)) bob_y.append(bob_y[k - 1] + np.sin(alpha) + np.random.normal(0, .1)) # Create the bobs vp = vtkPlotter(title="Multiple Pendulum", axes=0, verbose=0) vp.box(pos=(bob_x[0], bob_y[0], 0), length=12, width=12, height=.7, c='k', wire=1) bob = [vp.sphere(pos=(bob_x[0], bob_y[0], 0), r=R / 2, c='gray')] for k in range(1, N + 1): bob.append(vp.cylinder(pos=(bob_x[k], bob_y[k], 0), r=R, height=.3, c=k)) # Create the springs out of N links link = [0] * N for k in range(N): p0 = bob[k].pos() p1 = bob[k + 1].pos()
#!/usr/bin/env python # # Example use of method light() # import plotter vp = plotter.vtkPlotter() cow = vp.load('data/cow.g', c='grey', alpha=.7) vp.plane(pos=[0, -3.6, 0], normal=[0, 1, 0], s=20, texture='grass') # vp.light() returns a vtkLight object with focal point, fp, to actor cow # fp can also be explicitly set as fp=[x,y,z] l = vp.light(pos=[-6, 6, 6], fp=cow, deg=12, showsource=1) # can be switched on/off this way #l.SwitchOff() vp.show()
## Example ## make a textured floor, a lamp post, and load a mesh of a car ## make copies of the car, rotate and move them in a loop ## vp.render() adds the actor to the list vp.actors ## rate=10 limits the speed of the loop to maximum 10 fps from __future__ import division, print_function import plotter vp = plotter.vtkPlotter(verbose=0, axes=0) vp.plane(pos=(4, 0, -.45), s=12, texture='metalfloor1') # load and set its position (commands can be concatenated) vp.load('data/shapes/lamp.vtk').pos([1.7, -0.4, 2]) a = vp.load('data/shapes/porsche.ply', c='r').rotateX(90) a.normalize() # set actor at origin and scale size to 1 print('Scene is ready, press q to continue') vp.show() for i in range(1, 10): b = a.clone(c='aqua', alpha=.04 * i) b.rotateX(-20 * i).rotateY(-10 * i).pos([i, i / 2, i / 2]) vp.render(b, rate=10) # add actor b, maximum frame rate in hertz print(i, 'time:', vp.clock, 's') vp.show()
RingThickness = 0.3 # thickness of the toroid RingRadius = 1 k = 1.4E-23 # Boltzmann constant T = 300 # room temperature dt = 1E-5 ############################################################# def reflection(p, pos): n = vp.norm(pos) return np.dot(np.identity(3) - 2 * n * n[:, np.newaxis], p) vp = plotter.vtkPlotter(title='gas in toroid', verbose=0, axes=0) vp.ring(c='g', r=RingRadius, thickness=RingThickness, alpha=.1, wire=1) ### <-- Atoms = [] poslist = [] plist, mlist, rlist = [], [], [] mass = Matom * Ratom**3 / Ratom**3 pavg = np.sqrt(2. * mass * 1.5 * k * T) # average kinetic energy p**2/(2mass) = (3/2)kT for i in range(Natoms): alpha = 2 * np.pi * random() x = RingRadius * np.cos(alpha) * .9 y = RingRadius * np.sin(alpha) * .9 z = 0
################################################################# from __future__ import division, print_function import plotter, numpy as np ### send the spring from p12 to q12, keeping its section size vp = plotter.vtkPlotter(verbose=0, projection=1) p1 = [-.6, 0.1, -0.5] p2 = [3, 1, 1] q1 = [0.9, 0.2, 0.7] q2 = [2, 0.1, 1] vp.points([p1, p2]) vp.line(p1, p2, lw=3, c='m') vp.points([q1, q2]) ####################################################### # actor = vp.helix(p1, p2, r=.2, thickness=.03, c='r') # actor = vp.arrow(p1, p2, c='r/.2') # actor = vp.line(p1, p2, c='r') # actor = vp.cylinder([p1, p2], r=.03, c='r') actor = vp.cone(p1, r=.1, c='r/.2') ####################################################### vp.show() for i in range(314 * 2): q2 = np.array(q2) + [np.sin(i / 100) / 500, 0, 0] vp.point(q2) actor.stretch(q1, q2) ##### <---
from __future__ import division, print_function from random import uniform as u from plotter import printc, ProgressBar, vtkPlotter N = 10 # nr of particles along axis s = 0.01 # random step size scene = vtkPlotter(verbose=0, axes=0) scene.plane(pos=[.44, .44, -.1], texture='wood7') for i in range(N): # generate a grid of points for j in range(N): for k in range(N): p = [i / N, j / N, k / N] scene.point(p, c=p) # color point by its own position printc('Scene is ready, press q to continue', c='green') scene.show() pb = ProgressBar(0, 100, c='red') for t in pb.range(): # loop of 400 steps pb.print() for i in range(1, N * N * N): # for each particle actor = scene.actors[i] r = [u(-s, s), u(-s, s), u(-s, s)] # random step p = actor.pos() # get point position q = p + r # add the noise if q[2] < 0: q[2] *= -1 # if bounce on the floor actor.pos(q) # set its new position scene.render(resetcam=0)
# For each point finds the 9 closest ones and fit a sphere # color points based on the size of the sphere radius # from __future__ import division, print_function from plotter import vtkPlotter, colorMap, norm vp = vtkPlotter(verbose=0, axes=0) s = vp.load('data/shapes/cow.vtk', alpha=0.3) #.subdivide() pts1, pts2, vals, cols, lns = [], [], [], [], [] for i, p in enumerate(s.coordinates()): pts = s.closestPoint(p, N=12) # find the N closest points to p sph = vp.fitSphere(pts) # find the fitting sphere if sph is None: continue if not i % 500: print(i, '/', s.N()) value = sph.radius * 10 color = colorMap(value, name='jet') # map value to a RGB color n = norm(p - sph.center) # unit vector from sphere center to p vals.append(value) cols.append(color) pts1.append(p) pts2.append(p + n / 8) vp.actors = [s] # reset the list of actors vp.points(pts1, c=cols) vp.addScalarBar() vp.lines(pts1, pts2, c='black 0.2')
#!/usr/bin/env python2 # # Example of boolean operations with actors or polydata # import plotter # declare the instance of the class vp = plotter.vtkPlotter(shape=(2,2), interactive=0, axes=3) # build to sphere actors s1 = vp.sphere(pos=[-.7,0,0], c='r', alpha=0.5) s2 = vp.sphere(pos=[0.7,0,0], c='g', alpha=0.5) # make 3 different possible operations: b1 = vp.booleanOperation(s1, s2, 'intersect', c='m') b2 = vp.booleanOperation(s1, s2, 'plus', c='b', wire=True) b3 = vp.booleanOperation(s1, s2, 'minus', c=None) # show the result in 4 different subwindows 0->3 vp.show([s1,s2], at=0, legend='2 spheres') vp.show(b1, at=1, legend='intersect') vp.show(b2, at=2, legend='plus') vp.show(b3, at=3, legend='minus') vp.addScalarBar() # adds a scalarbar to the last actor vp.show(interactive=1)
# Example usage of align() method: # generate two random sets of points as 2 actors # and align them using vtkIterativeClosestPointTransform. # Retrieve the vtk transformation matrix. # from __future__ import division, print_function from random import uniform as u import plotter vp = plotter.vtkPlotter(shape=[1, 2], verbose=0, axes=2) N1 = 15 # number of points of first set N2 = 10 # number of points of second set x = 1. # add some randomness pts1 = [(u(0, x), u(0, x), u(0, x) + i) for i in range(N1)] pts2 = [(u(0, x) + 3, u(0, x) + i / 2 + 2, u(0, x) + i + 1) for i in range(N2)] act1 = vp.points(pts1, c='b', legend='source') act2 = vp.points(pts2, c='r', legend='target') vp.show(at=0, interactive=0) # find best alignment between the 2 sets of points alpts1 = vp.align(act1, act2).coordinates() for i in range(N1): #draw arrows to see where points end up vp.arrow(pts1[i], alpts1[i], c='k', s=0.007, alpha=.1) vp.show(at=1, interactive=1)
# Moving Least Squares (MLS) algorithm to project a cloud # of 20k points to become a smooth surface. # The parameter f controls the size of the local regression. # The input actor's polydata is modified by the method # so more than one pass is possible. # If showNPlanes>0 an actor is built demonstrating the # details of the regression for some random points # In the second window we show the error estimated for # each point in color scale (left) or in size scale (right). # from __future__ import division, print_function from plotter import vtkPlotter, cos, sqrt, colorMap, vector from random import gauss import numpy as np vp1 = vtkPlotter(shape=(1, 4), axes=0) # Generate a random cloud of 20k points in space def fnc(p): x, y, z = p return vector(x, y, z + cos(x * y) / 1.5) #whatever function.. pts = [] for i in range(20000): x, y, z = gauss(0, 1), gauss(0, 1), gauss(0, 1) r = sqrt(x**2 + y**2 + z**2) / 3 p = [x / r, y / r, z / r] #generates a point on a sphere pts.append(fnc(p) * gauss(1, 0.07)) #modify and randomize point
# # Normal jpg/png images can be loaded and rendered as any vtkImageActor # import plotter vp = plotter.vtkPlotter(axes=3) for i in range(5): a = vp.load('data/images/dog.jpg') a.scale(1-i/10.) # image can be scaled in size a.rotateX(20*i).pos([0, 0, 30*i]) # can concatenate methods vp.show()
# Example of using delaunay2D() and cellCenters() # import plotter vp = plotter.vtkPlotter(shape=(1,2), interactive=0) d0 = vp.load('data/250.vtk', edges=1, legend='original mesh').rotateY(-90) coords = d0.coordinates() # get the coordinates of the mesh vertices # Build a mesh starting from points in space (they must be projectable on the XY plane) d1 = vp.delaunay2D(coords, c='r', wire=1, legend='delaunay mesh') cents = vp.cellCenters(d1) ap = vp.points(cents, legend='cell centers') vp.show([d0,d1], at=0) # NB: d0 and d1 are slightly different vp.show([d1,ap], at=1, interactive=1)
# # - Smoothing applies a gaussian smoothing with a standard deviation # which is expressed in units of pixels. # # - Backface color is set to violet (bc='v') to spot where the vtk # reconstruction is (by mistake!) inverting the normals to the surface. # # - If the spacing of the tiff stack is uneven in xyz, this can be # corrected by setting scaling factors with scaling=[xfac,yfac,zfac] import plotter # Read volume data from a tif file: f = 'data/embryo.tif' vp = plotter.vtkPlotter(shape=(1, 3), interactive=0) a0 = vp.load(f, bc='v', threshold=80, connectivity=1, legend='connectivity=True') a1 = vp.load(f, bc='v', threshold=80, connectivity=0, legend='connectivity=False') a2 = vp.load(f, bc='v', smoothing=2, legend='thres=automatic\nsmoothing=2') vp.show(a0, at=0) vp.show(a1, at=1) vp.show(a2, at=2)
# Takes 2 shapes, source and target, and morphs source on target # this is obtained by fitting 18 parameters of a non linear, # quadratic, transformation defined in transform() # The fitting minimizes the distance to the target surface # using algorithms available in the scipy.optimize package. # from __future__ import division, print_function import vtk, plotter try: import scipy.optimize as opt except: print('This example needs scipy to run.') exit() vp = plotter.vtkPlotter(shape=[1, 3], interactive=0) class Morpher: def __init__(self): self.source = None self.target = None self.bound = 0.1 self.method = 'SLSQP' #'SLSQP', 'L-BFGS-B', 'TNC' ... self.tolerance = 0.0001 self.subsample = 200 #pick only subsample pts self.allowScaling = False self.params = [] self.msource = None self.s_size = ([0, 0, 0], 1) # ave position and ave size self.fitResult = None
#!/usr/bin/env python # # Example of use of function() method. # Draw a surface representing the 3D function specified as a string # or as a reference to an external already existing function. # Red points indicate where the function does not exist. # import math import plotter def my_z(x, y): return math.sin(2 * x * y) * math.cos(3 * y) / 2 vp = plotter.vtkPlotter(shape=(2, 2), axes=2, sharecam=False) # draw at renderer nr.0 the first actor, show it with a texture # an existing function z(x,y) can be passed: f1 = vp.fxy(my_z, texture='paper') vp.show(f1, at=0, interactive=0) # c=None shows the original z-scalar color scale. No z-level lines. f2 = vp.fxy(lambda x, y: math.sin(x * y), c=None, zlevels=None, texture=None, wire=1) vp.show(f2, at=1) # red dots are shown where the function does not exist (y>x):
# Example that shows how to draw very large number of # spheres (same for points, lines) with different color # or different radius. Resolution (res) can be specified. # (vtk versions<8.0 might be slow) # from __future__ import division, print_function from plotter import vtkPlotter from random import gauss N=100000 vp = vtkPlotter(N=2, axes=3, interactive=0) cols = range(N) #color numbers pts = [(gauss(0,1), gauss(0,2), gauss(0,1)) for i in cols] rads = [abs(pts[i][1])/10 for i in cols] # radius=0 for y=0 print('..spheres generated:', N) # all have same radius but different colors: s0 = vp.spheres(pts, c=cols, r=0.1, res=3) # res=resolution # all have same color (texture) but different radius along y: s1 = vp.spheres(pts, r=rads, res=10, texture='gold1') print('..spheres rendered:', N*2) vp.show(s0, at=0) vp.show(s1, at=1, legend='N='+str(N), interactive=1)
# In this example we modify the mesh of a shape # by moving the points along the normals to the surface # and along the radius of a sphere centered at the center of mass. # At each step we redefine the actor so that the normals are # recalculated for the underlying polydata. # from __future__ import division, print_function from plotter import vtkPlotter, norm, mag vp = vtkPlotter(axes=0) s = vp.load('data/290.vtk', wire=1) vp.actors.append(s.clone(c='red 1.0', wire=0)) c = vp.centerOfMass(s) vp.point(c) Niter = 4 for t in range(Niter): print('iteration', t) coords = s.coordinates() normals = s.normals() aves = vp.averageSize(s) * 1.5 for i in range(s.N()): n = normals[i] p = coords[i] q = norm(p - c) * aves + c dp = mag(q - p) alongn = n * dp alongr = q - p # bias normal
# ################################################################ # Example usage of colorMap(value, name) # This method returns a color from a float in the range [0,1] # by looking it up in matplotlib database of colormaps # ################################################################ from __future__ import division, print_function from plotter import vtkPlotter, colorMap mapkeys = [ 'copper', 'gray', 'binary', 'cool', 'rainbow', 'winter', 'jet', 'paired', 'hot', 'afmhot', 'bone' ] vp = vtkPlotter(shape=(3, 4), axes=3, verbose=0, interactive=0) #load actor and subdivide mesh to increase the nr of vertex points act = vp.load('data/shapes/mug.ply', c='gray/0.1', wire=1).subdivide() pts = act.coordinates() print('range in y is:', act.ybounds()) for i, key in enumerate(mapkeys): # for each available color map name # make a list of colors based on the y position of point p cols = [colorMap(p[1] / .087, name=key) for p in pts] apts = vp.points(pts, cols) vp.show([act, apts], at=i, legend=key) vp.show(interactive=1)
# In this example we fit spheres to a region of a surface defined by # N points that are closest to a given point of the surface. # For some of these point we show the fitting sphere. # Red lines join the center of the sphere to the surface point. # Blue points are the N points used for fitting. # Green histogram is the distribution of residuals from the fitting. # Red histogram is the distribution of the curvatures (1/r**2). # Fitted radius can be accessed from attribute actor.radius from __future__ import division, print_function import plotter vp = plotter.vtkPlotter(verbose=0) # load mesh and increase by a lot (N=2) the nr of surface vertices s = vp.load('data/shapes/cow.vtk').alpha(0.3).subdivide(N=2) reds, invr = [], [] for i, p in enumerate(s.coordinates()): if i%1000: continue # skip most points pts = s.closestPoint(p, N=16) # find the N closest points to p sph = vp.fitSphere(pts, alpha=0.05) # find the fitting sphere if sph is None: continue # may fail if all points sit on a plane vp.points(pts) vp.line(sph.center, p, lw=2) reds.append(sph.residue) invr.append(1/sph.radius**2) h1 = vp.histogram(reds, title='residue', bins=12, c='g', corner=3) h2 = vp.histogram(invr, title='1/r**2', bins=12, c='r', corner=4)
grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat = grid_reco.lats()[i] for j, value in enumerate(longs): ilong = grid_reco.lons()[j] th = (90 - ilat) / 57.3 ph = ilong / 57.3 r = value + rbias p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r pts.append(p) return pts vp = plotter.vtkPlotter(shape=[2, 2], verbose=0, axes=3, interactive=0) shape1 = vp.sphere(alpha=0.2) shape2 = vp.load('data/shapes/icosahedron.vtk', edges=1).normalize() agrid1, actorpts1 = makegrid(shape1, N) vp.show(at=0, actors=[shape1, actorpts1]) agrid2, actorpts2 = makegrid(shape2, N) vp.show(at=1, actors=[shape2, actorpts2]) 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
# The difference between one time point and the next is shown as # a blue component. # from __future__ import division, print_function from plotter import vector, vtkPlotter, ProgressBar import numpy as np # Load (with numpy) an existing set of mesh points and a list # of scalars that represent the concentration of a substance mesh, conc, cgradfac = np.load('data/turing_data.npy', encoding='latin1') conc = conc / 1000. # normalize concentrations read from file nc, n = conc.shape # nc= nr. of time points, n= nr. of vertices # Create the vtkPlotter instance and position the camera. # (values can be copied in the code by pressing C in the rendering window) vp = vtkPlotter(verbose=0, axes=0, interactive=0) vp.camera.SetPosition(962, -239, 1034) vp.camera.SetFocalPoint(0.0, 0.0, 10.0) vp.camera.SetViewUp(-0.693, -0.479, 0.539) pb = ProgressBar(0, nc, c='g') # a green progress bar for t1 in pb.range(): # for each time point t2 = t1 + 1 if t1 == nc - 1: t2 = t1 # avoid index overflow with last time point vp.actors = [] # clean up the list of actors at each iteration vp.cylinder([0, 0, -15], r=260, height=10, texture='marble', res=60) vp.cylinder([0, 0, 10], r=260, height=50, wire=1, c='gray', res=60) pts, cols = [], [] for i, p in enumerate(mesh): # for each vertex in the mesh
# particle in a swarm of small particles in 2D motion. # The spheres collide elastically with themselves and # with the walls of the box. The masses of the spheres # are proportional to their radius**3 (as in 3D). # # Adapted by M. Musy from E. Velasco (2009) #======================================================= from __future__ import division, print_function import random, plotter import numpy as np screen_w = 600 screen_h = 600 vp = plotter.vtkPlotter(title="Brownian Motion", size=(screen_w, screen_h), axes=0, verbose=0) # Constants and time step Nsp = 200 # Number of small spheres Rb = screen_w / 32 # Radius of the big sphere Rs = Rb * 0.43 # Radius of small spheres Ms = (Rs / Rb)**3 # Mass of the small spheres (Mbig=1) Dt = 0.03 # Time step LBox = (screen_w / 2, screen_h / 2) # Size of the box = 2LBox[0].2LBox[1] Lb0 = LBox[0] - Rb Lb1 = LBox[1] - Rb Ls0 = LBox[0] - Rs Ls1 = LBox[1] - Rs
from __future__ import division, print_function from plotter import vtkPlotter, mag import numpy as np scene = vtkPlotter(title='Lorenz attractor', axes=2) scene.verbose = 0 dt = 0.001 y = [25, -10, -7] # Starting point (initial condition) pts, cols = [], [] scene.point(y, r=20, c='g', alpha=0.3) for t in np.linspace(0, 20, int(20 / dt)): # Integrate a funny differential equation dydt = np.array([ -8 / 3 * y[0] + y[1] * y[2], -10 * (y[1] - y[2]), -y[1] * y[0] + 28 * y[1] - y[2] ]) y = y + dydt * dt c = np.clip([mag(dydt) * 0.005], 0, 1)[0] # color by speed pts.append(y) cols.append([c, 0, 1 - c]) scene.points(pts, cols, r=2) scene.show()
# Example to show how to use recoSurface() to reconstruct a surface from points. # 1. An object is loaded and noise is added to its vertices. # 2. the point cloud is smoothened with MLS (see moving_least_squares.py) # 3. cleanPolydata imposes a minimum distance among points where # 'tol' is the fraction of the actor size. # 4. a triangular mesh is extracted from this set of sparse points # 'bins' is the number of voxels of the subdivision # NB: recoSurface only works with vtk version >7 # from __future__ import division, print_function from plotter import vtkPlotter import numpy as np vp = vtkPlotter(shape=(1,4), axes=0) act = vp.load('data/shapes/pumpkin.vtk') vp.show(act, at=0) noise = np.random.randn(act.N(), 3)*0.05 act_pts0 = vp.points(act.coordinates()+noise, r=3) #add noise act_pts1 = act_pts0.clone() #make a copy to modify vp.show(act_pts0, at=1, legend='noisy cloud') vp.smoothMLS(act_pts1, f=0.4) #smooth cloud print('Nr of points before cleanPolydata:', act_pts1.N()) vp.cleanPolydata(act_pts1, tol=0.01) #impose a min distance among points print(' after cleanPolydata:', act_pts1.N())