首先设定初始随机种群数目,然后让虾群自动繁殖,最后就可以得出虾群的最终种群数目。例如设定初始的种群数目为20,最终在繁殖后得到的种群数目为35。
import random
class Shrimp():
def __init__(self, pos, mapSize):
# The position of the shrimp as x & y values stored in a list
# 虾的位置作为存储在列表中的 x 和 y 值
self.pos = pos
self.mapSize = mapSize
def stepChange(self):
self.pos[0] += random.randint(-10, 10)
self.pos[1] += random.randint(-10, 10)
# If the shrimp moved off the map, move it back on
# 如果虾移出地图,将其移回地图
if self.pos[0] < 0:
self.pos[0] = 0
elif self.pos[0] >= self.mapSize[0]:
self.pos[0] = self.mapSize[0]
if self.pos[1] < 0:
self.pos[1] = 0
elif self.pos[1] >= self.mapSize[1]:
self.pos[1] = self.mapSize[1]
import random
import matplotlib.pyplot as plt
from shrimp import Shrimp
import sys
para_list = sys.argv
XMAX = 1000
YMAX = 500
def main():
try:
numOfShrimp = int(para_list[1])
display = para_list[2]
except IndexError:
numOfShrimp = 15 # 虾的初始种群
display = "Y"
shrimpList = []
for i in range(numOfShrimp):
randX = random.randint(0, XMAX)
randY = random.randint(0, YMAX)
shrimpList.append(Shrimp([randX, randY], [XMAX, YMAX]))
for i in range(15):
xvalues = []
yvalues = []
for shrimp in shrimpList:
shrimp.stepChange()
xvalues.append(shrimp.pos[0])
yvalues.append(shrimp.pos[1])
# 虾以8%的速度繁殖
for i in range(int(numOfShrimp * 0.08)):
randX = random.randint(0, XMAX)
randY = random.randint(0, YMAX)
shrimpList.append(Shrimp([randX, randY], [XMAX, YMAX]))
# 绘制并保存图片
plt.scatter(xvalues, yvalues)
plt.xlim(0,XMAX)
plt.ylim(0,YMAX)
plt.savefig("mygraph.png")
# 若输入参数为 Y,则展示图片
if display == "Y":
image = plt.imread('mygraph.png')
plt.imshow(image)
plt.show()
# 将初始种群数和最终种群数保存到 shrimp_pop.csv
print(str(numOfShrimp) + "," + str(len(shrimpList)))
if __name__ == "__main__":
main()
#!/bin/bash
low_pop=$1 # 初始数目
hi_pop=$2 # 结束数目
step_pop=$3 # 间隔
echo "Parameters are: "
echo "Population : " $low_pop $hi_pop $step_pop
outfile="shrimp_pop"$low_pop"-"$hi_pop".csv"
echo "Initial Population,Final Population" > $outfile
for p in `seq $low_pop $step_pop $hi_pop`;
do
echo "Experiment: " $p
# 在此处添加代码以使用相关参数调用 shrimpBase.py
# 并将输出重定向到 outfile
echo `python shrimpBase.py $p N` >> $outfile
done
标签:plt,python,self,random,pos,pop,shrimp,算法,磷虾
From: https://www.cnblogs.com/tiansz/p/17052733.html