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;
        });
    }
        public void Evolve_ManyGenerations_Fast()
        {
            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation = new UniformMutation(true);
            var chromosome = new AutoConfigChromosome();
            var targetChromosome = new TspChromosome(10);
            var targetFitness = new TspFitness(10, 0, 100, 0, 100);            
            var fitness = new AutoConfigFitness(targetFitness, targetChromosome);
            fitness.PopulationMinSize = 20;
            fitness.PopulationMaxSize = 20;
            fitness.Termination = new TimeEvolvingTermination(TimeSpan.FromSeconds(5));
            
            var population = new Population(10, 10, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            
            ga.TaskExecutor = new SmartThreadPoolTaskExecutor()
            {
                MinThreads = 10,
                MaxThreads = 20
            };        

            ga.Termination = new GenerationNumberTermination(2);
            ga.Start();

            Assert.NotNull(ga.BestChromosome);            
        }
        public void Evolve_ManyGenerations_Fast()
        {
            var selection = new EliteSelection();
            var crossover = new ThreeParentCrossover();
            var mutation = new UniformMutation(true);

            var fitness = new FunctionBuilderFitness(
                new FunctionBuilderInput(
                    new double[] { 1, 2, 3 },
                    6)
                ,
                new FunctionBuilderInput(
                    new double[] { 2, 3, 4 },
                    24)
            );
            var chromosome = new FunctionBuilderChromosome(fitness.AvailableOperations, 5);

            var population = new Population(100, 200, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            ga.Termination = new FitnessThresholdTermination(0);
            ga.Start();
            var bestChromosome = ga.BestChromosome as FunctionBuilderChromosome;
            Assert.AreEqual(0.0, bestChromosome.Fitness.Value);
            var actual = fitness.GetFunctionResult(
                             bestChromosome.BuildFunction(),
                             new FunctionBuilderInput(new double[] { 3, 4, 5 }, 60)
                );

            Assert.AreEqual(60.0, actual);
        }
Beispiel #4
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 Mutate_InvalidIndexes_Exception()
        {
            var target = new UniformMutation (0, 3);
            var chromosome = MockRepository.GenerateStub<ChromosomeBase>(3);
            chromosome.ReplaceGenes(0, new Gene[]
                                                     {
                new Gene(1),
                new Gene(1),
                new Gene(1)
            });

            chromosome.Expect(c => c.GenerateGene(0)).Return(new Gene(0));

            RandomizationProvider.Current = MockRepository.GenerateMock<IRandomization> ();

            ExceptionAssert.IsThrowing (new MutationException (target, "The chromosome has no gene on index 3. The chromosome genes lenght is 3."), () => {
                target.Mutate (chromosome, 1);
            });

            chromosome.VerifyAllExpectations ();
            RandomizationProvider.Current.VerifyAllExpectations ();
        }
        public void Mutate_Indexes_RandomIndexes()
        {
            var target = new UniformMutation(0, 2);
            var chromosome = MockRepository.GenerateStub<ChromosomeBase>(3);
            chromosome.ReplaceGenes(0, new Gene[]
                                                     {
                new Gene(1),
                new Gene(1),
                new Gene(1)
            });

            chromosome.Expect(c => c.GenerateGene(0)).Return(new Gene(0));
            chromosome.Expect(c => c.GenerateGene(2)).Return(new Gene(10));
            RandomizationProvider.Current = MockRepository.GenerateMock<IRandomization>();

            target.Mutate(chromosome, 1);
            Assert.AreEqual(0, chromosome.GetGene(0).Value);
            Assert.AreEqual(1, chromosome.GetGene(1).Value);
            Assert.AreEqual(10, chromosome.GetGene(2).Value);

            chromosome.VerifyAllExpectations();
            RandomizationProvider.Current.VerifyAllExpectations();
        }
        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_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_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);
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("GeneticSharp - ConsoleApp");
            Console.ResetColor();
            Console.WriteLine("Select the sample:");
            Console.WriteLine("1) TSP (Travelling Salesman Problem)");
            Console.WriteLine("2) Ghostwriter");
            var sampleNumber = Console.ReadLine();
            ISampleController sampleController = null;

            switch (sampleNumber)
            {
                case "1":
                    sampleController = new TspSampleController(20);
                    break;

                case "2":
                    sampleController = new GhostwriterSampleController();
                    break;

                default:
                    return;
            }

            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation = new UniformMutation(true);
            var fitness = sampleController.CreateFitness();
            var population = new Population(50, 70, sampleController.CreateChromosome());

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            ga.MutationProbability = 0.4f;
            ga.Termination = new FitnessStagnationTermination(100);

            ga.TaskExecutor = new SmartThreadPoolTaskExecutor()
            {
                MinThreads = 25,
                MaxThreads = 50
            };

            ga.GenerationRan += delegate
            {
                Console.CursorLeft = 0;
                Console.CursorTop = 5;

                var bestChromosome = ga.Population.BestChromosome;
                Console.WriteLine("Generations: {0}", ga.Population.GenerationsNumber);
                Console.WriteLine("Fitness: {0:n4}", bestChromosome.Fitness);
                Console.WriteLine("Time: {0}", ga.TimeEvolving);
                sampleController.Draw(bestChromosome);
            };

            try
            {
                ga.Start();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine();
                Console.WriteLine("Error: {0}", ex.Message);
                Console.ResetColor();
                Console.ReadKey();
                return;
            }

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine();
            Console.WriteLine("Evolved.");
            Console.ResetColor();
            Console.ReadKey();
        }
        public void Start_UsingAllConfigurationCombinationsAvailable_AllRun()
        {
            var selections = SelectionService.GetSelectionNames();
            var crossovers = CrossoverService.GetCrossoverNames();
            var mutations = MutationService.GetMutationNames();
            var reinsertions = ReinsertionService.GetReinsertionNames();
            var chromosome = new OrderedChromosomeStub();

            foreach (var s in selections)
            {
                foreach (var c in crossovers)
                {
                    foreach (var m in mutations)
                    {
                        foreach (var r in reinsertions)
                        {
                            var selection = SelectionService.CreateSelectionByName(s);
                            var crossover = CrossoverService.CreateCrossoverByName(c);
                            var mutation = MutationService.CreateMutationByName(m);
                            var reinsertion = ReinsertionService.CreateReinsertionByName(r);

                            if (crossover.IsOrdered ^ mutation.IsOrdered)
                            {
                                continue;
                            }

                            if (crossover.ParentsNumber > crossover.ChildrenNumber && !reinsertion.CanExpand)
                            {
                                continue;
                            }

                            if (mutation is UniformMutation)
                            {
                                mutation = new UniformMutation(1);
                            }

                            var target = new GeneticAlgorithm(
                                 new Population(50, 50, chromosome.Clone())
                                 {
                                     GenerationStrategy = new TrackingGenerationStrategy()
                                 },
                                 new FitnessStub() { SupportsParallel = false },
                                 selection,
                                 crossover,
                                 mutation);

                            target.Reinsertion = reinsertion;
                            target.Termination = new GenerationNumberTermination(25);
                            target.CrossoverProbability = reinsertion.CanExpand ? 0.75f : 1f;

                            target.Start();
                            Assert.AreEqual(25, target.Population.Generations.Count);
                        }
                    }
                }
            }
        }
        public void Start_ThreeParentCrossover_KeepsMinSizePopulation()
        {
            var selection = new EliteSelection();
            var crossover = new ThreeParentCrossover();
            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(100, target.Population.Generations.Count);

            Assert.IsTrue(target.Population.Generations.All(g => g.Chromosomes.Count >= 100));
        }
        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 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_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_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 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_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();
                                       });
        }