def test_life_36(self): l = Life(1,3) l.neighbors = 2 c2 = ConwayCell() c2.evolve(l) assert c2.alive == False
def test_life_35(self): l = Life(1,3) l.neighbors = 3 c1 = ConwayCell() c1.evolve(l) assert c1.alive == True
def docross(self,lives,x, y): child1 = self.getChild(1,lives, x, y) child2 = self.getChild(2,lives, x, y) child1=self.modify_circle(child1) child2=self.modify_circle(child2) lives[x] = Life(child1) lives[y] = Life(child2)
def test_life_34(self): l = Life(2,2) l.neighbors = 2 c1 = ConwayCell(True) c1.evolve(l) assert c1.alive == True
def cross(self, parent1: Life, parent2: Life): """ 交叉:两染色体相同位置的片段之间的部分交叉 输入:父代染色体(Life类) 输出:交叉后的子代染色体(Life类) """ index1 = np.random.randint(len(origincoor)) index2 = np.random.randint(index1 + 1, len(origincoor) + 1) tempGene1 = [[], []] tempGene2 = [[], []] tempGene1[0] = parent1.gene[0][index1 * 3:index2 * 3] # 交叉的基因片段 tempGene1[1] = parent1.gene[1][index1 * 3:index2 * 3] tempGene2[0] = parent2.gene[0][index1 * 3:index2 * 3] # 交叉的基因片段 tempGene2[1] = parent2.gene[1][index1 * 3:index2 * 3] parent1.gene[0][index1 * 3:index2 * 3] = tempGene2[0] parent1.gene[1][index1 * 3:index2 * 3] = tempGene2[1] parent2.gene[0][index1 * 3:index2 * 3] = tempGene1[0] parent2.gene[1][index1 * 3:index2 * 3] = tempGene1[1] if checklegal(parent1.gene[0], len(targetcoor[0])) == False: parent1.gene = wipe(parent1.gene, index1 * 3, index2 * 3) parent1.gene = correctchrome(parent1.gene, index1, index2, TargetNum, ReconNum, UnionNum, CombatNum) if checklegal(parent2.gene[0], len(targetcoor[0])) == False: parent2.gene = wipe(parent2.gene, index1 * 3, index2 * 3) parent2.gene = correctchrome(parent2.gene, index1, index2, TargetNum, ReconNum, UnionNum, CombatNum) parent1.score = totaldis(parent1.gene, origincoor, targetcoor, ThreatRadius, TurnRadius, ReconTime, Velocity) parent2.score = totaldis(parent2.gene, origincoor, targetcoor, ThreatRadius, TurnRadius, ReconTime, Velocity) self.crossCount += 1 return parent1, parent2 '''
def test_life_25(self): k = FredkinCell(True) l = Life(1,1) l.addCell(0,0,k) l.countLives() k.evolve(l) assert k.alive == False
def test_life_18(self): k = AbstractCell(True) l = Life(1,1) l.addCell(0,0,k) k.evolve(l) k.evolve(l) k.evolve(l) assert k.alive
def test_foerste(self): l = Life(0, 20, 0, 20, self.alive) xmin, xmax, ymin, ymax = l.foerste() self.assertEqual(xmin, 0) self.assertEqual(xmax, 20) self.assertEqual(ymin, 0) self.assertEqual(xmax, 20)
def make_viewer(n, m, row, col, *strings): """Makes a Life and LifeViewer object. n, m: rows and columns of the Life array row, col: upper left coordinate of the cells to be added strings: list of strings of '0' and '1' """ life = Life(n, m) # n行m列的格子 life.add_cells(row, col, *strings) # 左上角坐标 viewer = LifeViewer(life) # 瞅一眼 return viewer
def test_life_26(self): k1 = FredkinCell(True) k2 = FredkinCell(True) l = Life(2,2) l.addCell(0,0,k1) l.addCell(1,0,k2) l.countLives() k1.evolve(l) assert k1.alive == True
def judge(self, f=lambda lf, av: 1): # 根据传入的方法 f ,计算每个个体的得分 lastAvg = self.bounds / float(self.lifeCount) self.bounds = 0.0 self.best = Life(self) self.best.setScore(-1.0) for lf in self.lives: lf.score = f(lf, lastAvg) if lf.score > self.best.score: self.best = lf self.bounds += lf.score
def test_life_27(self): k1 = FredkinCell(True) k2 = FredkinCell(True) l = Life(2,2) l.addCell(0,0,k1) l.addCell(1,0,k2) l.countLives() k1.age = 1 k1.evolve(l) assert isinstance(k1,ConwayCell)
def test_life_5(self): l = Life(2,2) c1 = FredkinCell(True) c2 = FredkinCell(True) c3 = FredkinCell(True) c4 = FredkinCell(True) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) assert str(l) == '00\n00'
def test_life_6(self): l = Life(2,2) c1 = ConwayCell(True) c2 = ConwayCell(False) c3 = FredkinCell(True) c4 = FredkinCell(False) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) assert str(l) == '*.\n0-'
def test_life_10(self): l1 = Life(1,1) c1 = FredkinCell(True) l1.addCell(0,0,c1) l1.populationEvolve() l2 = Life(1,1) c2 = ConwayCell(True) l2.addCell(0,0,c2) l2.populationEvolve() assert str(l2) == '.' and str(l1) == '-'
def run_game(board_size, life_cells, refresh): """ Play the game with the given parameters. :param board_size: the grid size of the board :param life_cells: the number of starter life cells :param refresh: the refresh rate of the game """ print( f'Total cells: {board_size * board_size}, Life cells: {life_cells}\n') life_game = Life(size=board_size, initial_cells=life_cells, interval=refresh) life_game.play()
def initPopulation(self): """初始化种群""" self.lives = [] for i in range(self.lifeCount): if i==0 and self.prim_path: gene = self.prim_path life = Life(gene) self.lives.append(life) else: gene = [ x for x in range(self.geneLenght) ] random.shuffle(gene) life = Life(gene) self.lives.append(life)
def test_life_42(self): l = Life(2,2) c1 = ConwayCell(True) c2 = ConwayCell(True) c3 = FredkinCell() c4 = FredkinCell() l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.countLives() l.cellExecute(1,1) assert l.liveNeighbors() == 1
def main(): #initialize # Assumes Linux setup cmd = "cd ~/Documents; pwd 2>/dev/null >/tmp/life_directory; cd - > /dev/null" output = subprocess.check_output(cmd, shell=True).split() documents_directory_path = subprocess.check_output( "cat /tmp/life_directory", shell=True).split()[0] life_directory = documents_directory_path + "/RealLifeGTA/" life_filename = "gta.data" life_complete_path = life_directory + life_filename try: life = _load_from_file(life_complete_path) #print "Loading life from datastore" except: #traceback.print_exc(file=sys.stdout) print "Couldn't load life from datastore, creating a new file at path:" + life_directory subprocess.check_output("mkdir -p " + life_directory, shell=True) life = Life() # start main loop CommandLineInterface(life)._process_single_command() #persist data try: _save_to_file(life, life_complete_path) except: traceback.print_exc(file=sys.stdout)
def next(self): """产生下一代""" self.judge() newLives = [] """for lf in self.lives: if lf.score > 5*self.initScore: newLives.append(lf)""" newLives.append(self.best) #把最好的个体加入下一代 basicgene = [0 for x in range(self.geneLenght)] #把最基本的加入下一代 newLives.append(Life(basicgene)) newLives.append(Life(self.init)) #把DFS得到的加入下一代 while len(newLives) < self.lifeCount: newLives.append(self.newChild()) self.lives = newLives self.generation += 1
def __init__(self, xRate=0.7, mutationRate=0.005, lifeCount=50, geneLength=100, judge=lambda lf, av: 1, save=lambda: 1, mkLife=lambda: None, xFunc=None, mFunc=None): self.xRate = xRate self.mutationRate = mutationRate self.mutationCount = 0 self.generation = 0 self.lives = [] self.bounds = 0.0 # 得分总数 self.best = None self.lifeCount = lifeCount self.geneLength = geneLength self.__judge = judge self.save = save self.mkLife = mkLife # 默认的产生生命的函数 self.xFunc = (xFunc, self.__xFunc)[xFunc == None] # 自定义交叉函数 self.mFunc = (mFunc, self.__mFunc)[mFunc == None] # 自定义变异函数 for i in range(lifeCount): self.lives.append(Life(self, self.mkLife()))
def __init__(self, x_rate=0.7, mutation_rate=0.005, life_count=50, gene_length=100, judge=lambda lf, av: 1, save=lambda: 1, mk_life=lambda: None, x_func=None, m_func=None): self.x_rate = x_rate self.mutation_rate = mutation_rate self.mutation_count = 0 self.generation = 0 self.lives = [] self.bounds = 0.0 # 得分总数 self.best = None self.life_count = life_count self.gene_length = gene_length self.__judge = judge self.save = save self.mk_life = mk_life # 默认的产生生命的函数 self.x_func = (x_func, self.__x_func)[x_func == None] # 自定义交叉函数 self.m_func = (m_func, self.__m_func)[m_func == None] # 自定义变异函数 for i in range(life_count): self.lives.append(Life(self, self.mk_life()))
def main(script, *args): """Constructs the rabbits methusela. http://www.argentum.freeserve.co.uk/lex_r.htm#rabbits """ rabbits = ['1000111', '111001', '01'] n = 400 m = 600 life = Life(n, m) life.add_cells(n // 2, m // 2, *rabbits) viewer = LifeViewer(life) anim = viewer.animate(frames=100, interval=1) plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99) plt.show()
def __init__(self, spark = 42, d = -1): Life.__init__(self) self.d = d self.domains = ["Bacteria", "Archaea", "Eukaryota"] self.domain = self.domains[self.d] def domainRandomize(self): self.d = random.randint(0,2) self.domain = self.domains[self.d] pass if (self.d < 0): domainRandomize(self) pass if __name__ == '__main__': #print "The Answer to Life, the Universe and Everything is: ", self.TheAnswerToLifeTheUniverseAndEverything pass
def textToLife(self, text): # figure out game dimensions width = len(text) * 5 + 1 height = 9 lifeGame = Life(height=height, width=width) lifeGame.clean(state=LifeState.DEAD) currI = 1 currJ = 1 for character in text.upper(): for iIdx in range(7): for jIdx in range(4): gameIndices = (currI + iIdx, currJ + jIdx) dictIndices = (iIdx, jIdx) lifeGame.game[0][gameIndices[0]][gameIndices[1]].state \ = self.strDict[character][dictIndices[0]][dictIndices[1]] currJ += 5 return lifeGame
def initPopulation(self): """初始化种群""" self.lives = [] for i in range(self.lifeCount): gene = [x for x in range(self.geneLenght)] random.shuffle(gene) life = Life(gene) self.lives.append(life)
def AngleMutation(self, parent: Life): flag = 0 ''' 角度突变:某一个任务的角度变化 输入:要突变的染色体(Life类) 输出:突变后的染色体(Life类) ''' ###############################待修改突变函数################################## while flag == 0: index = np.random.randint(len(parent.gene[0]) + 1) if parent.gene[0][index] != 0: flag = 1 parent.gene[1][index] = np.random.randint(1, 361) parent.score = totaldis(parent.gene, origincoor, targetcoor, ThreatRadius, TurnRadius, ReconTime, Velocity) self.mutationCount += 1 return parent '''
def initPopulation(self): """初始化种群""" self.lives = [] for i in range(self.lifeCount): gene = [x for x in range(self.geneLenght)] # 初始化染色体 # shuffle() 方法将序列的所有元素随机排序。 random.shuffle(gene) life = Life(gene) # 生成个体 self.lives.append(life)
def initPopulation(self): """初始化种群""" self.lives = [] for i in range(self.lifeCount): gene = self.initOrder #print(gene) #random.shuffle(gene) # 随机洗牌 # life = Life(gene) self.lives.append(life)
def newChild(self): """产生新后的""" parent1 = self.getOne() parent2 = self.getOne() rate = random.random() # 按概率交叉 if rate < self.croessRate: # 交叉 gene1, gene2 = self.cross(parent1, parent2) else: gene1, gene2 = parent1.gene, parent2.gene # 按概率突变 rate = random.random() if rate < self.mutationRate: gene1, gene2 = self.mutation(gene1), self.mutation_bk(gene2) return Life(gene1), Life(gene2)
def newChild(self): """产生新后的""" mutationLives = [] # 按概率突变 for i in self.notBests: gene = self.mutation(i) mutationLives.append(Life(gene)) return mutationLives
def initPopulation(self): """initial the population""" self.population = [] for i in range(self.population_size): #gene = [0,1,…… ,self.chromosome_length-1] gene = self.init_chromosome[:] random.shuffle(gene) pop = Life(gene) # put individual in the population self.population.append(pop)
def initPopulation(self): """初始化种群""" self.lives = [] count = 0 while count < self.lifeCount: gene = np.random.randint(0, 2, self.geneLenght) life = Life(gene) random.shuffle(gene) # 随机洗牌 # self.lives.append(life) count += 1
def test_life_45(self): l = Life(2,2) c1 = ConwayCell(True) c2 = ConwayCell(True) c3 = ConwayCell(True) c4 = ConwayCell(False) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.countLives() l.cellExecute(2,2) assert c4.getAlive()
def test_life_47(self): l = Life(2,2) c1 = FredkinCell(True) c2 = FredkinCell(True) c3 = FredkinCell(True) c4 = FredkinCell(False) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.countLives() l.cellExecute(1,1) assert not c1.getAlive()
def initPopulation(self): """初始化种群""" self.lives = [] for i in range(self.lifeCount): gene = [ x for x in range(self.geneLenght) ] random.shuffle(gene) #将序列的所有元素随机排序 self.modify_circle(gene) life = Life(gene) self.lives.append(life) self.best=self.lives[0] self.judge()
def test_life_8(self): l = Life(2,2) c1 = FredkinCell(True) c2 = FredkinCell(True) c3 = FredkinCell(True) c4 = FredkinCell(True) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.countLives() l.livesCount = [[2,2],[2,2]]
def main(script, *args): """Constructs the rabbits methusela. http://www.argentum.freeserve.co.uk/lex_r.htm#rabbits """ rabbits = [ '1000111', '111001', '01' ] n = 400 m = 600 life = Life(n, m) life.add_cells(n//2, m//2, *rabbits) viewer = LifeViewer(life) anim = viewer.animate(frames=100, interval=1) plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99) plt.show()
def test_life_40(self): l = Life(2,2) c1 = ConwayCell(True) c2 = ConwayCell(False) c3 = ConwayCell(False) c4 = ConwayCell(True) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.cellExecute(1,1) assert l.liveNeighbors() == 0
def newChild(self): """产生新后的""" parent1 = self.getOne() gene = parent1.gene # 按概率突变 rate = random.random() if rate < self.mutationRate: gene = self.mutation(gene) return Life(gene)
def add_life(self, life_img, count): if count < 3: count = 3 self.life = count for num in range(0, count): life = Life(life_img, [20 + num * life_img.get_rect().width, 20]) self.lifeGroup.add(life) self.lifeC.append(life)
def next(self): """产生下一代""" self.generation += 1 self.judge() do_best = self.domutation(self.best1.gene) push_best = self.pushmutation(self.best1.gene) newLives = [] newLives.append(Life(self.best.gene)) # 把最好的个体加入下一代 newLives.append(Life(do_best)) newLives.append(Life(push_best)) newLives.append(Life(self.best1.gene)) self.setRoulette() while len(newLives) < self.lifeCount: newLives.append(self.getOne()) newLives = self.crossover(newLives) newLives = self.mutation(newLives) self.lives = newLives
def newChild(self): parent1 = self.getOne() rate = random.random() if rate < self.crossRate: parent2 = self.getOne() gene = self.cross(parent1, parent2) else: gene = parent1.gene rate = random.random() if rate < self.mutationRate: gene = self.mutation(gene) return Life(gene)
def initPopulation(self): """初始化种群""" start1 = time.clock() self.lives = [] for i in range(self.lifeCount): gene = self.initLife() life = Life(gene) self.lives.append(life) end1 = time.clock() runtime = end1 - start1 print("----------------初始化种群,用时" + str(("%.2f") % (runtime)) + "秒------------------")
def __init__(self, sense): self.sense = sense self.FACE = 1, RobotFace(sense) self.RADIO = 2, Radio(sense) self.LIFE = 3, Life(sense, 8, 8) self.MUSICPLAYER = 4, MusicPlayer(sense) self.stateList = (self.FACE, self.RADIO, self.LIFE, self.MUSICPLAYER) # Start with some state self.current = self.MUSICPLAYER self.current[1].select()
def test_fut_curr_3(self): x = Life(5, 3, [['-','-','-'], ['0','1','0'], ['0','-','-'], ['-','-','0'], ['*','0','-']]) x.future = '-' x.moat_grid() x.fut_curr() x.grid[2][3].count = 0 x.grid[2][3].state = '-'
def test_fut_curr_2(self): x = Life(5, 3, [['.','.','.'], ['*','.','.'], ['*','*','*'], ['.','.','*'], ['.','.','*']]) x.future = '*' x.moat_grid() x.fut_curr() x.grid[2][2].count = 0 x.grid[2][2].state = '*'\
def initPopulation(self): """初始化种群""" self.lives = [] for _ in range(self.lifeCount): # gene = [0,1,…… ,self.geneLength-1] gene = list(range(self.geneLength)) # 将0到33序列的所有元素随机排序得到一个新的序列 random.shuffle(gene) # Life这个类就是一个基因序列,初始化life的时候,两个参数,一个是序列gene,一个是这个序列的初始适应度值 # 因为适应度值越大,越可能被选择,所以一开始种群里的所有基因都被初始化为-1 life = Life(gene) #把生成的这个基因序列life填进种群集合里 self.lives.append(life)
def __init__(self, width, height): super(SubWindow, self).__init__() self.width = width self.height = height self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.isUntitled = True widget = QtGui.QScrollArea() self.qp = QtGui.QPainter() if width and height: self.field = Field(width, height) self.setWidget(self.field) self.life = Life(width, height, False) self.reset() self.field.cells = self.life.cells
def next(self): start = time.clock() """产生下一代""" self.judge() newLives = [] newLives.extend(self.newChild()) while len(newLives) < self.lifeCount: newLives.append(Life(self.initLife())) self.lives = newLives self.generation += 1 end = time.clock() runtime = end - start print("----------------迭代一轮需要用时" + str(("%.2f") % (runtime)) + "秒------------------")
def test_life_11(self): l = Life(2,2) c1 = FredkinCell(True) c2 = FredkinCell(False) c3 = FredkinCell(False) c4 = FredkinCell(False) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.populationEvolve() assert str(l) == '-0\n0-'
def test_life_7(self): l = Life(2,2) c1 = ConwayCell(True) c2 = ConwayCell(True) c3 = ConwayCell(True) c4 = ConwayCell(True) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.countLives() l.livesCount == [[3,3],[3,3]]
def test_life_12(self): l = Life(2,2) c1 = ConwayCell(True) c2 = ConwayCell(True) c3 = ConwayCell(False) c4 = ConwayCell(True) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) l.populationEvolve() assert str(l) == '**\n**'
def next(self, n=1): # 演化至下n代 while n > 0: # self.__getBounds() self.judge(self.__judge) new_lives = [Life(self, self.best.gene)] # self.bestHistory.append(self.best) while len(new_lives) < self.life_count: new_lives.append(self.__new_child()) self.lives = new_lives self.generation += 1 # print("gen: %d, mutation: %d, best: %f" % (self.generation, self.mutationCount, self.best.score)) self.save(self.best, self.generation) n -= 1
def test_life_50(self): l = Life(2,2) c1 = FredkinCell(False) c2 = FredkinCell(False) c3 = FredkinCell(False) c4 = FredkinCell(False) l.addCell(0,0,c1) l.addCell(0,1,c2) l.addCell(1,0,c3) l.addCell(1,1,c4) assert l.getPopulation() == 0
def loadFile(self, fileName): file = QtCore.QFile(fileName) if not file.open( QtCore.QFile.ReadOnly | QtCore.QFile.Text): QtGui.QMessageBox.warning(self, "Reading error", "Cannot read file %s:\n%s." % (fileName, file.errorString())) return False instr = QtCore.QTextStream(file) start = False width = 0 lines = [] while not instr.atEnd(): line = instr.readLine() if width < len(line): width = len(line) if line[0] != '#': start = True lines.append(line) if line[0] == '#' and start: break height = len(lines) if not width or not height: return False self.width = width self.height = height self.field = Field(width, height) self.setWidget(self.field) self.life = Life(width, height, False) self.field.cells = self.life.cells y=0 for line in lines: x = 0 for char in line: if char == '*': self.life.cells[x,y] = True x += 1 y += 1 self.field.update() self.setCurrentFile(fileName) return True
# ------- import sys from Life import Life, AbstractCell, ConwayCell, FredkinCell, life_read # --------------------- # Life ConwayCell 21x13 # --------------------- print("*** Life ConwayCell 21x13 ***") """ Simulate 12 evolutions. Print every grid (i.e. 0, 1, 2, 3, ... 12) """ row, col, grid = life_read(sys.stdin) x = Life(row, col, grid) x.moat_grid() x.print_grid(12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # --------------------- # Life ConwayCell 20x29 # --------------------- print("*** Life ConwayCell 20x29 ***") """ Simulate 28 evolutions. Print every 4th grid (i.e. 0, 4, 8, ... 28) """ row, col, grid = life_read(sys.stdin) x = Life(row, col, grid) x.moat_grid()
def test_find_edges(self): l = Life(0, 20, 0, 20, self.alive) l.foerste() self.assertEqual(l.find_edges(0, 0), [(0, 1), (1, 1), (1, 0)])
def test_levende(self): l = Life(0, 20, 0, 20, self.alive) l.foerste() self.assertEqual(l.levende(10, 9), True)