public void ItHasAValidConstructor() { var parentSelection = new StochasticUniversalSamplingSelection(); parentSelection.Setup(_pool, GATestHelper.GetTravelingSalesmanDefaultConfiguration()); parentSelection.GetParents(); }
public ISelection StochasticUniversalSampling() { var target = new StochasticUniversalSamplingSelection(); target.SelectChromosomes(_chromosomesNumber, _generation); return(target); }
public void SelectChromosomes_NullGeneration_Exception() { var target = new StochasticUniversalSamplingSelection(); ExceptionAssert.IsThrowing(new ArgumentNullException("generation"), () => { target.SelectChromosomes(2, null); }); }
public void ItCanGetAValidParent() { var parentSelection = new StochasticUniversalSamplingSelection(); parentSelection.Setup(_pool, GATestHelper.GetTravelingSalesmanDefaultConfiguration()); var parent = parentSelection.GetParent(0.22); Assert.IsNotNull(parent); }
public void SelectChromosomes_NullGeneration_Exception() { var target = new StochasticUniversalSamplingSelection(); var actual = Assert.Catch <ArgumentNullException>(() => { target.SelectChromosomes(2, null); }); Assert.AreEqual("generation", actual.ParamName); }
public void SelectChromosomes_InvalidNumber_Exception() { var target = new StochasticUniversalSamplingSelection(); ExceptionAssert.IsThrowing(new ArgumentOutOfRangeException("number", "The number of selected chromosomes should be at least 2."), () => { target.SelectChromosomes(-1, null); }); ExceptionAssert.IsThrowing(new ArgumentOutOfRangeException("number", "The number of selected chromosomes should be at least 2."), () => { target.SelectChromosomes(0, null); }); ExceptionAssert.IsThrowing(new ArgumentOutOfRangeException("number", "The number of selected chromosomes should be at least 2."), () => { target.SelectChromosomes(1, null); }); }
public void SelectChromosomes_InvalidNumber_Exception() { var target = new StochasticUniversalSamplingSelection(); Assert.Catch <ArgumentOutOfRangeException>(() => { target.SelectChromosomes(-1, null); }, "The number of selected chromosomes should be at least 2."); Assert.Catch <ArgumentOutOfRangeException>(() => { target.SelectChromosomes(0, null); }, "The number of selected chromosomes should be at least 2."); Assert.Catch <ArgumentOutOfRangeException>(() => { target.SelectChromosomes(1, null); }, "The number of selected chromosomes should be at least 2."); }
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(); }); }
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)); }
public void SelectChromosomes_Generation_ChromosomesSelected() { var target = new StochasticUniversalSamplingSelection(); var c1 = new ChromosomeStub(); c1.Fitness = 0.1; var c2 = new ChromosomeStub(); c2.Fitness = 0.5; var c3 = new ChromosomeStub(); c3.Fitness = 0; var c4 = new ChromosomeStub(); c4.Fitness = 0.7; var generation = new Generation(1, new List <IChromosome>() { c1, c2, c3, c4 }); // Fitness sum: 0.1 + 0.5 + 0 + 0.7 = 1.3 // c1: 8% = 0.08 // c2: 38% = 0.46 // c3: 0% = 0.46 // c4: 54% = 1.00 var rnd = MockRepository.GenerateMock <IRandomization>(); rnd.Expect(r => r.GetDouble()).Return(0.3); RandomizationProvider.Current = rnd; // Step size 1/2 = 0.5 var actual = target.SelectChromosomes(2, generation); Assert.AreEqual(2, actual.Count); Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3 Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.8 // Step size 1/3 = 0.33 actual = target.SelectChromosomes(3, generation); Assert.AreEqual(3, actual.Count); Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3 Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.63 Assert.AreEqual(c4.Fitness, actual[2].Fitness); // 0.96 // Step size 1/4 = 0.25 actual = target.SelectChromosomes(4, generation); Assert.AreEqual(4, actual.Count); Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3 Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.55 Assert.AreEqual(c4.Fitness, actual[2].Fitness); // 0.80 Assert.AreEqual(c1.Fitness, actual[3].Fitness); // 0.05 // Step size 1/5 = 0.20 actual = target.SelectChromosomes(5, generation); Assert.AreEqual(5, actual.Count); Assert.AreEqual(c2.Fitness, actual[0].Fitness); // 0.3 Assert.AreEqual(c4.Fitness, actual[1].Fitness); // 0.5 Assert.AreEqual(c4.Fitness, actual[2].Fitness); // 0.7 Assert.AreEqual(c4.Fitness, actual[3].Fitness); // 0.9 Assert.AreEqual(c2.Fitness, actual[4].Fitness); // 0.1 }
/// <summary> /// Loads presetsProfile into service. /// </summary> /// <exception cref="T:System.InvalidOperationException">Thrown when an attempt to load presetsProfile twice is made.</exception> public void AddGeneticAlgorithm(GADefinition definition, Guid Key) { var chromosome = new FloatingPointChromosome( minValue: new double[] { 0, 0, 0, 0 }, maxValue: new double[] { _maxWidth, _maxHeight, _maxWidth, _maxHeight }, totalBits: new int[] { 20, 20, 20, 20 }, fractionDigits: new int[] { 0, 0, 0, 0 }, geneValues: _geneValues); ICrossover gaCrossover = default; switch (definition.Crossover) { case Crossovers.Uniform: gaCrossover = new UniformCrossover(mixProbability: 0.5f); break; case Crossovers.OnePoint: gaCrossover = new OnePointCrossover(swapPointIndex: 40); break; case Crossovers.ThreeParent: gaCrossover = new ThreeParentCrossover(); break; default: throw new ArgumentOutOfRangeException(paramName: nameof(definition.Crossover), actualValue: definition.Crossover, message: "Crossover has wrong value"); } ISelection gaSelection = default; switch (definition.Selection) { case Selections.Elite: gaSelection = new EliteSelection(); break; case Selections.Roulette: gaSelection = new RouletteWheelSelection(); break; case Selections.Tournament: gaSelection = new TournamentSelection( size: decimal.ToInt32(d: decimal.Multiply(definition.Population, new decimal(0.2f)))); break; case Selections.StohasticUniversalSampling: gaSelection = new StochasticUniversalSamplingSelection(); break; default: throw new ArgumentOutOfRangeException(paramName: nameof(definition.Selection), actualValue: definition.Selection, message: "Selection has wrong value"); } var gaMutation = new UniformMutation(true); var gaPopulation = new Population(minSize: definition.Population, maxSize: definition.Population, adamChromosome: chromosome); var ga = new GeneticAlgorithm(population: gaPopulation, fitness: new EuclideanDistanceFitness(), selection: gaSelection, crossover: gaCrossover, mutation: gaMutation); ga.MutationProbability = (float)definition.Mutation; ga.GenerationRan += GeneticAlgorithmOnGenerationRan; ga.Termination = new FitnessStagnationTermination(expectedStagnantGenerationsNumber: 5); _geneticAlgorithms.Add(key: Key, value: ga); }