public void Cross_ParentsWithTwoGenes_Cross()
        {
            var target = new OnePointCrossover(0);
            var chromosome1 = MockRepository.GenerateStub<ChromosomeBase>(2);
            chromosome1.ReplaceGenes(0, new Gene[]
            {
                new Gene(1),
                new Gene(2)
            });
            chromosome1.Expect(c => c.CreateNew()).Return(MockRepository.GenerateStub<ChromosomeBase>(2));

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

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

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

            Assert.AreEqual(1, actual[0].GetGene(0).Value);
            Assert.AreEqual(4, actual[0].GetGene(1).Value);

            Assert.AreEqual(3, actual[1].GetGene(0).Value);
            Assert.AreEqual(2, actual[1].GetGene(1).Value);
        }
        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
                });
            });
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var selection = new EliteSelection();
            var crossover = new OnePointCrossover(0);
            var mutation = new UniformMutation(true);
            var fitness = new Issue1Fitness();
            var chromosome = new Issue1Chromosome();
            var population = new Population(50, 50, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            ga.Termination = new GenerationNumberTermination(100);

            Console.WriteLine("GA running...");
            ga.Start();
            Console.WriteLine("GA done in {0} generations.", ga.GenerationsNumber);

            var bestChromosome = ga.BestChromosome as Issue1Chromosome;
            Console.WriteLine("Best solution found is X:{0}, Y:{1} with {2} fitness.", bestChromosome.X, bestChromosome.Y, bestChromosome.Fitness);
		    Console.ReadKey();
        }
        public void Start_NotParallelManyGenerations_Optimization()
        {
            var selection = new EliteSelection();
            var crossover = new OnePointCrossover(2);
            var mutation = new UniformMutation();
            var chromosome = new ChromosomeStub();
            var target = new GeneticAlgorithm(new Population(50, 50, chromosome),
                new FitnessStub() { SupportsParallel = false }, selection, crossover, mutation);

            Assert.IsInstanceOf<EliteSelection>(target.Selection);
            Assert.IsInstanceOf<OnePointCrossover>(target.Crossover);
            Assert.IsInstanceOf<UniformMutation>(target.Mutation);

            target.Termination = new GenerationNumberTermination(25);
            Assert.AreEqual(GeneticAlgorithmState.NotStarted, target.State);
            Assert.IsFalse(target.IsRunning);

            target.Start();

            Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
            Assert.IsFalse(target.IsRunning);

            Assert.AreEqual(25, target.Population.Generations.Count);

            var lastFitness = 0.0;

            foreach (var g in target.Population.Generations)
            {
                Assert.GreaterOrEqual(g.BestChromosome.Fitness.Value, lastFitness);
                lastFitness = g.BestChromosome.Fitness.Value;
            }

            Assert.GreaterOrEqual(lastFitness, 0.8);
            Assert.AreEqual(lastFitness, target.BestChromosome.Fitness);
        }
        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.Termination = new GenerationNumberTermination(100);
            target.Start();
            Assert.AreEqual(target.Population.Generations.Count, 100);
            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 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);

            ExceptionAssert.IsThrowing(new InvalidOperationException("Attempt to resume a genetic algorithm with a termination (GenerationNumberTermination (HasReached: True)) already reached. Please, specify a new termination or extend the current one."), () =>
            {
                target.Resume();
            });
        }
        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(10000));
            target.TaskExecutor = new SmartThreadPoolTaskExecutor();

            var stoppedCount = 0;
            target.Stopped += (e, a) =>
            {
                Assert.AreEqual(GeneticAlgorithmState.Stopped, target.State);
                Assert.IsFalse(target.IsRunning);
                stoppedCount++;
            };

            Parallel.Invoke(
            () => target.Start(),
            () =>
            {
                Thread.Sleep(500);
                target.Stop();
            });

            Thread.Sleep(2000);

            Parallel.Invoke(
                () => target.Resume(),
                () =>
                {
                    Thread.Sleep(2000);
                    Assert.AreEqual(GeneticAlgorithmState.Resumed, target.State);
                    Assert.IsTrue(target.IsRunning);
                });

            Assert.AreEqual(1, stoppedCount);
        }
        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);

            ExceptionAssert.IsThrowing(new InvalidOperationException("Attempt to resume a genetic algorithm which was not yet started."), () =>
            {
                target.Resume();
            });
        }
        public void Start_ParallelManyGenerations_Optimization()
        {
            var taskExecutor = new SmartThreadPoolTaskExecutor();
            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 Start_ManyCallsTerminationChanged_NewEvolutions()
        {
            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(100);

            target.Start();
            var lastTimeEvolving = target.TimeEvolving.TotalMilliseconds;
            Assert.AreEqual(100, target.Population.Generations.Count);
            Assert.Greater(target.TimeEvolving.TotalMilliseconds, 1);
            Assert.Less(target.TimeEvolving.TotalMilliseconds, 1000);
            Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
            Assert.IsFalse(target.IsRunning);

            target.Termination = new GenerationNumberTermination(50);
            target.Start();
            Assert.AreEqual(50, target.Population.Generations.Count);
            Assert.Less(target.TimeEvolving.TotalMilliseconds, lastTimeEvolving);
            lastTimeEvolving = target.TimeEvolving.TotalMilliseconds;
            Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
            Assert.IsFalse(target.IsRunning);

            target.Termination = new GenerationNumberTermination(25);
            target.Start();
            Assert.AreEqual(25, target.Population.Generations.Count);
            Assert.Less(target.TimeEvolving.TotalMilliseconds, lastTimeEvolving);
            Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
            Assert.IsFalse(target.IsRunning);
        }
        public void Start_ManyCalls_NewEvolutions()
        {
            RandomizationProvider.Current = new BasicRandomization();
            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(1000);
            Assert.AreEqual(GeneticAlgorithmState.NotStarted, target.State);
            Assert.IsFalse(target.IsRunning);

            target.Start();

            Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
            Assert.IsFalse(target.IsRunning);
            var lastTimeEvolving = target.TimeEvolving.Ticks;
            Assert.AreEqual(1000, target.Population.Generations.Count);
            Assert.Greater(target.TimeEvolving.TotalMilliseconds, 1);

            target.Start();

            Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
            Assert.IsFalse(target.IsRunning);
            Assert.AreEqual(1000, target.Population.Generations.Count);
            Assert.AreNotEqual(lastTimeEvolving, target.TimeEvolving.Ticks);

            target.Start();

            Assert.AreEqual(GeneticAlgorithmState.TerminationReached, target.State);
            Assert.IsFalse(target.IsRunning);
            Assert.AreEqual(1000, target.Population.Generations.Count);
            Assert.AreNotEqual(lastTimeEvolving, target.TimeEvolving.Ticks);
        }
        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.Termination = new GenerationNumberTermination(1);
            var raised = false;
            target.TerminationReached += (e, a) =>
            {
                raised = true;
            };

            target.Start();

            Assert.IsTrue(raised);
        }
        public void Start_ParallelGAs_Fast()
        {
            // GA 1     
            var selection1 = new EliteSelection();
            var crossover1 = new OnePointCrossover(2);
            var mutation1 = new UniformMutation();
            var chromosome1 = new ChromosomeStub();
            var ga1 = new GeneticAlgorithm(new Population(100, 199, chromosome1),
                    new FitnessStub() { SupportsParallel = false }, selection1, crossover1, mutation1);

            ga1.Termination = new GenerationNumberTermination(1000);

            // GA 2     
            var selection2 = new EliteSelection();
            var crossover2 = new OnePointCrossover(2);
            var mutation2 = new UniformMutation();
            var chromosome2 = new ChromosomeStub();
            var ga2 = new GeneticAlgorithm(new Population(100, 199, chromosome2),
                    new FitnessStub() { SupportsParallel = false }, selection2, crossover2, mutation2);

            ga2.Termination = new GenerationNumberTermination(1000);

            Parallel.Invoke(
                () => ga1.Start(),
                () => ga2.Start());


            Assert.AreEqual(1000, ga1.Population.Generations.Count);
            Assert.AreEqual(1000, ga2.Population.Generations.Count);
        }
        public void Start_NotParallelManyGenerations_Fast()
        {
            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(100);

            TimeAssert.LessThan(30000, () =>
            {
                target.Start();
            });

            Assert.AreEqual(100, target.Population.Generations.Count);
            Assert.Greater(target.TimeEvolving.TotalMilliseconds, 1);
        }
        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 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.Greater(target.TimeEvolving.TotalMilliseconds, 8.8);
        }
        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();
                                       });
        }