public static Population EvolvePopulation(Population p) { Population newPopulation = new Population(p.Size(), false); if (elitism) { newPopulation.SaveIndividual(0, p.GetFittest()); } int elitismOffset; if (elitism) { elitismOffset = 1; } else { elitismOffset = 0; } for (int i = elitismOffset; i < p.Size(); i++) { Individual indiv1 = TournamentSelection(p); Individual indiv2 = TournamentSelection(p); Individual newIndiv = Crossover(indiv1, indiv2); newPopulation.SaveIndividual(i, newIndiv); } for (int i = elitismOffset; i < newPopulation.Size(); i++) { Mutate(newPopulation.GetIndividual(i)); } return(newPopulation); }
void RunGA() { FitnessCalculator.SetSolution("1111000000000001111000000000000000000000000000000000000000001111"); Population pop = new Population(6, true); int epoch = 0; while (pop.GetFittest().GetFitness() < FitnessCalculator.GetMaxFitness()) { epoch++; pop = Algorithm.EvolvePopulation(pop); System.Console.WriteLine("Generation: " + epoch + " Fittest: " + pop.GetFittest().GetFitness()); System.Console.WriteLine(pop.GetFittest()); } System.Console.WriteLine("Solution found"); System.Console.WriteLine("Generation: " + epoch); System.Console.WriteLine("Genes:"); System.Console.WriteLine(pop.GetFittest()); }
/// <summary> /// /// </summary> /// <param name="p"></param> /// <returns></returns> private static Individual TournamentSelection(Population p) { Population tournament = new Population(tournamentSize, false); Random rndgen = new Random(); for (int i = 0; i < tournamentSize; i++) { int randomID = (int)(rndgen.NextDouble() * p.Size()); tournament.SaveIndividual(i, p.GetIndividual(randomID)); } Individual fittest = tournament.GetFittest(); return(fittest); }
void Start() { //We need to set a candidate solution (feel free ti change this if you want to) FitnessCalc.SetSolution(new byte[] { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }); //Create initial population, a population of 50 should be fine Population myPop = new Population(50, true); int generationCount = 0; int bestFittness = 0; while (myPop.GetFittest().GetFitness() < FitnessCalc.GetMaxFitness()) { generationCount++; if (myPop.GetFittest().GetFitness() > bestFittness) { Console.WriteLine("Generation: " + generationCount + " Fittest: " + myPop.GetFittest().GetFitness()); Console.WriteLine("Fittest: "); foreach (byte b in myPop.GetFittest().GetGenes()) { Console.Write(b); } Console.WriteLine(""); bestFittness = myPop.GetFittest().GetFitness(); } myPop = Algorithm.EvolvePopulation(myPop); } Console.WriteLine("Solution found!"); Console.WriteLine("Generation: " + generationCount); Console.WriteLine("Genes: "); Console.WriteLine(myPop.GetFittest()); }