def runTime(key, vplt): secs = [str(i) for i in range(10)] if key not in secs: return printc('Will execute score for '+key+' seconds') vplt.interactive = False vplt.clock = int(key) vplt.interactor.ExitCallback()
def runTime(self, key): secs = [str(i) for i in range(10)] if key not in secs: return printc('Will execute score for ' + key + ' seconds') self.vp.interactive = False self.vp.clock = int(key) self.vp.interactor.ExitCallback()
def _moveHand(self, side, t):############# runs inside play() loop if side == 1: c1,c2 = 'tomato', 'orange' engagedkeys = self.engagedkeysR engagedfingers = self.engagedfingersR H = self.rightHand vpH = self.vpRH else: c1,c2 = 'purple', 'mediumpurple' engagedkeys = self.engagedkeysL engagedfingers = self.engagedfingersL H = self.leftHand vpH = self.vpLH for i, n in enumerate(H.noteseq):##################### start, stop, f = n.time, n.time+n.duration, n.fingering if isinstance(f, str): continue if f and stop <= t <= stop+self.dt and engagedkeys[i]: #release key engagedkeys[i] = False engagedfingers[f] = False name = nameof(n) krelease(self.KB[name]) frelease(vpH[f]) self.vp.interactor.Render() for i, n in enumerate(H.noteseq):##################### start, stop, f = n.time, n.time+n.duration, n.fingering if isinstance(f, str): print('Warning: cannot understand lyrics:',f, 'skip note',i) continue if f and start <= t < stop and not engagedkeys[i] and not engagedfingers[f]: #press key if i >= len(H.fingerseq): return engagedkeys[i] = True engagedfingers[f] = True name = nameof(n) if t> self.t0 + self.vp.clock: self.t0 = t self.vp.show(zoom=2, interactive=True) for g in [1,2,3,4,5]: vpH[g].x( side * H.fingerseq[i][g] ) vpH[0].x(vpH[3].x()) # index 0 is arm, put it where middle finger is fpress(vpH[f], c1) kpress(self.KB[name], c2) self.vp.show(zoom=2, interactive=False) if self.verbose: msg = 'meas.'+str(n.measure)+' t='+str(round(t,2)) if side==1: printc((msg,'\t\t\t\tRH.finger', f, 'hit', name), 'b') else: printc((msg, '\tLH.finger', f, 'hit', name), 'm') if self.playsounds: playSound(n, self.speedfactor) else: time.sleep(n.duration*self.speedfactor)
def myloop(*event): global counts # this is needed because counts is being modified: counts += 0.1 # reference 'actor' is not modified so doesnt need to be global # (internal properties of the object are, but python doesn't know..) actor.pos([0, counts / 20, 0]).color(counts) # move cube and change color rp = [u(-1, 1), u(0, 1), u(-1, 1)] # a random position s = sphere(rp, r=0.05, c='blue 0.2') vp.render(s, resetcam=True) # show() would cause exiting the loop # waste cpu time to slow down program for i in range(100000): sin(i) printc('#', end='')
def myfnc(key): if not vp.clickedActor or key != "c": printc("click an actor and press c.", c="r") return printc("clicked actor :", vp.clickedActor.legend(), c=4) printc("clicked 3D point:", vp.picked3d, c=4) printc("clicked renderer:", [vp.renderer], c=2) vp.add(Sphere(pos=vp.picked3d, r=0.005, c="v")) vp.show()
def myfnc(key): if not vp.clickedActor or key != 'c': printc('click an actor and press c.', c='r') return printc('clicked actor :', vp.clickedActor.legend(), c=4) printc('clicked 3D point:', vp.picked3d, c=4) printc('clicked renderer:', vp.clickedRenderer, c=2) vp.add(Sphere(pos=vp.picked3d, r=.005, c='v')) vp.show()
def myfnc(key): if not vp.clickedActor or key != 'c': printc('click an actor and press c.', c='r') return cb = sphere(pos=vp.picked3d, r=.05, c='v') vp.render(cb) printc('clicked actor :', vp.clickedActor.legend, c=4) printc('clicked 3D point:', vp.picked3d, c=4) printc('clicked renderer:', vp.clickedRenderer, c=2)
def animation(coord, connect, amp, disp_vector): ''' Plot deformed mesh animation. Args: coord (:obj:`numpy.array`): Coordinates of the element. connect (:obj:`numpy.array`): Element connectivity. amp (:obj:`int`): Amplitude. disp_vector (:obj:`numpy.array`): Displacement. ''' vt.printc("Press F1 to exit.", c="red", invert=1) vp = vt.Plotter(axes=0, interactive=0) vp += __doc__ ind_faces_U = free_faces(coord, connect) aux = np.linspace(-1, 1, num=400) factor = amp * np.sin(aux * 2 * np.pi) while True: for f in factor: coord3D_U = fc.apply_U(disp_vector, coord, factor=f) verts_U = coord3D_U[:, 1:] mesh = build_mesh(verts_U, ind_faces_U) vp.clear() vp.add(mesh) vp.show()
def demo3d_hanoi(**kwargs): nr_disks = kwargs.get("nr_disks", 5) interactive = kwargs.get("interactive", 1) hanoi = Hanoi(nr_disks) tower_states = list([hanoi.towers]) for _ in hanoi.moves(): tower_states.append(hanoi.towers) vp = Plotter(axes=0, interactive=0, bg="w", size=(800, 600)) vp.camera.SetPosition([18.5, -20.7, 7.93]) vp.camera.SetFocalPoint([3.0, 0.0, 2.5]) vp.camera.SetViewUp([-0.1, +0.17, 0.977]) cols = makePalette("red", "blue", hanoi.nr_disks + 1, hsv=True) disks = { hanoi.nr_disks - i: Cylinder(pos=[0, 0, 0], r=0.2 * (hanoi.nr_disks - i + 1), c=cols[i]) for i in range(hanoi.nr_disks) } for k in disks: vp += disks[k] vp += Box(pos=(3.0, 0, -.5), length=12.0, width=4.0, height=0.1) vp.show(zoom=1.2) printc("\n Press q to continue, Esc to exit. ", c="y", invert=1) pb = ProgressBar(0, len(tower_states), 1, c="b", ETA=False) for t in pb.range(): pb.print() state = tower_states[t] for tower_nr in range(3): for i, disk in enumerate(state[tower_nr]): disks[disk].pos([3 * tower_nr, 0, i + 0.5]) vp.show(resetcam=0, interactive=interactive, rate=10) vp.show(resetcam=0, interactive=1)
def play(self): printc('Press [0-9] to proceed by one note or for more seconds', c=1) printc('Press Esc to exit.', c=1) self.vp.keyPressFunction = self.runTime # enable observer if self.rightHand: self.engagedkeysR = [False] * len(self.rightHand.noteseq) self.engagedfingersR = [False] * 6 # element 0 is dummy if self.leftHand: self.engagedkeysL = [False] * len(self.leftHand.noteseq) self.engagedfingersL = [False] * 6 t = 0.0 while True: if self.rightHand: self._moveHand(1, t) if self.leftHand: self._moveHand(-1, t) if t > 1000: break t += self.dt # absolute time flows if self.verbose: printc('End of note sequence reached.') self.vp.keyPressFunction = None # disable observer
"""Recreate a model of a geothermal reservoir, Utah (Credits: A. Pollack, SCRF)""" from vtkplotter import Plotter, Mesh, Points, Line, Lines, printc import pandas as pd from scipy.spatial import Delaunay #import the file from github basegithuburl = 'https://raw.githubusercontent.com/ahinoamp/Example3DGeologicModelUsingVTKPlotter/master/' #Load surfaces printc("...loading data, please wait", invert=1) fileVertices = basegithuburl + 'land_surface_vertices.csv' landSurfacePD = pd.read_csv(fileVertices) fileVertices = basegithuburl + '175C_vertices.csv' vertices_175CPD = pd.read_csv(fileVertices) fileVertices = basegithuburl + '225C_vertices.csv' vertices_225CPD = pd.read_csv(fileVertices) fileVertices = basegithuburl + 'Negro_Mag_Fault_vertices.csv' Negro_Mag_Fault_verticesPD = pd.read_csv(fileVertices) fileVertices = basegithuburl + 'Opal_Mound_Fault_vertices.csv' Opal_Mound_Fault_verticesPD = pd.read_csv(fileVertices) fileVertices = basegithuburl + 'top_granitoid_vertices.csv' top_granitoid_verticesPD = pd.read_csv(fileVertices) fileVertices = basegithuburl + 'top_granitoid_vertices.csv'
link[k] = vp.add(Spring(p0, p1, thickness=0.015, r=R / 3, c="gray")) # Create some auxiliary variables x_dot_m = [0] * (N + 1) y_dot_m = [0] * (N + 1) dij = [0] * (N + 1) # array with distances to previous bob dij_m = [0] * (N + 1) for k in range(1, N + 1): dij[k] = mag([bob_x[k] - bob_x[k - 1], bob_y[k] - bob_y[k - 1]]) fctr = lambda x: (x - 1) / x Dt *= np.sqrt(1 / g) Dt2 = Dt / 2 # Midpoint time step DiaSq = (2 * R)**2 # Diameter of bob squared printc("Press F1 to exit.", c="red", invert=1) while True: bob_x_m = list(map((lambda x, dx: x + Dt2 * dx), bob_x, x_dot)) # midpoint variables bob_y_m = list(map((lambda y, dy: y + Dt2 * dy), bob_y, y_dot)) for k in range(1, N + 1): factor = fctr(dij[k]) x_dot_m[k] = x_dot[k] - Dt2 * (Ks * (bob_x[k] - bob_x[k - 1]) * factor + gamma * x_dot[k]) y_dot_m[k] = y_dot[k] - Dt2 * (Ks * (bob_y[k] - bob_y[k - 1]) * factor + gamma * y_dot[k] + g)
"""Manually build a mesh from points and faces""" from vtkplotter import Mesh, printc, show verts = [(50,50,50), (70,40,50), (50,40,80), (80,70,50)] faces = [(0,1,2), (2,1,3), (1,0,3)] # (the first triangle face is formed by vertex 0, 1 and 2) # Build the polygonal Mesh object: m = Mesh([verts, faces]) m.backColor('violet').lineColor('tomato').lineWidth(2) # retrieve them as numpy arrays printc('points():\n', m.points(), c=3) printc('faces(): \n', m.faces(), c=3) show(m, __doc__, viewup='z', axes=8)
"""Recreate a model of a geothermal reservoir, Utah (Credits: A. Pollack, SCRF)""" from vtkplotter import Plotter, Mesh, Points, Line, Lines, printc, exportWindow from scipy.spatial import Delaunay import pandas as pd # Load surfaces, import the file from github printc("...loading data...", invert=1, end='') url = "https://raw.githubusercontent.com/ahinoamp/Example3DGeologicModelUsingVTKPlotter/master/" landSurfacePD = pd.read_csv(url + "land_surface_vertices.csv") vertices_175CPD = pd.read_csv(url + "175C_vertices.csv") vertices_225CPD = pd.read_csv(url + "225C_vertices.csv") microseismic = pd.read_csv(url + "Microseismic.csv") Negro_Mag_Fault_verticesPD = pd.read_csv(url + "Negro_Mag_Fault_vertices.csv") Opal_Mound_Fault_verticesPD = pd.read_csv(url + "Opal_Mound_Fault_vertices.csv") top_granitoid_verticesPD = pd.read_csv(url + "top_granitoid_vertices.csv") # The well path and different logs for the well paths well_5832_path = pd.read_csv(url + "path5832.csv") pressure_well = pd.read_csv(url + "pressure5832.csv") temp_well = pd.read_csv(url + "temperature5832.csv") nphi_well = pd.read_csv(url + "nphi5832.csv") # Since most of the wells in the area were just vertical, I split them into two files: # One file with the top of the wells and the other with the bottom point of the wellbore wellsmin = pd.read_csv(url + "MinPointsWells.csv") wellsmax = pd.read_csv(url + "MaxPointsWells.csv") # Project boundary area on the surface
# Align 2 shapes and for each vertex of the first draw # and arrow to the closest point of the second. # The source transformation is saved in actor.transform # rigid=True doesn't allow scaling # from vtkplotter import Plotter, printc, mag2 from vtkplotter.analysis import align vp = Plotter(verbose=0, axes=4) limb = vp.load('data/270.vtk', alpha=0.3) rim = vp.load('data/270_rim.vtk') rim.color('r').lineWidth(4) arim = align(rim, limb, iters=100, rigid=True) arim.color('g').lineWidth(4) vp.actors.append(arim) d = 0 prim = arim.coordinates() for p in prim: cpt = limb.closestPoint(p) vp.arrow(p, cpt, c='g') d += mag2(p - cpt) # square of residual distance printc('ave. squared distance =', d / len(prim), c='g') vp.show()
def onLeftClick(actor): printc("Left button pressed on", [actor], c="g")
def onMiddleClick(actor): printc("Middle button pressed on", [actor], c="y")
def buttonfunc(): act.alpha(1 - act.alpha()) # toggle mesh transparency bu.switch() # change to next status printc(bu.status(), box='_', dim=True)
to add a sphere and some info is printed. """ from vtkplotter import Plotter, printc, Sphere, Text, datadir ############################################################################## def myfnc(key): if not vp.clickedActor or key != "c": printc("click an actor and press c.", c="r") return printc("clicked actor :", vp.clickedActor.legend(), c=4) printc("clicked 3D point:", vp.picked3d, c=4) printc("clicked renderer:", [vp.renderer], c=2) vp.add(Sphere(pos=vp.picked3d, r=0.005, c="v")) vp.show() ############################################################################## vp = Plotter(verbose=0) vp.keyPressFunction = myfnc # make it known to Plotter class vp.load(datadir + "bunny.obj") vp.add(Text(__doc__)) printc("\nPress c to execute myfnc()", c=1) vp.show()
pl = Plane(mesh.centroid, normal=[0, 0, 1], sx=6, sy=4, alpha=0.3) slice_2D, to_3D = mslice.to_planar() # show objects on N=2 non-synced renderers: show([(mesh, pl), (slice_2D, txt)], N=2, sharecam=False, axes=True) # if we wanted to take a bunch of parallel slices, like for a 3D printer # we can do that easily with the section_multiplane method # we're going to slice the mesh into evenly spaced chunks along z # this takes the (2,3) bounding box and slices it into [minz, maxz] z_extents = mesh.bounds[:, 2] # slice every .125 model units (eg, inches) z_levels = np.arange(*z_extents, step=0.125) # find a bunch of parallel cross sections sections = mesh.section_multiplane(plane_origin=mesh.bounds[0], plane_normal=[0, 0, 1], heights=z_levels) N = len(sections) printc("nr. of sections:", N, c='green') # summing the array of Path2D objects will put all of the curves # into one Path2D object, which we can plot easily combined = np.sum(sections) sections.append([combined, 'combined']) # show objects in N synced renderers: show(sections, N=N, axes=True, newPlotter=True)
link[k] = vp.add(Spring(p0, p1, thickness=0.015, r=R / 3, c="gray")) # Create some auxiliary variables x_dot_m = [0] * (N + 1) y_dot_m = [0] * (N + 1) dij = [0] * (N + 1) # array with distances to previous bob dij_m = [0] * (N + 1) for k in range(1, N + 1): dij[k] = mag([bob_x[k] - bob_x[k - 1], bob_y[k] - bob_y[k - 1]]) fctr = lambda x: (x - 1) / x Dt *= np.sqrt(1 / g) Dt2 = Dt / 2 # Midpoint time step DiaSq = (2 * R)**2 # Diameter of bob squared printc("Press Esc to exit.", c="red") while True: bob_x_m = list(map((lambda x, dx: x + Dt2 * dx), bob_x, x_dot)) # midpoint variables bob_y_m = list(map((lambda y, dy: y + Dt2 * dy), bob_y, y_dot)) for k in range(1, N + 1): factor = fctr(dij[k]) x_dot_m[k] = x_dot[k] - Dt2 * (Ks * (bob_x[k] - bob_x[k - 1]) * factor + gamma * x_dot[k]) y_dot_m[k] = y_dot[k] - Dt2 * (Ks * (bob_y[k] - bob_y[k - 1]) * factor + gamma * y_dot[k] + g)
Mouse click event example click of the mouse causes a call to a custom function. """ from vtkplotter import Plotter, printc, Text, datadir def onLeftClick(actor): printc("Left button pressed on", [actor], c="g") def onMiddleClick(actor): printc("Middle button pressed on", [actor], c="y") def onRightClick(actor): printc("Right button pressed on", [actor], c="r") vp = Plotter(verbose=0) vp.load(datadir + "skyscraper.obj") vp.mouseLeftClickFunction = onLeftClick vp.mouseMiddleClickFunction = onMiddleClick vp.mouseRightClickFunction = onRightClick printc("Click object to trigger function call", invert=1, box="-") vp.add(Text(__doc__)) vp.show()
# Check to see if they are colliding for i in range(1, N): for j in range(i + 1, N + 1): dist2 = (bob_x[i] - bob_x[j])**2 + (bob_y[i] - bob_y[j])**2 if dist2 < DiaSq: # are colliding Ddist = np.sqrt(dist2) - 2 * R tau = norm(vector(bob_x[j] - bob_x[i], bob_y[j] - bob_y[i])) DR = Ddist / 2 * tau bob_x[i] += DR[0] # DR.x bob_y[i] += DR[1] # DR.y bob_x[j] -= DR[0] # DR.x bob_y[j] -= DR[1] # DR.y Vji = vector(x_dot[j] - x_dot[i], y_dot[j] - y_dot[i]) DV = np.dot(Vji, tau) * tau x_dot[i] += DV[0] # DV.x y_dot[i] += DV[1] # DV.y x_dot[j] -= DV[0] # DV.x y_dot[j] -= DV[1] # DV.y # Update the loations of the bobs and the stretching of the springs for k in range(1, N + 1): bob[k].pos([bob_x[k], bob_y[k], 0]) link[k - 1].stretch(bob[k - 1].pos(), bob[k].pos()) vp.render(resetcam=True) # show() would cause exiting the loop vp.camera.Azimuth(0.1) # move camera a bit printc('Press q to exit.', c='red') vp.show(execute=loop)
"""Read and show meshio objects""" import meshio from vtkplotter import datadir, show, Actor, Text, printc mesh = meshio.read(datadir + 'shuttle.obj') # vtkplotter understands meshio format: printc(mesh, c='y') show(mesh, Text(__doc__)) # or explicitly convert it to an Actor object: a = Actor(mesh).lineWidth(1).color('tomato') show(a)
# Available colors: # 0-black, 1-red, 2-green, 3-yellow, 4-blue, 5-magenta, 6-cyan, 7-white # Available modifiers: # c (foreground color), bc (background color) # hidden, bold, blink, underLine, dim, invert, box from vtkplotter import printc, printHistogram import numpy as np printc(" 1- Change the world~world by being yourself - Amy Poehler", c=1) printc(" 2- Never regret anything that made you smile ~smile - Mark Twain", c="r", bold=0) printc(" 3- Every moment is a fresh beginning - T.S Eliot~copyright", c="m", underline=1) printc(" 4- Die with memories, not dreams - Unknown~registered", blink=1, bold=0) printc(" 5- Aspire to inspire before we expire - Unknown", c=2, hidden=1) printc(" 6- Everything you can imagine is real - Pablo Picasso~rocket", c=3) printc( " 7- Simplicity is the ultimate sophistication - Leonardo da Vinci~idea", c=4) printc(" 8- Whatever you do, do it well - ~rainbowWalt Disney", c=3, bc=1) printc(" 9- What we think, we become - Buddha ~target", c=6, invert=1) printc("10- All limitations are self-imposed ~sparks Oliver Wendell Holmes", c=7, dim=1) printc("11- When words fail, music speaks - Shakespeare ~pin") printc(
@author: HernanV """ #Recreate a model of geotermal reservoir, Utah from vtkplotter import Plotter, Mesh, Points, Line, Lines ,printc, exportWindow, embedWindow from scipy.spatial import Delaunay import pandas as pd embedWindow(False) # or itkwidgets, False (for a popup) ######################### # Load surfaces, import the file from pandas ######################### printc("...loading data...", invert=1) path(data="C:\Users\HernanV\Documents\Spyder (python) files\Modelamiento en 3D con Python\Example3DGeologicModelUsingVTKPlotter-master') path(open(data, mode, encoding=str)) landSurfacePD = path_csv('landsurface_vertices.csv') vertices_175CPD = pd.read_csv('175C_vertices.csv') vertices_225CPD = pd.read_csv('225C_vertices.csv') Negro_Mag_Fault_verticesPD = pd.read_csv('Negro_Mag_Fault_vertices.csv') Opal_Mound_Fault_verticesPD = pd.read_csv('Opal_Mound_Fault_vertices.csv') top_granitoid_verticesPD = pd.read_csv('top_granitoid_vertices.csv') microseismic = pd.read_csv('Microseismic.csv') # The well path and different logs for the well paths well_5832_path = pd.read_csv('path5832.csv') temp_well = pd.read_csv('temperature5832.csv') nphi_well = pd.read_csv('nphi5832.csv')
# Extract the mesh region that has the largest connected surface # from vtkplotter.analysis import extractLargestRegion from vtkplotter.utils import area from vtkplotter import Plotter, printc vp = Plotter(shape=(2,1)) act1 = vp.load('data/embryo.slc', c='y') printc('area1 =', area(act1), c='y') act2 = extractLargestRegion(act1).color('b') printc('area2 =', area(act2), c='b') vp.show(act1, at=0) vp.show(act2, at=1, zoom=1.2, interactive=1)
# Extract the mesh region that has the largest connected surface # from vtkplotter import Plotter, printc, extractLargestRegion vp = Plotter(shape=(2,1)) act1 = vp.load('data/embryo.slc', c='y') printc('area1 =', act1.area(), c='y') act2 = extractLargestRegion(act1).color('b') printc('area2 =', act2.area(), c='b') vp.show(act1, at=0) vp.show(act2, at=1, zoom=1.2, interactive=1)
# Every time a key is pressed the picked point of the mesh is used # to add a sphere and some info is printed. # from vtkplotter import Plotter, printc, sphere ############################################################################## def myfnc(key): if not vp.clickedActor or key != 'c': printc('click an actor and press c.', c='r') return cb = sphere(pos=vp.picked3d, r=.05, c='v') vp.render(cb) printc('clicked actor :', vp.clickedActor.legend, c=4) printc('clicked 3D point:', vp.picked3d, c=4) printc('clicked renderer:', vp.clickedRenderer, c=2) ############################################################################## vp = Plotter(verbose=0) vp.keyPressFunction = myfnc # make it known to Plotter class vp.load('data/shapes/bunny.obj').normalize() printc('\nPress c to execute myfnc()', c=1) vp.show()
def onRightClick(actor): printc("Right button pressed on", [actor], c="r")