Esempio n. 1
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);
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            // Creates and run the first GA.
            var chromosome = new TspChromosome(100);
            var population = new Population(50, 50, chromosome);
            var ga         = CreateGA(population);

            ga.Termination = new GenerationNumberTermination(100);
            ga.Start();
            Console.WriteLine("Best chromosome before chromossomes serialization is:");
            ShowChromosome(ga.BestChromosome as TspChromosome);
            SerializeChromosomes(population.CurrentGeneration.Chromosomes);


            // Reload GA with serialized chromossomes from previous GA.
            Console.WriteLine("Deserializing...");
            var chromosomes = DerializeChromosomes();

            // Use a diff IPopulation implementation.
            var preloadPopulation = new PreloadPopulation(50, 50, chromosomes);

            ga             = CreateGA(preloadPopulation);
            ga.Termination = new GenerationNumberTermination(1);
            ga.Start();
            Console.WriteLine("Best chromosome is:");
            ShowChromosome(ga.BestChromosome as TspChromosome);

            Console.ReadKey();
        }
Esempio n. 3
0
        public void GenerateGene_FitnessLowerThanZero_Zero()
        {
            var target    = new TspChromosome(10);
            var cityIndex = Convert.ToDouble(target.GenerateGene(0).Value);

            Assert.IsTrue(cityIndex >= 0 && cityIndex < 10);
        }
    private void Start()
    {
        var fitness    = new TspFitness(m_numberOfCities);
        var chromosome = new TspChromosome(m_numberOfCities);

        // This operators are classic genetic algorithm operators that lead to a good solution on TSP,
        // but you can try others combinations and see what result you get.
        var crossover  = new OrderedCrossover();
        var mutation   = new ReverseSequenceMutation();
        var selection  = new RouletteWheelSelection();
        var population = new Population(50, 100, chromosome);

        m_ga             = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
        m_ga.Termination = new TimeEvolvingTermination(System.TimeSpan.FromHours(1));

        // The fitness evaluation of whole population will be running on parallel.
        m_ga.TaskExecutor = new ParallelTaskExecutor
        {
            MinThreads = 100,
            MaxThreads = 200
        };

        // Everty time a generation ends, we log the best solution.
        m_ga.GenerationRan += delegate
        {
            var distance = ((TspChromosome)m_ga.BestChromosome).Distance;
            Debug.Log($"Generation: {m_ga.GenerationsNumber} - Distance: ${distance}");
        };

        DrawCities();

        // Starts the genetic algorithm in a separate thread.
        m_gaThread = new Thread(() => m_ga.Start());
        m_gaThread.Start();
    }
Esempio n. 5
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(100000, () =>
            {
                ga.Start();
            });

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

            Assert.Less(lastDistance, firstDistance);
        }
Esempio n. 6
0
        public void Clone_NoArgs_Cloned()
        {
            var target = new TspChromosome(10);

            var actual = target.Clone() as TspChromosome;

            Assert.IsFalse(Object.ReferenceEquals(target, actual));
        }
Esempio n. 7
0
        /// <summary>
        /// Updates the sample.
        /// </summary>
        public override void Update()
        {
            var population = Context.Population;

            if (population != null && population.CurrentGeneration != null)
            {
                m_bestChromosome = population.BestChromosome as TspChromosome;
            }
        }
Esempio n. 8
0
        public void Evaluate_ChromosomeWithLowerCities_FitnessDividedByDiff()
        {
            var target     = new TspFitness(10, 0, 10, 0, 10);
            var chromosome = new TspChromosome(9);

            var actual = target.Evaluate(chromosome);

            Assert.AreNotEqual(0, actual);
        }
Esempio n. 9
0
        public void Evaluate_FitnessLowerThanZero_Zero()
        {
            var target     = new TspFitness(10, 0, 10000000, 0, 10000000);
            var chromosome = new TspChromosome(10);

            var actual = target.Evaluate(chromosome);

            Assert.AreEqual(0, actual);
        }
Esempio n. 10
0
        private static void ShowChromosome(TspChromosome c)
        {
            Console.WriteLine("Fitness: {0:n2}", c.Fitness);
            Console.WriteLine("Cities: {0:n0}", c.Length);
            Console.WriteLine("Distance: {0:n2}", c.Distance);

            var cities = c.GetGenes().Select(g => g.Value.ToString()).ToArray();

            Console.WriteLine("City tour: {0}", string.Join(", ", cities));
        }
        public void Cross_TspChromosome_Child()
        {
            var target      = new AlternatingPositionCrossover();
            var chromosome1 = new TspChromosome(100);
            var chromosome2 = new TspChromosome(100);
            var actual      = target.Cross(new TspChromosome[] { chromosome1, chromosome2 });

            Assert.AreEqual(2, actual.Count);

            CollectionAssert.AllItemsAreUnique(chromosome1.GetGenes());
            CollectionAssert.AllItemsAreUnique(chromosome2.GetGenes());
        }
        public override IFitness CreateFitness()
        {
            var targetChromosome = new TspChromosome(10);
            var targetFitness    = new TspFitness(10, 0, 100, 0, 100);

            var fitness = new AutoConfigFitness(targetFitness, targetChromosome);

            fitness.Termination       = new FitnessStagnationTermination(500);
            fitness.PopulationMinSize = 20;
            fitness.PopulationMaxSize = 20;

            return(fitness);
        }
Esempio n. 13
0
    public void Initialize(int numberOfCities, int areaWidth, int areaHeight)
    {
        Stop();
        Fitness = new TspFitness(numberOfCities, areaWidth, areaHeight);
        var chromosome = new TspChromosome(numberOfCities);

        // This operators are classic genetic algorithm operators that lead to a good solution on TSP,
        // but you can try others combinations and see what result you get.
        var crossover  = new OrderedCrossover();
        var mutation   = new ReverseSequenceMutation();
        var selection  = new RouletteWheelSelection();
        var population = new Population(50, 100, chromosome);

        _ga = new GeneticAlgorithm(population, Fitness, selection, crossover, mutation);
    }
Esempio n. 14
0
        public void Evaluate_StartOk_Fitness()
        {
            var chromosome       = new AutoConfigChromosome();
            var targetChromosome = new TspChromosome(10);

            var targetFitness = new TspFitness(10, 0, 100, 0, 100);
            var target        = new AutoConfigFitness(targetFitness, targetChromosome);

            target.PopulationMinSize = 20;
            target.PopulationMaxSize = 20;
            target.Termination       = new FitnessThresholdTermination(0.1f);

            var actual = target.Evaluate(chromosome);

            Assert.AreNotEqual(0, actual);
        }
Esempio n. 15
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);
        }
        public void GA_WithAlternatingPositionCrossover_Evolve()
        {
            var chromosome = new TspChromosome(50);
            var population = new Population(50, 50, chromosome)
            {
                GenerationStrategy = new TrackingGenerationStrategy()
            };
            var fitness   = new TspFitness(chromosome.Length, 0, 1000, 0, 1000);
            var crossover = new AlternatingPositionCrossover();
            var ga        = new GeneticAlgorithm(population, fitness, new EliteSelection(), crossover, new ReverseSequenceMutation())
            {
                Termination = new GenerationNumberTermination(100)
            };

            ga.Start();

            Assert.Less(
                population.Generations.First().BestChromosome.Fitness.Value,
                population.Generations.Last().BestChromosome.Fitness.Value);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            var fitness    = new TspFitness(m_numberOfCities);
            var chromosome = new TspChromosome(m_numberOfCities);

            // This operators are classic genetic algorithm operators that lead to a good solution on TSP,
            // but you can try others combinations and see what result you get.
            var crossover  = new GeneticSharp.Domain.Crossovers.OrderedCrossover();
            var mutation   = new GeneticSharp.Domain.Mutations.ReverseSequenceMutation();
            var selection  = new GeneticSharp.Domain.Selections.RouletteWheelSelection();
            var population = new GeneticSharp.Domain.Populations.Population(500, 1000, chromosome);

            m_ga             = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            m_ga.Termination = new GeneticSharp.Domain.Terminations.TimeEvolvingTermination(System.TimeSpan.FromHours(1));

            // The fitness evaluation of whole population will be running on parallel.
            m_ga.TaskExecutor = new ParallelTaskExecutor
            {
                MinThreads = 100,
                MaxThreads = 200
            };

            // Every time a generation ends, we log the best solution.
            m_ga.GenerationRan += delegate
            {
                var distance = ((TspChromosome)m_ga.BestChromosome).Distance;
                Console.WriteLine($"Generation: {m_ga.GenerationsNumber} - Distance: ${distance}");
            };

            // Starts the genetic algorithm in a separate thread.
            m_gaThread = new Thread(() => m_ga.Start());
            m_gaThread.Start();


            Console.ReadLine();


            // When the script is destroyed we stop the genetic algorithm and abort its thread too.
            m_ga.Stop();
            m_gaThread.Abort();
        }
        private GeneticAlgorithm CreateGA(Func <TspChromosome, Population> createPopulation = null)
        {
            var selection  = new EliteSelection();
            var crossover  = new OrderedCrossover();
            var mutation   = new ReverseSequenceMutation();
            var chromosome = new TspChromosome(_numberOfCities);
            var fitness    = new TspFitness(_numberOfCities, 0, 1000, 0, 1000);

            var population = createPopulation == null
            ? new Population(_minPopulationSize, _minPopulationSize, chromosome)
            : createPopulation(chromosome);

            population.GenerationStrategy = new PerformanceGenerationStrategy();

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

            return(ga);
        }
        protected override GeneticAlgorithm CreateGA()
        {
            var size = (int)Camera.main.orthographicSize - 1;

            m_fitness = new TspFitness(m_numberOfCities, -size, size, -size, size);
            var chromosome = new TspChromosome(m_numberOfCities);
            var crossover  = new OrderedCrossover();
            var mutation   = new ReverseSequenceMutation();
            var selection  = new RouletteWheelSelection();
            var population = new Population(50, 100, chromosome);
            var ga         = new GeneticAlgorithm(population, m_fitness, selection, crossover, mutation);

            ga.Termination  = new TimeEvolvingTermination(System.TimeSpan.FromDays(1));
            ga.TaskExecutor = new ParallelTaskExecutor
            {
                MinThreads = 100,
                MaxThreads = 200
            };

            return(ga);
        }
Esempio n. 20
0
    public void TSPSolve(int numberOfPoints, List <Point> stationList)
    {
        var fitness    = new TspFitness(stationList);
        var chromosome = new TspChromosome(numberOfPoints);

        var crossover  = new OrderedCrossover();
        var mutation   = new ReverseSequenceMutation();
        var selection  = new RouletteWheelSelection();
        var population = new Population(50, 100, chromosome);

        m_ga             = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
        m_ga.Termination = new FitnessStagnationTermination(100);

        m_ga.TaskExecutor = new ParallelTaskExecutor {
            MinThreads = 100,
            MaxThreads = 200
        };

        m_ga.GenerationRan += delegate {
            var distance = ((TspChromosome)m_ga.BestChromosome).Distance;
        };

        m_ga.TerminationReached += delegate {
            var c      = m_ga.Population.CurrentGeneration.BestChromosome as TspChromosome;
            var genes  = c.GetGenes();
            var points = ((TspFitness)m_ga.Fitness).Points;
            finalPoints = new List <Point>();
            for (int i = 0; i < genes.Length; i++)
            {
                finalPoints.Add(points[(int)genes[i].Value]);
            }
            tspSolved();
        };

        m_gaThread = new Thread(() => m_ga.Start());
        m_gaThread.Start();
    }
Esempio n. 21
0
        /// <summary>
        /// GeneticSharp TSP Console Application template.
        /// <see href="https://github.com/giacomelli/GeneticSharp"/>
        /// </summary>
        static void Main(string[] args)
        {
            var selection = new EliteSelection();
            var crossover = new OrderedCrossover();
            var mutation  = new TworsMutation();

            var fitness    = new TspFitness(20, 0, 1000, 0, 1000);
            var chromosome = new TspChromosome(fitness.Cities.Count);

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

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

            ga.GenerationRan += (s, e) =>
            {
                Console.Clear();
                Console.WriteLine($"Generation: {ga.GenerationsNumber}");

                var c = ga.BestChromosome as TspChromosome;
                Console.WriteLine("Cities: {0:n0}", c.Length);
                Console.WriteLine("Distance: {0:n2}", c.Distance);

                var cities = c.GetGenes().Select(g => g.Value.ToString()).ToArray();
                Console.WriteLine("City tour: {0}", string.Join(", ", cities));
            };

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

            Console.WriteLine();
            Console.WriteLine($"Elapsed time: {ga.TimeEvolving}");
            Console.WriteLine("Done.");
            Console.ReadKey();
        }
Esempio n. 22
0
 /// <summary>
 /// Resets the sample.
 /// </summary>
 public override void Reset()
 {
     m_bestChromosome = null;
 }