Esempio n. 1
0
 internal GeneticAlgorithm(
     IMutator <T> mutator,
     ICrossOver <T> crossOver,
     IPopulationCreator <T> populationCreator,
     int populationSize,
     double mutationProbability,
     int maxGenerations,
     int eliteSize,
     double solutionPrecision,
     Func <T[], int> fitnessFunction)
 {
     this.mutator             = mutator;
     this.crossOver           = crossOver;
     this.populationCreator   = populationCreator;
     this.populationSize      = populationSize;
     this.mutationProbability = mutationProbability;
     this.fitnessFunction     = fitnessFunction;
     this.maxGenerations      = maxGenerations;
     this.eliteSize           = eliteSize;
     this.solutionPrecision   = solutionPrecision;
 }
Esempio n. 2
0
        /// <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);
        }
Esempio n. 3
0
 /// <summary>
 /// Adds the specified crossover operator
 /// </summary>
 /// <param name="elite">The crossover operator</param>
 public void Add(ICrossOver crossover)
 {
     _crossover = crossover;
 }