def ga(maxPop, mutation_rate, chromosome_length, maxGen): pop = Population(maxPop, mutation_rate, chromosome_length=chromosome_length) # populating with maxPop elements pop.populate() i = 0 for i in range(maxGen): # calculating fitness pop.calc_fitness() # natural selection parents = pop.selection() # crossover + mutation pop.crossover(parents) pop.mutate() # printing print('Gen ' + str(i) + ": ", pop.getFittest()[0], pop.getAvgFitness()) pop.population[pop.getFittest()[1]].plot() pop.population[pop.getFittest()[1]].plot()
class PopulationTestCase(TestCase): def setUp(self): self.population = Population() def testMutateCross(self): fake_cm_plugin = FakeCmPlugin() self.population.individuals = [1, 2, 3] self.population(fake_cm_plugin) self.population.mutate() self.population.cross() self.assertEqual(self.population.cm_plugin, fake_cm_plugin) self.assertEqual( fake_cm_plugin.c_count, fake_cm_plugin.m_count) def testSelect(self): fake_selector = FakeSelector() self.population.use_selector(fake_selector) self.population.individuals = [1, 2, 3] self.population.select() self.assertEqual( fake_selector.i_count, len(self.population.individuals))