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)
import numpy as np from vedo import settings, Line, show, interactive settings.defaultFont = "Theemim" # Generate random data np.random.seed(1) data = np.random.uniform(0, 1, (25, 100)) X = np.linspace(-1, 1, data.shape[-1]) G = 0.15 * np.exp(-4 * X**2) # use a gaussian as a weight # Generate line plots lines = [] for i in range(len(data)): pts = np.c_[X, np.zeros_like(X)+i/10, G*data[i]] lines.append(Line(pts, lw=3)) # Set up the first frame axes = dict(xtitle='\Deltat /\mus', ytitle="source", ztitle="") plt = show(lines, __doc__, axes=axes, elevation=-30, interactive=False, bg='k8') # vd = Video("anim_lines.mp4") for i in range(50): data[:, 1:] = data[:, :-1] # Shift data to the right data[:, 0] = np.random.uniform(0, 1, len(data)) # Fill-in new values for i in range(len(data)): # Update data newpts = lines[i].points() newpts[:,2] = G * data[i] lines[i].points(newpts).cmap('gist_heat_r', newpts[:,2]) plt.show() # vd.addFrame()
"""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 f(psi): # a smart numpy way to calculate the second derivative in x: nabla2psi[1 : N+1] = (psi[0:N] + psi[2 : N+2] - 2 * psi[1 : N+1]) / dx2 return 1j * (nabla2psi - V*psi) # this is the RH of Schroedinger equation! def d_dt(psi): # find Psi(t+dt)-Psi(t) /dt with 4th order Runge-Kutta method k1 = f(psi) k2 = f(psi + dt / 2 * k1) k3 = f(psi + dt / 2 * k2) k4 = f(psi + dt * k3) return (k1 + 2 * k2 + 2 * k3 + k4) / 6 plt = Plotter(interactive=False) bck = plt.load(dataurl+"images/schrod.png").alpha(.3).scale(.0256).pos([0,-5,-.1]) barrier = Line(np.stack((x, V*15, np.zeros_like(x)), axis=1), c="black", lw=2) box = bck.box().c('black') lines = [] for i in range(0, Nsteps): for j in range(500): Psi += d_dt(Psi) * dt # integrate for a while before showing things A = np.real(Psi * np.conj(Psi)) * 1.5 # psi squared, probability(x) coords = np.stack((x, A), axis=1) Aline = Line(coords, c="db", lw=3) plt.show(barrier, bck, Aline, box).remove(Aline) lines.append([Aline, A]) # store objects # now show the same lines along z representing time plt.actors= [] # clean up internal list of objects to show plt.camera.Elevation(20)
printc("In the example shown:\n", repr(txt), c='y') print() printc('Font Summary', c='g', box='-') for i, f in enumerate(fonts): printc('Font: ', f, c='g') ################################################################################## 3D cam = dict(pos=(67.7, -3.94, 145), focalPoint=(29.3, -37.3, 1.55), viewup=(-0.0642, 0.976, -0.210), distance=152, clippingRange=(122, 194)) ln0 = Line([-1, 1.5], [52, 1.5], lw=0.1, c='grey') ln1 = Line([-1, -2], [52, -2], lw=0.1, c='grey') fn3d = [ln0, ln1] gap = 0 txt = "Font Name\n" for i, font in enumerate(fonts + ['VTK']): txt += font + ": abcdefghijklmnopqrtuvwxyz 1234567890" if font in [ "Theemim", "Kanopus", "Normografo", "VictorMono", "Galax", "LogoType", "Comae" ]: txt += "\n αβγδεζηθκλμνξπρστφχψω ΔΘΛΞΠΣΦΨΩ" gap -= 2 if "Biysk" in font: txt += " v3do" if "VictorMono" == font or "Kanopus" == font or "LogoType" == font or "Comae" == font: txt += " БГДЖЗИЙКЛ"
"""Koch snowflake fractal""" from vedo import sqrt, Line, show levels = 7 def koch(level): # Compute Koch fractal contour points k = sqrt(3)/2 if level: points = koch(level-1) + [(0, 0)] # recursion! kpts = [] for i in range(len(points)-1): p1, p2 = points[i], points[i+1] dx, dy = (p2[0]-p1[0])/3, (p2[1]-p1[1])/3 pa = (p1[0] + dx , p1[1] + dy ) pb = (p1[0] + dx*2, p1[1] + dy*2) z = complex(pb[0]-pa[0], pb[1]-pa[1]) * (0.5-k*1j) p3 = (pa[0]+z.real, pa[1]+z.imag) kpts += [p1, pa, p3, pb] return kpts else: return [(0, 0), (1, 0), (0.5, k)] kochs = [] for i in range(levels): # Create a Line from the points and mesh the inside with minimum resolution kmsh = Line(koch(i)).tomesh(resMesh=1).lw(0).color(-i).z(-i/1000) kochs.append(kmsh) show(kochs, __doc__+ f"\nlevels: {levels}\npoints: {kmsh.N()}", axes=10)
v = TestFunction(V) a = dot(grad(w), grad(v)) * dx L = p * v * dx # Compute solution w = Function(V) solve(a == L, w, bc) p = interpolate(p, V) # Curve plot along x = 0 comparing p and w import numpy as np tol = 0.001 # avoid hitting points outside the domain y = np.linspace(-1 + tol, 1 - tol, 101) points = [(0, y_) for y_ in y] # 2D points w_line = np.array([w(point) for point in points]) p_line = np.array([p(point) for point in points]) ####################################################################### from vedo.dolfin import plot from vedo import Line, Latex pde = r'-T \nabla^{2} D=p, ~\Omega=\left\{(x, y) | x^{2}+y^{2} \leq R\right\}' tex = Latex(pde, pos=(0, 1.1, .1), s=0.2, c='w') wline = Line(y, w_line * 10, c='white', lw=4) pline = Line(y, p_line / 4, c='lightgreen', lw=4) plot(w, wline, tex, at=0, N=2, bg='bb', text='Deflection') plot(p, pline, at=1, bg='bb', text='Load')
# time goes from 0 to 90 hours pb = ProgressBar(0, 50, step=0.1, c=1) for t in pb.range(): msg = "[Nb,Ng,Nr,t] = " plt.actors = [] # clean up the list of actors 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:
) # this is the RH of Schroedinger equation! def d_dt(psi): # find Psi(t+dt)-Psi(t) /dt with 4th order Runge-Kutta method k1 = f(psi) k2 = f(psi + dt / 2 * k1) k3 = f(psi + dt / 2 * k2) k4 = f(psi + dt * k3) return (k1 + 2 * k2 + 2 * k3 + k4) / 6 vp = Plotter(interactive=0, axes=2, size=(1000, 500)) vp.xtitle = "" vp.ytitle = "|\Psi(x,t)|\^2" bck = vp.load(datadir + "images/schrod.png").scale(0.015).pos([0, 0, -0.5]) barrier = Line(np.stack((x, V * 15), axis=1), c="dr", lw=3) lines = [] for j in range(150): for i in range(500): Psi += d_dt(Psi) * dt # integrate for a while A = np.real(Psi * np.conj(Psi)) * 1.5 # psi squared, probability(x) coords = np.stack((x, A, np.zeros_like(x)), axis=1) Aline = Tube(coords, c="db", r=0.08) vp.show(Aline, barrier, bck, zoom=2) lines.append(Aline) interactive()
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()
import numpy as np # create 5 whisker bars with some random data ws = [] for i in range(5): xval = i * 2 # position along x axis data = xval / 4 + np.random.randn(25) w = whisker(data, bc=i, s=0.5).x(xval) ws.append(w) # print(i, 'whisker:\n', w.info) # build some theoretical expectation to be shown as a grey band x = np.linspace(-1, 9, 100) y = x / 5 + 0.2 * np.sin(x) ye = y**2 / 5 + 0.1 # error on y line = Line(np.c_[x, y]) band = Ribbon(np.c_[x, y - ye], np.c_[x, y + ye]).c('black', 0.1) # build braces to inndicate stats significance and dosage bra1 = Brace([0, 3], [2, 3], comment='*~*', s=0.7, style='[') bra2 = Brace([4, -1], [8, -1], comment='dose > 3~\mug/kg', s=0.7) # build custom axes axes = Axes( xrange=[-1, 9], yrange=[-3, 5], htitle='\beta_c -expression: change in time', xtitle=' ', ytitle='Level of \beta_c protein in \muM/l', xValuesAndLabels=[ (0, 'Experiment^A\nat t=1h'),
"""Forward kinematics: hover the mouse to drag the chain""" from vedo import Plotter, versor, Plane, Line n = 15 # number of points l = 3 # length of one segment def move(evt): if not evt.actor: return coords = line.points() coords[0] = evt.picked3d for i in range(1, n): v = versor(coords[i] - coords[i - 1]) coords[i] = coords[i - 1] + v * l line.points(coords) # update positions nodes.points(coords) plt.render() plt = Plotter() plt.addCallback("mouse move", move) surf = Plane(sx=60, sy=60) line = Line([l * n / 2, 0], [-l * n / 2, 0], res=n, lw=12) nodes = line.clone().c('red3').pointSize(15) plt.show(surf, line, nodes, __doc__, zoom=1.3).close()
"""Share the same color and trasparency mapping across different volumes""" from vedo import Volume, Line, show import numpy as np arr = np.zeros(shape=(50, 50, 50)) for i in range(50): for j in range(50): for k in range(50): arr[i, j, k] = j vol1 = Volume(arr).mode(1).cmap('jet', alpha=[0, 1], vmin=0, vmax=80).addScalarBar("vol1") vol2 = Volume(arr + 30).mode(1).cmap('jet', alpha=[0, 1], vmin=0, vmax=80).addScalarBar("vol2") # or equivalently, to set transparency: # vol1.alpha([0,1], vmin=0, vmax=70) # can also manually build a scalarbar object to span the whole range: sb = Line([50, 0, 0], [50, 50, 0]).cmap('jet', [0, 70]).addScalarBar3D("vol2", c='black').scalarbar show([(vol1, __doc__), (vol2, sb)], N=2, axes=1)