/// <summary> /// Performs the elite operator. /// This will copy the best chromosones from the current population to the next population /// </summary> /// <param name="currentPopulation">The current population.</param> /// <param name="nextPopulation">The next population.</param> public virtual void Process(Population currentPopulation, Population nextPopulation) { var amountToKeep = (int)(_elitePercentage * currentPopulation.Count); for (var x = 0; x < amountToKeep; ++x) { nextPopulation.Add(currentPopulation[x].Clone()); } }
/// <summary> /// Creates a new population. /// </summary> /// <param name="population">The current population.</param> /// <param name="elite">The elite operator.</param> /// <param name="mutate">The mutate operator.</param> /// <param name="crossover">The crossover operator.</param> /// <param name="diversify">The diversify operator.</param> /// <returns></returns> public Population CreateNewPopulation(Population population, IElite elite, IMutate mutate, ICrossOver crossover, IDiversify diversify) { IChromosome parent1, parent2; IChromosome child1 = null, child2 = null; // create a new population var nextPopulation = new Population(); // copy all elites to the new population elite?.Process(population, nextPopulation); // make sure the population is diversified enough diversify?.Process(nextPopulation, population.Count); // while next population is not filled completely while (nextPopulation.Count < population.Count) { // select 2 parents DoTournament(population, out parent1, out parent2); // perform crossover so we get 2 children crossover?.Process(parent1, parent2, out child1, out child2); // mutate both children mutate?.Process(child1); mutate?.Process(child2); // and add the children to the next population nextPopulation.Add(child1); if (nextPopulation.Count < population.Count) { nextPopulation.Add(child2); } } return(nextPopulation); }
/// <summary> /// Adds new random chromosone to the next population to make sure the population is diversified enough. /// </summary> /// <param name="nextPopulation">The next population.</param> /// <param name="populationSize">Size of the population.</param> public void Process(Population nextPopulation, int populationSize) { var amount = (int)(populationSize * _replacePopulationPercentage); for (var i = 0; i < amount; ++i) { var chromosome = CreateRandomChromosome(); if (chromosome != null) { nextPopulation.Add(chromosome); } if (nextPopulation.Count >= populationSize) { return; } } }