Example #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)]
Example #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)
Example #3
0
    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
        hitlist.remove(j*Natoms+i)           # remove symmetric j,i pair from list
Example #4
0
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) 
    if not i%200: # add trace and render all, every 200 iterations
Example #5
0
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)

#vp.write(img, 'imgcube.tif') # or .vti
Example #6
0
# ############################################################ 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()

vp.show(interactive=1)
Example #7
0
# 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
Example #8
0
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)