private List <String> GreedyKnapsack(int?seed, bool penalized, EffectType type) { List <String> results = new List <String>(); var evaluations = GenerateProblems(); foreach (var evaluation in evaluations) { ((CBinaryKnapsackEvaluation)evaluation).bSetPenalized(penalized); IterationsStopCondition stopCondition = new IterationsStopCondition(evaluation.dMaxValue, 100); BinaryRandomGenerator generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed); OnePointCrossover crossover = new OnePointCrossover(0.5, seed); BinaryBitFlipMutation mutation = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed); TournamentSelection selection = new TournamentSelection(2, seed); KnapsackGA ga = new KnapsackGA(((CBinaryKnapsackEvaluation)evaluation), stopCondition, generator, selection, crossover, mutation, 50, type, seed); ga.Run(); results.Add(FormatSave(ga)); ReportOptimizationResult(ga.Result, debug: true); } return(results); }
public void Resume_TerminationReachedAndTerminationExtend_Resumed() { var selection = new EliteSelection(); var crossover = new OnePointCrossover(2); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 199, chromosome), new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation); target.Population.GenerationStrategy = new TrackingGenerationStrategy(); target.Termination = new GenerationNumberTermination(100); target.Start(); Assert.AreEqual(100, target.Population.Generations.Count); var timeEvolving = target.TimeEvolving.Ticks; Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State); Assert.IsFalse(target.IsRunning); target.Termination = new GenerationNumberTermination(200); target.Resume(); Assert.AreEqual(target.Population.Generations.Count, 200); Assert.Less(timeEvolving, target.TimeEvolving.Ticks); Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State); Assert.IsFalse(target.IsRunning); target.Termination = new GenerationNumberTermination(300); target.Resume(); Assert.AreEqual(target.Population.Generations.Count, 300); Assert.Less(timeEvolving, target.TimeEvolving.Ticks); Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State); Assert.IsFalse(target.IsRunning); }
public void Stop_Started_Stopped() { var selection = new EliteSelection(); var crossover = new OnePointCrossover(2); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 199, chromosome), new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation); target.Termination = new GenerationNumberTermination(10000); Parallel.Invoke( () => target.Start(), () => { Thread.Sleep(10); Assert.AreEqual(GeneticAlgorithmState.Started, target.State); Assert.IsTrue(target.IsRunning); target.Stop(); Thread.Sleep(30); Assert.AreEqual(GeneticAlgorithmState.Stopped, target.State); Assert.IsFalse(target.IsRunning); }); Assert.Less(target.Population.Generations.Count, 10000); Assert.Less(target.TimeEvolving.TotalMilliseconds, 1000); }
public void Resume_TerminationReachedAndTerminationNotChanged_Exception() { var selection = new EliteSelection(); var crossover = new OnePointCrossover(2); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 199, chromosome), new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation); target.Termination = new GenerationNumberTermination(10); target.Start(); Assert.AreEqual(10, target.Population.Generations.Count); var timeEvolving = target.TimeEvolving.Ticks; Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State); Assert.IsFalse(target.IsRunning); Assert.Catch <InvalidOperationException>(() => { target.Resume(); }, "Attempt to resume a genetic algorithm with a termination (GenerationNumberTermination (HasReached: True)) already reached. Please, specify a new termination or extend the current one."); }
public void GivenSortedSubsetChromosomes_WhenOnePointCrossOver_WithConflict_ThenShouldReply() { var chromosomes = SortedSubsetTestData.CreateChromosomes(); var random = new PredeterminedRandom(5, 7); //Crossover gene value before and after conflicts var parameterSet = new ParameterSet(); parameterSet.SetValue(ParameterNames.FailedCrossoverRetryCount, 1); var conflictDetectors = new List <INeighborhoodConflictDetector>() { new PredeterminedConflictDetector(false, true, true, false, false, false, false, false, false, false) }; var crossover = new OnePointCrossover(random, parameterSet, conflictDetectors); var results = crossover.Cross(chromosomes[0], chromosomes[1]); var result1 = results[0] as SortedSubsetChromosome; var result2 = results[1] as SortedSubsetChromosome; result1.Sections[0].Should().BeEquivalentTo(new int[] { 1, 4, 5, 9 }); result1.Sections[1].Should().BeEquivalentTo(new int[] { 3, 6, 7 }); result1.Sections[2].Should().BeEquivalentTo(new int[] { 2, 8 }); result2.Sections[0].Should().BeEquivalentTo(new int[] { 3, 4, 7 }); result2.Sections[1].Should().BeEquivalentTo(new int[] { 2, 5, 8 }); result2.Sections[2].Should().BeEquivalentTo(new int[] { 1, 6, 9 }); }
private static void Lab73(int?seed = null) { string filename = "lab73_order3.txt"; IEvaluation <bool> evaluation = new CBinaryStandardDeceptiveConcatenationEvaluation(3, 100); RunningTimeStopCondition stopCondition = new RunningTimeStopCondition(evaluation.dMaxValue, 30); BinaryRandomGenerator generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed); OnePointCrossover crossover = new OnePointCrossover(0.5, seed); BinaryBitFlipMutation mutation = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed); TournamentSelection selection = new TournamentSelection(2, seed); GAwithDSM ga = new GAwithDSM(evaluation, stopCondition, generator, selection, crossover, mutation, 50); ga.Run(); SaveDSMs(ga.dsms, filename); filename = "lab73_order10.txt"; evaluation = new CBinaryBimodalDeceptiveConcatenationEvaluation(10, 100); stopCondition = new RunningTimeStopCondition(evaluation.dMaxValue, 30); generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed); crossover = new OnePointCrossover(0.5, seed); mutation = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed); selection = new TournamentSelection(2, seed); ga = new GAwithDSM(evaluation, stopCondition, generator, selection, crossover, mutation, 50); ga.Run(); SaveDSMs(ga.dsms, filename); }
public Program() { var synapseTracker = new SynapseInnovNbTracker(); var initialGenerationGenerator = new NeuralInitialGenerationCreatorBase( InitModel(), new RecursiveNetworkOpBaker()); //var selection = new EliteSelection(); var selection = new RouletteWheelSelectionWithRepetion(); var crossover = new OnePointCrossover(true); var breeding = new BreedingClassic( crossoverPart, 1, selection, crossover, InitMutations() ); var reinsertion = new ReinsertionFromSelection( reinsertionPart, 0, new EliteSelection()); var producers = new IGenomeProducer[] { breeding, reinsertion }; var genomeForge = new GenomeForge(producers); var generationManager = new GenerationManagerKeepLast(); geneticManager = new GeneticManagerClassic( generationManager, initialGenerationGenerator, genomeForge, genomesCount ); geneticManager.Init(); }
static void Main(string[] args) { var get = new DataReader(); //fitness Fitness fitness = new Fitness(get.DataPregnant(), get.Data());// insert the data from DataReader for the population creation. //selection var highestFitness = 1; var lowestFitness = 2; ISelection roulette = new RouletteWheel(); ISelection ranking = new Ranking(highestFitness); //crossover var crossoverProbability = 0.6; ICrossover onePointCrosseover = new OnePointCrossover(); ICrossover twoPointCrosseover = new TwoPointCrossover(); //mutation var Mutation = (chanceMutation : 0.01, min : -1, max : 1); var RandomLimits = (min : -1, max : 1); //population var populationSize = 60; // create a new population var population = fitness.GenerateNewPopulation(populationSize, RandomLimits); var ga = new GeneticAlgorithm(population, fitness, 100, onePointCrosseover, crossoverProbability, Mutation, roulette); System.Collections.Generic.List <double> predict = get.Data()[400]; Console.WriteLine("prediction for value " + 400 + " : " + new Prediction().Predict(ga.BestSeed.DNA, predict)); Console.ReadLine(); }
public Tuple <List <String>, List <String> > Lab6FindStallingParameter(IEvaluation <bool>[] problems, int[] seeds) { List <String> stuckResults = new List <String>(); List <String> results = new List <String>(); double[] pMuts = new double[] { 0.01, 0.001, 0.0001, 0.00000001 }; int[] popSizes = new int[] { 100, 50, 20, 4 }; int iter = 1; int maxI = pMuts.Length * popSizes.Length; foreach (var pMut in pMuts) { foreach (var popSize in popSizes) { Dictionary <String, int> problemStallCounter = new Dictionary <String, int>(); foreach (var seed in seeds) { TournamentSelection selection = new TournamentSelection(4, seed); OnePointCrossover crossover = new OnePointCrossover(.5); foreach (var problem in problems) { results.Add(Lab6BinaryGA(problem, selection, crossover, pMut, popSize, problemStallCounter, seed)); } } Console.WriteLine("\nParameters - mutation probability: " + pMut.ToString() + ", population size: " + popSize.ToString() + " /// " + DateTime.Now.ToString("HH:mm:ss.fff") + " | " + iter.ToString() + "/" + maxI.ToString()); stuckResults.Add(pMut.ToString() + ", " + popSize.ToString() + ", " + String.Join(", ", problemStallCounter.Select(x => x.Value).ToArray())); problemStallCounter.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine); iter++; } } return(new Tuple <List <String>, List <String> >(results, stuckResults)); }
public DemoPlayerInputStrategy() { var population = new Population (6, 6, new DemoPlayerChromosome ()); var fitness = new DemoPlayerFitness (); var selection = new EliteSelection (); var crossover = new OnePointCrossover (0); var mutation = new UniformMutation (true); m_ga = new GeneticAlgorithm ( population, fitness, selection, crossover, mutation); m_ga.MutationProbability = 0.5f; m_ga.GenerationRan += (sender, e) => { m_bestChromossome = m_ga.BestChromosome as DemoPlayerChromosome; if(m_bestChromossome.AvoidAliensProjectilesProbability > 0.9f) { HorizontalDirection = 1f; } }; m_ga.Start (); SHThread.PingPong (.01f, 0, 1, (t) => { m_ga.Termination = new GenerationNumberTermination (m_ga.GenerationsNumber + 1); m_ga.Resume(); return true; }); }
protected void InitGeneticManager() { var initialGenerationGenerator = new NeuralInitialGenerationCreatorBase( InitNeuralModel(), new RecursiveNetworkOpBaker()); var selection = new RouletteWheelSelectionWithRepetion(); var crossover = new OnePointCrossover(true); var breeding = new BreedingClassic( crossoverPart, minProduction: 1, selection: selection, crossover: crossover, mutationManager: InitMutations() ); var reinsertion = new ReinsertionFromSelection( reinsertionPart, minProduction: 0, selection: new EliteSelection()); var producers = new IGenomeProducer[] { breeding, reinsertion }; var genomeForge = new GenomeForge(producers); var generationManager = new GenerationManagerKeepLast(); geneticManager = new GeneticManagerClassic( generationManager, initialGenerationGenerator, genomeForge, genomesCount ); geneticManager.Init(); }
public void Resume_Stopped_Resumed() { var selection = new EliteSelection(); var crossover = new OnePointCrossover(2); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 199, chromosome), new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation); target.Termination = new TimeEvolvingTermination(TimeSpan.FromMilliseconds(1000)); Parallel.Invoke( () => target.Start(), () => { Thread.Sleep(30); target.Stop(); Thread.Sleep(30); Assert.AreEqual(GeneticAlgorithmState.Stopped, target.State); Assert.IsFalse(target.IsRunning); }); Parallel.Invoke( () => target.Resume(), () => { Thread.Sleep(30); Assert.AreEqual(GeneticAlgorithmState.Resumed, target.State); Assert.IsTrue(target.IsRunning); }); }
public void Start_InvalidFitnessEvaluateResult_Exception() { var selection = new RouletteWheelSelection(); var crossover = new OnePointCrossover(1); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var fitness = MockRepository.GenerateMock <IFitness>(); fitness.Expect(f => f.Evaluate(null)).IgnoreArguments().Return(1.1); var target = new GeneticAlgorithm( new Population(20, 20, chromosome), fitness, selection, crossover, mutation); ExceptionAssert.IsThrowing(new FitnessException(fitness, "The {0}.Evaluate returns a fitness with value 1.1. The fitness value should be between 0.0 and 1.0.".With(fitness.GetType())), () => { target.Start(); }); fitness = MockRepository.GenerateMock <IFitness>(); fitness.Expect(f => f.Evaluate(null)).IgnoreArguments().Return(-0.1); target = new GeneticAlgorithm( new Population(20, 20, chromosome), fitness, selection, crossover, mutation); ExceptionAssert.IsThrowing(new FitnessException(fitness, "The {0}.Evaluate returns a fitness with value -0.1. The fitness value should be between 0.0 and 1.0.".With(fitness.GetType())), () => { target.Start(); }); }
public void Start_ParallelManySlowFitness_Timeout() { var taskExecutor = new SmartThreadPoolTaskExecutor(); taskExecutor.MinThreads = 100; taskExecutor.MaxThreads = 100; taskExecutor.Timeout = TimeSpan.FromMilliseconds(1000); var selection = new RouletteWheelSelection(); var crossover = new OnePointCrossover(1); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 150, chromosome), new FitnessStub() { SupportsParallel = true, ParallelSleep = 1500 }, selection, crossover, mutation); target.TaskExecutor = taskExecutor; ExceptionAssert.IsThrowing(new TimeoutException("The fitness evaluation rech the 00:00:01 timeout."), () => { target.Start(); }); Assert.IsFalse(target.IsRunning); Assert.AreEqual(GeneticAlgorithmState.Stopped, target.State); }
public void GivenSortedSubsetChromosomes_WhenOnePointCrossOver_ThenShouldBeProper() { var chromosomes = SortedSubsetTestData.CreateChromosomes(); var random = new PredeterminedRandom(5); //Crossover gene value var parameterSet = new ParameterSet(); parameterSet.SetValue(ParameterNames.FailedCrossoverRetryCount, 0); var conflictDetectors = new List <INeighborhoodConflictDetector>() { AllRightConflictDetector.Instance }; var crossover = new OnePointCrossover(random, parameterSet, conflictDetectors); var results = crossover.Cross(chromosomes[0], chromosomes[1]); var result1 = results[0] as SortedSubsetChromosome; var result2 = results[1] as SortedSubsetChromosome; result1.Sections[0].Should().BeEquivalentTo(new int[] { 1, 4, 9 }); result1.Sections[1].Should().BeEquivalentTo(new int[] { 3, 5, 7 }); result1.Sections[2].Should().BeEquivalentTo(new int[] { 2, 6, 8 }); result2.Sections[0].Should().BeEquivalentTo(new int[] { 3, 4, 5, 7 }); result2.Sections[1].Should().BeEquivalentTo(new int[] { 2, 6, 8 }); result2.Sections[2].Should().BeEquivalentTo(new int[] { 1, 9 }); }
public void Start_TplManySlowFitness_Timeout() { var taskExecutor = new TplTaskExecutor(); taskExecutor.Timeout = TimeSpan.FromMilliseconds(1000); var selection = new RouletteWheelSelection(); var crossover = new OnePointCrossover(1); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new TplPopulation(100, 150, chromosome), new FitnessStub() { SupportsParallel = true, ParallelSleep = 1500 }, selection, crossover, mutation); target.OperatorsStrategy = new TplOperatorsStrategy(); target.TaskExecutor = taskExecutor; Assert.Catch <TimeoutException>(() => { target.Start(); }, "The fitness evaluation reached the 00:00:01 timeout."); Assert.IsFalse(target.IsRunning); Assert.AreEqual(GeneticAlgorithmState.Stopped, target.State); }
private void InitGenetics() { var initialGenerationGenerator = new NeuralInitialGenerationCreatorBase( //Init4InputsNeuralModel(), Init2InputsNeuralModel(), new FeedForwardOpBaker()); //var selection = new EliteSelection(); //var selection = new RouletteWheelSelection(); var selection = new RouletteWheelSelectionWithRepetion(); var crossover = new OnePointCrossover(true); var breeding = new BreedingClassic( crossoverPart, 1, selection, crossover, InitMutations() ); var reinsertion = new ReinsertionFromSelection(reinsertionPart, 0, new EliteSelection()); var producers = new IGenomeProducer[] { breeding, reinsertion }; var genomeForge = new GenomeForge(producers); var generationManager = new GenerationManagerKeepLast(); geneticManager = new GeneticManagerClassic( generationManager, initialGenerationGenerator, genomeForge, genomesCount ); geneticManager.Init(); }
public void Start_TerminationReached_TerminationReachedEventRaised() { var selection = new EliteSelection(); var crossover = new OnePointCrossover(2); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 199, chromosome), new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation); target.Population.GenerationStrategy = new TrackingGenerationStrategy(); target.Termination = new GenerationNumberTermination(1); var raised = false; target.TerminationReached += (e, a) => { raised = true; }; target.Start(); Assert.IsTrue(raised); }
static void Main(string[] args) { Population populacja = new Population(5, 6, n => n * n, new Random()); int ilosc = 5;//ilosc pokoleń for (int i = 0; i < ilosc; i++) { for (int j = 0; j <= 2; i++) { foreach (var z in populacja.Individuals) { foreach (var x in populacja.Individuals) { var crossoverOperator = new OnePointCrossover(new Random()); crossoverOperator.Crossover(z, x); } } } var lambda = new OnePointCrossover(new Random()); var pokolenie = lambda.IndividualsLambda; foreach (var y in pokolenie) { populacja.Individuals.Add(y); } var top = populacja.Individuals.OrderByDescending(x => x.Fitness).Take(5); populacja = null; populacja.Individuals.Add(top); } }
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); Func <double, double> fitness = x => 2 * x + 1; var ga = new GeneticAlgorithm(1500, 500, new OnePointCrossover(), new ClassicMutationOperator(), new RouletteWheelSelection(), fitness); //ga.PrintStatistics = true; var result = ga.RunSimulation(500); Console.WriteLine($"x = {result.Chromosome.DecodedValue}, f = {result.Fitness}"); var ind = new Individual(10); ind.ReplaceGenes(new bool[] { true, true, true, true, true, true, true, true, true, true }); Console.WriteLine($"x = {ind.Chromosome.DecodedValue}, f = {fitness(ind.Chromosome.DecodedValue)}"); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds + "ms"); Console.ReadLine(); return; var ind1 = new Individual(10); var ind2 = new Individual(10); Console.WriteLine("Individual 1: "); Console.WriteLine(ind1); Console.WriteLine("Individual 2: "); Console.WriteLine(ind2); var crossover = new OnePointCrossover(); crossover.Crossover(ind1, ind2); Console.WriteLine("Individual 1: "); Console.WriteLine(ind1); Console.WriteLine("Individual 2: "); Console.WriteLine(ind2); var mutation = new ClassicMutationOperator(); Console.WriteLine("--Before mutation: "); Console.WriteLine("Individual 1: "); Console.WriteLine(ind1); mutation.Mutation(ind1, 0.1); Console.WriteLine("--After mutation: "); Console.WriteLine("Individual 1: "); Console.WriteLine(ind1); }
public void TestMovelistLengthOne_SameLists() { var opc = new OnePointCrossover(new ZeroRandomizer()); //Randomizer doesn't matter var children = opc.DoCrossover(_parentWithSizeOneA, _parentWithSizeOneB); Assert.That(children.Item1[0].Coordinate == CoordinateProvider.GetCoordinate('D', 3)); Assert.That(children.Item2[0].Coordinate == CoordinateProvider.GetCoordinate('B', 6)); }
public void OnePointCrossoverTest() { IChromosome<int> a = new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 3, 4 }); IChromosome<int> b = new DigitalChromosome().GenerateFromArray(new int[] { 4, 3, 2, 1 }); OnePointCrossover<int> cross = new OnePointCrossover<int>(2); IChromosome<int>[] res = cross.Crossover(a, b); IChromosome<int>[] exp = new IChromosome<int>[2] { new DigitalChromosome().GenerateFromArray(new int[] { 1, 2, 2, 1 }), new DigitalChromosome().GenerateFromArray(new int[] { 4, 3, 3, 4 }) }; CollectionAssert.AreEqual(res, exp); }
public void TestMoveListLengthTwo_SwapFirstElements() { var opc = new OnePointCrossover(new OneRandomizer()); var children = opc.DoCrossover(_parentWithSizeTwoA, _parentWithSizeTwoB); Assert.That(children.Item1[0].Coordinate == CoordinateProvider.GetCoordinate('E', 1)); Assert.That(children.Item1[1].Coordinate == CoordinateProvider.GetCoordinate('A', 2)); Assert.That(children.Item2[0].Coordinate == CoordinateProvider.GetCoordinate('A', 1)); Assert.That(children.Item2[1].Coordinate == CoordinateProvider.GetCoordinate('G', 2)); }
public void Start_ParallelManyGenerations_Optimization() { var taskExecutor = new ParallelTaskExecutor(); taskExecutor.MinThreads = 100; taskExecutor.MaxThreads = 100; var selection = new EliteSelection(); var crossover = new OnePointCrossover(1); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); FlowAssert.IsAtLeastOneAttemptOk(20, () => { var target = new GeneticAlgorithm(new Population(100, 150, chromosome), new FitnessStub() { SupportsParallel = true }, selection, crossover, mutation); target.TaskExecutor = taskExecutor; Assert.AreEqual(GeneticAlgorithmState.NotStarted, target.State); Assert.IsFalse(target.IsRunning); target.Start(); Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State); Assert.IsFalse(target.IsRunning); Assert.IsTrue(target.Population.CurrentGeneration.Chromosomes.Count >= 100); Assert.IsTrue(target.Population.CurrentGeneration.Chromosomes.Count <= 150); Assert.IsNotNull(target.Population.BestChromosome); Assert.IsTrue(target.Population.BestChromosome.Fitness >= 0.9); Assert.IsTrue(target.Population.Generations.Count > 0); }); FlowAssert.IsAtLeastOneAttemptOk(20, () => { var target = new GeneticAlgorithm(new Population(100, 150, chromosome), new FitnessStub() { SupportsParallel = true }, selection, crossover, mutation); target.TaskExecutor = taskExecutor; target.Start(); Assert.IsTrue(target.Population.CurrentGeneration.Chromosomes.Count >= 100); Assert.IsTrue(target.Population.CurrentGeneration.Chromosomes.Count <= 150); Assert.IsNotNull(target.Population.BestChromosome); Assert.IsTrue(target.Population.BestChromosome.Fitness >= 0.9); Assert.IsTrue(target.Population.Generations.Count > 0); }); }
public void OnePointCrossLinkTest2() { Organism parent1 = new Organism(); Organism parent2 = new Organism(); parent1.Chromosomes.Add(new Chromosome(1, "11")); parent2.Chromosomes.Add(new Chromosome(1, "00")); IRandom rand = new Deterministic(1, 1); OnePointCrossover crossLinker = new OnePointCrossover(rand, 0); var answer = crossLinker.CrossLink(parent1, parent2); Assert.AreEqual("11", answer.Item1.Chromosomes[0].ToString()); Assert.AreEqual("00", answer.Item2.Chromosomes[0].ToString()); }
public void Cross_LessGenesThenSwapPoint_Exception() { var target = new OnePointCrossover(1); var chromosome1 = Substitute.For <ChromosomeBase>(2); var chromosome2 = Substitute.For <ChromosomeBase>(2); Assert.Catch <ArgumentOutOfRangeException>(() => { target.Cross(new List <IChromosome>() { chromosome1, chromosome2 }); }, "The swap point index is 1, but there is only 2 genes. The swap should result at least one gene to each side."); }
public void Cross_LessGenesThenSwapPoint_Exception() { var target = new OnePointCrossover(1); var chromosome1 = MockRepository.GenerateStub <ChromosomeBase>(2); var chromosome2 = MockRepository.GenerateStub <ChromosomeBase>(2); ExceptionAssert.IsThrowing(new ArgumentOutOfRangeException("parents", "The swap point index is 1, but there is only 2 genes. The swap should result at least one gene to each side."), () => { target.Cross(new List <IChromosome>() { chromosome1, chromosome2 }); }); }
public void Start_FitnessEvaluationFailed_FitnessException() { var selection = new RouletteWheelSelection(); var crossover = new OnePointCrossover(1); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var fitness = new FuncFitness((c) => throw new Exception("TEST")); var target = new GeneticAlgorithm(new Population(100, 150, chromosome), fitness, selection, crossover, mutation); Assert.Catch <FitnessException>(target.Start); Assert.IsFalse(target.IsRunning); Assert.AreEqual(GeneticAlgorithmState.Stopped, target.State); }
private String Lab4BinaryGaMutationCrossover(IEvaluation <bool> evaluation, double pMut, double pCro, int?seed) { IterationsStopCondition stopCondition = new IterationsStopCondition(evaluation.dMaxValue, 500); BinaryRandomGenerator generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed); BinaryBitFlipMutation mutation = new BinaryBitFlipMutation(pMut, evaluation, seed); OnePointCrossover crossover = new OnePointCrossover(pCro, seed); TournamentSelection selection = new TournamentSelection(5, seed); GeneticAlgorithm <bool> ga = new GeneticAlgorithm <bool>(evaluation, stopCondition, generator, selection, crossover, mutation, 50); ga.Run(); return(FormatSave(ga)); }
private static void Lab5(int?seed) { CBinaryKnapsackEvaluation evaluation = new CBinaryKnapsackEvaluation(EBinaryKnapsackInstance.knapPI_1_100_1000_1); IterationsStopCondition stopCondition = new IterationsStopCondition(evaluation.dMaxValue, 100); BinaryRandomGenerator generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed); OnePointCrossover crossover = new OnePointCrossover(0.5, seed); BinaryBitFlipMutation mutation = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed); TournamentSelection selection = new TournamentSelection(2, seed); GeneticAlgorithm <bool> ga = new GeneticAlgorithm <bool>(evaluation, stopCondition, generator, selection, crossover, mutation, 50); ga.Run(); ReportOptimizationResult(ga.Result); }
public void Resume_NotStarted_Exception() { var selection = new EliteSelection(); var crossover = new OnePointCrossover(2); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 199, chromosome), new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation); Assert.Catch <InvalidOperationException>(() => { target.Resume(); }, "Attempt to resume a genetic algorithm which was not yet started."); }
public void Stop_NotStarted_Exception() { var selection = new EliteSelection(); var crossover = new OnePointCrossover(2); var mutation = new UniformMutation(); var chromosome = new ChromosomeStub(); var target = new GeneticAlgorithm(new Population(100, 199, chromosome), new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation); ExceptionAssert.IsThrowing(new InvalidOperationException("Attempt to stop a genetic algorithm which was not yet started."), () => { target.Stop(); }); }