达尔文_自然选择_python模拟.doc_第1页
达尔文_自然选择_python模拟.doc_第2页
达尔文_自然选择_python模拟.doc_第3页
达尔文_自然选择_python模拟.doc_第4页
达尔文_自然选择_python模拟.doc_第5页
已阅读5页,还剩19页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Natural selection_pythonB y QQ:231469242欢迎共同爱好者交流,并改进代码奉承开源精神,公开源码。初代版本是美国密歇根大学的两位教授所写,一半以上代码已被改进,并添加了许多新功能。同时纠正了两位教授代码的错误。介绍:达尔文是伟大的科学家,进化论创始人,自然选择是他的伟大学说。此程序模拟简单的自然选择可以辅助证明达尔文适者生存法则。/snackbar/wator/A.K. Dewdne博士在美国自然科学杂志报告 A.K. Dewdne in Scientific American magazineDescriptionWATOR is a simulation of the interaction over time of predator and prey in a small rectangular area. It is a simple program originally described by A.K. Dewdney in Scientific American magazine. The game is to arrange the parameters so the populations are stable when the area is made small.The program is dependent upon five parameters, plus the size of the rectangular grid. The first parameter is the number of fish, the prey. A fish swims at random to one of the four horizontally or vertically adjacent spaces on the grid, if it is unoccupied. The grid wraps around so a fish can swim off one edge and appear at the opposite edge. The second parameter is the fish breed time. If a fish survives this number of cycles and an open space is available, a new fish is bred. The third parameter is the number of sharks, the predators. A shark eats a fish in an adjacent space on the grid. A shark swims to an open space if there is no adjacent fish. The fourth parameter is the shark starve time. If a shark finds no fish for this number of cycles, it dies. The final parameter is the shark breed time. A shark breeds in the same way as a fish.If the number of sharks is very small, the fish population will increase quickly and the shark population will soon follow because they find plenty of food. Eventually the fish will become overcrowded and overwhelmed by the large shark population and the fish population will crash. Depending upon the quantity and distribution of sharks at the beginning of the crash, the fish may disappear entirely, the sharks may become isolated and disappear or catastrophe may be narrowly averted.Studies of small, isolated biological systems that lack diversity have shown similar patterns, though never as simply. The ebb and flow of populations is interesting in itself and there is probably slim evidence to support any particular social or political philosophy.ImplementationThis program shows the simulated Wa-tor world at the top and a graph of the populations at the bottom. The slides to adjust the parameters are shown at the right of the Wa-tor world, with control buttons below the slides.Fish are green, sharks, red and the background is light blue. The graph shows the numbers of fish and sharks with zero at the bottom and the total number of spaces on the grid at the top. A vertical black line sweeps from left to right moving one pixel each cycle and when it reaches the right edge, wraps around to the left edge. When any of the parameters is altered or the Remix button is pushed, the discontinuity is noted with a vertical white line.When a breed or starve parameter is altered, each fish and shark receives the new value after it next breeds or eats. When a fish or shark is created, its breed and starve values are randomized somewhat. The numbers of fish and sharks are updated continuously by the program, but may be altered by the user. Whenever the numbers of fish or sharks or the size of the grid is altered, the simulation is remixed.The geometry of fish and sharks on the grid affects the simulation, and is well mixed initially. This can be done explicitly with the Remix button. The simulation can be paused and restarted with the Stop and Go buttons. Your browser may suspend the program independently when it is scrolled off the screen.Usage NotesThis is a Java Applet. If your browser does not support Java, imagine a program running in a window within this web page, near the top. The language appears to be relatively new and thus unstable. This program runs reasonably well on Netscape 3.0 under Windows 95, but there is reason to believe it will not work as well elsewhere. There is no reason to believe this programmer understands the documentation.If most of the toolbars and such are cleared away, the entire program can be viewed at once with a high screen resolution, or in two halves in a low resolution.There is no persistent information associated with this program. There is no record of it after your browser quits. 1999年,A.K. Dewdney博士把一程序发布于美国自然科学杂志。WAT-OR游戏,代码是Java,该程序模拟自然栖息地中“捕食者-猎物”问题。实例是鲨鱼和鱼。 “捕食者-猎物”问题充分体现捕食者与猎物之间相互作用,一组动物构成猎物,一组动物构成食肉动物(捕食者)。模拟结果将展示这两个种群之间动态交互。它代表一种栖息地战争,两个种群为生存而挣扎,存活或发展壮大。通常情况下,这两个群体有固定出生率。猎物通常生育速度比捕食者快,猎物数量不断增长。猎物增加供养了更多捕食者,这反过来会增加捕食者数量。一段时间后,猎物数量减少,之后捕食者因食物减少,达到临界点,数量也随之减少,猎物数量反之又增长,理论上这两个种群数量不断交互增长和衰落。虽然已有公式对捕食者与猎物关系建模,但可以用计算机来模拟这种关系,fun ! 这里用大蟒蛇重构模拟,Java用的代码太多,五百多行代码。编写了捕食者和猎物在岛上生存模拟仿真环境,忽略了一些实际因素。一个研究栖息地中捕食者与被捕食者之间关系的典型实例,是苏必利尔湖中罗亚尔岛上的狼和驼鹿,如网址 所示。罗亚尔岛位于苏必利尔湖西北部,岛上只有狼和驼鹿,是孤立的岛屿(偶尔,苏必利尔湖会结冻,能从陆地走到岛上)。岛的独立,使成为研究捕食者-猎物相互作用的影响的完美实验室。自1959年以来,岛上种群数目变化能在 上找到。罗亚岛的生态科学家们美国官网提供的数据:/sites/default/files/annual-report-pdf/wolf%20moose%20annual%20report%202014%20-%20color%20for%20web.pdf/http%3A//products/precip/CWlink/pna/nao.shtml;1.年平均数来看,狼为25只,鹿为1000-1500左右,鹿数量是狼的25倍左右2.上限值:狼的上限值是50只,鹿为2500只,不会无限繁殖这是线性回归图,本人写的线性回归分析程序可以作自动化统计。Python代码模拟结果:开始后来源码import random,pylabclass Island(): Island,n*n grid where zero value indicates an unoccupied cell. #生成一个n排,n列的点矩阵,矩阵是笛卡尔坐标系,x向右递增,y向上递增,(0,0)是左下角,(9,0)是右下角 #(0,9)是左上角,(9,9)是右上角 #程序输出顺序是从左上角(0,9)开始,(1,9),(2,9)。到右下角结尾(9,0) #岛上空白是数字0,在str显示时被.取代 def _init_(self,n,preyCnt=0,predatorCnt=0,advanced_predator_init=0): #print in island init self.gridSize=n self.grid= for i in range(n): #生成一个点矩阵 row=0*n #row is a list of zero self.grid.append(row) self.initAnimals(preyCnt,predatorCnt,advanced_predator_init) def _str_(self): string representation for printing. (0,0)will be in the lower-left corner. #print in island str s= for j in range(self.gridSize-1,-1,-1): #print row size-1 first for i in range(self.gridSize): #each row starts at 0 if not self.gridij: #print a . for empty space s+=%-2s%.+ # 字符串负号表示左对齐,这里表示左对齐2个单位 else: s+=%-2s%(str(self.gridij)+ s+=n return s def _repr_(self): return self._str_() def _getitem_(self,a): #print in getitem #可以通过索引查看岛屿地域,还可以通过赋值语句让动物注册到岛上,更加人性化,比register方法更快 return self.grida def register(self,animal): register animal with island, i.e.put it at the animals coordinate #register函数是动物和岛屿交互的桥梁,动物的位置x,y被保存到岛屿笛卡尔坐标系中 #print in island register x=animal.x y=animal.y self.gridxy=animal def size(self): reture the size of island:one dimension #print in island size return self.gridSize def animal(self,x,y): #print in animal check #查看岛屿某位置是否有Animal实例 if 0=xself.gridSize and 0=yself.gridSize: #print ok return self.gridxy else: #print no return -1 #outside the land boundary def initAnimals(self,preyCnt,predatorCnt,advanced_predator_init): put some initial animals on the island #猎物初始化 cnt=0 #while loop continues until preyCnt unoccupied positions are found while cntpreyCnt: x=random.randint(0,self.gridSize-1) y=random.randint(0,self.gridSize-1) if selfxy=0: #if not self.animal(x,y): newPrey=Prey(island=self,x=x,y=y) cnt+=1 self.register(newPrey) #捕食者初始化 cnt=0 while cntpredatorCnt: x=random.randint(0,self.gridSize-1) y=random.randint(0,self.gridSize-1) if selfxy=0: #if not self.animal(x,y): newPred=Predator(island=self,x=x,y=y) cnt+=1 self.register(newPred) #高级捕食者初始化 cnt=0 while cnt0.6: printin prey equilibrium before_remove_prey_numbers=preyCnt/2 #需要移除的猎物数量 after_remove_prey_cnt=0 #统计核实移除数量是否正确 for x in range(size): for y in range(size): animal = self.animal(x,y) if animal: #如果是动物 if isinstance(animal,Prey): #如果动物是捕食者,则运行eat()方法 animal.island.remove(animal)#移除猎物 before_remove_prey_numbers-=1 after_remove_prey_cnt+=1 if before_remove_prey_numbers0.3: printin predator equilibrium before_remove_pred_numbers=predCnt/3 print before remove_pred_numbers:%d%(before_remove_pred_numbers) after_remove_pred_cnt=0 #统计核实移除数量是否正确 for x in range(size): for y in range(size): animal = self.animal(x,y) if animal: #如果是动物 if isinstance(animal,Predator): #如果动物是捕食者,则运行eat()方法 animal.island.remove(animal)#移除猎物 print remove predator before_remove_pred_numbers-=1 after_remove_pred_cnt+=1 if before_remove_pred_numbers=0: print nature has removed:%d%(after_remove_pred_cnt) break #有问题,数字不准确,移除是大概值,这里可以解释为随机性或不可预测造成 class Animal(object): def _init_(self,island,x=0,y=0,name=A): initialize the animals name and their position #print in animal init #x和y的值表示岛上的动物将被放置的位置。 #Animal实例还需要知道它位于哪个岛屿 #最后需要它的名字:moose或wolf self.island=island =name self.x=x self.y=y self.moved=False #设置为静止,即未移动状态 self.clockTicked=False #生物钟递减为否 def _str_(self): #print in animal str return def _repr_(self): #print in animal repr return self._str_() def position(self): return the coordinates of current position #print in animal position return self.x, self.y def checkGrid(self,typeLookingFor=int): look in the 8 direction from the animals location and return the first location that presently has an object of the specified type.return 0 if no such location exists #eat(),move()函数都会用到checkGrid(),把此函数改为随机性 # neighbor offsets offset = (-1,1),(0,1),(1,1),(-1,0),(1,0),(-1,-1),(0,-1),(1,-1) result = 0 for i in range(len(offset)*8): random_move=random.randint(0,len(offset)-1) x=self.x+offsetrandom_move0 y=self.y+offsetrandom_move1 if not 0 = x self.island.size() or not 0 = y self.island.size(): continue if type(self.island.animal(x,y)=typeLookingFor: #print found target result=(x,y) break return result def move(self): Move to an open, neighboring position移动到旁边一个空位置 if not self.moved: #如果未移动,则下面程序执行 location = self.checkGrid(int) #寻找空白地 if location: # print Move, %s, from %d,%d to %d,%d% # (type(self),self.x,self.y,location0,location1) self.island.remove(self) # remove from current spot self.x = location0 # new coordinates self.y = location1 self.island.register(self) # register new coordinates self.moved=True #移动标记设置为真,则移动后不会再次移动 def breed(self): breed a new Animal,if there is room in one of the 8 locations, place the new prey there.otherwise,you have to wait if self.breedClock=0: location=self.checkGrid(int) if location: self.breedClock=self.breedTime #printself.breedClock now return to:,self.breedClock theClass=self._class_ newAnimal=theClass(self.island,x=location0,y=location1) self.island.register(newAnimal) def clearMovedFlag(self): #让动物移动设置为False,方便下次移动 self.moved=False self.clockTicked=False class Prey(Animal): #每个实例都有自己时钟,用于跟踪繁殖时间。predator还有第二个时钟,用于跟踪挨饿时间。也就是 #说,创建实例需要初始化内部“时钟”。每个实例通过clockTick方法,在每个时排,更新自己的时钟。当他们 #繁殖时钟计数到0时,他们能繁殖。饥饿时钟同理 def _init_(self,island,x=0,y=0,s=O): #printin prey init Animal._init_(self,island,x,y,s) self.breedClock=self.breedTime #breedClock是时钟,会变化,所以用另一个变量名 def clockTick(self): prey updates only its local breed clock if self.clockTicked=False: self.breedClock-=1 self.clockTicked=True class Predator(Animal): def _init_(self,island,x=0,y=0,s=X): #print in predator init Animal._init_(self,island,x,y,s) self.breedClock=self.breedTime self.starveClock=self.starveTime def move(self): if not self.moved: #如果未移动,则下面程序执行 offset = (-1,1),(0,1),(1,1),(-1,0),(1,0),(-1,-1),(0,-1),(1,-1) result = 0 for i in range(len(offset)*8): random_move=random.randint(0,len(offset)-1) x=self.x+offsetrandom_move0 y=self.y+offsetrandom_move1 #如果x,y超过取值范围,则重新循环 if not 0 = x self.island.size() or not 0 = y self.island.size(): continue #如果目的地是空地,则移动 if type(self.island.animal(x,y)=int: self.island.remove(self) # remove from current spot self.x =x # new coordinates self.y =y self.island.register(self) # register new coordinates self.moved=True #移动标记设置为真,则移动后不会再次移动 break #如果目的地是猎物,则进食 if type(self.island.animal(x,y)=Prey: self.island.remove(self.island.animal(x,y)#删除location上的prey self.island.remove(self) # remov

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论