示例#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 showSolution3D(S, start, goal):
    from vtkplotter import Text, Cube, Line, Grid, mergeActors, 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 = mergeActors(cubes).clean().texture('metal2')

    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.wireframe(False).cellColors(gradient, cmap='gist_earth_r')
    grd.addScalarBar(title='Gradient', horizontal=True)

    txts.append(Text(__doc__, c='k'))
    txts.append(Text('Start', pos=[start[1] - 1, -start[0] + 1.5, 1], c='k'))
    txts.append(Text('Goal!', pos=[goal[1] - 2, -goal[0] - 2.7, 1], c='k'))
    show(path, walls, grd, txts, bg='white', axes=0, zoom=1.2)
示例#3
0
# -----------------------------------------------------


Z = np.zeros((n+2, n+2), [('U', np.double), ('V', np.double)])
U, V = Z['U'], Z['V']
u, v = U[1:-1, 1:-1], V[1:-1, 1:-1]

r = 20
u[...] = 1.0
U[n//2-r:n//2+r, n//2-r:n//2+r] = 0.50
V[n//2-r:n//2+r, n//2-r:n//2+r] = 0.25
u += 0.05*np.random.uniform(-1, 1, (n, n))
v += 0.05*np.random.uniform(-1, 1, (n, n))

sy, sx = V.shape
grd = Grid(sx=sx, sy=sy, resx=sx, resy=sy)
grd.lineWidth(0).wireframe(False).lighting(ambient=0.5)

for step in range(Nsteps):
    for i in range(20):
        Lu = (                  U[0:-2, 1:-1] +
              U[1:-1, 0:-2] - 4*U[1:-1, 1:-1] + U[1:-1, 2:] +
                                U[2:  , 1:-1])
        Lv = (                  V[0:-2, 1:-1] +
              V[1:-1, 0:-2] - 4*V[1:-1, 1:-1] + V[1:-1, 2:] +
                                V[2:  , 1:-1])
        uvv = u*v*v
        u += (Du*Lu - uvv + F*(1-u))
        v += (Dv*Lv + uvv - (F+k)*v)

    vvals = np.flip(V, axis=0).ravel()
示例#4
0
Du, Dv, F, k, name = 0.16, 0.08, 0.035, 0.060, 'Zebrafish'
# ---------------------------------------------------------------

Z = np.zeros((n + 2, n + 2), [('U', np.double), ('V', np.double)])
U, V = Z['U'], Z['V']
u, v = U[1:-1, 1:-1], V[1:-1, 1:-1]

r = 20
u[...] = 1.0
U[n // 2 - r:n // 2 + r, n // 2 - r:n // 2 + r] = 0.50
V[n // 2 - r:n // 2 + r, n // 2 - r:n // 2 + r] = 0.25
u += 0.05 * np.random.uniform(-1, 1, (n, n))
v += 0.05 * np.random.uniform(-1, 1, (n, n))

sy, sx = V.shape
grd = Grid(sx=sx, sy=sy, resx=sx, resy=sy)
grd.lineWidth(0).wireframe(False).lighting(ambient=0.5)
formula = r'(u,v)=(D_u\cdot\Delta u -u v v+F(1-u), D_v\cdot\Delta v +u v v -(F+k)v)'
ltx = Latex(formula, s=15, pos=(0, -sy / 1.9, 0))
print('Du, Dv, F, k, name =', Du, Dv, F, k, name)

for step in range(Nsteps):
    for i in range(25):
        Lu = (U[0:-2, 1:-1] + U[1:-1, 0:-2] - 4 * U[1:-1, 1:-1] + U[1:-1, 2:] +
              U[2:, 1:-1])
        Lv = (V[0:-2, 1:-1] + V[1:-1, 0:-2] - 4 * V[1:-1, 1:-1] + V[1:-1, 2:] +
              V[2:, 1:-1])
        uvv = u * v * v
        u += Du * Lu - uvv + F * (1 - u)
        v += Dv * Lv + uvv - (F + k) * v
# Create an array with all the radius and a list with all the masses
Radius = np.concatenate( (np.array([Rb]), np.array([Rs]*(Nsp-1))) )
Mass=[1.0]+[Ms]*(Nsp-1)

# Create the initial array of velocities at random with big sphere at rest
ListVel=[(0.,0.)]
for s in range(1,Nsp):
    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]
示例#6
0
u1, u2 = TrialFunctions(V)
v1, v2 = TestFunctions(V)
a1 = u1 * v1 - Constant(0.5 * dt) * u2 * v1
L1 = un1 * v1 + Constant(0.5 * dt) * un2 * v1
a2 = u2 * v2 + Constant(0.5 * c**2 * dt) * inner(grad(u1), grad(v2))
L2 = un2 * v2 - Constant(0.5 * c**2 * dt) * inner(grad(un1), grad(v2))
a = (a1 + a2) * dx
L = (L1 + L2) * dx
uh = Function(V)

############################################################
from vtkplotter.dolfin import plot
from vtkplotter import Grid

#build a thin gray frame to avoid camera jumping around
frame = Grid(pos=[0.5, 0, 0]).c('gray').alpha(0.1)

for i in range(nt):

    solve(a == L, uh, [bc1, bc2])
    uk1, uk2 = uh.split()
    un.assign(uh)
    #
    #    plot(uk1, warpYfactor=.0)
    #    exit()

    if not i % 4:
        plot(
            uk1,
            frame,
            at=0,
示例#7
0
width   = 10e-6    # slit width in m
D       = 0.1      # screen distance in m
#########################################

# create the slits as a set of individual coherent point-like sources
n = 10 # nr of elementary sources in slit (to control precision).
slit1 = list(zip([0]*n, arange(0,n)*width/n, [0]*n)) # source points inside slit 1
slit2 = list(slit1 + array([1e-5, 0,0]))             # a shifted copy of slit 1
slits = slit1 + slit2  
#slits += list(slit1 + array([-2e-5, 1e-5, 0]))      # add an other copy of slit 1
#slits = [(cos(x)*4e-5, sin(x)*4e-5, 0) for x in arange(0,2*pi, .1)] # Arago spot
#slits = Grid(sx=1e-4, sy=1e-4, resx=9, resy=9).coordinates() # a square lattice

vp = Plotter(title='The Double Slit Experiment', axes=0, verbose=0, bg='black')

screen = vp.add(Grid(pos=[0,0,-D], sx=0.1, sy=0.1, resx=200, resy=50))
screen.wire(False) # show it as a solid plane (not as wireframe)

k  = 0.0 + 1j * 2*pi/lambda1 # complex wave number
norm = len(slits)*5e+5
amplitudes = []

for i, x in enumerate(screen.coordinates()):
    psi = 0
    for s in slits:
        r = mag(x-s)
        psi += exp( k * r )/r
    psi2 = real( psi * conj(psi) ) # psi squared
    amplitudes.append(psi2)
    screen.setPoint(i, x+[0,0, psi2/norm]) # elevate grid in z
示例#8
0
Mass = [1.0] + [Ms] * (Nsp - 1)

# Create the initial array of velocities at random with big sphere at rest
ListVel = [(0.0, 0.0)]
for s in range(1, Nsp):
    ListVel.append((Rb * random.uniform(-1, 1), Rb * random.uniform(-1, 1)))
Vel = np.array(ListVel)

# 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]
示例#9
0
import vtk
from vtkplotter import Grid, Tensors, show

domain = Grid(resx=5, resy=5, c='gray')

# Generate random attributes on a plane
ag = vtk.vtkRandomAttributeGenerator()
ag.SetInputData(domain.polydata())
ag.GenerateAllDataOn()
ag.Update()

ts = Tensors(ag.GetOutput(), scale=0.1)
#ts.printInfo()

show(domain, ts)