from genetic import * """ Test code for the genetic module. Numeric DNA @author Scott Hurring (scott at hurring dot com) @uri http://hurring.com/code/python/genetic/ @license GPL """ class MyCell(Cell): length = 10 name = "NumericCell" def init(self): self.dna = [0,0,0,0,0,0,0,0,0,0] def randomize(self): for i in range(self.length): self.dna[i] = (random.random()>0.5) def clone(self): return MyCell() def get(self, i): return self.dna[i] def set(self, i, value): self.dna[i] = value def mutate(self, value): """mutate a piece of my dna by flipping the bit""" return not value class MyFitnessJudge(object): """Judge fitness of a cell""" def fitness(self, cell): maximum = int(pow(2,cell.length)-1) step = 100.0 / maximum # The fitness target # The closer a cell gets to this number, the better its score target = 39 raw = 0 for i in range(cell.length): raw += pow(2, i) * cell.dna[i] score = 100 - (abs(raw-target) * step) return score if __name__ == '__main__': # Number of generations to run numgens = 10 # Number of cells per generation numcells = 10 # Create Nature and tell it how to judge cells nature = Nature(MyFitnessJudge()) # Adjust the breed percentage since we're using a small number of cells nature.breed_pct = 0.20 # Setup initial population population = nature.initial_population(MyCell, numcells) # Run simulation for a number of generations population = nature.run(population, numgens)