/// <summary> /// Setup and solve the TSP. /// </summary> public void Execute(IExampleInterface app) { this.app = app; var builder = new StringBuilder(); initCities(); IPopulation pop = initPopulation(); ICalculateScore score = new TSPScore(cities); genetic = new TrainEA(pop, score); genetic.AddOperation(0.9, new SpliceNoRepeat(CITIES / 3)); genetic.AddOperation(0.1, new MutateShuffle()); int sameSolutionCount = 0; int iteration = 1; double lastSolution = Double.MaxValue; while (sameSolutionCount < MAX_SAME_SOLUTION) { genetic.Iteration(); double thisSolution = genetic.Error; builder.Length = 0; builder.Append("Iteration: "); builder.Append(iteration++); builder.Append(", Best Path Length = "); builder.Append(thisSolution); Console.WriteLine(builder.ToString()); if (Math.Abs(lastSolution - thisSolution) < 1.0) { sameSolutionCount++; } else { sameSolutionCount = 0; } lastSolution = thisSolution; } Console.WriteLine("Good solution found:"); displaySolution(); genetic.FinishTraining(); }
/// <summary> /// Setup and solve the TSP. /// </summary> public void Execute(IExampleInterface app) { this.app = app; var builder = new StringBuilder(); initCities(); IPopulation pop = initPopulation(); ICalculateScore score = new TSPScore(cities); genetic = new TrainEA(pop,score); genetic.AddOperation(0.9,new SpliceNoRepeat(CITIES/3)); genetic.AddOperation(0.1,new MutateShuffle()); int sameSolutionCount = 0; int iteration = 1; double lastSolution = Double.MaxValue; while (sameSolutionCount < MAX_SAME_SOLUTION) { genetic.Iteration(); double thisSolution = genetic.Error; builder.Length = 0; builder.Append("Iteration: "); builder.Append(iteration++); builder.Append(", Best Path Length = "); builder.Append(thisSolution); Console.WriteLine(builder.ToString()); if (Math.Abs(lastSolution - thisSolution) < 1.0) { sameSolutionCount++; } else { sameSolutionCount = 0; } lastSolution = thisSolution; } Console.WriteLine("Good solution found:"); displaySolution(); genetic.FinishTraining(); }
private void initPopulation(GeneticAlgorithm ga) { ICalculateGenomeScore score = new TSPScore(cities); ga.CalculateScore = score; IPopulation population = new BasicPopulation(POPULATION_SIZE); ga.Population = population; for (int i = 0; i < POPULATION_SIZE; i++) { var genome = new TSPGenome(ga, cities); ga.Population.Genomes.Add(genome); ga.PerformCalculateScore(genome); } population.Sort(); }