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 onkeypress( self, evt): ###################################### MORPH & GENERATE if evt.keyPressed == 'm': ##--------- morph mesh1 based on the existing arrows if len(self.arrow_starts) != len(self.arrow_stops): printc("You must select your end point first!", c='y') return output = [self.mesh1.clone().c('grey4'), self.mesh2, self.msg2] warped_plane = self.plane1.clone().pickable(False) warped_plane.warp(self.arrow_starts, self.arrow_stops, mode=self.mode) output.append(warped_plane + Axes(warped_plane, xyGrid=0, textScale=0.6)) mw = self.mesh1.clone().applyTransform( warped_plane.transform).c('red4') output.append(mw) T_inv = warped_plane.transform.GetInverse() a = Points(self.arrow_starts, r=10).applyTransform(warped_plane.transform) b = Points(self.arrow_stops, r=10).applyTransform(warped_plane.transform) self.dottedln = Lines( a, b, res=self.n).applyTransform(T_inv).pointSize(5) output.append(self.dottedln) self.msg1.text(self.instructions) self.msg2.text("Morphed output:") self.plotter.clear(at=1).addRendererFrame().add(output, at=1) elif evt.keyPressed == 'g': ##------- generate intermediate shapes if not self.dottedln: return intermediates = [] allpts = self.dottedln.points() allpts = allpts.reshape(len(self.arrow_starts), self.n + 1, 3) for i in range(self.n + 1): pi = allpts[:, i, :] m_nterp = self.mesh1.clone().warp(self.arrow_starts, pi, mode=self.mode).c('b3').lw(1) intermediates.append(m_nterp) self.msg2.text("Morphed output + Interpolation:") self.plotter.add(intermediates, at=1) self.dottedln = None elif evt.keyPressed == 'c': ##------- clear all self.arrow_starts = [] self.arrow_stops = [] self.toggle = False self.dottedln = None self.msg1.text(self.instructions) self.msg2.text("[output will show here]") self.plotter.clear(at=0).clear(at=1).addRendererFrame() self.plotter.add([self.plane1, self.msg1, self.mesh1, self.mesh2], at=0) self.plotter.add([self.plane2, self.msg2], at=1)
def PauseButtonFunc(self): vedo.printc(self.PauseButton.status(), box="_", dim=True) if self.PauseButton.status() == "PAUSE": self.Plot.interactive = True else: self.Plot.interactive = False self.PauseButton.switch() # change to next status
def _func(self, pars): shift = np.array(np.split(pars, 2)).T # recreate the shift vectors z = np.zeros((self.npts, 1)) shift = np.append(shift, z, axis=1) # make them 3d self.morphed_source = self.source.clone().warp(self.ptsource, self.ptsource + shift, sigma=self.sigma, mode="2d") d = self.morphed_source.points() - self.target.points() chi2 = np.sum(np.multiply(d, d)) #/len(d) if chi2 < self.chi2: printc("new minimum ->", chi2) self.chi2 = chi2 return chi2
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 space to proceed by one note', c=1) printc('Press Esc to exit.', c=1) 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
def onKeypress(self, evt): printc("You have pressed key:", evt.keyPressed, c='b') if evt.keyPressed == 'q': self.vp.close() self.vtkWidget.close() exit()
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]) if hasattr(self.vp, 'interactor'): self.vp.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(interactive=False, resetcam=False) 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) 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, c='b') else: printc(msg, '\tLH.finger', f, 'hit', name, c='m') if self.playsounds: self.vp.show(interactive=False, resetcam=False) playSound(n, self.speedfactor, wait=True) if hasattr(self.vp, 'interactor'): self.vp.interactor.Start() else: self.vp.show(interactive=1, resetcam=0)
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)
"""Manually build a mesh from points and faces""" from vedo 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: mesh = Mesh([verts, faces]) mesh.backColor('violet').lineColor('tomato').lineWidth(2) labs = mesh.labels('id').c('black') # retrieve them as numpy arrays printc('points():\n', mesh.points(), c=3) printc('faces(): \n', mesh.faces(), c=3) show(mesh, labs, __doc__, viewup='z', axes=1).close()
Press q: Control returns to terminal, window will not close but become unresponsive""" from vedo import Paraboloid, Hyperboloid, Plotter, show, printc mesh = Paraboloid() vp1 = show(mesh, __doc__, title='First Plotter instance') # Now press 'q' to exit the window interaction, # windows stays open but not reactive anymore. # You can go back to interavtion mode by simply calling: #show() printc('\nControl returned to terminal shell:', c='tomato', invert=1) printc('window is now unresponsive (press Enter here)', c='tomato', invert=1) input() vp1.closeWindow() # window should now close, the Plotter instance becomes unusable # but mesh objects still exist in it: printc("First Plotter actors:", vp1.actors, '\n press enter again') vp1.show() # THIS HAS NO EFFECT: window does not exist anymore. Cannot reopen. ################################################################## # Can now create a brand new Plotter and show the old object in it vp2 = Plotter(title='Second Plotter instance', pos=(500, 0)) vp2.show(vp1.actors[0].color('red'))
''' compute_collision() will compute the collision of all the entities with a Point while compute_first_collision() will always return its first entry. Especially if a point is on an element edge this can be tricky. You may also want to compare with the Cell.contains(Point) tool. ''' # Script by Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vedo.dolfin import plot from vedo import printc, pointcloud n = 4 Px = 0.5 Py = 0.5 mesh = dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc("collisions : ", collisions) printc("collisions 1st: ", collisions1st) for cell in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py)) printc("Cell", cell.index(), "contains P:", contains, c=contains) ########################################### pt = pointcloud.Point([Px, Py], c='blue') plot(mesh, pt, text=__doc__)
def onEvent(event): printc(event.name, 'happened at mouse position', event.picked2d)
"""Use iminuit to find the minimum of a 3D scalar field""" from vedo import show, Point, Line, printc from iminuit import Minuit # pip install iminuit # https://github.com/scikit-hep/iminuit import numpy as np def fcn(x, y, z): f = (x - 4)**4 + (y - 3)**4 + (z - 2)**2 if not vals or f < vals[-1]: path.append([x, y, z]) vals.append(f) return f paths = [] for x, y, z in np.random.rand(200, 3) * 3: path, vals = [], [] m = Minuit(fcn, x=x, y=y, z=z) m.errordef = m.LEAST_SQUARES # m.simplex() # run simplex optimiser m.migrad() # run migrad optimiser line = Line(path).cmap('jet_r', vals).lw(2).alpha(0.25) paths.append(line) printc('Last optimization output:', c='green7', invert=1) printc(m, c='green7', italic=1) show(paths, Point([4, 3, 2]), __doc__, axes=1)
def buttonfunc(): mesh.alpha(1 - mesh.alpha()) # toggle mesh transparency bu.switch() # change to next status printc(bu.status(), box="_", dim=True)
def onMouseClick(self, evt): printc("You have clicked your mouse button. Event info:\n", evt, c='y')
def onKeypress(self, evt): printc("You have pressed key:", evt.keyPressed, c='b')
"""Non blocking interactive rendering window, python flow is not blocked but displayed objects cannot be accessed""" import time, os from multiprocessing import Process from vedo import Sphere, show, printc printc("..starting main", c='g') sphere = Sphere().alpha(0.1).lw(0.1) # ------ instead of (typical): #show(sphere, __doc__, axes=1) # ------ spawn an independent subprocess: def spawn(): show(sphere, __doc__, axes=1) Process(target=spawn).start() printc("..python flow is not blocked, wait 1 sec..", c='y') time.sleep(1) printc("..continuing in main", c='r') os._exit(0) # this exits immediately with no cleanup or buffer flushing
def onClick(self): printc("..calling onClick") self.vp.actors[0].color('red').rotateZ(40) self.vp.interactor.Render()
txt = Text2D('..' + data.filename[-30:], font='MonospaceTypewriter') plt.show(vol, msh, sb, box, txt, at=index, interactorStyle=6) def func(widget, event): i = int(widget.GetRepresentation().GetValue()) plt.renderer = widget.GetCurrentRenderer() plt.resetcam = False msh = vol.zSlice(i).lighting('off') msh.pointColors(cmap=cmaps[index], vmin=vmin, vmax=vmax) plt.remove(visibles[0], render=False) if 0 < i < dims[2]: zlev = zb[1] / (zb[1] - zb[0]) * i + zb[0] plt.add([msh, sb.z(zlev)]) visibles[0] = msh return func ###################################################################### plt = Plotter(shape=(1, 3), sharecam=False, bg2='lightcyan') for index, data in enumerate(volumes): plt.addSlider2D(slicerfunc(index, data), 0, data.dimensions()[2], value=0, pos=(sliderstart, sliderstop)) printc("Right click to rotate, use slider to slice along z.", box='-') plt.show(interactive=True)
def StopButtonFunc(self): vedo.printc(self.StopButton.status(), box="_", dim=True) if self.StopButton.status() == "STOP": self.Finalize() self.Continue = False
from vedo import dataurl, Volume, printc, show import numpy as np vol = Volume(dataurl + 'vase.vti') nx, ny, nz = vol.dimensions() r0, r1 = vol.scalarRange() vol.addScalarBar3D(title='original voxel scalars') # create a set of scalars and add it to the Volume vol.pointdata["myscalars1"] = np.linspace(r0, r1, num=nx * ny * nz) # create another set of scalars and add it to the Volume vol.pointdata["myscalars2"] = np.random.randint(-100, +100, nx * ny * nz) # make SLCImage scalars the active array (can set 0, to pick the first): printc('Arrays in Volume are:\n', vol.pointdata.keys(), invert=True) vol.pointdata.select( "SLCImage") # select the first data array as the active one # Build the isosurface of the active scalars, # but use testscals1 to colorize this isosurface, and then smooth it iso1 = vol.isosurface().cmap('jet', 'myscalars1').smooth().lw(0.1) iso1.addScalarBar3D(title='myscalars1') iso2 = vol.isosurface().cmap('viridis', 'myscalars2') iso2.addScalarBar3D(title='myscalars2') show([ (vol, __doc__), (iso1, "Colorize isosurface using\nmyscalars1"), (iso2, "Colorize isosurface using\nmyscalars2"),
def onClose(self): #Disable the interactor before closing to prevent it #from trying to act on already deleted items printc("..calling onClose") self.vtkWidget.close()
"""Mouse click and other type of events will trigger a call to a custom function""" from vedo import printc, Plotter, Mesh, datadir printc("Click object to trigger a function call", invert=1) # callback functions def onLeftClick(event): if not event.actor: return printc("Left button pressed on", [event.actor], c=event.actor.color()) # printc('full dump of event:', event) def onEvent(event): printc(event.name, 'happened at mouse position', event.picked2d) ###################### tea = Mesh(datadir + "teapot.vtk").c("gold") mug = Mesh(datadir + "mug.ply").rotateX(90).scale(8).pos(2, 0, -.7).c("silver") plt = Plotter(axes=11) plt.addCallback('LeftButtonPress', onLeftClick) plt.addCallback('Interaction', onEvent) # mouse dragging triggers this plt.show(tea, mug, __doc__)
"""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()
def onLeftClick(event): if not event.actor: return printc("Left button pressed on", [event.actor], c=event.actor.color())
titleFont=fnt, labelFont=fnt, digits=2, yTitleOffset=-.015, xLabelSize=0.015, yLabelSize=0.015, zLabelSize=0.015, ), at=i, camera=cam, resetcam=not bool(i), ) ################################################################################ printout for font in fonts: printc(font + " - available characters are:", " " * 25, bold=1, invert=1) try: fontfile = settings.fonts_path + font + '.npz' font_meshes = np.load(fontfile, allow_pickle=True)['font'][0] except: pass for k in font_meshes.keys(): printc(k, end=' ') print() printc('\n(use the above to copy&paste any char into your python script!)', italic=1) printc('Symbols ~ ^ _ are reserved modifiers:', italic=1) printc(' use ~ to add a short space, 1/4 of the default size,', italic=1) printc(' use ^ and _ to start up/sub scripting, space terminates them.\n', italic=1)
plt += link[k] # Create some auxiliary variables x_dot_m = np.zeros(N + 1) y_dot_m = np.zeros(N + 1) dij = np.zeros(N + 1) # array with distances to previous bob dij_m = np.zeros(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", 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)
# Available modifiers: # c (foreground color), bc (background color) # bold, blink, underLine, dim, invert, box from vedo import printc, printHistogram import numpy as np printc(" 1- Change the world by being yourself - Amy Poehler\world", c=1) printc(" 2- Never regret anything that made you smile - Mark Twain\smile", c="r", bold=0) printc(" 3- Every moment is a fresh beginning - T.S Eliot", c="m", underline=1) printc(" 4- Die with memories, not dreams - Unknown\ethumbup", blink=1, bold=0) printc(" 5- When words fail, music speaks - Shakespeare \pin") printc(" 6- Everything you can imagine is real - Pablo Picasso\erocket", c=3) printc( " 7- Simplicity is the ultimate sophistication - Leonardo da Vinci\idea", c=4) printc(" 8- Whatever you do, do it well - Walt Disney\erainbow", c=3, bc=1) printc(" 9- What we think, we become - Buddha \etarget", c=6, invert=1) printc("10- All limitations are self-imposed - Oliver Wendell Holmes\sparks", c=7, dim=1) printc( "11- If you tell the truth you dont have to remember anything - Mark Twain\checked", underline=1, invert=1, c=6, dim=1, )