Sunday, March 6, 2016

DLA Cluster in Python

 It's using random parameter, so if it'll show the different result every time it's executed.


"""
Cluster
"""
import numpy as np                          #untuk operasi array
import matplotlib.pyplot as plt             #untuk gambar grafik
import matplotlib.animation as animation    #untuk menggerakkan grafik

fig, ax = plt.subplots()

plt.ylim(0,40)
plt.xlim(0,40)
#variabel
n   = 39
x0   = 19
y0   = 19
a   = np.zeros((n,n))
a[x0,y0]  = 1
#print a
rx  = []    
ry  = []

#membuat garis/kurva dengan sumbu-x adalah x, sumbu-y adalah y
line, = ax.plot(x0, y0, 'o')

x0  = np.random.randint(n)
y0  = np.random.randint(n)
x   = x0
y   = y0

def animate(i):
    global line
    global x0,y0,rx,ry,n
          
    #menentukan seed baru
    x   = x0 + np.random.randint(-1,2)
    y   = y0 + np.random.randint(-1,2)
    
    #print 'x = ', x, ' y = ', y
    #apakah keluar batas?
    #apakah menyentuh cluster utama? 
    if (x>(n-2)) or (y>(n-2)) or (x<1) or (y<1) or\
            (a[x,y-1] + a[x,y] + a[x,y+1] + a[x-1,y-1] + a[x-1,y] + a[x-1,y+1] +\
            a[x+1,y-1] + a[x+1,y] + a[x+1,y+1]) >= 1:
        #renew()
        #update subcluster menjadi bagian dari cluster (0 ke 1)
        a[x,y]  = 1
        for i in np.arange(len(rx)):
            a[rx[i],ry[i]] = 1
        #print a
        ok  = 0
        while ok==0:
            x   = np.random.randint(n)
            y   = np.random.randint(n)
            #cek
            if (a[x,y]==0) and (x>1) and (y>1) and (x<(n-2))and (y<(n-2)):
                ok  = 1
        ok  = 0
        #kosongkan 
        #print 'rx', rx
        rx  = []
        ry  = []
        #print 'rx',rx
        
    #print 'xnew = ', x, ' y = ', y

    #setelah mendapatkan seed baru, rekam titiknya
    rx.append(x)
    ry.append(y)
    x0  = x
    y0  = y
    
    line, = ax.plot(x,y,'o')
    return line,

ani = animation.FuncAnimation(fig, animate, frames=777, interval=100, blit=False)
ani.save('clusterDLA.mp4',bitrate=1024)
#plt.show()



.