def constructNextPopulation(self, currentFitnesses, currentPopulation): newPopulation = [] while len(newPopulation) < self.populationSize: candidate = self.selectCandidateBasedOnFitness(currentFitnesses) newCandidate = CandidateSolution(self.vocabulary, self.chromosomeSize) newCandidate.setChromosome(candidate.getChromosome()) if random.random() < self.mutationProbability: newCandidate.pointMutation(self.mutationProbability) newPopulation.append(newCandidate) elif random.random() < self.crossoverProbability: # One-point crossover # ( offspring1, offspring2 ) = self.recombineTwoCandidates_OnePivot( newCandidate, random.choice( currentPopulation ) ) # newPopulation.append( offspring1 ) # newPopulation.append( offspring2 ) # Two-point crossover (offspring1, offspring2, offspring3) = self.recombineTwoCandidates_TwoPivots( newCandidate, random.choice(currentPopulation) ) newPopulation.append(offspring1) newPopulation.append(offspring2) newPopulation.append(offspring3) elif random.random() < self.reproduceProbability: newPopulation.append(candidate) return newPopulation
def recombineTwoCandidates_OnePivot(self, candidateOne, candidateTwo): pivotIndex = random.randint(0, self.chromosomeSize - 1) offspringChromosome1 = candidateOne.getChromosome()[0:pivotIndex] offspringChromosome1 += candidateTwo.getChromosome()[pivotIndex:] offspringChromosome2 = candidateTwo.getChromosome()[0:pivotIndex] offspringChromosome2 += candidateOne.getChromosome()[pivotIndex:] offspring1 = CandidateSolution(self.vocabulary, self.chromosomeSize) offspring2 = CandidateSolution(self.vocabulary, self.chromosomeSize) offspring1.setChromosome(offspringChromosome1) offspring2.setChromosome(offspringChromosome2) return (offspring1, offspring2)