Ejemplo n.º 1
0
        public IChromosome Compute(TrainingModel <ContextInfo> model, IChromosome baseChromosome)
        {
            model.InitializePartitions(_folds);

            var sw = new Stopwatch();

            sw.Start();

            var selection  = new EliteSelection();
            var crossover  = new TwoPointCrossover(); // Or OnePoint
            var mutation   = new UniformMutation(true);
            var fitness    = new Fitness(model);
            var chromosome = baseChromosome == null ? new Chromosome() : baseChromosome;
            var population = new Population(2, 5, chromosome);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new OrTermination(
                    new GenerationNumberTermination(5),
                    new FitnessStagnationTermination(),
                    new FitnessThresholdTermination(baseChromosome.Fitness.HasValue ? baseChromosome.Fitness.Value : 0.0))
            };

            Console.WriteLine("GA running...");
            ga.Start();

            sw.Stop();
            Console.WriteLine("Best solution found has {0} fitness. Time elapsed {1}", ga.BestChromosome.Fitness, sw.Elapsed);
            foreach (var gene in ga.BestChromosome.GetGenes())
            {
                Console.WriteLine(gene);
            }

            return(ga.BestChromosome);
        }
        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);
        }
Ejemplo n.º 3
0
        public void Mutate_AllGenesMutablesTrue_AllGenesMutaed()
        {
            var target     = new UniformMutation(true);
            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(1)).Return(new Gene(10));
            chromosome.Expect(c => c.GenerateGene(2)).Return(new Gene(20));
            RandomizationProvider.Current = MockRepository.GenerateMock <IRandomization>();

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

            chromosome.VerifyAllExpectations();
            RandomizationProvider.Current.VerifyAllExpectations();
        }
Ejemplo n.º 4
0
        public static Sudoku Eval(Sudoku sudoku, int populationSize, double fitnessThreshold, int generationNb)
        {
            //creation du chromosome
            IChromosome chromosome = new SudokuPermutationsChromosome(sudoku);
            var         fitness    = new SudokuFitness(sudoku);

            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation  = new UniformMutation();

            var population = new Population(populationSize, populationSize, chromosome);
            var ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new OrTermination(new ITermination[]
                {
                    new FitnessThresholdTermination(fitnessThreshold),
                    new GenerationNumberTermination(generationNb)
                })
            };

            ga.Start();

            var bestIndividual = ((ISudokuChromosome)ga.Population.BestChromosome);
            var solutions      = bestIndividual.GetSudokus();

            return(solutions[0]);
        }
Ejemplo n.º 5
0
        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);
            });
        }
Ejemplo n.º 6
0
        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();
            });
        }
Ejemplo n.º 7
0
        public AnalysisResults Optimize(PixelStructure structure)
        {
            var chromosome = new StructuralChromosome(structure.Pixels.Count);

            var population = new Population(5, 10, chromosome);

            var fitness = new StructuralFitness(structure);

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new UniformMutation(); //FlipBitMutation();
            var termination = new FitnessStagnationTermination(10);

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

            ga.Termination = termination;

            ga.GenerationRan += GenerationRan;

            ga.Start();

            var structRes = ga.BestChromosome as StructuralChromosome;

            return(structRes.Results);
        }
Ejemplo n.º 8
0
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.Error.WriteLine("You have to at least specify the data file path");
                return;
            }

            var mutation  = new UniformMutation(MutationProbability);
            var selection = new KTournamentSelection(TournamentSize);
            var crossover = new ArithmeticCrossover();

            var fitnessFunction = new FitnessFunction(args[0]);

            IGeneticAlgorithm <DecimalArrayChromosome> geneticAlgorithm;

            if (args.Length == 2 && args[1].ToLower() == "gen")
            {
                geneticAlgorithm = new GenerationGeneticAlgorithm(mutation, selection, crossover, fitnessFunction,
                                                                  IterationLimit, FitnessTerminator, PopulationSize);
            }
            else
            {
                geneticAlgorithm = new EliminationGeneticAlgorithm(mutation, selection, crossover, fitnessFunction,
                                                                   IterationLimit, FitnessTerminator, PopulationSize);
            }

            var optimum = geneticAlgorithm.FindOptimum();

            Console.WriteLine();
            Console.WriteLine(optimum);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// GeneticSharp Console Application template.
        /// <see href="https://github.com/giacomelli/GeneticSharp"/>
        /// </summary>
        static void Main(string[] args)
        {
            // TODO: use the best genetic algorithm operators to your optimization problem.
            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation  = new UniformMutation(true);

            var fitness    = new chessQueenFitness();
            var chromosome = new chessQueenChromosome();

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

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

            //ga.Termination = new FitnessStagnationTermination(4);
            ga.Termination = new FitnessThresholdTermination(0);

            ga.GenerationRan += (s, e) => Console.WriteLine($"Generation {ga.GenerationsNumber}. Best fitness: {ga.BestChromosome.Fitness.Value}");
            ga.GenerationRan += (s, e) => Console.WriteLine($"Chromosome Sample 1:" + String.Join("", ga.Population.CurrentGeneration.Chromosomes[0].GetGenes()));
            ga.GenerationRan += (s, e) => Console.WriteLine($"Chromosome Sample 2:" + String.Join("", ga.Population.CurrentGeneration.Chromosomes[1].GetGenes()));
            ga.GenerationRan += (s, e) => Console.WriteLine($"Chromosome Sample 3:" + String.Join("", ga.Population.CurrentGeneration.Chromosomes[2].GetGenes()));
            ga.GenerationRan += (s, e) => Console.WriteLine($"Chromosome Sample 4:" + String.Join("", ga.Population.CurrentGeneration.Chromosomes[3].GetGenes()));
            ga.GenerationRan += (s, e) => Console.WriteLine($"Chromosome Sample 5:" + String.Join("", ga.Population.CurrentGeneration.Chromosomes[4].GetGenes()));
            ga.GenerationRan += (s, e) => Console.WriteLine($"Best Chromosome: " + String.Join("", ga.Population.CurrentGeneration.BestChromosome.GetGenes()));


            Console.WriteLine("GA running...");
            ga.Start();

            Console.WriteLine();
            Console.WriteLine($"Best solution found has fitness: {ga.BestChromosome.Fitness}");
            Console.WriteLine($"Elapsed time: {ga.TimeEvolving}");
            //Console.ReadKey();
        }
        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.");
        }
Ejemplo n.º 11
0
        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 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);
        }
        public void Start_UsingAllConfigurationCombinationsAvailable_AllRun()
        {
            var selections   = SelectionService.GetSelectionNames();
            var crossovers   = CrossoverService.GetCrossoverNames();
            var mutations    = MutationService.GetMutationNames().Where(m => !m.Equals("Flip Bit"));
            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);
                        }
                    }
                }
            }
        }
Ejemplo n.º 14
0
        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.Less(target.TimeEvolving.TotalMilliseconds, 1000);
        }
Ejemplo n.º 16
0
        private GeneticAlgorithm PrepareGeneticAlgorithm(string[][] board)
        {
            double[][] parsedBoard = this.ParseBoardToDouble(board);

            var chromosome = new TicTacToeChromosome(parsedBoard);
            var population = new Population(50, 100, chromosome);
            var fitness    = new TicTacToeFitness
            {
                Minimum = BOARD_SIZE
            };
            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new UniformMutation();
            var termination = new OrTermination(new ITermination[]
            {
                new FitnessStagnationTermination(3000),
                new FitnessThresholdTermination(4),
                new FitnessThresholdTermination(3),
                new FitnessThresholdTermination(2)
            });

            var geneticAlgorithm = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = termination
            };

#if DEBUG
            geneticAlgorithm.GenerationRan += (sender, e) =>
            {
                var bestChromosome = geneticAlgorithm.BestChromosome as TicTacToeChromosome;
                Console.WriteLine($"Generation { geneticAlgorithm.GenerationsNumber }: Position ({ bestChromosome.Position.X }, { bestChromosome.Position.Y }) = { bestChromosome.Fitness }");
            };
#endif
            return(geneticAlgorithm);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// GeneticSharp Console Application template.
        /// <see href="https://github.com/giacomelli/GeneticSharp"/>
        /// </summary>
        static void Main(string[] args)
        {
            // TODO: use the best genetic algorithm operators to your optimization problem.
            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation  = new UniformMutation(true);

            var fitness    = new MyProblemFitness();
            var chromosome = new MyProblemChromosome();

            var population = new Population(50, 70, chromosome);

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

            ga.Termination    = new FitnessStagnationTermination(100);
            ga.GenerationRan += (s, e) => Console.WriteLine($"Generation {ga.GenerationsNumber}. Best fitness: {ga.BestChromosome.Fitness.Value}");

            Console.WriteLine("GA running...");
            ga.Start();

            Console.WriteLine();
            Console.WriteLine($"Best solution found has fitness: {ga.BestChromosome.Fitness}");
            Console.WriteLine($"Elapsed time: {ga.TimeEvolving}");
            Console.ReadKey();
        }
Ejemplo n.º 18
0
        public void Solve()
        {
            SudokuBoard sudokuBoard = Transform(Sudoku);
            IChromosome chromosome  = new SudokuPermutationsChromosome(sudokuBoard);

            var fitness   = new SudokuFitness(sudokuBoard);
            var selection = new EliteSelection();
            var crossover = new UniformCrossover();
            var mutation  = new UniformMutation();

            var population = new Population(5000, 5000, chromosome);
            var ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new OrTermination(new ITermination[]
                {
                    new FitnessThresholdTermination(0),
                    new GenerationNumberTermination(100)
                })
            };

            ga.Start();

            var bestIndividual = ((ISudokuChromosome)ga.Population.BestChromosome);
            var solutions      = bestIndividual.GetSudokus();

            Sudoku = Transform(solutions[0]);
        }
Ejemplo n.º 19
0
        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)
                ,
                new FunctionBuilderInput(
                    new double[] { 2, 3 },
                    5)
                );
            var chromosome = new FunctionBuilderChromosome(fitness.AvailableOperations, 3);

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

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

            ga.Termination = new OrTermination(new FitnessThresholdTermination(0), new TimeEvolvingTermination(TimeSpan.FromSeconds(15)));
            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 }, 7)
                );

            Assert.AreEqual(7, actual);
        }
Ejemplo n.º 20
0
        public void Start()
        {
            var fitness = new StringFitness(targetString);
            var chromosome = new StringChromosome(targetString.Length);
            var crossover = new UniformCrossover(0.5f);
            var mutation = new UniformMutation();
            var selection = new EliteSelection();
            var population = new Population(1000, 1000, chromosome);
            var termination = new FitnessThresholdTermination(1.00);

            ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            ga.Termination = termination;

            var latestFitness = 0.0;

            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as StringChromosome;
                var bestFitness = bestChromosome.Fitness.Value;

                Console.WriteLine(
                        "Generation {0}: \n{1} \nFitness: {2}",
                        ga.GenerationsNumber,
                        bestChromosome.Sentence,
                        bestFitness
                    );

                if (bestFitness > latestFitness)
                {
                    latestFitness = bestFitness;
                }
            };

            ga.Start();
        }
        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);
        }
Ejemplo n.º 22
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine($"[{DateTime.Now}] Tuner start");
            SettingsLoader.Init("settings.json");

            _webService          = new WebService();
            _generationStopwatch = new Stopwatch();

            await _webService.EnableIfAvailable();

            _testId = await _webService.RegisterTest();

            var selection  = new EliteSelection();
            var crossover  = new UniformCrossover(0.5f);
            var mutation   = new UniformMutation(true);
            var fitness    = new EvaluationFitness(_testId, _webService);
            var chromosome = new EvaluationChromosome();
            var population = new Population(SettingsLoader.Data.MinPopulation, SettingsLoader.Data.MaxPopulation, chromosome);

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

            geneticAlgorithm.Termination    = new GenerationNumberTermination(SettingsLoader.Data.GenerationsCount);
            geneticAlgorithm.GenerationRan += GeneticAlgorithm_GenerationRan;

            _generationStopwatch.Start();
            geneticAlgorithm.Start();

            Console.WriteLine("Best solution found has {0} fitness.", geneticAlgorithm.BestChromosome.Fitness);
            Console.ReadLine();
        }
Ejemplo n.º 23
0
        static async Task Main(string[] args)
        {
            Console.WriteLine($"[{DateTime.Now}] Tuner start");
            SettingsLoader.Init("settings.json");

            IFitness    fitness    = null;
            IChromosome chromosome = null;

            _webService = new WebService();
            await _webService.EnableIfAvailable();

            _testId = await _webService.RegisterTest(new RegisterTestRequest
            {
                Type = TestType.Texel
            });

            var scalingFactorMode = args.Contains("scaling_factor");

            if (scalingFactorMode)
            {
                SettingsLoader.Data.Genes.Clear();
                SettingsLoader.Data.Genes.Add(new GeneInfo
                {
                    Name     = "ScalingFactor",
                    MinValue = 0,
                    MaxValue = 2000
                });
                SettingsLoader.Data.Genes.Add(new GeneInfo
                {
                    Name     = "Unused",
                    MinValue = 0,
                    MaxValue = 1
                });

                fitness    = new ScalingFactorFitness(_testId, _webService);
                chromosome = new ScalingFactorChromosome();
            }
            else
            {
                fitness    = new EvaluationFitness(_testId, _webService);
                chromosome = new EvaluationChromosome();
            }

            var selection        = new EliteSelection();
            var crossover        = new UniformCrossover(0.5f);
            var mutation         = new UniformMutation(true);
            var population       = new Population(SettingsLoader.Data.MinPopulation, SettingsLoader.Data.MaxPopulation, chromosome);
            var geneticAlgorithm = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

            geneticAlgorithm.Termination    = new GenerationNumberTermination(SettingsLoader.Data.GenerationsCount);
            geneticAlgorithm.GenerationRan += GeneticAlgorithm_GenerationRan;

            _generationStopwatch = new Stopwatch();
            _generationStopwatch.Start();
            geneticAlgorithm.Start();

            Console.WriteLine("Best solution found has {0} fitness.", geneticAlgorithm.BestChromosome.Fitness);
            Console.ReadLine();
        }
Ejemplo n.º 24
0
        public IMutation UniformMutation()
        {
            var target = new UniformMutation();

            target.Mutate(new TspChromosome(_numberOfCities), _probability);

            return(target);
        }
Ejemplo n.º 25
0
        public void Should_Perform_Mutation()
        {
            var algorithm = new UniformMutation(1, -0.1, 0.1);
            var a         = new Element(new double[] { 8D, 3D, 2D, 9D, 1D, 0D, 7D, 6D, 5D, 4D });
            var index     = 1;

            algorithm.Mutate(ref a, index);
            Assert.NotEqual(3D, a.Data[1]);
            Assert.InRange(a.Data[1], 2.9, 3.1);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Рассчитать топологию для графа проекта с помощью генетического алгоритма.
        /// </summary>
        /// <param name="project">Объект свойств проекта по внедрению сети.</param>
        /// <returns>Сгенерированная топология или null, если произошла ошибка.</returns>
        public static Topology CalculateTopologyWithGA(Project project)
        {
            try
            {
                Console.Write("Setup GA... ");

                var chromosome = new TopologyChromosome(project);
                var selection  = new EliteSelection();
                var crossover  = new UniformCrossover(0.5f);
                var mutation   = new UniformMutation(true);
                var fitness    = new TopologyFitness();
                var population = new Population(POPULATION_SIZE, POPULATION_SIZE, chromosome);

                var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
                {
                    Termination = new GenerationNumberTermination(NUMBER_OF_GENERATIONS)
                };

                // Записать значения в csv файл и строить график фитнес-функции
                using (var streamwriter = File.AppendText(Path.Combine(OUTPUT_DIR_NAME, $"fitness-{DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")}.csv")))
                {
                    ga.GenerationRan += (c, e) =>
                    {
                        Console.WriteLine("Generations: {0}", ga.Population.GenerationsNumber);
                        Console.WriteLine("Time: {0}", ga.TimeEvolving);

                        var bc = ga.Population.BestChromosome as TopologyChromosome;

                        streamwriter.WriteLine($"{ga.Population.GenerationsNumber};{ga.TimeEvolving:hh\\:mm\\:ss};{bc.Fitness:0.00};");

                        Console.WriteLine("Best solution found with {0} fitness.", bc.Fitness);
                    };

                    Console.Write("Done!\nRun GA... ");

                    ga.Start();
                }

                Console.WriteLine("Done in {0} generations!", ga.GenerationsNumber);

                var bestChromosome = ga.BestChromosome as TopologyChromosome;

                Console.WriteLine("Best solution found with {0} fitness", bestChromosome.Fitness);

                return(bestChromosome.Decode());
            }
            catch (Exception ex)
            {
                Console.WriteLine("CalculateResultWithGA failed! {0}", ex.Message);
                return(null);
            }
        }
        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);
            });
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            // Problem: Simple addition
            // 1 + 1 = 2
            // 2 + 2 = 4
            // 3 + 2 = 5
            var myInputs = new List <FunctionBuilderInput>
            {
                new FunctionBuilderInput(new List <double> {
                    1, 1
                }, 2),
                new FunctionBuilderInput(new List <double> {
                    2, 2
                }, 4),
                new FunctionBuilderInput(new List <double> {
                    3, 2
                }, 5)
            };
            var myFitness    = new FunctionBuilderFitness(myInputs.ToArray());
            var myChromosome = new FunctionBuilderChromosome(myFitness.AvailableOperations, 5);
            var selection    = new EliteSelection();
            var crossover    = new ThreeParentCrossover();
            var mutation     = new UniformMutation(true);
            var fitness      = myFitness;
            var chromosome   = myChromosome;
            var population   = new Population(100, 200, chromosome)
            {
                GenerationStrategy = new PerformanceGenerationStrategy()
            };
            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new FitnessThresholdTermination(0)
            };

            ga.GenerationRan += delegate
            {
                Console.Clear();
                var bestChromosome = ga.Population.BestChromosome;
                Console.WriteLine("Generations: {0}", ga.Population.GenerationsNumber);
                Console.WriteLine("Fitness: {0,10}", bestChromosome.Fitness);
                Console.WriteLine("Time: {0}", ga.TimeEvolving);
                Console.WriteLine("Speed (gen/sec): {0:0.0000}", ga.Population.GenerationsNumber / ga.TimeEvolving.TotalSeconds);
                var best = bestChromosome as FunctionBuilderChromosome;
                Console.WriteLine("Function: {0}", best.BuildFunction());
            };
            ga.Start();
            Console.WriteLine("Evolved.");
            Console.ReadKey();
        }
        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);
        }
Ejemplo n.º 30
0
        public void Evolve_ManyGenerations_Fast()
        {
            var selection  = new EliteSelection();
            var crossover  = new UniformCrossover();
            var mutation   = new UniformMutation(true);
            var chromosome = new GhostwriterChromosome(4, new string[] { "The", "C#", "Genetic", "Algorithm", "library" });
            var fitness    = new GhostwriterFitness((t) => t.Length);

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

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

            Assert.NotNull(ga.BestChromosome);
        }