Beispiel #1
0
        public void Evolve_ManyGenerations_Fast()
        {
            var selection    = new EliteSelection();
            var crossover    = new UniformCrossover();
            var mutation     = new TworsMutation();
            var chromosome   = new BitmapChromosome(32, 32);
            var targetBitmap = new Bitmap(32, 32);
            var fitness      = new BitmapEqualityFitness(targetBitmap);

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

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

            ga.TaskExecutor = new ParallelTaskExecutor()
            {
                MinThreads = 10,
                MaxThreads = 20
            };

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

            var c = ga.BestChromosome as BitmapChromosome;

            Assert.IsNotNull(c);

            var bitmap = c.BuildBitmap();

            Assert.IsNotNull(bitmap);
            Assert.AreEqual(32, bitmap.Width);
            Assert.AreEqual(32, bitmap.Height);
        }
Beispiel #2
0
        public GeneticAlgorithm CreateGA(Func <RobotChromosome, Task <ContestGame> > contestFactory, RobotEvolutionConfiguration config)
        {
            NumberOfSimultaneousEvaluations = 2;
            var fitness    = new RobotFitness(contestFactory, config);
            var chromosome = new RobotChromosome(config);
            var crossover  = new UniformCrossover();
            var mutation   = new FlipBitMutation();
            var selection  = new EliteSelection();
            var population = new Population(NumberOfSimultaneousEvaluations, NumberOfSimultaneousEvaluations, chromosome)
            {
                GenerationStrategy = new PerformanceGenerationStrategy()
            };

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new RobotTermination(),

                //TaskExecutor = new LinearTaskExecutor(),
                TaskExecutor = new ParallelTaskExecutor
                {
                    MaxThreads = 10
                }
            };

            ga.GenerationRan += delegate
            {
                Console.WriteLine("Generation complete");
            };

            ga.MutationProbability = .1f;

            return(ga);
        }
Beispiel #3
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();
        }
Beispiel #4
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);
        }
Beispiel #5
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]);
        }
Beispiel #6
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);
        }
Beispiel #7
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);
        }
Beispiel #8
0
        public GeneticSharpSolver Setup()
        {
            var chromosome = new FloatingPointChromosome(
                _decisions.Select(d => d.LowerBound).ToArray(),
                _decisions.Select(d => d.UpperBound).ToArray(),
                _decisions.Select(d => d.TotalBits).ToArray(),
                _decisions.Select(d => d.FractionDigits).ToArray());

            var population = new Population(_populationSize, _populationSize + _offspringNumber, chromosome);

            var fitness     = new FuncFitness((c) => { return(_objective(c as FloatingPointChromosome, this)); });
            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new FlipBitMutation();
            var termination = new GenerationNumberTermination(_maxGenerations);

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

            _ga.Termination = termination;
            if (_generationCallback != null)
            {
                _ga.GenerationRan += (sender, e) => _generationCallback(_ga);
            }

            return(this);
        }
Beispiel #9
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();
        }
        protected override GeneticAlgorithm CreateGA()
        {
            NumberOfSimultaneousEvaluations = SimulationsGrid.x * SimulationsGrid.y;
            m_fitness = new CarFitness();
            var chromosome = new CarChromosome(Config);
            var crossover  = new UniformCrossover();
            var mutation   = new FlipBitMutation();
            var selection  = new EliteSelection();

            var population = new Population(NumberOfSimultaneousEvaluations, NumberOfSimultaneousEvaluations, chromosome)
            {
                GenerationStrategy = new PerformanceGenerationStrategy()
            };

            var ga = new GeneticAlgorithm(population, m_fitness, selection, crossover, mutation)
            {
                Termination  = new CarTermination(),
                TaskExecutor = new ParallelTaskExecutor
                {
                    MinThreads = population.MinSize,
                    MaxThreads = population.MaxSize * 2
                }
            };

            ga.GenerationRan += delegate
            {
                m_lastPosition = Vector3.zero;
                m_evaluationPool.ReleaseAll();
            };

            ga.MutationProbability = .1f;

            return(ga);
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            var data = new Data();

            var selection  = new EliteSelection();
            var crossover  = new UniformCrossover(0.5f);
            var mutation   = new FlipBitMutation();
            var fitness    = new FitnessFunction(data);
            var chromosome = new Chromosome(data.ItemsCount);
            var population = new Population(50, 70, chromosome);

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

            ga.Termination = new GenerationNumberTermination(100);

            Console.WriteLine("Rozpoczęcie wykonania algorytmu...");
            var watch = System.Diagnostics.Stopwatch.StartNew();

            ga.Start();
            watch.Stop();
            var executionTime = watch.ElapsedMilliseconds;

            Console.WriteLine("---------Wynik---------");
            var result = new Result(ga.BestChromosome, executionTime, data.ListOfItems);

            result.DisplayResult();

            Console.ReadLine();
        }
        public void InitiGA(GeneticAlgoritmConfig config)
        {
            Config = config;
            //IChromosome adamChromosome = new FloatingPointChromosome(config.MinChromosomeValue, config.MaxChromosomeValue, config.ChromosomeSize, config.ChromosomeFractionDigits);

            float       maxWidth       = 1000000;
            float       maxHeight      = 1000000;
            IChromosome adamChromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0 },
                new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
                new int[] { 64, 64, 64, 64 },
                new int[] { 2, 2, 2, 2 });

            Population population = new Population(config.MinPopulationSize, config.MinPopulationSize, adamChromosome);

            IFitness     fitness     = new SimpleFitness();
            ISelection   selection   = new EliteSelection();
            ICrossover   crossover   = new UniformCrossover(0.1f);
            IMutation    mutation    = new FlipBitMutation();
            ITermination termination = new FitnessStagnationTermination(config.StagnationGenerationCount);

            population.GenerationStrategy = new PerformanceGenerationStrategy();

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

            geneticAlgorithm.CrossoverProbability = config.CrossoverProbability;
            geneticAlgorithm.MutationProbability  = config.MutationProbability;

            geneticAlgorithm.GenerationRan      += OnNewGeneration;
            geneticAlgorithm.TerminationReached += OnTermination;
            geneticAlgorithm.Start();
        }
        /// <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 static GeneticSharp.Domain.GeneticAlgorithm DefaultGeneticAlgorithm(Func <double[], double> func, Tuple <double, double>[] minmax)
        {
            var population = new Population(20, 40, chromosome.CreateIntChromosone(minmax));

            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var values = fc.ToFloatingPoints();
                return(func(values));
            });

            var selection = new EliteSelection();
            var crossover = new UniformCrossover(0.5f);
            var mutation  = new FlipBitMutation();

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

            var termination = new FitnessStagnationTermination(100);

            ga.Termination = termination;


            Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");

            return(ga);
        }
Beispiel #15
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();
        }
Beispiel #16
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]);
        }
Beispiel #17
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();
        }
Beispiel #18
0
        public void OptimizeAI()
        {
            if (frequency != turnsSinceLastOptimization)
            {
                turnsSinceLastOptimization++;
                return;
            }

            GenerateScoreData();

            int maxSize = GetMaxSize();
            AiSettingsChromosome intelligenceChromosome = new AiSettingsChromosome(3);
            Population           population             = new Population(maxSize, maxSize, intelligenceChromosome);

            FuncFitness fitness;

            if (HistoryManagr.Instance.savingHistory == true)
            {
                fitness = new FuncFitness((c) => { return(GetHistoryFitness(c)); });
            }
            else
            {
                fitness = new FuncFitness((c) => { return(GetFitness(c)); });
            }

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new DisplacementMutation();
            var termination = new GenerationNumberTermination(2);

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            List <IChromosome> savedChromosomes = new List <IChromosome>();

            ga.Termination    = termination;
            ga.GenerationRan += (sender, e) =>
            {
                if (ga.GenerationsNumber == 2)
                {
                    savedChromosomes = (List <IChromosome>)ga.Population.CurrentGeneration.Chromosomes;
                }
            };

            ga.Start();

            turnsSinceLastOptimization = 0;
            settingsScoreData.Clear();
            settingsData.Clear();

            SetGeneratedData(savedChromosomes);
            foreach (PlayerData player in PlayerManager.Instance.players)
            {
                EventSaverManager.Instance.SaveDDAEvolutionAIEvent(player.id);
            }
        }
Beispiel #19
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);
            }
        }
Beispiel #20
0
        public void PerformTest(int childrenCount, int parentsCount, int cutPoints, int bitAlign)
        {
            _uniformCrossover = new UniformCrossover()
            {
                BitAlign = 1, ChildrenCount = childrenCount, ParentsCount = parentsCount
            };
            var children = _uniformCrossover.Cross(_parents.Take(parentsCount).ToArray());

            Assert.NotNull(children);
            Assert.AreEqual(childrenCount, children.Length);
            foreach (var genotype in children)
            {
                Assert.NotNull(genotype);
            }
            Assert.Pass();
        }
        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);
        }
        public void Start_FloatingPoingChromosome_Evolved()
        {
            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0 },
                new double[] { 1000, 1000, 1000, 1000 },
                new int[] { 10, 10, 10, 10 },
                new int[] { 0, 0, 0, 0 });

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

            var fitness = new FuncFitness((c) =>
            {
                var f = c as FloatingPointChromosome;

                var values = f.ToFloatingPoints();
                var x1     = values[0];
                var y1     = values[1];
                var x2     = values[2];
                var y2     = values[3];

                // Euclidean distance: https://en.wikipedia.org/wiki/Euclidean_distance
                return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)));
            });

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover();
            var mutation    = new FlipBitMutation();
            var termination = new FitnessStagnationTermination(100);

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

            ga.Termination = termination;
            ga.Start();

            var bc     = ga.BestChromosome as FloatingPointChromosome;
            var points = bc.ToFloatingPoints();

            Assert.AreEqual(4, points.Length);

            Assert.AreEqual(1414.2135623730951, bc.Fitness);
            Assert.GreaterOrEqual(ga.GenerationsNumber, 100);
        }
Beispiel #23
0
        public static void Main(string[] args)
        {
            FitnessFunction.Rides         = ParseData(out int fleetSize, out int bonus, out int steps);
            Chromosome.FleetSize          = fleetSize;
            FitnessFunction.NumberOfSteps = steps;
            FitnessFunction.Bonus         = bonus;

            var mutation        = new UniformMutation(MutationProbability);
            var selection       = new KTournamentSelection(TournamentSize);
            var crossover       = new UniformCrossover();
            var fitnessFunction = new FitnessFunction();

            var geneticAlgorithm = new EliminationGeneticAlgorithm(mutation, selection, crossover, fitnessFunction,
                                                                   IterationLimit, FitnessTerminator, PopulationSize, FitnessFunction.Rides.Count);

            var optimum = geneticAlgorithm.FindOptimum();

            WriteOutput(optimum);
        }
Beispiel #24
0
        public Sudoku ResoudreSudoku(Sudoku s)
        {
            var populationSize = 100000;

            var sudokuChromosome = new SudokuPermutationsChromosome(s);


            var fitness = new SudokuFitness(s);

            var selection = new EliteSelection();

            var crossover = new UniformCrossover();

            var mutation = new UniformMutation();



            var population = new Population(populationSize, populationSize, sudokuChromosome);

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

            {
                Termination = new OrTermination(new ITermination[]

                {
                    new FitnessThresholdTermination(0),

                    new GenerationNumberTermination(80)
                })
            };



            ga.Start();



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

            var solutions = bestIndividual.GetSudokus();

            return(solutions[0]);
        }
Beispiel #25
0
        public void Evolve_CompareToSingleChromosome_Evolved()
        {
            int numberOfCities = 30;
            var selection      = new EliteSelection();
            var crossover      = new UniformCrossover();
            var mutation       = new TworsMutation();


            // Given enough generations, the Multiple Chromosome should start exhibiting convergence
            // we compare TSP /25 gen with 3*TSP / 500 gen

            IChromosome chromosome = new TspChromosome(numberOfCities);
            IFitness    fitness    = new TspFitness(numberOfCities, 0, 1000, 0, 1000);
            var         population = new Population(30, 30, chromosome);
            var         ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new GenerationNumberTermination(26)
            };

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

            chromosome = new MultipleChromosome((i) => new TspChromosome(numberOfCities), 3);
            //MultiChromosome should create 3 TSP chromosomes and store them in the corresponding property
            Assert.AreEqual(((MultipleChromosome)chromosome).Chromosomes.Count, 3);
            var tempMultiFitness = ((MultipleChromosome)chromosome).Chromosomes.Sum(c => fitness.Evaluate(c));

            fitness = new MultipleFitness(fitness);
            //Multi fitness should sum over the fitnesses of individual chromosomes
            Assert.AreEqual(tempMultiFitness, fitness.Evaluate(chromosome));
            population = new Population(30, 30, chromosome);
            ga         = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                Termination = new GenerationNumberTermination(501)
            };
            ga.Start();
            var bestTSPChromosome = (TspChromosome)((MultipleChromosome)ga.Population.BestChromosome).Chromosomes
                                    .OrderByDescending(c => c.Fitness).First();
            var multiChromosomesDistance = bestTSPChromosome.Distance;

            Assert.Less(multiChromosomesDistance, simpleChromosomeDistance);
        }
Beispiel #26
0
        public static Sudoku Eval(Sudoku sudoku, int populationSize, double fitnessThreshold, int generationNb)
        {
            //creation du chromosome
            IChromosome chromosome = new SudokuPermutationsChromosome(sudoku);

            //variable qui indique l'erreure
            var fitness = new SudokuFitness(sudoku);

            //choix de la selection : ici elite
            var selection = new EliteSelection();
            //var selection = new RouletteWheelSelection();
            //var selection = new SelectionException();
            //var selection = new TournamentSelection();

            //Choix du crossover : ici uniform
            var crossover = new UniformCrossover();

            //choix de la mutation : ici uniform
            var mutation = new UniformMutation();

            //creation de la population
            var population = new Population(populationSize, populationSize, chromosome);

            //création de l'algo génétique
            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                //pour mettre fin a l'exec si on atteint le threshold ou le nombre de rep fixé
                Termination = new OrTermination(new ITermination[]
                {
                    new FitnessThresholdTermination(fitnessThreshold),
                    new GenerationNumberTermination(generationNb)
                })
            };

            ga.Start();

            //recupération de la meilleure solution
            var bestIndividual = ((ISudokuChromosome)ga.Population.BestChromosome);
            var solutions      = bestIndividual.GetSudokus();

            return(solutions[0]);
        }
Beispiel #27
0
        public Task <Timetable> RunAsync()
        {
            var adamChromosome = CreateAdamChromosome();

            var population = new Population(50, 100, adamChromosome);

            var fitness = new FuncFitness(TimetablerFitnessFunction);

            var selection = new EliteSelection();

            var crossover = new UniformCrossover(0.5f);

            var mutation = new FlipBitMutation();

            var termination = new TimeEvolvingTermination(TimeSpan.FromSeconds(20));

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

            geneticAlgorithm.GenerationRan += (sender, e) =>
            {
                var bestChromosome = geneticAlgorithm.BestChromosome as FloatingPointChromosome;
                GeneticSolution = ChromosomeToTimetable(bestChromosome);
            };

            GeneticAlgorithm = geneticAlgorithm;

            return(Task.Factory.StartNew(() =>
            {
                geneticAlgorithm.Start();
                return GeneticSolution;
            }));
        }
        public static GeneticAlgorithm GetGeneticAlgorithm()
        {
            var chromosome  = new ConfigurationChromosome();
            var population  = new Population(50, 100, chromosome);
            var fitness     = new CorrectPercentageFitness();
            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new FlipBitMutation();
            var termination = new FitnessStagnationTermination(100);

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

            return(ga);
        }
        public void SinglePointCrossoverApplyTest()
        {
            TestRandom   random = new TestRandom();
            BinaryVector parent1, parent2, expected, actual;
            bool         exceptionFired;

            // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 49
            random.Reset();
            random.DoubleNumbers = new double[] { 0.35, 0.62, 0.18, 0.42, 0.83, 0.76, 0.39, 0.51, 0.36 };
            parent1  = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
            parent2  = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
            expected = new BinaryVector(new bool[] { false, true, false, false, false, false, false, false, false });
            actual   = UniformCrossover.Apply(random, parent1, parent2);
            Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

            // The following test is based on Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, p. 49
            random.Reset();
            random.DoubleNumbers = new double[] { 0.35, 0.62, 0.18, 0.42, 0.83, 0.76, 0.39, 0.51, 0.36 };
            parent2  = new BinaryVector(new bool[] { false, false, false, false, true, false, false, false, false });
            parent1  = new BinaryVector(new bool[] { true, true, false, true, false, false, false, false, true });
            expected = new BinaryVector(new bool[] { true, false, false, true, true, false, false, false, true });
            actual   = UniformCrossover.Apply(random, parent1, parent2);
            Assert.IsTrue(Auxiliary.BinaryVectorIsEqualByPosition(actual, expected));

            // The following test is not based on any published examples
            random.Reset();
            random.DoubleNumbers = new double[] { 0.35, 0.62, 0.18, 0.42, 0.83, 0.76, 0.39, 0.51, 0.36 };
            parent1        = new BinaryVector(new bool[] { false, true, true, false, false }); // this parent is longer
            parent2        = new BinaryVector(new bool[] { false, true, true, false });
            exceptionFired = false;
            try {
                actual = UniformCrossover.Apply(random, parent1, parent2);
            }
            catch (System.ArgumentException) {
                exceptionFired = true;
            }
            Assert.IsTrue(exceptionFired);
        }
Beispiel #30
0
        public static FloatingPointChromosome EvolveGeneticAlgorithm(FloatingPointChromosome chromosome, IOthelloAgent agent, string chromosomeLabel = "")
        {
            IPopulation population = new TplPopulation(30, 60, chromosome);
            IFitness    fitness    = new EvaluationFitness(agent);
            ISelection  selection  = new RouletteWheelSelection(); //Guess
            ICrossover  crossover  = new UniformCrossover();       //Guess
            IMutation   mutation   = new UniformMutation();        //Guess


            ITermination stagnation = new FitnessStagnationTermination(500);
            ITermination threshold  = new FitnessThresholdTermination(.9);

            ITaskExecutor taskExecutor = new ParallelTaskExecutor()
            {
                MaxThreads = Environment.ProcessorCount,
                MinThreads = Environment.ProcessorCount / 2
            };


            GeneticAlgorithm algorithm = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                TaskExecutor        = new TplTaskExecutor(),
                MutationProbability = .2f
            };

            algorithm.TaskExecutor = taskExecutor;
            algorithm.Termination  = stagnation;

            algorithm.Start();

            SaveChromosome((FloatingPointChromosome)algorithm.BestChromosome, chromosomeLabel);

            Debug.WriteLine("finished Training, with {0} time spent on evolving", algorithm.TimeEvolving);
            Debug.WriteLine("fitness of this generation vs the last : {0}", algorithm.Fitness);

            return((FloatingPointChromosome)algorithm.BestChromosome);
        }