public GeneticAlgorithm(int elitismSize, GrammaticalEvolution ge, FitnessCalculator fitnessCalculator, Selection selection, Crossover crossover, Mutation mutation, Population population, ExecutionParameters parameters) { ElitismSize = elitismSize; GE = ge; _FitnessCalculator = fitnessCalculator; Selection = selection; Crossover = crossover; Mutation = mutation; Population = population; Parameters = parameters; }
public GeneticAlgorithmResult Evolve(int generations, double crossoverProbability, double mutationProbability, double duplicationProbability, double pruningProbability) { GeneticAlgorithmResult result = new GeneticAlgorithmResult(); result.stats = new List <GenerationStats>(); //Evaluate and save the results of the first generation Console.WriteLine("Eseguendo generazione iniziale"); Evaluate(Population.CurrentGeneration); Population.CurrentGeneration.Stats.fitnessValues = Population.CurrentGeneration.Select(x => x.Fitness.Value).ToList(); Population.CurrentGeneration.Stats.bestChromosome = Population.CurrentGeneration.OrderByDescending(x => x.Fitness).First(); result.stats.Add(Population.CurrentGeneration.Stats); for (int i = 1; i < generations; i++) { Console.WriteLine("Eseguendo generazione " + (i + 1) + " di " + generations); Generation newGeneration = new Generation(); //Finds all the individuals with a valid fitness and takes the best ones int elitesNumber = Math.Min(Population.CurrentGeneration.FindAll(x => x.Fitness.HasValue).Count, ElitismSize); List <Chromosome> elites = Population.CurrentGeneration.OrderByDescending(x => x.Fitness.Value).Take(elitesNumber).Select(x => x.GetClone()).ToList(); int newGenerationSize = Population.CurrentGeneration.Count - elitesNumber; while (newGeneration.Count < newGenerationSize) { Tuple <Chromosome, Chromosome> parents = Selection.Select(Population.CurrentGeneration); Tuple <Chromosome, Chromosome> children = Crossover.Cross(parents.Item1, parents.Item2, crossoverProbability); //If there is room for only one individual, choose randomly if (newGeneration.Count == newGenerationSize - 1) { if (GrammaticalEvolution.random.NextDouble() > 0.5) { newGeneration.Add(children.Item1); } else { newGeneration.Add(children.Item2); } } else { newGeneration.Add(children.Item1); newGeneration.Add(children.Item2); } } foreach (Chromosome c in newGeneration) { Mutation.Mutate(c, mutationProbability); } Evaluate(newGeneration); Prune(newGeneration, pruningProbability); Duplicate(newGeneration, duplicationProbability); newGeneration.AddRange(elites); newGeneration.Stats.fitnessValues = newGeneration.Select(x => x.Fitness.Value).ToList(); newGeneration.Stats.bestChromosome = newGeneration.OrderByDescending(x => x.Fitness).First().GetClone(); Population.Add(newGeneration); //We remove the chromosomes of older generations (but store their fitness) if (!SaveChromosomes && Population.Count > 1) { Population[Population.Count - 2].Clear(); } result.stats.Add(newGeneration.Stats); } return(result); }