|
| 1 | +from matplotlib import pyplot as plt |
| 2 | +from numpy import exp,sin,cos, array, square,sqrt,var,mean,linspace |
| 3 | +from random import random |
| 4 | +from time import clock |
| 5 | + |
| 6 | +def fun(x): |
| 7 | + x = array(x) |
| 8 | + return (sin(x+square(x*10)))/(sqrt(x+square(x))) |
| 9 | + |
| 10 | + |
| 11 | +def initial(size,down,up): |
| 12 | + pops = [] |
| 13 | + for item in range(size): |
| 14 | + a = down+random()*(up-down) |
| 15 | + pops.append(a) |
| 16 | + y_pops = fun(pops) |
| 17 | + his_individual = pops |
| 18 | + y_pops = y_pops.tolist() |
| 19 | + y_pops_index = y_pops.index(max(y_pops)) |
| 20 | + his_social = pops[y_pops_index] |
| 21 | + return pops,his_individual,his_social |
| 22 | +def pops_update(pops,w,v,c1,c2,his_individual,his_social,down,up): |
| 23 | + for i in range(len(pops)): |
| 24 | + v = w*v+c1*random()*(his_individual[i]-pops[i])+c2*random()*(his_social-pops[i]) |
| 25 | + pops[i] = pops[i]+v |
| 26 | + if pops[i]>up: |
| 27 | + pops[i] = up |
| 28 | + if pops[i]<down: |
| 29 | + pops[i] = down |
| 30 | + return pops |
| 31 | +def his_update(pops,his_ind): |
| 32 | + y_pops = fun(pops) |
| 33 | + y_his_ind = fun(his_ind) |
| 34 | + for i in range(len(pops)): |
| 35 | + if y_his_ind[i]<y_pops[i]: |
| 36 | + his_ind[i] = pops[i] |
| 37 | + |
| 38 | + y_pops = y_pops.tolist() |
| 39 | + y_pop_index = y_pops.index(max(y_pops)) |
| 40 | + his_soc = pops[y_pop_index] |
| 41 | + return his_ind,his_soc |
| 42 | + |
| 43 | +if __name__ == '__main__': |
| 44 | + bagin = clock() |
| 45 | + up =0.4 |
| 46 | + down = 0.2 |
| 47 | + pop_size = 10 |
| 48 | + w = 0.1 |
| 49 | + v = 1 |
| 50 | + c1 = 2 |
| 51 | + c2 = 2 |
| 52 | + pops_0,his_individual,his_social = initial(pop_size,down,up) |
| 53 | + plt.plot(pops_0,fun(pops_0),'r*') |
| 54 | + pops_1 = pops_0 |
| 55 | + while var(pops_1)/mean(pops_1)>0.0001: |
| 56 | + pops_1 = pops_update(pops_1,w,v,c1,c2,his_individual,his_social,down,up) |
| 57 | + his_individual,his_social = his_update(pops_1,his_individual) |
| 58 | + |
| 59 | + plt.plot(pops_1, fun(pops_1), 'k*') |
| 60 | + end = clock() |
| 61 | + print pops_1,'\n',var(pops_1),'\n',end-bagin |
| 62 | + |
| 63 | + x = linspace(down,up,1000) |
| 64 | + y =fun(x) |
| 65 | + plt.plot(x,y,'b--') |
| 66 | + plt.show() |
| 67 | + |
0 commit comments