コード例 #1
0
    def learn(self, n_epoch=10000, sigma=(0.25, 0.01), lrate=(0.5, 0.01)):

        t = np.linspace(0, 1, n_epoch)
        lrate = lrate[0] * (lrate[1] / lrate[0])**t
        sigma = sigma[0] * (sigma[1] / sigma[0])**t
        I = np.random.randint(0, len(self.samples), n_epoch)
        self.samples = self.samples[I]
        pts = Points(self.samples, r=2)
        doc = Text(__doc__)

        pb = ProgressBar(0, n_epoch)
        for i in pb.range():
            pb.print("epochs")
            # Get random sample
            data = self.samples[i]

            # Get index of nearest node (minimum distance)
            winner = np.argmin(((self.codebook - data)**2).sum(axis=-1))

            # Gaussian centered on winner
            G = np.exp(-self.distance[winner]**2 / sigma[i]**2)

            # Move nodes towards sample according to Gaussian
            self.codebook -= lrate[i] * G[...,
                                          np.newaxis] * (self.codebook - data)

            # Draw network
            if i > 500 and not i % 20 or i == n_epoch - 1:
                x, y, z = [self.codebook[:, i].reshape(n, n) for i in range(3)]
                grd = Grid(resx=n - 1,
                           resy=n - 1).wire(False).lw(0.5).bc('lightblue')
                for i in range(n):
                    for j in range(n):
                        grd.setPoint(i * n + j, (x[i, j], y[i, j], z[i, j]))
                show(doc,
                     pts,
                     grd,
                     axes=6,
                     bg='w',
                     azimuth=2,
                     interactive=False)

        return [self.codebook[:, i].reshape(n, n) for i in range(3)]
コード例 #2
0
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)
コード例 #3
0
ファイル: gas.py プロジェクト: dongbo-BUAA-VR/vtkplotter
    mlist.append(mass)
    rlist.append(Ratom)

pos = np.array(poslist)
poscircle = pos
p = np.array(plist)
m = np.array(mlist)
m.shape = (Natoms, 1) 
radius = np.array(rlist)
r = pos-pos[:, np.newaxis] # all pairs of atom-to-atom vectors

ds = (p/m)*(dt/2.)
if 'False' not in np.less_equal(mag(ds), radius).tolist():
    pos = pos+(p/mass)*(dt/2.) # initial half-step

pb = ProgressBar(0,Nsteps, c=1)
for i in pb.range():

    # Update all positions
    ds = mag((p/m)*(dt/2.))
    if 'False' not in np.less_equal(ds, radius).tolist(): 
        pos = pos+(p/m)*dt

    r = pos-pos[:,np.newaxis]                # all pairs of atom-to-atom vectors
    rmag = np.sqrt(np.sum(np.square(r), -1)) # atom-to-atom scalar distances
    hit = np.less_equal(rmag, radius+radius[:, None]) - np.identity(Natoms)
    hitlist = np.sort(np.nonzero(hit.flat)[0]).tolist() # i,j encoded as i*Natoms+j

    # If any collisions took place:
    for ij in hitlist:
        i, j = divmod(ij,Natoms)             # decode atom pair
コード例 #4
0
ファイル: spring.py プロジェクト: yordankyosev/vtkplotter
b = 0.5  # viscosity friction (proportional to velocity)
dt = 0.1  # time step

#initial conditions
v = vector(0, 0, 0.2)
x = vector(x0, 0, 0)
xr = vector(l_rest, 0, 0)
sx0 = vector(-0.8, 0, 0)
offx = 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

    block.pos(x)  # update block position
    spring.stretch(sx0, x)  # stretch helix accordingly
    trace = vp.point(x + offx, c='r/0.5', r=3)  # leave a red trace

    vp.camera.Azimuth(.1)
    vp.camera.Elevation(.1)
    vp.render(trace)  # add trace to the list of actors and render
    pb.print('Fx=' + str(F[0]))
コード例 #5
0
    ynew = y + (yk1 + 2 * yk2 + 2 * yk3 + yk4) / 6
    vnew = v + (vk1 + 2 * vk2 + 2 * vk3 + vk4) / 6
    return ynew, vnew


def euler(y, v, t, dt):  # simple euler integrator
    vnew = v + accel(y, v, t) * dt
    ynew = y + vnew * dt + 1 / 2 * accel(y, vnew, t) * dt**2
    return ynew, vnew


positions_eu, positions_rk = [], []
y_eu, y_rk = np.array(y), np.array(y)
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 = Plotter(interactive=0, axes=2)  # choose axes type nr.2
vp.ytitle = "u(x,t)"
vp.ztitle = ""  # will not draw z axis
コード例 #6
0
# ############################################################ the scene
vp = Plotter(verbose=0, axes=3, interactive=0)

shaft = vp.cylinder([[0,0,0],         [Lshaft,0,0]], r=.03, c='dg')
rotor = vp.cylinder([[Lshaft/2.2,0,0],[Lshaft/1.8,0,0]], r=R, texture='marble')
base  = vp.sphere([     0, 0, 0], c='dg', r=.03)
tip   = vp.sphere([Lshaft, 0, 0], c='dg', r=.03)
gyro  = vp.makeAssembly([shaft, rotor, base, tip]) # group relevant actors

pedestal = vp.box([0,-0.63,0], height=.1, length=.1, width=1, texture='wood5')
pedbase  = vp.box([0,-1.13,0], height=.5, length=.5, width=.05, texture='wood5')
pedpin   = vp.pyramid([0,-.08,0], axis=[0,1,0], s=.05, height=.12, texture='wood5')
formulas = vp.load('data/images/gyro_formulas.png', alpha=.9).scale(.003).pos([-1,-1,-1.1])

# ############################################################ the physics
pb = ProgressBar(0, 4, dt, c='b')
for i, t in enumerate(pb.range()):
    st, ct, sp, cp = sin(x[0]), cos(x[0]), sin(x[1]), cos(x[1])

    thetadot, phidot, psidot = v # unpack
    atheta = st*ct*phidot**2 + (M*g*r*st-I3*(psidot+phidot*ct)*phidot*st)/I1
    aphi = (I3/I1)*(psidot+phidot*ct)*thetadot/st - 2*ct*thetadot*phidot/st
    apsi = phidot*thetadot*st - aphi*ct
    a = vector(atheta, aphi, apsi)

    v += a*dt  # update velocities   
    x += v*dt  # update Lagrangian coordinates

    gaxis = (Lshaft+0.03)*vector(st*sp, ct, st*cp)
    # set orientation along gaxis and rotate it around its axis by psidot*t degrees
    gyro.orientation(gaxis, rotation=psidot*t*57.3) 
コード例 #7
0
npts = 60  # nr. of points of known scalar value

img = vtk.vtkImageData()
img.SetDimensions(bins, bins, bins)  # range is [0, bins-1]
img.AllocateScalars(vtk.VTK_FLOAT, 1)

coords = np.random.rand(npts, 3)  # range is [0, 1]
scals = np.abs(coords[:, 2])  # let the scalar be the z of point itself
fact = 1. / (bins - 1)  # conversion factor btw the 2 ranges

vp = Plotter(verbose=0)
vp.ztitle = 'z == scalar value'
cloud = vp.points(coords)

# fill the vtkImageData object
pb = ProgressBar(0, bins, c=4)
for iz in pb.range():
    pb.print()
    for iy in range(bins):
        for ix in range(bins):

            pt = vector(ix, iy, iz) * fact
            closestPointsIDs = cloud.closestPoint(pt, N=5, returnIds=True)

            num, den = 0, 0
            for i in closestPointsIDs:  # work out RBF manually on N points
                invdist = 1 / (mag2(coords[i] - pt) + 1e-06)
                num += scals[i] * invdist
                den += invdist
            img.SetScalarComponentFromFloat(ix, iy, iz, 0, num / den)
コード例 #8
0
ファイル: gyroscope1.py プロジェクト: charliekind/vtkplotter
cm = gpos + 0.5*Ls*gaxis  # center of mass of shaft

# ############################################################ the scene
vp = Plotter(verbose=0, axes=0, interactive=0)

shaft = vp.cylinder([[0,0,0], Ls*gaxis], r=0.03, c='dg')
rotor = vp.cylinder([(Ls-0.55)*gaxis, (Ls-0.45)*gaxis], r=R, c='t')
bar   = vp.cylinder([Ls*gaxis/2-R*vector(0,1,0), Ls*gaxis/2+R*vector(0,1,0)], r=R/6, c='r')
gyro  = vp.Assembly([shaft, rotor, bar]) # group actors into a single one

spring= vp.helix(top, gpos, r=0.06, thickness=0.01, c='gray')
vp.box(top, length=0.2, width=0.02, height=0.2, c='gray')
vp.box(pos=(0,.5,0), length=2.2, width=3, height=2.2, c='gray', wire=1, alpha=.2)

# ############################################################ the physics
pb = ProgressBar(0, 5, dt, c='b')
for t in pb.range():
    Fspring = -ks*norm(gpos-top)*(mag(gpos-top)-Lrest)
    torque  = cross(-1/2*Ls*norm(Lrot), Fspring) # torque about center of mass
    Lrot    += torque*dt
    precess += (Fgrav+Fspring)*dt  # momentum of center of mass
    cm      += (precess/M)*dt
    gpos    = cm - 1/2*Ls*norm(Lrot)

    # set orientation along gaxis and rotate it around its axis by omega*t degrees
    gyro.orientation(Lrot, rotation=omega*t*57.3).pos(gpos)
    spring.stretch(top, gpos)
    vp.point(gpos + Ls*norm(Lrot), r=1, c='g') # add trace point to show in the end
    vp.render() 
    pb.print()
コード例 #9
0
    ListVel.append( (Rb*random.uniform(-1,1), Rb*random.uniform(-1,1)) )
Vel = np.array(ListVel)

# Create the spheres 
Spheres = [vp.add(Sphere(pos=(Pos[0][0],Pos[0][1],0), r=Radius[0], c='red'))]
for s in range(1,Nsp):
    a = vp.add(Sphere(pos=(Pos[s][0],Pos[s][1],0), r=Radius[s], c='blue'))
    Spheres.append(a)
vp.add(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]
    elif Pos[0,0] >= Lb0:
        Pos[0,0] = Lb0
        Vel[0,0] = -Vel[0,0]
    elif Pos[0,1] <=  -Lb1:
        Pos[0,1] = -Lb1
        Vel[0,1] = -Vel[0,1]
    elif Pos[0,1] >= Lb1:
コード例 #10
0
ファイル: turing.py プロジェクト: yordankyosev/vtkplotter
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 = Plotter(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
        c1, c2 = conc[t1,i], conc[t2,i]
        cgrad = abs(c2-c1)*cgradfac     # intensity of variation
        gx, gy, gz = np.random.randn(3) # make points wiggle a bit
        pts.append(p + vector(gx/4, gy/4, gz + c1*20))
        cols.append([0, c1, cgrad])     # RGB color
コード例 #11
0
ファイル: cell_main.py プロジェクト: zlinzju/vtkplotter
# (get these numbers by pressing Shift-C)
vp.camera.SetPosition([2.5, 2.5, 5.5])
vp.camera.SetFocalPoint([0.4, 0.4, 0.4])
vp.camera.SetParallelScale(1.8)
vp.camera.SetViewUp([-0.1, 1, -0.3])

# Let's start with creating 3 colonies of 1 cell each
# of types: red, green and blue, in different positions in space
# and with 3 differents rates of division (tdiv in hours)
c1 = Colony([Cell([1, 0, 0], tdiv=8)], c="b")
c2 = Colony([Cell([0, 1, 0], tdiv=9)], c="g")
c3 = Colony([Cell([0, 0, 1], tdiv=10)], c="r")
colonies = [c1, c2, c3]

# 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] = "
    vp.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
                vp += Line(cell.pos, newc.pos, c="k", lw=3, alpha=0.5)
                newcells.append(newc)
コード例 #12
0
ファイル: diffusion.py プロジェクト: yordankyosev/vtkplotter
from random import uniform as u
from vtkplotter import printc, ProgressBar, Plotter

N = 10  # nr of particles along axis
s = 0.01  # random step size

scene = Plotter(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

pb = ProgressBar(0, 80, 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.camera.Azimuth(.5)
    scene.camera.Roll(-.5)
    scene.render()

scene.show(resetcam=0)
コード例 #13
0
#initial conditions
v = vector(0, 0, 0.2)
x = vector(x0, 0, 0)
xr = vector(L, 0, 0)
sx0 = vector(-0.8, 0, 0)
offx= vector(0, 0.3, 0)

vp.add(box(pos=(0, -0.1, 0), length=2.0, width=0.02, height=0.5)) #surface
vp.add(box(pos=(-.82,.15,0), length=.04, width=0.50, height=0.3)) #wall
block = cube(pos=x, length=0.2, c='tomato')
block.addTrail(offset=[0,0.2,0], alpha=0.6, lw=2, n=500) 
spring = helix(sx0, x, r=.06, thickness=.01, texture='metal1')
vp.add([block, spring])

pb = ProgressBar(0,300, 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
    
    block.pos(x)                    # update block position and trail
    spring.stretch(sx0, x)          # stretch helix accordingly
    
    vp.camera.Azimuth(0.1)
    vp.camera.Elevation(0.1)
    vp.render() 
    pb.print('Fx='+str(round(F[0], 1))) # print Fx component

vp.show(interactive=1)
コード例 #14
0
ファイル: brownian2D.py プロジェクト: neoglez/vtkplotter
# Create the spheres
Spheres = [Sphere(pos=(Pos[0][0], Pos[0][1], 0), r=Radius[0], c="red")]
for s in range(1, Nsp):
    a = Sphere(pos=(Pos[s][0], Pos[s][1], 0), r=Radius[s], c="blue")
    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]
    elif Pos[0, 0] >= Lb0:
        Pos[0, 0] = Lb0
        Vel[0, 0] = -Vel[0, 0]
    elif Pos[0, 1] <= -Lb1:
        Pos[0, 1] = -Lb1
        Vel[0, 1] = -Vel[0, 1]
    elif Pos[0, 1] >= Lb1:
コード例 #15
0
    ynew = y + (yk1 + 2 * yk2 + 2 * yk3 + yk4) / 6
    vnew = v + (vk1 + 2 * vk2 + 2 * vk3 + vk4) / 6
    return ynew, vnew


def euler(y, v, t, dt):  # simple euler integrator
    vnew = v + accel(y, v, t) * dt
    ynew = y + vnew * dt + 1 / 2 * accel(y, vnew, t) * dt**2
    return ynew, vnew


positions_eu, positions_rk = [], []
y_eu, y_rk = np.array(y), np.array(y)
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 = Plotter(verbose=0, axes=2)  # choose axes type nr.2
vp.ytitle = 'u(x,t)'
vp.ztitle = ''  # will not draw z axis
コード例 #16
0
ファイル: brownian2D.py プロジェクト: zlinzju/vtkplotter
# Create the spheres
Spheres = [Sphere(pos=(Pos[0][0], Pos[0][1], 0), r=Radius[0], c="red")]
for s in range(1, Nsp):
    a = Sphere(pos=(Pos[s][0], Pos[s][1], 0), r=Radius[s], c="blue")
    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]
    elif Pos[0, 0] >= Lb0:
        Pos[0, 0] = Lb0
        Vel[0, 0] = -Vel[0, 0]
    elif Pos[0, 1] <= -Lb1:
        Pos[0, 1] = -Lb1
        Vel[0, 1] = -Vel[0, 1]
    elif Pos[0, 1] >= Lb1: