Exemplo n.º 1
0
        public void Cross_DocumentationSample_Child()
        {
            var target = new VotingRecombinationCrossover(4, 3);

            // 1 4 3 5 2 6
            var chromosome1 = Substitute.For <ChromosomeBase>(6);

            chromosome1.ReplaceGenes(0, new Gene[] {
                new Gene(1),
                new Gene(4),
                new Gene(3),
                new Gene(5),
                new Gene(2),
                new Gene(6)
            });

            var child = Substitute.For <ChromosomeBase>(6);

            child.GenerateGene(2).Returns(new Gene(22));
            child.GenerateGene(3).Returns(new Gene(33));
            child.GenerateGene(4).Returns(new Gene(44));
            chromosome1.CreateNew().Returns(child);

            // 1 2 4 3 5 6
            var chromosome2 = Substitute.For <ChromosomeBase>(6);

            chromosome2.ReplaceGenes(0, new Gene[]
            {
                new Gene(1),
                new Gene(2),
                new Gene(4),
                new Gene(3),
                new Gene(5),
                new Gene(6)
            });

            // 3 2 1 5 4 6
            var chromosome3 = Substitute.For <ChromosomeBase>(6);

            chromosome3.ReplaceGenes(0, new Gene[]
            {
                new Gene(3),
                new Gene(2),
                new Gene(1),
                new Gene(5),
                new Gene(4),
                new Gene(6)
            });

            // 1 2 3 4 5 6
            var chromosome4 = Substitute.For <ChromosomeBase>(6);

            chromosome4.ReplaceGenes(0, new Gene[]
            {
                new Gene(1),
                new Gene(2),
                new Gene(3),
                new Gene(4),
                new Gene(5),
                new Gene(6)
            });

            var actual = target.Cross(new List <IChromosome>()
            {
                chromosome1, chromosome2, chromosome3, chromosome4
            });

            Assert.AreEqual(1, actual.Count);
            var actualChild = actual[0];

            Assert.AreEqual(6, actualChild.Length);

            Assert.AreEqual(1, actualChild.GetGene(0).Value);
            Assert.AreEqual(2, actualChild.GetGene(1).Value);
            Assert.AreEqual(22, actualChild.GetGene(2).Value);
            Assert.AreEqual(33, actualChild.GetGene(3).Value);
            Assert.AreEqual(44, actualChild.GetGene(4).Value);
            Assert.AreEqual(6, actualChild.GetGene(5).Value);
        }
Exemplo n.º 2
0
        private void EvolveGeneticStrategyButton_Click(object sender, RoutedEventArgs e)
        {
            OutputTextBlock.Text = "Evolving...";

            Task.Run(() =>
            {
                var chromosome = new BlackjackChromosome();
                var fitness    = new BlackjackFitness();
                var population = new Population(Settings.GeneticSettings.MinPopulationSize, Settings.GeneticSettings.MaxPopulationSize, chromosome);

                ISelection selection;

                switch (Settings.GeneticSettings.SelectionType)
                {
                case SelectionType.Elite:
                    selection = new EliteSelection();
                    break;

                case SelectionType.RouletteWheel:
                    selection = new RouletteWheelSelection();
                    break;

                case SelectionType.StochasticUniversalSampling:
                    selection = new StochasticUniversalSamplingSelection();
                    break;

                case SelectionType.Tournament:
                    selection = new TournamentSelection(Settings.GeneticSettings.TournamentSize);
                    break;

                default:
                    throw new InvalidOperationException();
                }

                ICrossover crossover;

                switch (Settings.GeneticSettings.CrossoverType)
                {
                case CrossoverType.AlternatingPosition:
                    crossover = new AlternatingPositionCrossover();
                    break;

                case CrossoverType.CutAndSplice:
                    crossover = new CutAndSpliceCrossover();
                    break;

                case CrossoverType.Cycle:
                    crossover = new CycleCrossover();
                    break;

                case CrossoverType.OnePoint:
                    crossover = new OnePointCrossover();
                    break;

                case CrossoverType.TwoPoint:
                    crossover = new TwoPointCrossover();
                    break;

                case CrossoverType.OrderBased:
                    crossover = new OrderBasedCrossover();
                    break;

                case CrossoverType.Ordered:
                    crossover = new OrderedCrossover();
                    break;

                case CrossoverType.PartiallyMapped:
                    crossover = new PartiallyMappedCrossover();
                    break;

                case CrossoverType.PositionBased:
                    crossover = new PositionBasedCrossover();
                    break;

                case CrossoverType.ThreeParent:
                    crossover = new ThreeParentCrossover();
                    break;

                case CrossoverType.Uniform:
                    crossover = new UniformCrossover(Settings.Current.GeneticSettings.MixProbability);
                    break;

                case CrossoverType.VotingRecombination:
                    crossover = new VotingRecombinationCrossover();
                    break;

                default:
                    throw new InvalidOperationException();
                }

                var mutation     = new UniformMutation();
                var termination  = new FitnessStagnationTermination(Settings.Current.GeneticSettings.NumStagnantGenerations);
                var taskExecutor = new ParallelTaskExecutor();

                var ga = new GeneticAlgorithm(
                    population,
                    fitness,
                    selection,
                    crossover,
                    mutation);

                ga.Termination          = termination;
                ga.TaskExecutor         = taskExecutor;
                ga.MutationProbability  = Settings.GeneticSettings.MutationProbability;
                ga.CrossoverProbability = Settings.GeneticSettings.CrossoverProbability;

                var latestFitness = double.MinValue;

                ga.GenerationRan += (s, o) =>
                {
                    geneticStrategy = (IStrategy)ga.BestChromosome;

                    var generationNumber = ga.GenerationsNumber;
                    var bestFitness      = ga.BestChromosome.Fitness.Value;
                    var avgFitness       = ga.Population.CurrentGeneration.Chromosomes.Average(c => c.Fitness.Value);

                    Dispatcher.Invoke(() =>
                    {
                        if (generationNumber == 1)
                        {
                            OutputTextBlock.Text = string.Empty;
                        }

                        OutputTextBlock.Text = $"Gen: {generationNumber}\tFit: {bestFitness}\tAvg: {avgFitness.ToString("0")}\n" + OutputTextBlock.Text;

                        if (bestFitness != latestFitness)
                        {
                            latestFitness = bestFitness;

                            var savedImageName = Settings.Current.GeneticSettings.SaveImagePerGeneration ? "gen" + generationNumber : null;

                            StrategyViewer.Draw(GeneticStrategyCanvas, geneticStrategy, $"Best from generation {generationNumber}", savedImageName);
                        }
                    }, DispatcherPriority.Background);
                };

                ga.TerminationReached += (s, o) =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        OutputTextBlock.Text = "Termination reached.\n" + OutputTextBlock.Text;
                        TestGeneticStrategyButton.IsEnabled = true;
                    }, DispatcherPriority.Background);
                };

                ga.Start();
            });
        }
        public IList <IChromosome> VotingRecombinationCrossover()
        {
            var target = new VotingRecombinationCrossover();

            return(target.Cross(CreateThreeParents()));
        }