/// <summary> /// The entry point for this example. If you would like to make this example /// stand alone, then add to its own project and rename to Main. /// </summary> /// <param name="args">Not used.</param> public static void ExampleMain(string[] args) { // Create a new population. IPopulation pop = new BasicPopulation(); ISpecies species = pop.CreateSpecies(); // Create 1000 genomes, assign the score to be the index number. for (int i = 0; i < 1000; i++) { IGenome genome = new IntegerArrayGenome(1); genome.Score = i; genome.AdjustedScore = i; pop.Species[0].Add(genome); } IGenerateRandom rnd = new MersenneTwisterGenerateRandom(); // Create a trainer with a very simple score function. We do not care // about the calculation of the score, as they will never be calculated. // We only care that we are maximizing. IEvolutionaryAlgorithm train = new BasicEA(pop, new NullScore()); // Perform the test for round counts between 1 and 10. for (int roundCount = 1; roundCount <= 10; roundCount++) { var selection = new TournamentSelection(train, roundCount); int sum = 0; int count = 0; for (int i = 0; i < 100000; i++) { int genomeID = selection.PerformSelection(rnd, species); IGenome genome = species.Members[genomeID]; sum += (int) genome.AdjustedScore; count++; } sum /= count; Console.WriteLine("Rounds: " + roundCount + ", Avg Score: " + sum); } }
/// <summary> /// Construct an EA. /// </summary> /// <param name="thePopulation">The population.</param> /// <param name="theScoreFunction">The score function.</param> public BasicEA(IPopulation thePopulation, IScoreFunction theScoreFunction) { RandomNumberFactory = new MersenneTwisterFactory(); EliteRate = 0.3; MaxTries = 5; MaxOperationErrors = 500; CODEC = new GenomeAsPhenomeCODEC(); Population = thePopulation; ScoreFunction = theScoreFunction; Selection = new TournamentSelection(this, 4); // set the score compare method if (theScoreFunction.ShouldMinimize) { SelectionComparer = new MinimizeAdjustedScoreComp(); BestComparer = new MinimizeScoreComp(); } else { SelectionComparer = new MaximizeAdjustedScoreComp(); BestComparer = new MaximizeScoreComp(); } // set the iteration foreach (ISpecies species in thePopulation.Species) { foreach (IGenome genome in species.Members) { IterationNumber = Math.Max(IterationNumber, genome.BirthGeneration); } } // Set a best genome, just so it is not null. // We won't know the true best genome until the first iteration. if (Population.Species.Count > 0 && Population.Species[0].Members.Count > 0) { BestGenome = Population.Species[0].Members[0]; } }