/// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        public IList<IChromosome> SelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            ExceptionHelper.ThrowIfNull("population", population);
            ExceptionHelper.ThrowIfNull("offspring", offspring);
            ExceptionHelper.ThrowIfNull("parents", parents);

            if (!CanExpand && offspring.Count < population.MinSize) {
                throw new ReinsertionException (this, "Cannot expand the number of chromosome in population. Try another reinsertion!");
            }

            if (!CanCollapse && offspring.Count > population.MaxSize) {
                throw new ReinsertionException (this, "Cannot collapse the number of chromosome in population. Try another reinsertion!");
            }

            return PerformSelectChromosomes (population, offspring, parents);
        }
Beispiel #2
0
        public void Evolve_ManyGenerations_Fast()
        {
            int numberOfCities = 40;
            var selection = new EliteSelection();
            var crossover = new OrderedCrossover();
            var mutation = new TworsMutation();
            var chromosome = new TspChromosome(numberOfCities);
            var fitness = new TspFitness (numberOfCities, 0, 1000, 0, 1000);

            var population = new Population (40, 40, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

            ga.Start();
            var firstDistance = ((TspChromosome)ga.Population.BestChromosome).Distance;

            ga.Termination = new GenerationNumberTermination (1001);

            TimeAssert.LessThan(3000, () =>
            {
                ga.Start();
            });

            var lastDistance = ((TspChromosome)ga.Population.BestChromosome).Distance;

            Assert.Less(lastDistance, firstDistance);
        }
        public void SelectChromosomes_offspringSizeGreaterThanMaxSize_Selectoffspring()
        {
            var target = new FitnessBasedReinsertion ();

            var population = new Population (2, 3, MockRepository.GenerateStub<ChromosomeBase> (2));
            var offspring = new List<IChromosome> () {
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (3),
                MockRepository.GenerateStub<ChromosomeBase> (4)
            };

            offspring [0].Fitness = 0.2;
            offspring [1].Fitness = 0.3;
            offspring [2].Fitness = 0.5;
            offspring [3].Fitness = 0.7;

            var parents = new List<IChromosome> () {
                MockRepository.GenerateStub<ChromosomeBase> (5),
                MockRepository.GenerateStub<ChromosomeBase> (6),
                MockRepository.GenerateStub<ChromosomeBase> (7),
                MockRepository.GenerateStub<ChromosomeBase> (8)
            };

            var selected = target.SelectChromosomes (population, offspring, parents);
            Assert.AreEqual (3, selected.Count);
            Assert.AreEqual (4, selected [0].Length);
            Assert.AreEqual (3, selected [1].Length);
            Assert.AreEqual (2, selected [2].Length);
        }
        public void SelectChromosomes_offspringSizeLowerThanMinSize_Selectoffspring()
        {
            var target = new UniformReinsertion();

            var population = new Population(6, 8, MockRepository.GenerateStub<ChromosomeBase>(2));
            var offspring = new List<IChromosome>() {
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (3),
                MockRepository.GenerateStub<ChromosomeBase> (4)
            };

            var parents = new List<IChromosome>() {
                MockRepository.GenerateStub<ChromosomeBase> (5),
                MockRepository.GenerateStub<ChromosomeBase> (6),
                MockRepository.GenerateStub<ChromosomeBase> (7),
                MockRepository.GenerateStub<ChromosomeBase> (8)
            };

            var rnd = MockRepository.GenerateMock<IRandomization>();
            rnd.Expect(r => r.GetInt(0, 4)).Return(1);
            rnd.Expect(r => r.GetInt(0, 5)).Return(3);
            RandomizationProvider.Current = rnd;

            var selected = target.SelectChromosomes(population, offspring, parents);
            Assert.AreEqual(6, selected.Count);
            Assert.AreEqual(2, selected[0].Length);
            Assert.AreEqual(2, selected[1].Length);
            Assert.AreEqual(3, selected[2].Length);
            Assert.AreEqual(4, selected[3].Length);
            Assert.AreEqual(2, selected[4].Length);
            Assert.AreEqual(4, selected[5].Length);
        }
        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);
        }
        public void SelectChromosomes_offspringSizeLowerThanMinSize_Selectoffspring()
        {
            var target = new ElitistReinsertion ();

            var population = new Population (6, 8, MockRepository.GenerateStub<ChromosomeBase> (2));
            var offspring = new List<IChromosome> () {
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (3),
                MockRepository.GenerateStub<ChromosomeBase> (4)
            };

            var parents = new List<IChromosome> () {
                MockRepository.GenerateStub<ChromosomeBase> (5),
                MockRepository.GenerateStub<ChromosomeBase> (6),
                MockRepository.GenerateStub<ChromosomeBase> (7),
                MockRepository.GenerateStub<ChromosomeBase> (8)
            };

            parents [0].Fitness = 0.2;
            parents [1].Fitness = 0.3;
            parents [2].Fitness = 0.5;
            parents [3].Fitness = 0.7;

            var selected = target.SelectChromosomes (population, offspring, parents);
            Assert.AreEqual (6, selected.Count);
            Assert.AreEqual (2, selected [0].Length);
            Assert.AreEqual (2, selected [1].Length);
            Assert.AreEqual (3, selected [2].Length);
            Assert.AreEqual (4, selected [3].Length);
            Assert.AreEqual (8, selected [4].Length);
            Assert.AreEqual (7, selected [5].Length);
        }
Beispiel #8
0
        public void Evolve_ManyGenerations_Fast()
        {
            int movesAhead = 10;
            int boardSize = 10;
            var selection = new EliteSelection();
            var crossover = new OrderedCrossover();
            var mutation = new TworsMutation();
            var chromosome = new CheckersChromosome(movesAhead, boardSize);
            var fitness = new CheckersFitness(new CheckersBoard(boardSize));

            var population = new Population(40, 40, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            ga.GenerationRan += delegate
            {
                if (ga.Population.GenerationsNumber % 100 == 0)
                {
                    fitness.Update(ga.Population.BestChromosome as CheckersChromosome);
                }
            };

            ga.Start();
            var firstFitness = ((CheckersChromosome)ga.Population.BestChromosome).Fitness;

            ga.Termination = new GenerationNumberTermination(2001);

            TimeAssert.LessThan(100000, () =>
            {
                ga.Start();
            });

            var lastFitness = ((CheckersChromosome)ga.Population.BestChromosome).Fitness;

            Assert.LessOrEqual(firstFitness, lastFitness);
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            if (offspring.Count > population.MaxSize) {
                return offspring.OrderByDescending (o => o.Fitness).Take (population.MaxSize).ToList ();
            }

            return offspring;
        }
Beispiel #10
0
        public void CreateInitialGeneration_AdamChromosomeCreateNewNull_Exception()
        {
            var population = new Population(2, 2, MockRepository.GenerateStub<ChromosomeBase>(4));

            ExceptionAssert.IsThrowing(new InvalidOperationException("The Adam chromosome's 'CreateNew' method generated a null chromosome. This is a invalid behavior, please, check your chromosome code."), () =>
            {
                population.CreateInitialGeneration();
            });
        }
        /// <summary>
        /// Register that a new generation has been created.
        /// </summary>
        /// <param name="population">The population where the new generation has been created.</param>
        public void RegisterNewGeneration(Population population)
        {
            ExceptionHelper.ThrowIfNull("population", population);

            if (population.Generations.Count > GenerationsNumber)
            {
                population.Generations.RemoveAt(0);
            }
        }
        public void SelectChromosomes_ParentsNull_Exception()
        {
            var target = MockRepository.GeneratePartialMock<ReinsertionBase>(false, false);
            var chromosome = MockRepository.GenerateStub<ChromosomeBase>(2);
            var population = new Population(5, 6, chromosome);
            var offspring = new List<IChromosome>() {
                chromosome, chromosome, chromosome, chromosome
            };

            ExceptionAssert.IsThrowing(new ArgumentNullException("parents"), () =>
            {
                target.SelectChromosomes(population, offspring, null);
            });
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            var diff = population.MinSize - offspring.Count;

            if (diff > 0) {
                var bestParents = parents.OrderByDescending (p => p.Fitness).Take (diff);

                foreach (var p in bestParents) {
                    offspring.Add (p);
                }
            }

            return offspring;
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            if (offspring.Count == 0)
            {
                throw new ReinsertionException(this, "The minimum size of the offspring is 1.");
            }

            var rnd = RandomizationProvider.Current;

            while (offspring.Count < population.MinSize) {
                offspring.Add (offspring [rnd.GetInt (0, offspring.Count)]);
            }

            return offspring;
        }
Beispiel #15
0
        public void EndCurrentGeneration_BestChromosomeChanged_ChangeEventRaise()
        {
            var target = new Population(2, 2, new ChromosomeStub());
            var eventRaise = false;
            target.BestChromosomeChanged += (e, a) =>
            {
                eventRaise = true;
            };

            target.CreateInitialGeneration();
            target.CurrentGeneration.Chromosomes.Each(c => c.Fitness = 1);
            target.CurrentGeneration.BestChromosome = target.CurrentGeneration.Chromosomes[0];
            target.EndCurrentGeneration();

            Assert.IsTrue(eventRaise);
        }
        public double TrainNeuralNetwork()
        {
            var chromosome = new KasandraChromosome(_fitness.TotalNumberOfWeights);

            var population = new Population(minPopulation, maxPopulation, chromosome);
            _geneticAlgorithm = new GeneticAlgorithm(population, _fitness, new EliteSelection(), new UniformCrossover(), new UniformMutation(true));

            _geneticAlgorithm.MutationProbability = mutationRate;
            _geneticAlgorithm.CrossoverProbability = crossoverProbabilty;
            _geneticAlgorithm.Termination = new GenerationNumberTermination(maxIterations);
            _geneticAlgorithm.TerminationReached += _geneticAlgorithm_TerminationReached;
            _geneticAlgorithm.GenerationRan += _geneticAlgorithm_GenerationRan;

            _geneticAlgorithm.Start();

            return 0;
        }
        public void SelectChromosomes_OffspringSizeEqualsZero_Exception()
        {
            var target = new UniformReinsertion();
            var population = new Population(6, 8, MockRepository.GenerateStub<ChromosomeBase>(2));
            var offspring = new List<IChromosome>();

            var parents = new List<IChromosome>() {
                MockRepository.GenerateStub<ChromosomeBase> (5),
                MockRepository.GenerateStub<ChromosomeBase> (6),
                MockRepository.GenerateStub<ChromosomeBase> (7),
                MockRepository.GenerateStub<ChromosomeBase> (8)
            };

            ExceptionAssert.IsThrowing(new ReinsertionException(target, "The minimum size of the offspring is 1."), () =>
            {
                target.SelectChromosomes(population, offspring, parents);
            });
        }
Beispiel #18
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 SelectChromosomes_CanExpandFalseWithoffspringSizeLowerThanMinSize_Exception()
        {
            var target = MockRepository.GeneratePartialMock<ReinsertionBase>(false, false);
            var chromosome = MockRepository.GenerateStub<ChromosomeBase> (2);
            var population = new Population (5, 6, chromosome);
            var offspring = new List<IChromosome> () {
                chromosome, chromosome, chromosome, chromosome
            };

            var parents = new List<IChromosome> () {
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2)
            };

            ExceptionAssert.IsThrowing (new ReinsertionException (target, "Cannot expand the number of chromosome in population. Try another reinsertion!"), () => {
                target.SelectChromosomes(population, offspring, parents);
            });
        }
        public void RegisterNewGeneration_AnyGeneration_DoNothing()
        {
            var target = new TrackingGenerationStrategy();
            var population = new Population(2, 6, new ChromosomeStub());

            population.CreateInitialGeneration();
            target.RegisterNewGeneration(population);
            Assert.AreEqual(1, population.Generations.Count);

            population.CreateNewGeneration(new List<IChromosome>() { new ChromosomeStub(), new ChromosomeStub() });
            target.RegisterNewGeneration(population);
            Assert.AreEqual(2, population.Generations.Count);

            population.CreateNewGeneration(new List<IChromosome>() { new ChromosomeStub(), new ChromosomeStub() });
            target.RegisterNewGeneration(population);
            Assert.AreEqual(3, population.Generations.Count);

            population.CreateNewGeneration(new List<IChromosome>() { new ChromosomeStub(), new ChromosomeStub() });
            target.RegisterNewGeneration(population);
            Assert.AreEqual(4, population.Generations.Count);
        }
        public void SelectChromosomes_CanCollapseAndExpandFalseWithoffspringSizeBetweenMinOrMaxSize_ChromosomesSelected()
        {
            var target = MockRepository.GeneratePartialMock<ReinsertionBase>(false, false);

            var chromosome = MockRepository.GenerateStub<ChromosomeBase> (2);
            var population = new Population (2, 5, chromosome);
            var offspring = new List<IChromosome> () {
                chromosome, chromosome, chromosome, chromosome
            };

            var parents = new List<IChromosome> () {
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2)
            };

            ExceptionAssert.IsThrowing (typeof(Rhino.Mocks.Exceptions.ExpectationViolationException), () => {
                target.SelectChromosomes (population, offspring, parents);
            });
        }
        public void RegisterNewGeneration_GenerationExceedGenerationsNumber_RemoveOldOne()
        {
            var target = new PerformanceGenerationStrategy();
            var population = new Population(2, 6, new ChromosomeStub());

            population.CreateInitialGeneration();
            target.RegisterNewGeneration(population);
            Assert.AreEqual(1, population.Generations.Count);

            population.CreateNewGeneration(new List<IChromosome>() { new ChromosomeStub(), new ChromosomeStub() });
            target.RegisterNewGeneration(population);
            Assert.AreEqual(1, population.Generations.Count);

            population.CreateNewGeneration(new List<IChromosome>() { new ChromosomeStub(), new ChromosomeStub() });
            target.RegisterNewGeneration(population);
            Assert.AreEqual(1, population.Generations.Count);

            population.CreateNewGeneration(new List<IChromosome>() { new ChromosomeStub(), new ChromosomeStub() });
            target.RegisterNewGeneration(population);
            Assert.AreEqual(1, population.Generations.Count);
        }
        public double Evaluate(IChromosome chromosome)
        {
            var autoConfigChromosome = chromosome as AutoConfigChromosome;
            var selection = autoConfigChromosome.Selection;
            var crossover = autoConfigChromosome.Crossover;
            var mutation = autoConfigChromosome.Mutation;
            var population = new Population(PopulationMinSize, PopulationMaxSize, m_targetChromosome);

            var ga = new GeneticAlgorithm(population, m_targetFitness, selection, crossover, mutation);
            ga.Termination = Termination;
            ga.TaskExecutor = TaskExecutor;

            try
            {
                ga.Start();
            }
            catch (Exception)
            {
                return 0;
            }

            return ga.BestChromosome.Fitness.Value;
        }
        public void SelectChromosomes_offspringSizeEqualsParentsSizeAndGreaterThanMinSizeAndLowerThanMaxSize_Selectoffspring()
        {
            var target = new PureReinsertion ();
            var chromosome = MockRepository.GenerateStub<ChromosomeBase> (2);

            var population = new Population (2, 6, chromosome);
            var offspring = new List<IChromosome> () {
                chromosome, chromosome, chromosome, chromosome
            };

            var parents = new List<IChromosome> () {
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2),
                MockRepository.GenerateStub<ChromosomeBase> (2)
            };

            var selected = target.SelectChromosomes (population, offspring, parents);
            Assert.AreEqual (4, selected.Count);
            Assert.AreEqual (2, selected [0].Length);
            Assert.AreEqual (2, selected [1].Length);
            Assert.AreEqual (2, selected [2].Length);
            Assert.AreEqual (2, selected [3].Length);
        }
 /// <summary>
 /// Selects the chromosomes which will be reinserted.
 /// </summary>
 /// <returns>The chromosomes to be reinserted in next generation..</returns>
 /// <param name="population">The population.</param>
 /// <param name="offspring">The offspring.</param>
 /// <param name="parents">The parents.</param>
 protected abstract IList<IChromosome> PerformSelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents);
        /// <summary>
        /// Initializes a new instance of the <see cref="GeneticSharp.Domain.GeneticAlgorithm"/> class.
        /// </summary>
        /// <param name="population">The chromosomes population.</param>
        /// <param name="fitness">The fitness evaluation function.</param>
        /// <param name="selection">The selection operator.</param>
        /// <param name="crossover">The crossover operator.</param>
        /// <param name="mutation">The mutation operator.</param>
        public GeneticAlgorithm(
            Population population,
            IFitness fitness,
            ISelection selection,
            ICrossover crossover,
            IMutation mutation)
        {
            ExceptionHelper.ThrowIfNull("Population", population);
            ExceptionHelper.ThrowIfNull("fitness", fitness);
            ExceptionHelper.ThrowIfNull("selection", selection);
            ExceptionHelper.ThrowIfNull("crossover", crossover);
            ExceptionHelper.ThrowIfNull("mutation", mutation);

            Population = population;
            Fitness = fitness;
            Selection = selection;
            Crossover = crossover;
            Mutation = mutation;
            Reinsertion = new ElitistReinsertion();
            Termination = new GenerationNumberTermination(1);

            CrossoverProbability = DefaultCrossoverProbability;
            MutationProbability = DefaultMutationProbability;
            TimeEvolving = TimeSpan.Zero;
            State = GeneticAlgorithmState.NotStarted;
            TaskExecutor = new LinearTaskExecutor();
        }
Beispiel #27
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();
        }
        private static void Run()
        {
            Console.SetError(TextWriter.Null);
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("GeneticSharp - ConsoleApp");
            Console.ResetColor();
            Console.WriteLine("Select the sample:");

            var sampleNames = TypeHelper.GetDisplayNamesByInterface<ISampleController>();

            for (int i = 0; i < sampleNames.Count; i++)
            {
                Console.WriteLine("{0}) {1}", i + 1, sampleNames[i]);
            }

            int sampleNumber = 0;
            string selectedSampleName = string.Empty;

            try
            {
                sampleNumber = Convert.ToInt32(Console.ReadLine());
                selectedSampleName = sampleNames[sampleNumber - 1];
            }
            catch (Exception)
            {
                Console.WriteLine("Invalid option.");
            }

            var sampleController = TypeHelper.CreateInstanceByName<ISampleController>(selectedSampleName);
            DrawSampleName(selectedSampleName);
            sampleController.Initialize();

            Console.WriteLine("Starting...");

            var selection = sampleController.CreateSelection();
            var crossover = sampleController.CreateCrossover();
            var mutation = sampleController.CreateMutation();
            var fitness = sampleController.CreateFitness();
            var population = new Population(100, 200, sampleController.CreateChromosome());
            population.GenerationStrategy = new PerformanceGenerationStrategy();

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

            var terminationName = ga.Termination.GetType().Name;

            ga.GenerationRan += delegate
            {
                DrawSampleName(selectedSampleName);

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

            try
            {
                sampleController.ConfigGA(ga);
                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();
            Run();
        }
 /// <summary>
 /// Register that a new generation has been created.
 /// </summary>
 /// <param name="population">The population where the new generation has been created.</param>
 public void RegisterNewGeneration(Population population)
 {
     // Do nothing, because wants to keep all generations in the line.
 }
 /// <summary>
 /// Selects the chromosomes which will be reinserted.
 /// </summary>
 /// <returns>The chromosomes to be reinserted in next generation..</returns>
 /// <param name="population">The population.</param>
 /// <param name="offspring">The offspring.</param>
 /// <param name="parents">The parents.</param>
 protected override IList<IChromosome> PerformSelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents)
 {
     return offspring;
 }
Beispiel #31
0
        /// <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);
        }