public void TornamentTest() { var minGenes = 10; var maxGenes = 20; var geneset = CreateGeneSet(); var watch = Stopwatch.StartNew(); void FnDisplay(List <Rule> genes, int wins, int ties, int losses, int generation) { Console.WriteLine("-- generation {0} --", generation); Display( new Chromosome <Rule, Fitness>(genes, new Fitness(wins, ties, losses, genes.Count), Strategy.None), watch); } var mutationRoundCounts = new List <int> { 1 }; var mutationOperators = new FnMutateDelegate[] { genes => MutateAdd(genes, geneset), genes => MutateReplace(genes, geneset), MutateRemove, MutateSwapAdjacent, MutateMove, }; void FnMutate(List <Rule> genes) => Mutate(genes, x => new Fitness(0, 0, 0, 0), mutationOperators, mutationRoundCounts); List <Rule> FnCrossover(IReadOnlyList <Rule> parent, IReadOnlyList <Rule> doner) { var child = parent.Take(parent.Count / 2).Concat(doner.Skip(doner.Count / 2)).ToList(); FnMutate(child); return(child); } List <Rule> FnCreate() => Rand.RandomSample(geneset, Rand.Random.Next(minGenes, maxGenes)); int FnSortKey(List <Rule> genes, int wins, int ties, int losses) => - 1000 * losses - ties + 1 / genes.Count; var unused = Genetic <Rule, Fitness> .Tournament(FnCreate, FnCrossover, PlayOneOnOne, FnDisplay, FnSortKey, 13); }
public void PerfectKnowledgeTest() { var minGenes = 10; var maxGenes = 20; var geneset = CreateGeneSet(); var watch = Stopwatch.StartNew(); void FnDisplay(Chromosome <Rule, Fitness> candidate, int?length) => Display(candidate, watch); Fitness FnGetFitness(IReadOnlyList <Rule> genes) => GetFitness(genes); var mutationRoundCounts = new List <int> { 1 }; var mutationOperators = new FnMutateDelegate[] { genes => MutateAdd(genes, geneset), genes => MutateReplace(genes, geneset), MutateRemove, MutateSwapAdjacent, MutateMove, }; void FnMutate(List <Rule> genes) => Mutate(genes, FnGetFitness, mutationOperators, mutationRoundCounts); List <Rule> FnCrossover(IReadOnlyList <Rule> parent, IReadOnlyList <Rule> doner) { var child = parent.Take(parent.Count / 2).Concat(doner.Skip(doner.Count / 2)).ToList(); FnMutate(child); return(child); } List <Rule> FnCreate() => Rand.RandomSample(geneset, Rand.Random.Next(minGenes, maxGenes)); var optimalFitness = new Fitness(620, 120, 0, 11); var best = Genetic <Rule, Fitness> .GetBest(FnGetFitness, minGenes, optimalFitness, null, FnDisplay, FnMutate, FnCreate, 500, 20, FnCrossover); Assert.IsTrue(optimalFitness.CompareTo(best.Fitness) <= 0); }