/// <summary> /// Setup and solve the TSP. /// </summary> public void Solve() { IGenerateRandom rnd = new MersenneTwisterGenerateRandom(); var builder = new StringBuilder(); InitCities(rnd); IPopulation pop = InitPopulation(rnd); IScoreFunction score = new TSPScore(_cities); _genetic = new BasicEA(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 < MaxSameSolution) { _genetic.Iteration(); double thisSolution = _genetic.LastError; 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:"); var best = (IntegerArrayGenome)_genetic.BestGenome; DisplaySolution(best); _genetic.FinishTraining(); }
/// <summary> /// Process the specified file. /// </summary> /// <param name="filename">The filename to process.</param> public void Process(String filename) { // read the data from the resources Assembly assembly = Assembly.GetExecutingAssembly(); Stream res = assembly.GetManifestResourceStream("AIFH_Vol2.Resources.simple-poly.csv"); // did we fail to read the resouce if (res == null) { Console.WriteLine("Can't read iris data from embedded resources."); return; } // load the data var istream = new StreamReader(res); DataSet ds = DataSet.Load(istream); istream.Close(); // Extract supervised training. IList<BasicData> training = ds.ExtractSupervised(0, 1, 1, 1); IGenerateRandom rnd = new MersenneTwisterGenerateRandom(); var eval = new EvaluateExpression(rnd); IPopulation pop = InitPopulation(rnd, eval); IScoreFunction score = new ScoreSmallExpression(training, 30); IEvolutionaryAlgorithm genetic = new BasicEA(pop, score); genetic.AddOperation(0.3, new MutateTree(3)); genetic.AddOperation(0.7, new CrossoverTree()); genetic.ShouldIgnoreExceptions = false; int sameSolutionCount = 0; int iteration = 1; double lastSolution = double.MaxValue; var builder = new StringBuilder(); while (sameSolutionCount < MaxSameSolution && iteration < 1000) { genetic.Iteration(); double thisSolution = genetic.LastError; builder.Length = 0; builder.Append("Iteration: "); builder.Append(iteration++); builder.Append(", Current error = "); builder.Append(thisSolution); builder.Append(", Best Solution Length = "); builder.Append(genetic.BestGenome.Count); Console.WriteLine(builder.ToString()); if (Math.Abs(lastSolution - thisSolution) < 1.0) { sameSolutionCount++; } else { sameSolutionCount = 0; } lastSolution = thisSolution; } Console.WriteLine("Good solution found:"); var best = (TreeGenome) genetic.BestGenome; Console.WriteLine(eval.DisplayExpressionNormal(best.Root)); genetic.FinishTraining(); }