Demo entry 6720810

test.py

   

Submitted by anonymous on Mar 18, 2018 at 11:30
Language: Python 3. Code size: 4.7 kB.

import turtle
import math
import random
import time
#declare: global constant
DESTX=100
DESTY=100
N=30    #the number of birds
GENE=200    #the generation to go

#declare: global variable
global geval
geval=1000000000
gbestx=0
gbesty=0

#function: initialization for canvas &birds
def preset():
    turtle.setup(800,800,0,0)
    turtle.colormode(255)
    turtle.speed(10)
    draw_circle(DESTX,DESTY,50)
    preset_birds()
    draw_birds()

def preset_birds():
    global birds
    presentx=file_process("list_presentx.txt")
    presenty=file_process("list_presenty.txt")
    vx=file_process("list_vx.txt")
    vy=file_process("list_vy.txt")
    birds=[bird(presentx[i],presenty[i],vx[i],vy[i]) for i in range(N)]
#文件处理,从文件读入数据的基本操作函数,将文件中储存的信息(进行去除换行符操作)以列表的形式返回
def file_process(file_name):
    file_index=open(file_name,"r")
    alist=file_index.readlines()
    for i in range(len(alist)):
        alist[i]=float(alist[i].rstrip())
    file_index.close
    return alist

#function: draw the destination
def draw_circle(centerx,centery,radius):
    turtle.up()
    turtle.goto(centerx,centery)
    turtle.forward(radius)
    turtle.down()
    turtle.left(90)
    turtle.circle(radius)
    turtle.up()
#function: draw the birds
def draw_birds():
    for i in range(N):
        draw_bird(birds[i].x,birds[i].y)
        
#function: draw one bird on the canvas
def draw_bird(presentx,presenty):
    turtle.goto(presentx,presenty)
    turtle.dot(3)
    
class bird():
    def __init__(self,presentx,presenty,vx,vy):
        self.x=presentx
        self.y=presenty
        self.vx=vx
        self.vy=vy
        self.eval=10000000000
        
        self.peval=10000000000
        self.pbestx=presentx
        self.pbesty=presenty
    #calculate this bird`s eval at present    
    def cal_eval(self):
        self.eval=math.sqrt((self.x-DESTX)**2)+math.sqrt((self.y-DESTY)**2)
    #update this bird`s best eval and positon
    def update_pbest(self):
        if self.eval<self.peval:
            self.peval=self.eval
            self.pbestx=self.x
            self.pbesty=self.y
    #move the bird and draw on the canvas
    def update_v(self):
        self.vx=self.vx+p_increment*(random.random())*(self.pbestx-self.x)+g_increment*(random.random())*(gbestx-self.x)
        self.vy=self.vy+p_increment*(random.random())*(self.pbesty-self.y)+g_increment*(random.random())*(gbesty-self.y)
    def move(self):
        self.x=self.x+self.vx
        self.y=self.y+self.vy
        

#update the geval & gbestx & gbesty & self.peval self.pestx self.pbesty
def update_gpeval():
    global geval
    global gbestx
    global gbesty
    global birds
    for i in range(N):
        birds[i].cal_eval()
        birds[i].update_pbest()
        if birds[i].peval<geval:
            geval=birds[i].peval
            gbestx=birds[i].pbestx
            gbesty=birds[i].pbesty
    



def main():
    start=time.time()
    result=[]
    p_eval_list=["bird{}".format(i) for i in range(N)]
    preset()#initialize the canvas and the destination and birds
    for gene in range(GENE):
        update_gpeval()
        sum=0
        for i in range(N):
            birds[i].update_v()
            birds[i].move()
            sum+=birds[i].eval
            p_eval_list[i]=p_eval_list[i]+"    "+str(birds[i].eval)
        print("{}`s average eval is {:.2f}.".format(gene,sum/N))
        result.append(str(sum/N)+"\n")

        #绘制鸟的位置
        pencolor=int(255/GENE)*gene
        turtle.pencolor(255-pencolor,0,0)
        draw_birds()
    end=time.time()
    print("{:.2f}".format(end-start))
    #写文件来记录每一代的平均eval
    file=open("test_g-{}_p-{}.txt".format(g_increment,p_increment),"w")
    file.writelines(result)
    file.write("g_increment={}\t p_increment={}\t formular1".format(g_increment,p_increment))
    file.close()
    #对每一只鸟的eval记录处理,在结尾处加换行符,使得每只鸟单独一行
    for i in range(N):
        p_eval_list[i]=p_eval_list[i]+"\n"
    #写文件来记录每只鸟每一代的eval,每只鸟是一个字符串,以4个空格为分隔符,以bird[i]为行头
    file1=open("test_g-{}_p-{}_p_eval.txt".format(g_increment,p_increment),"w")
    file1.writelines(p_eval_list)
    file1.write("g_increment={}\t p_increment={}\t formular_1".format(g_increment,p_increment))
    file1.close()
    #写ps文件来记录每次试验的turtle图像    
    picture=turtle.getscreen()
    picture.getcanvas().postscript(file="test_g-{}_p-{}.ps".format(g_increment,p_increment))
    turtle.reset()


#对不同的g,p函数进行测试
for g_increment in [0.05,0.1,0.2,0.5]:
    for p_increment in [0.05,0.1,0.2,0.5]:
        main()
        
        
        
        

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).