public override void Evolve()
        {
            int individualsToEliminate = (int)(_generationGap * _populationSize);

            // A single generation is when GenerationGap % of population is eliminated and replaced
            IList <T> offspringPopulation = new List <T>();

            while (offspringPopulation.Count < individualsToEliminate)
            {
                IList <T> matingPool = new List <T>(CrossoverOperator.NumberOfParents);
                for (int j = 0; j < CrossoverOperator.NumberOfParents; j++)
                {
                    T mate = SelectionOperator.Execute(_population);
                    matingPool.Add(mate);
                }

                IList <T> children = CrossoverOperator.Execute(matingPool);

                for (int j = 0; j < children.Count; j++)
                {
                    MutationOperator.Execute(children[j]);
                    _problem.Evaluate(children[j]);
                    offspringPopulation.Add(children[j]);
                }
            }

            offspringPopulation = offspringPopulation.Take(individualsToEliminate).ToList();

            _population = ReplacementOperator.Execute(_population, offspringPopulation);

            UpdateState();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Runs a random walk of n steps along a landscape defined by a crossover operator and returns its results.
        /// </summary>
        /// <param name="steps">Number of steps.</param>
        /// <param name="searchOperator">Operator defining a neighbourhood.</param>
        /// <returns></returns>
        public RandomWalk RandomWalk(int steps, CrossoverOperator searchOperator)
        {
            RandomWalk statistics = new RandomWalk(steps);
            Chromosome parent1 = ChromosomeFactory.RandomSolution(Problem.GeneCount(), Problem);
            Chromosome parent2 = ChromosomeFactory.RandomSolution(Problem.GeneCount(), Problem);
            bool       firstParent = RandomGeneratorThreadSafe.NextBool();
            Chromosome parent = (firstParent ? parent1 : parent2), child;

            GatherData(parent, 0, statistics);

            const int minPopSize = 8, maxPopSize = 15;
            int       popSize = RandomGeneratorThreadSafe.NextInt(minPopSize, maxPopSize);

            Chromosome[] supportPopulation = new Chromosome[popSize];
            for (int i = 0; i < popSize; ++i)
            {
                supportPopulation[i] = ChromosomeFactory.RandomSolution(Problem.GeneCount(), Problem);
            }

            IGene[] childGenes1, childGenes2;
            for (int i = 0; i < steps; ++i)
            {
                searchOperator.Run(parent1.Genes, parent2.Genes, out childGenes1, out childGenes2);
                child = ChromosomeFactory.MakeChromosome(Problem, RandomGeneratorThreadSafe.NextBool() ? childGenes1 : childGenes2);
                GatherData(child, i, statistics);
                parent1 = child;
                parent2 = supportPopulation[RandomGeneratorThreadSafe.NextInt(popSize)];
            }

            return(statistics);
        }
Ejemplo n.º 3
0
        public static async Task <Chromosome> DoMa(string filename, CrossoverOperator crossOp, MutationOperator mutOp)
        {
            var problem    = new VrptwProblemReader().ReadFromFile(filename);
            var parameters = new Parameters()
            {
                ChromosomeFactory  = new SolutionFactory(),
                ConvergenceLimit   = 0.15f,
                CrossoverOperators = new List <CrossoverOperator> {
                    crossOp
                },
                CrossoverProbability = 0.9f,
                EliteChildrenCount   = 4,
                Fitness              = new FitnessFunction(200000, 1),
                FitnessStrategy      = FitnessStrategy.MINIMIZE,
                GeneCount            = problem.GeneCount(),
                Heuristics           = new SimulatedAnnealing(),
                HeuristicsParameters = new float[] { 100, 0.90f, 50 },
                MaxIterations        = 300,
                MutationOperators    = new List <MutationOperator> {
                    mutOp
                },
                MutationProbability        = 0.15f,
                PopulationSize             = 200,
                PreservedChromosomesNumber = 4,
                Selection = new TournamentSelection()
            };
            MemeticAlgorithm ma  = new MemeticAlgorithm();
            Chromosome       sol = await ma.Run(problem, parameters, CallBackMa, crossOp.GetId() + "-" + mutOp.GetId());

            return(sol);
        }
Ejemplo n.º 4
0
        protected virtual IEnumerable <IDeploymentChromosome> Cross(IEnumerable <IDeploymentChromosome> parents)
        {
            var crossoverParents = new IDeploymentChromosome[CrossoverOperator.ParentsNumber];
            var i = 0;
            List <IDeploymentChromosome> offspring = new List <IDeploymentChromosome>();

            foreach (var parent in parents)
            {
                crossoverParents[i] = parent;
                i++;
                if (i == CrossoverOperator.ParentsNumber)
                {
                    if (RandomProvider.GetRandom() <= CrossoverProbability)
                    {
                        offspring.AddRange(CrossoverOperator.Cross(crossoverParents));
                    }
                    else
                    {
                        offspring.AddRange(crossoverParents);
                    }
                    i = 0;
                }
            }
            if (i != 0)
            {
                offspring.AddRange(crossoverParents.Take(i));
            }
            return(offspring);
        }
 static GeneticAlgorithm()
 {
     Input             = null;
     TournamentSize    = 3;
     MutationRate      = 0.5;
     Generations       = 0;
     CrossoverOperator = CrossoverOperator.Default;
 }
        private void CreateNextGeneration()
        {
            var startingIndex = UsingElitism ? NumberOfElite : 0;

            if (UsingElitism)
            {
                Population.SortByFitness();
                for (int i = 0; i < NumberOfElite; i++)
                {
                    Population.AddChromosome(i, Population.Chromosomes[i]);
                }

                startingIndex = NumberOfElite;
            }

            var populationSize = Population.PopulationSize;

            for (int i = startingIndex; i < populationSize; i++)
            {
                // TODO -> Should I make sure that both parents are different ??

                // selection operation
                var fatherChromosome = SelectionOperator.PopulationSelection(Population);
                var motherChromosome = SelectionOperator.PopulationSelection(Population);

                // TODO -> return more than one child always!!!
                // crossover operation
                var childChromosome = CrossoverOperator.Crossover(fatherChromosome, motherChromosome); // TODO -> some crossovers can return more than one child

                // mutate operation
                MutationOperator.Mutate(childChromosome);

                // add child chromsome to the next generation population
                CalculateFitness(childChromosome);
                Population.AddChromosome(i, childChromosome);
            }

            // prepare for next evolution
            Population.SetNextGeneration();
            SelectionOperator.SetNextGeneration();

            Generation++;
        }
 public GeneticAlgorithm(
     int populationSize, int paramsCount, double generationGapPart,
     ISelection selection,
     CrossoverOperator crossoverOperator,
     MutationOperator mutationOperator,
     IFitnessFunc fitnessFunc,
     FloatRange range)
 {
     chromosomes            = new List <IntChromosome>(populationSize);
     this.generationGapPart = generationGapPart;
     this.selection         = selection;
     this.crossoverOperator = crossoverOperator;
     this.mutationOperator  = mutationOperator;
     this.fitnessFunc       = fitnessFunc;
     this.paramsCount       = paramsCount;
     this.range             = range;
     generatePopulationInt  = new GeneratePopulationInt();
     random = new Random();
     bitCountForIntCoding = Coder.BitCountForIntCoding(range);
     GeneratePopulation();
 }
Ejemplo n.º 8
0
        public override void Evolve()
        {
            IList <T> offspringPopulation = new List <T>();

            // Let elites survive to next generation
            int       numberOfElites = (int)(_elitismRate * _populationSize);
            IList <T> elites         = _population
                                       .OrderByDescending(c => c, _problem.FitnessComparer)
                                       .Take(numberOfElites).ToList();

            foreach (T individual in elites)
            {
                offspringPopulation.Add(individual);
            }

            while (offspringPopulation.Count < _populationSize)
            {
                IList <T> matingPool = new List <T>(CrossoverOperator.NumberOfParents);
                for (int i = 0; i < CrossoverOperator.NumberOfParents; i++)
                {
                    matingPool.Add(SelectionOperator.Execute(_population));
                }

                IList <T> children = CrossoverOperator.Execute(matingPool);

                for (int i = 0; i < children.Count; i++)
                {
                    MutationOperator.Execute(children[i]);
                    _problem.Evaluate(children[i]);
                    offspringPopulation.Add(children[i]);
                }
            }

            // When there is some excess chromosomes, discard them by taking only the needed ones
            _population = offspringPopulation.Take(_populationSize).ToList();

            UpdateState();
        }
        /// <summary>
        /// Sets the options and other configuration used in the GA.
        /// </summary>
        private void ApplyOptions()
        {
            /*** setting the selection operator to the specified type ***/
            var selectionType = GaOptions.SelectionType;

            if (selectionType == SelectionType.None)
            {
                throw new Exception("Selection method cannot be none when setting the method.");
            }

            var populationSize = Population.PopulationSize;

            switch (selectionType)
            {
            case SelectionType.Rws:
                SelectionOperator = new RouletteWheelSelection <T>(populationSize, Random);
                break;

            case SelectionType.Tos:
                // the tournamnet selection percentage is hardcoded for now to 2%, TODO => this must be passed in the GA Options
                SelectionOperator = new TournamentSelection <T>(populationSize, Random, 0.02);
                break;
            }
            /*** setting the selection operator to the specified type ***/

            /*** setting the crossover operator to the specified type ***/
            var crossoverType = GaOptions.CrossoverType;

            if (crossoverType == CrossoverType.None)
            {
                throw new Exception("Crossover method cannot be none when setting the method.");
            }

            switch (crossoverType)
            {
            case CrossoverType.OrderOne:
                CrossoverOperator = new OrderOne <T>(Random);
                break;

            case CrossoverType.Cycle:
                CrossoverOperator = new CycleCrossover <T>(Random);
                break;
            }
            /*** setting the crossover operator to the specified type ***/

            /*** setting the mutation operator to the specified type ***/
            var mutationType = GaOptions.MutationType;

            if (mutationType == MutationType.None)
            {
                throw new Exception("Mutation method cannot be none when setting the method.");
            }

            switch (mutationType)
            {
            case MutationType.SingleSwap:
                MutationOperator = new SingleSwapMutation <T>(Random);
                break;

            case MutationType.InversionMutation:
                MutationOperator = new InversionMutation <T>(Random, GaOptions.MutationRate);
                break;
            }
            /*** setting the mutation operator to the specified type ***/

            /*** setting the stopping criteria for the algorithm ***/
            var stoppingCriteriaOptions = GaOptions.StoppingCriteriaOptions;
            var stoppingCriteriaType    = stoppingCriteriaOptions.StoppingCriteriaType;

            switch (stoppingCriteriaType)
            {
            case StoppingCriteriaType.TimeBased:
                var minutesPassed = stoppingCriteriaOptions.MinutesPassed;
                if (minutesPassed <= 0)
                {
                    throw new Exception($"When using {stoppingCriteriaType}, the minutes passed must be larger than 0.");
                }
                StoppingCriteria = new TimeBaseStoppingCriteria(minutesPassed);
                break;

            case StoppingCriteriaType.SpecifiedIterations:
                var maximumIterations = stoppingCriteriaOptions.MaximumIterations;
                if (maximumIterations <= 0)
                {
                    throw new Exception($"When using {stoppingCriteriaType}, the max iterations must be larger than 0.");
                }
                StoppingCriteria = new IterationStoppingCriteria(maximumIterations);
                break;
            }

            /*** setting the stopping criteria for the algorithm ***/
        }
 public AirfoilCrossover(CrossoverOperator crossoverOperator)
 {
     this.crossoverOperator = crossoverOperator;
 }
        private void Crossover(Individual[] generation, Individual[] extendedGeneration, int[] probabilities)
        {
            Random random = new Random(Guid.NewGuid().GetHashCode());

            for (int i = 0; i < extendedGeneration.Length; i += 2)
            {
                CrossoverOperator(SelectParents(), (extendedGeneration[i], extendedGeneration[i + 1]));
            }

            (Individual FirstParent, Individual SecondParent) SelectParents()
            {
                Individual first  = generation[probabilities[random.Next(0, probabilities.Length)]];
                Individual second = first;

                while (first == second)
                {
                    second = generation[probabilities[random.Next(0, probabilities.Length)]];
                }

                return(first, second);
            }

            void CrossoverOperator((Individual FirstParent, Individual SecondParent) parents, (Individual FirstChild, Individual SecondChild) childs)
            {
                Individual firstParent  = parents.FirstParent;
                Individual secondParent = parents.SecondParent;

                double firstParentFitness  = firstParent.Fitness;
                double secondParentFitness = secondParent.Fitness;

                Individual better;
                Individual worse;

                if (firstParentFitness < secondParentFitness)
                {
                    better = firstParent;
                    worse  = secondParent;
                }
                else
                {
                    better = secondParent;
                    worse  = firstParent;
                }

                double chanceToSelectBetter = worse.Fitness / (firstParentFitness + secondParentFitness);

                byte[] firstKey  = childs.FirstChild.Key;
                byte[] secondKey = childs.SecondChild.Key;

                HashSet <byte> left = CloneByteAlphabet;
                var            used = _marksArrayPool.Rent(_alphabetLength);

                FillKey(firstKey);

                left = CloneByteAlphabet;
                for (int i = 0; i < used.Length; i++)
                {
                    used[i] = false;
                }

                FillKey(secondKey);

                _marksArrayPool.Return(used, true);

                void FillKey(byte[] key)
                {
                    for (int i = 0; i < _alphabetLength; i++)
                    {
                        bool u_1 = used[better.Key[i]];
                        bool u_2 = used[worse.Key[i]];
                        byte value;

                        if ((u_1 && !u_2) || (u_2 && !u_1))
                        {
                            value = u_2 ? better.Key[i] : worse.Key[i];
                        }
                        else if (!u_1 && !u_2)
                        {
                            value = random.NextDouble() < chanceToSelectBetter ? better.Key[i] : worse.Key[i];
                        }
                        else
                        {
                            value = left.ElementAt(random.Next(0, left.Count));
                        }

                        key[i]      = value;
                        used[value] = true;
                        left.Remove(value);
                    }
                }
            }
        }
 public void SetUp()
 {
     singlePointCrossover = new SinglePointCrossover<int> ();
     mockNumberStream = new MockNumberStream ();
 }
        public void Test1()
        {
            AbstractChromosomeFactory factory = new SolutionFactory();

            int[] routeWeights = new int[]
            {
                20000, 50000, 120000, 200000, 350000
            };
            int distanceWeight = 1;

            string[] customerTypes = new string[] { "C1", "C2", "R1", "R2", "RC1", "RC2" };
            Dictionary <string, int> customerNumbers = new Dictionary <string, int>()
            {
                { "2", 20000 }, { "4", 50000 }, { "6", 120000 }, { "8", 200000 }, { "10", 350000 }
            };

            string[] customerInstances = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

            CrossoverOperator[] crossoverOps = new CrossoverOperator[]
            {
                new OrderCrossover(), new PartiallyMatchedCrossover(), new CycleCrossover(), new UniformBasedOrderCrossover()
            };

            MutationOperator[] mutationOps = new MutationOperator[]
            {
                new SwapOperator(), new InsertionOperator(), new InversionOperator(), new DisplacementOperator()
            };

            int randomWalkNumber = 2000, randomWalkSteps = 5000;

            string floatPattern = "0.000", separator = ",";
            float  epsilon = 0.05f;

            foreach (var type in customerTypes)
            {
                foreach (var number in customerNumbers)
                {
                    foreach (var instance in customerInstances)
                    {
                        string          instanceId = type + '_' + number.Key + '_' + instance;
                        VrptwProblem    problem    = reader.ReadFromFile(FILE_PATH + @"\" + instanceId + ".txt");
                        FitnessFunction ff         = new FitnessFunction(number.Value, distanceWeight);
                        Landscape       landscape  = new Landscape(problem, factory, ff);
                        foreach (var op in crossoverOps)
                        {
                            string path = RESULT_PATH + @"\" + instanceId + "_" + op.GetId() + ".csv";
                            if (!File.Exists(path))
                            {
                                File.Create(path).Close();
                                File.ReadAllText(path);
                                using (TextWriter tw = new StreamWriter(path))
                                {
                                    tw.WriteLine("AC, IC, PIC, DBI");
                                    for (int i = 0; i < randomWalkNumber; ++i)
                                    {
                                        var    rwResult = landscape.RandomWalk(randomWalkSteps, op);
                                        float  ac       = Autocorrelation.Run(rwResult);
                                        float  ic       = InformationContent.Run(rwResult, epsilon);
                                        float  pic      = PartialInformationContent.Run(rwResult, epsilon);
                                        float  dbi      = DensityBasinInformation.Run(rwResult, epsilon);
                                        string line     =
                                            ac.ToString(floatPattern) + separator +
                                            ic.ToString(floatPattern) + separator +
                                            pic.ToString(floatPattern) + separator +
                                            dbi.ToString(floatPattern);
                                        tw.WriteLine(line);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }