コード例 #1
0
        public IList <IChromosome> Cross(IPopulation population, ICrossover crossover, float crossoverProbability, IList <IChromosome> parents)
        {
            var minSize   = population.MinSize;
            var offspring = new List <IChromosome>(minSize);

            for (int i = 0; i < minSize; i += crossover.ParentsNumber)
            {
                var selectedParents = parents.Skip(i).Take(crossover.ParentsNumber).ToList();

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
                // have some rest chromosomes.
                if (selectedParents.Count == crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= crossoverProbability)
                {
                    offspring.AddRange(crossover.Cross(selectedParents));
                }
                else
                {
                    var left = crossover.ParentsNumber - selectedParents.Count;
                    for (int j = 0; j < left; j++)
                    {
                        offspring.Add(parents[RandomizationProvider.Current.GetInt(0, parents.Count)].Clone());
                    }
                }
            }

            return(offspring);
        }
コード例 #2
0
        public IList <IChromosome> Cross(IPopulation population, ICrossover crossover, float crossoverProbability, IList <IChromosome> parents)
        {
            var offspring     = new List <IChromosome>();
            var clonedParents = parents.Select(x => x.Clone()).ToList();

            for (int i = 0; i < population.MaxSize; i += crossover.ParentsNumber)
            {
                var selectedParents = clonedParents.Skip(i).Take(crossover.ParentsNumber).ToList();

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because in the end of the list we can
                // have some rest chromosomes.
                if (selectedParents.Count == crossover.ParentsNumber)
                {
                    bool shouldCrossover = RandomizationProvider.Current.GetDouble() <= crossoverProbability;

                    offspring.AddRange(shouldCrossover ?
                                       crossover.Cross(selectedParents) : selectedParents);
                }
                else
                {
                    offspring.AddRange(selectedParents);

                    int leftToAdd = crossover.ParentsNumber - selectedParents.Count;
                    for (int j = 0; j < leftToAdd; j++)
                    {
                        offspring.Add(clonedParents[RandomizationProvider.Current.GetInt(0, clonedParents.Count)].Clone());
                    }
                }
            }

            return(offspring);
        }
コード例 #3
0
        /// <summary>
        /// Enumerates through the offspring created from the specie.
        /// </summary>
        /// <param name="population"></param>
        /// <param name="specie"></param>
        /// <param name="crossover"></param>
        /// <param name="childrenCount"></param>
        /// <param name="allParents"></param>
        /// <param name="parentsLookup"></param>
        /// <returns></returns>
        protected virtual IEnumerable <IChromosome> PerformCrossSpecie(
            ISpeciedPopulation population,
            Specie specie,
            ICrossover crossover,
            int childrenCount,
            IList <IChromosome> allParents,
            ILookup <Specie, IChromosome> parentsLookup)
        {
            if (parentsLookup[specie].Count() < crossover.ParentsNumber)
            {
                throw new InvalidOperationException("Not enough specie parents available for this crossover.");
            }

            if (childrenCount <= 0)
            {
                yield break;
            }

            var curParents = new List <IChromosome>(crossover.ParentsNumber);
            int pInd       = 0;

            for (int i = 0; i < childrenCount; i += crossover.ChildrenNumber)
            {
                IList <IChromosome> kids;

                // Interspecie crossover
                if (RandomizationProvider.Current.GetDouble() <= InterspecieMatingRate)
                {
                    kids = PerformInterspecieCross(crossover, allParents);
                }
                // Crossover within specie
                else
                {
                    List <IChromosome> specieParents = parentsLookup[specie].ToList();
                    // Choose parents, place into curParents list
                    curParents.Clear();
                    while (curParents.Count < crossover.ParentsNumber)
                    {
                        curParents.Add(specieParents[pInd++]);
                        // Wrap around and re-shuffle
                        if (pInd >= specieParents.Count)
                        {
                            pInd          = 0;
                            specieParents = specieParents.Shuffle(RandomizationProvider.Current).ToList();
                        }
                    }
                    kids = crossover.Cross(curParents);
                }

                // Return children
                for (int k = 0; k < kids.Count; k++)
                {
                    if (i + k < childrenCount)
                    {
                        yield return(kids[k]);
                    }
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Performs a crossover by choosing parents uniformly from the list of parents.
        /// </summary>
        protected IList <IChromosome> PerformInterspecieCross(ICrossover crossover, IList <IChromosome> allParents)
        {
            var ints       = RandomizationProvider.Current.GetUniqueInts(crossover.ParentsNumber, 0, allParents.Count);
            var curParents = new IChromosome[crossover.ParentsNumber];

            for (int i = 0; i < crossover.ParentsNumber; i++)
            {
                curParents[i] = allParents[ints[i]];
            }
            return(crossover.Cross(curParents));
        }
コード例 #5
0
        public Individual[] ProcessEpoche()
        {
            Individual[] newPopulation = new Individual[population.Length];

            for (int i = 0; i < population.Length; i++)
            {
                Individual[] parents      = FindParents();
                Individual   child        = crossoverOperator.Cross(parents, cities);
                Individual   mutatedChild = methodOfMutation.Mutate(cities, child);
                newPopulation[i] = mutatedChild;
            }

            population = newPopulation;
            return(population);
        }
コード例 #6
0
        /// <summary>
        /// form parent matches and either executes the corresponding crossover with given probability to produce new children, or returns null children
        /// </summary>
        /// <param name="population">the population from which parents are selected</param>
        /// <param name="crossover">The crossover class.</param>
        /// <param name="crossoverProbability">The crossover probability.</param>
        /// <param name="parents">The parents.</param>
        /// <param name="firstParentIndex">the index of the first parent selected for a crossover</param>
        /// <returns>children for the current crossover if it was performed, null otherwise</returns>
        protected IList <IChromosome> SelectParentsAndCross(IPopulation population, ICrossover crossover,
                                                            float crossoverProbability, IList <IChromosome> parents, int firstParentIndex)
        {
            var selectedParents = parents.Skip(firstParentIndex).Take(crossover.ParentsNumber).ToList();

            // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
            // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
            // have some rest chromosomes.
            if (selectedParents.Count == crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= crossoverProbability)
            {
                return(crossover.Cross(selectedParents));
            }

            return(null);
        }
コード例 #7
0
        public Tour(Generation generation, ITwoElementsStrategy strategy, ICrossover crossover)
        {
            task = generation[0].Task;

            int index1, index2;

            strategy.Run(generation, out index1, out index2);
            Tour parent1 = generation[index1];
            Tour parent2 = generation[index2];

            parent1.CorrectRotation();
            parent2.CorrectRotation();

            vertices = crossover.Cross(parent1, parent2);
            UpdateLength();
        }
コード例 #8
0
        public void Run_WithChromsomeMatchingTerminationCriteria_CallsRightMethods()
        {
            var deploymentModel = CreateDeploymentModel();

            A.CallTo(() => _terminationCondition.HasReached(null, null)).WithAnyArguments().Returns(true);
            ConstructGeneticAlgorithm();

            var bestDeploymentModel = _testGeneticAlgorithm.Run(deploymentModel);

            A.CallTo(() => _deploymentChromosomeFactory.Create(deploymentModel)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => _initialPopulationCreator.CreateInitialPopulation(null, 0, 0)).WithAnyArguments().MustHaveHappened(Repeated.Exactly.Once);

            A.CallTo(() => _mutationOperator.Mutate(null)).WithAnyArguments().MustNotHaveHappened();
            A.CallTo(() => _crossoverOperator.Cross(null)).WithAnyArguments().MustNotHaveHappened();
            A.CallTo(() => _selectionStrategy.SelectChromosomes(0, null)).WithAnyArguments().MustNotHaveHappened();
            A.CallTo(() => _reinsertionStrategy.Reinsert(null, null)).WithAnyArguments().MustNotHaveHappened();

            Assert.AreEqual(0, _currentState.Count);
        }
コード例 #9
0
        /// <summary>
        /// Performs crossover of the two schedule chromosomes.
        /// </summary>
        /// <param name="parents"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public IList <IChromosome> Cross(IList <IChromosome> parents)
        {
            var scheduleParent1 = parents[0];
            var scheduleParent2 = parents[1];

            if (scheduleParent1.Length != scheduleParent2.Length)
            {
                throw new ArgumentException("Different length of parents, cannot be crossed.");
            }

            var scheduleChild1 = (ScheduleChromosome)scheduleParent1.Clone();
            var scheduleChild2 = (ScheduleChromosome)scheduleParent2.Clone();

            for (int i = 0; i < scheduleParent1.Length; i++)
            {
                var machine1 = (MachineChromosome)scheduleParent1.GetGene(i).Value;
                var machine2 = (MachineChromosome)scheduleParent2.GetGene(i).Value;

                if (machine1.Length < 3)
                {
                    continue;
                }

                var result = permutationCrossover.Cross(new List <IChromosome>()
                {
                    machine1, machine2
                });

                var child1 = (MachineChromosome)result[0];
                var child2 = (MachineChromosome)result[1];

                // replace genes (automatically resets fitness)
                scheduleChild1.ReplaceGene(i, new Gene(child1));
                scheduleChild1.ScheduleLength = 0;
                scheduleChild2.ReplaceGene(i, new Gene(child2));
                scheduleChild2.ScheduleLength = 0;
            }

            return(new List <IChromosome>()
            {
                scheduleChild1, scheduleChild2
            });
        }
コード例 #10
0
ファイル: GAMachine.cs プロジェクト: yzylovepmn/YToolKit
        private IList <ChromoSome> _Cross(IList <ChromoSome> parents)
        {
            var count      = _crossover.ParentCount;
            var subParents = new List <ChromoSome>();
            var children   = new List <ChromoSome>(_population.MinPopulationCount);

            foreach (var parent in parents)
            {
                subParents.Add(parent);
                if (subParents.Count == count)
                {
                    if (Util.NextDouble() < _crossoverProbability)
                    {
                        children.AddRange(_crossover.Cross(subParents));
                    }
                    subParents.Clear();
                }
            }
            return(children);
        }
コード例 #11
0
        public Individual <T> Select(List <Individual <T> > population)
        {
            var randomized = new int[_k];

            for (var i = 0; i < _k; i++)
            {
                var index = Random.Next(population.Count);
                randomized[i] = index;
            }

            randomized = randomized.OrderBy(i => population[i].Fitness).ToArray();

            var best       = population[randomized[0]];
            var secondBest = population[randomized[1]];
            var worst      = population[randomized[2]];

            var child = _crossover.Cross(best, secondBest);

            // A possible scientific breakthrough. The error was less than 1E-41 on 80 dimensions for F7.
            // _mutation.Mutate(child, _lowerBound, _upperBound, _mutationProbability, _mean, _deviation);
            _mutation.Mutate(child, _mean, _deviation, _lowerBound, _upperBound, _mutationProbability);
            child.Fitness = EvaluateIndividual(_function, child);


            if (child.Fitness > worst.Fitness)
            {
                population[randomized[2]] = child;
            }

            // This yields much better results
            // my mind is telling me no
            // but my body.. my body is telling me yes
            if (child.Fitness > best.Fitness)
            {
                population[randomized[0]] = child;
            }

            return(child);
        }
コード例 #12
0
        /// <summary>
        /// Crosses the specified parents.
        /// </summary>
        /// <param name="crossover">The crossover class.</param>
        /// <param name="crossoverProbability">The crossover probability.</param>
        /// <param name="parents">The parents.</param>
        /// <returns>The result chromosomes.</returns>
        public IList <IChromosome> Cross(IPopulation population, ICrossover crossover, float crossoverProbability, IList <IChromosome> parents)
        {
            var offspring = new ConcurrentBag <IChromosome>();

            Parallel.ForEach(Enumerable.Range(0, population.MinSize / crossover.ParentsNumber).Select(i => i * crossover.ParentsNumber), i =>
            {
                var selectedParents = parents.Skip(i).Take(crossover.ParentsNumber).ToList();

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
                // have some rest chromosomes.
                if (selectedParents.Count == crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= crossoverProbability)
                {
                    var children = crossover.Cross(selectedParents);
                    foreach (var item in children)
                    {
                        offspring.Add(item);
                    }
                }
            });

            return(offspring.ToList());
        }