Example #1
0
        public void ItCanPerformCrossover()
        {
            var one = GATestHelper.GetNumericChromosomeOne();
            var two = GATestHelper.GetNumericChromosomeTwo();

            var cc    = new CycleCrossover();
            var child = cc.Execute(one, two, GATestHelper.GetTravelingSalesmanDefaultConfiguration());

            Assert.AreEqual("1,2,6,4,5,3,7", string.Join(",", (IEnumerable <Gene>)child.Genes));
        }
Example #2
0
        public void ItCanDetermineTheCycle()
        {
            var one = GATestHelper.GetNumericChromosomeOne();
            var two = GATestHelper.GetNumericChromosomeTwo();

            var cc = new CycleCrossover();

            cc.Execute(one, two, GATestHelper.GetTravelingSalesmanDefaultConfiguration());

            Assert.AreEqual("0,4,1,3,6", string.Join(",", cc.Cycle));
        }
Example #3
0
        public void Cross_ParentWithNoOrderedGenes_Exception()
        {
            var target = new CycleCrossover();

            var chromosome1 = MockRepository.GenerateStub <ChromosomeBase>(10);

            chromosome1.ReplaceGenes(0, new Gene[] {
                new Gene(8),
                new Gene(4),
                new Gene(7),
                new Gene(3),
                new Gene(6),
                new Gene(2),
                new Gene(5),
                new Gene(1),
                new Gene(9),
                new Gene(0)
            });
            chromosome1.Expect(c => c.CreateNew()).Return(MockRepository.GenerateStub <ChromosomeBase>(10));

            var chromosome2 = MockRepository.GenerateStub <ChromosomeBase>(10);

            chromosome2.ReplaceGenes(0, new Gene[]
            {
                new Gene(0),
                new Gene(1),
                new Gene(2),
                new Gene(3),
                new Gene(5),
                new Gene(5),
                new Gene(6),
                new Gene(7),
                new Gene(8),
                new Gene(9),
            });
            chromosome2.Expect(c => c.CreateNew()).Return(MockRepository.GenerateStub <ChromosomeBase>(10));

            ExceptionAssert.IsThrowing(new CrossoverException(target, "The Cycle Crossover (CX) can be only used with ordered chromosomes. The specified chromosome has repeated genes."), () =>
            {
                target.Cross(new List <IChromosome>()
                {
                    chromosome1, chromosome2
                });
            });
        }
        public void Cross_ParentWithNoOrderedGenes_Exception()
        {
            var target = new CycleCrossover();

            var chromosome1 = Substitute.For <ChromosomeBase>(10);

            chromosome1.ReplaceGenes(0, new Gene[] {
                new Gene(8),
                new Gene(4),
                new Gene(7),
                new Gene(3),
                new Gene(6),
                new Gene(2),
                new Gene(5),
                new Gene(1),
                new Gene(9),
                new Gene(0)
            });
            chromosome1.CreateNew().Returns(Substitute.For <ChromosomeBase>(10));

            var chromosome2 = Substitute.For <ChromosomeBase>(10);

            chromosome2.ReplaceGenes(0, new Gene[]
            {
                new Gene(0),
                new Gene(1),
                new Gene(2),
                new Gene(3),
                new Gene(5),
                new Gene(5),
                new Gene(6),
                new Gene(7),
                new Gene(8),
                new Gene(9),
            });
            chromosome2.CreateNew().Returns(Substitute.For <ChromosomeBase>(10));

            Assert.Catch <CrossoverException>(() =>
            {
                target.Cross(new List <IChromosome>()
                {
                    chromosome1, chromosome2
                });
            }, "The Cycle Crossover (CX) can be only used with ordered chromosomes. The specified chromosome has repeated genes.");
        }
Example #5
0
        public void CxOperatorShouldReturnCorrectChildren()
        {
            IGene[] parent1 = new IGene[]
            {
                new UintGene(1), new UintGene(2), new UintGene(3),
                new UintGene(4), new UintGene(5), new UintGene(6),
                new UintGene(7), new UintGene(8), new UintGene(9)
            };
            IGene[] parent2 = new IGene[]
            {
                new UintGene(4), new UintGene(1), new UintGene(2),
                new UintGene(8), new UintGene(7), new UintGene(6),
                new UintGene(9), new UintGene(3), new UintGene(5)
            };
            IGene[] expectedChild1 = new IGene[]
            {
                new UintGene(1), new UintGene(2), new UintGene(3),
                new UintGene(4), new UintGene(7), new UintGene(6),
                new UintGene(9), new UintGene(8), new UintGene(5)
            };
            IGene[] expectedChild2 = new IGene[]
            {
                new UintGene(4), new UintGene(1), new UintGene(2),
                new UintGene(8), new UintGene(5), new UintGene(6),
                new UintGene(7), new UintGene(3), new UintGene(9)
            };
            var cx = new CycleCrossover();

            IGene[] child1, child2;
            cx.Run(parent1, parent2, out child1, out child2);
            bool areFirstChildrenEqual  = AreChildrenEqual(expectedChild1, child1);
            bool areSecondChildrenEqual = AreChildrenEqual(expectedChild2, child2);

            Assert.AreEqual(true, areFirstChildrenEqual);
            Assert.AreEqual(true, areSecondChildrenEqual);
        }
Example #6
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();
            });
        }
Example #7
0
        private static IAlgoritmo CriaAlgoritmoGenetico(Dictionary <string, string[]> dict, List <string> flat, Problema problema)
        {
            int         populacaoMin, populacaoMax;
            IPopulation population;

            ISelection   selection;
            ICrossover   crossover;
            IMutation    mutation;
            ITermination termination;
            IReinsertion reinsertion;
            float        crossoverProbability, mutationProbability;



            var p = dict.ValueOrDefault("p", "50,100").Split(new[] { ',' });

            if (p.Length != 2 || !int.TryParse(p[0], out populacaoMin) || !int.TryParse(p[1], out populacaoMax))
            {
                throw new ArgumentException("Faixa de população inválida.");
            }

            population = new Population(populacaoMin, populacaoMax, new CromossomoViajante(problema.Mapa.Locais.Count));

            switch (dict.ValueOrDefault("s", "t"))
            {
            case "e":
                selection = new EliteSelection();
                break;

            case "r":
                selection = new RouletteWheelSelection();
                break;

            case "s":
                selection = new StochasticUniversalSamplingSelection();
                break;

            case "t":
                selection = new TournamentSelection();
                break;

            default:
                throw new ArgumentException("Seleção inválida.");
            }

            switch (dict.ValueOrDefault("c", "o"))
            {
            case "s":
                crossover = new CutAndSpliceCrossover();
                break;

            case "c":
                crossover = new CycleCrossover();
                break;

            case "o":
                crossover = new OrderedCrossover();
                break;

            case "ob":
                crossover = new OrderBasedCrossover();
                break;

            case "op":
                crossover = new OnePointCrossover();
                break;

            case "pm":
                crossover = new PartiallyMappedCrossover();
                break;

            case "p":
                crossover = new PositionBasedCrossover();
                break;

            case "tpa":
                crossover = new ThreeParentCrossover();
                break;

            case "tp":
                crossover = new TwoPointCrossover();
                break;

            case "u":
                crossover = new UniformCrossover();
                break;

            default:
                throw new ArgumentException("Crossover inválido.");
            }

            switch (dict.ValueOrDefault("m", "r"))
            {
            case "d":
                mutation = new DisplacementMutation();
                break;

            case "f":
                mutation = new FlipBitMutation();
                break;

            case "i":
                mutation = new InsertionMutation();
                break;

            case "s":
                mutation = new PartialShuffleMutation();
                break;

            case "r":
                mutation = new ReverseSequenceMutation();
                break;

            case "t":
                mutation = new TworsMutation();
                break;

            case "u":
                mutation = new UniformMutation();
                break;

            default:
                throw new ArgumentException("Mutação inválida.");
            }

            switch (dict.ValueOrDefault("t", "s"))
            {
            case "s":
                termination = new FitnessStagnationTermination();
                break;

            case "t":
                termination = new FitnessThresholdTermination();
                break;

            case "g":
                termination = new GenerationNumberTermination();
                break;

            default:
                throw new ArgumentException("Terminação inválida.");
            }

            switch (dict.ValueOrDefault("e", "e"))
            {
            case "e":
                reinsertion = new ElitistReinsertion();
                break;

            case "p":
                reinsertion = new PureReinsertion();
                break;

            case "u":
                reinsertion = new UniformReinsertion();
                break;

            default:
                throw new ArgumentException("Reinserção inválida.");
            }

            if (!float.TryParse(dict.ValueOrDefault("cp", "0,75"), out crossoverProbability))
            {
                throw new ArgumentException("Probabilidade de crossover inválida.");
            }

            if (!float.TryParse(dict.ValueOrDefault("mp", "0,25"), out mutationProbability))
            {
                throw new ArgumentException("Probabilidade de mutação inválida.");
            }


            return(new AlgoritmoGenetico(problema, population, selection, crossover, crossoverProbability, mutation, mutationProbability, termination, reinsertion));
        }
Example #8
0
        public void Cross_ParentsWith10Genes_Cross()
        {
            var target = new CycleCrossover();

            // 8 4 7 3 6 2 5 1 9 0
            var chromosome1 = MockRepository.GenerateStub <ChromosomeBase>(10);

            chromosome1.ReplaceGenes(0, new Gene[] {
                new Gene(8),
                new Gene(4),
                new Gene(7),
                new Gene(3),
                new Gene(6),
                new Gene(2),
                new Gene(5),
                new Gene(1),
                new Gene(9),
                new Gene(0)
            });
            chromosome1.Expect(c => c.CreateNew()).Return(MockRepository.GenerateStub <ChromosomeBase>(10));

            // 0 1 2 3 4 5 6 7 8 9
            var chromosome2 = MockRepository.GenerateStub <ChromosomeBase>(10);

            chromosome2.ReplaceGenes(0, new Gene[]
            {
                new Gene(0),
                new Gene(1),
                new Gene(2),
                new Gene(3),
                new Gene(4),
                new Gene(5),
                new Gene(6),
                new Gene(7),
                new Gene(8),
                new Gene(9),
            });
            chromosome2.Expect(c => c.CreateNew()).Return(MockRepository.GenerateStub <ChromosomeBase>(10));

            // Child one: 8 1 2 3 4 5 6 7 9 0
            // Child two: 0 4 7 3 6 2 5 1 8 9
            var rnd = MockRepository.GenerateMock <IRandomization>();

            rnd.Expect(r => r.GetUniqueInts(2, 0, 10)).Return(new int[] { 7, 3 });
            RandomizationProvider.Current = rnd;

            IList <IChromosome> actual = null;;

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

            Assert.AreEqual(2, actual.Count);
            Assert.AreEqual(10, actual[0].Length);
            Assert.AreEqual(10, actual[1].Length);

            Assert.AreEqual(10, actual[0].GetGenes().Distinct().Count());
            Assert.AreEqual(10, actual[1].GetGenes().Distinct().Count());

            Assert.AreEqual(8, actual[0].GetGene(0).Value);
            Assert.AreEqual(1, actual[0].GetGene(1).Value);
            Assert.AreEqual(2, actual[0].GetGene(2).Value);
            Assert.AreEqual(3, actual[0].GetGene(3).Value);
            Assert.AreEqual(4, actual[0].GetGene(4).Value);
            Assert.AreEqual(5, actual[0].GetGene(5).Value);
            Assert.AreEqual(6, actual[0].GetGene(6).Value);
            Assert.AreEqual(7, actual[0].GetGene(7).Value);
            Assert.AreEqual(9, actual[0].GetGene(8).Value);
            Assert.AreEqual(0, actual[0].GetGene(9).Value);

            Assert.AreEqual(0, actual[1].GetGene(0).Value);
            Assert.AreEqual(4, actual[1].GetGene(1).Value);
            Assert.AreEqual(7, actual[1].GetGene(2).Value);
            Assert.AreEqual(3, actual[1].GetGene(3).Value);
            Assert.AreEqual(6, actual[1].GetGene(4).Value);
            Assert.AreEqual(2, actual[1].GetGene(5).Value);
            Assert.AreEqual(5, actual[1].GetGene(6).Value);
            Assert.AreEqual(1, actual[1].GetGene(7).Value);
            Assert.AreEqual(8, actual[1].GetGene(8).Value);
            Assert.AreEqual(9, actual[1].GetGene(9).Value);
        }
Example #9
0
        public void Cross_ParentsWith5ThreeCyclesGenes_Cross()
        {
            var target = new CycleCrossover();

            // 8 4 6 7 3
            var chromosome1 = MockRepository.GenerateStub <ChromosomeBase>(5);

            chromosome1.ReplaceGenes(0, new Gene[] {
                new Gene(8),
                new Gene(4),
                new Gene(6),
                new Gene(7),
                new Gene(3)
            });
            chromosome1.Expect(c => c.CreateNew()).Return(MockRepository.GenerateStub <ChromosomeBase>(5));

            // 4 3 6 7 8
            var chromosome2 = MockRepository.GenerateStub <ChromosomeBase>(5);

            chromosome2.ReplaceGenes(0, new Gene[]
            {
                new Gene(4),
                new Gene(3),
                new Gene(6),
                new Gene(7),
                new Gene(8)
            });
            chromosome2.Expect(c => c.CreateNew()).Return(MockRepository.GenerateStub <ChromosomeBase>(5));

            // Cycle 1 indexes: 0 1 4
            // Cycle 2 indexes: 2
            // Cycle 3 indexes: 3
            // Child one: 8 4 6 7 3
            // Child two: 4 3 6 7 8
            var rnd = MockRepository.GenerateMock <IRandomization>();

            rnd.Expect(r => r.GetUniqueInts(2, 0, 10)).Return(new int[] { 7, 3 });
            RandomizationProvider.Current = rnd;

            IList <IChromosome> actual = null;;

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

            Assert.AreEqual(2, actual.Count);
            Assert.AreEqual(5, actual[0].Length);
            Assert.AreEqual(5, actual[1].Length);

            Assert.AreEqual(5, actual[0].GetGenes().Distinct().Count());
            Assert.AreEqual(5, actual[1].GetGenes().Distinct().Count());

            Assert.AreEqual(8, actual[0].GetGene(0).Value);
            Assert.AreEqual(4, actual[0].GetGene(1).Value);
            Assert.AreEqual(6, actual[0].GetGene(2).Value);
            Assert.AreEqual(7, actual[0].GetGene(3).Value);
            Assert.AreEqual(3, actual[0].GetGene(4).Value);


            Assert.AreEqual(4, actual[1].GetGene(0).Value);
            Assert.AreEqual(3, actual[1].GetGene(1).Value);
            Assert.AreEqual(6, actual[1].GetGene(2).Value);
            Assert.AreEqual(7, actual[1].GetGene(3).Value);
            Assert.AreEqual(8, actual[1].GetGene(4).Value);
        }
Example #10
0
 public void Setup()
 {
     cycleCrossover = new CycleCrossover();
 }
        public void Cross_ParentsWith5OneCycleGenes_Cross()
        {
            var target = new CycleCrossover();

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

            chromosome1.ReplaceGenes(0, new Gene[] {
                new Gene(8),
                new Gene(4),
                new Gene(7),
                new Gene(3),
                new Gene(6)
            });
            chromosome1.CreateNew().Returns(Substitute.For <ChromosomeBase>(5));

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

            chromosome2.ReplaceGenes(0, new Gene[]
            {
                new Gene(4),
                new Gene(3),
                new Gene(6),
                new Gene(7),
                new Gene(8)
            });
            chromosome2.CreateNew().Returns(Substitute.For <ChromosomeBase>(5));

            // Cycle 1 indexes: 0 1 3 2 4
            // Child one: 4 3 6 7 8
            // Child two: 8 4 7 3 6
            var rnd = Substitute.For <IRandomization>();

            rnd.GetUniqueInts(2, 0, 10).Returns(new int[] { 7, 3 });
            RandomizationProvider.Current = rnd;

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

            Assert.AreEqual(2, actual.Count);
            Assert.AreEqual(5, actual[0].Length);
            Assert.AreEqual(5, actual[1].Length);

            Assert.AreEqual(5, actual[0].GetGenes().Distinct().Count());
            Assert.AreEqual(5, actual[1].GetGenes().Distinct().Count());

            Assert.AreEqual(8, actual[0].GetGene(0).Value);
            Assert.AreEqual(4, actual[0].GetGene(1).Value);
            Assert.AreEqual(7, actual[0].GetGene(2).Value);
            Assert.AreEqual(3, actual[0].GetGene(3).Value);
            Assert.AreEqual(6, actual[0].GetGene(4).Value);


            Assert.AreEqual(4, actual[1].GetGene(0).Value);
            Assert.AreEqual(3, actual[1].GetGene(1).Value);
            Assert.AreEqual(6, actual[1].GetGene(2).Value);
            Assert.AreEqual(7, actual[1].GetGene(3).Value);
            Assert.AreEqual(8, actual[1].GetGene(4).Value);
        }
        public IList <IChromosome> CycleCrossover()
        {
            var target = new CycleCrossover();

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