Example #1
0
        public void Simulate(int count, int length, int min, int max, int maxGeneration)
        {
            m_Population = new Population(count, length, min, max);
            m_Population.Evaluate(Fitness);
            Debug.Log(m_Population);

            while (m_Population.Generation < maxGeneration)
            {
                do
                {
                    IChromosome parent1 = Selection.Select(m_Population);
                    IChromosome parent2 = Selection.Select(m_Population);

                    IChromosome offspring1, offspring2;
                    Crossover.Crossover(parent1, parent2, out offspring1, out offspring2);

                    Mutation.Mutate(ref offspring1, min, max);
                    Mutation.Mutate(ref offspring2, min, max);

                    m_Population.AddChromosomeInNewPopulation(offspring1);
                    m_Population.AddChromosomeInNewPopulation(offspring2);
                } while (!m_Population.IsFullNewGeneration);

                m_Population.SwapGeneration();
                m_Population.Evaluate(Fitness);
                Debug.Log(m_Population);
            }
        }
Example #2
0
            public TIndividual Run(XFitnessFunction <TChromosome> fitnessFunction)
            {
                int generation = 0;

                var reproductionGroup = new List <TIndividual>();

                var currentPopulationsChromosomes = PopulationInitializer.Initialize();

                IReadOnlyList <TIndividual> currentPopulation = currentPopulationsChromosomes.Select(
                    chromosome => IndividualFactory.CreateIndividual(chromosome, fitnessFunction)
                    ).ToList();

                var bestSolution = currentPopulation[0];

                foreach (var individual in currentPopulation)
                {
                    if (individual.Fitness > bestSolution.Fitness)
                    {
                        bestSolution = individual;
                    }
                }

                while (ContinueCondition.ShouldContinue(currentPopulation, generation))
                {
                    var pairs = Breeding.Select(currentPopulation);

                    reproductionGroup.Clear();

                    foreach (var Compound in pairs.Select(pair => Crossover.Crossover(pair)))
                    {
                        reproductionGroup.AddRange(
                            Compound
                            .Select(chromosome => Mutation.Mutate(chromosome))
                            .Select(mutant => IndividualFactory.CreateIndividual(mutant, fitnessFunction)));
                    }

                    foreach (var individual in reproductionGroup)
                    {
                        if (individual.Fitness > bestSolution.Fitness)
                        {
                            bestSolution = individual;
                        }
                    }

                    currentPopulation = Strategy.NextGeneration(
                        currentPopulation,
                        reproductionGroup
                        );

                    generation++;
                }

                return(bestSolution);
            }
        public void Simulate(int count, int length, int min, int max, int maxGeneration)
        {
            m_Population = new Population <T>(count, length, min, max);
            m_Population.Evaluate(Fitness);

            m_Population.Save(Filename, false);
            if (Debug != null && (DebugMask & DebugMask.First) != 0)
            {
                Debug.Log(m_Population);
            }

            while (m_Population.Generation < maxGeneration)
            {
                m_Population.Elite(Elitism);

                do
                {
                    IChromosome <T> parent1 = Selection.Select(m_Population);
                    IChromosome <T> parent2 = Selection.Select(m_Population);

                    IChromosome <T> offspring1, offspring2;
                    Crossover.Crossover(parent1, parent2, out offspring1, out offspring2);

                    Mutation.Mutate(ref offspring1, min, max);
                    Mutation.Mutate(ref offspring2, min, max);

                    m_Population.AddChromosomeInNewPopulation(offspring1);
                    m_Population.AddChromosomeInNewPopulation(offspring2);
                } while (!m_Population.IsFullNewGeneration);

                m_Population.SwapGeneration();
                m_Population.Evaluate(Fitness);

                m_Population.Save(Filename, true);
                if (Debug != null && (DebugMask & DebugMask.Step) != 0)
                {
                    Debug.Log(m_Population);
                }
            }

            if (Debug != null && (DebugMask & DebugMask.Last) != 0)
            {
                Debug.Log(m_Population);
            }
        }
        public IList <IGenome <T> > Generate(IList <IGenome <T> > genomes)
        {
            IList <IGenome <T> > result;
            IList <IGenome <T> > babies;
            int n;

            n      = Count(genomes);
            result = new List <IGenome <T> >(n);
            Selector.BeforeAllSelections(genomes);
            while (result.Count < n)
            {
                babies = Crossover.Crossover(Selector.SelectNext());
                if (babies.Count == 0)
                {
                    ThrowInvalidChildProducedCount();
                }

                foreach (var babie in babies)
                {
                    Mutator.Mutate(babie);
                    result.Add(babie);
                    if (result.Count() > n)
                    {
                        break;
                    }
                }
            }

            if (result.Count() > n)
            {
                result = result.Take(n).ToArray();
            }

            if (result.Count() != n)
            {
                ThrowInvalidBreadCount(result.Count(), n);
            }

            return(result);
        }
Example #5
0
        public void Simulate(int maxGeneration)
        {
            Population.Evaluate(Fitness);

            if (Debug != null)
            {
                Debug.Log(Population);
            }

            while (Population.Generation < maxGeneration)
            {
                Elite();

                do
                {
                    IChromosome parent1 = Selection.Select(Population);
                    IChromosome parent2 = Selection.Select(Population);

                    Crossover.Crossover(parent1, parent2, out IChromosome offspring1, out IChromosome offspring2);

                    Mutation.Mutate(ref offspring1);
                    Mutation.Mutate(ref offspring2);

                    Population.AddChromosomeInNewPopulation(offspring1);
                    Population.AddChromosomeInNewPopulation(offspring2);
                } while (!Population.IsFullNewGeneration);

                Population.SwapGeneration();
                Population.Evaluate(Fitness);

                if (Debug != null)
                {
                    Debug.Log(Population);
                }
            }
        }
        //Creating the next generation
        public void NextGeneration()
        {
            int maxElite = 0;

            RouteGenome[] nextGen = new RouteGenome[PopSize];

            //Determining if elite percentage is active
            if (ElitePercent > 0)
            {
                maxElite = (PopSize * ElitePercent) / 100;
            }
            else
            {
                maxElite = (PopSize) / 100;
            }


            double totalLength = 0;
            double length      = 0;

            //making copies of the elites based on the percentage chosen by user
            for (int c = 0; c < maxElite; c++)
            {
                nextGen[c]   = currentGen[c];
                totalLength += nextGen[c].Length;
            }

            //creating the rest of the next generation
            for (int i = maxElite; i < PopSize; i++)
            {
                //Selection
                RouteGenome parent1 = Selection.Select(currentGen, TotalFitness);
                RouteGenome parent2 = Selection.Select(currentGen, TotalFitness);
                //to avoid two of the same parents
                while (parent2.DNA == parent1.DNA)
                {
                    parent2 = Selection.Select(currentGen, TotalFitness);
                }

                //Crossover
                RouteGenome child = Crossover.Crossover(parent1, parent2, CrossoverPercent);

                //Mutate
                child = Mutate.Mutate(child, MutatePercent);

                //calculation of new genomes length
                length       = CalcLength(child.DNA, CityPoints);
                child.Length = length;
                //saving the child to next generation
                nextGen[i]   = child;
                totalLength += length;
            }

            TotalLength = totalLength;

            //Calculating the next generations fitness
            int totalFit = 0;

            for (int j = 0; j < PopSize; j++)
            {
                nextGen[j].Fitness = CalcFitness(nextGen[j].Length / 5, totalLength / 5);
                totalFit          += nextGen[j].Fitness;
            }

            TotalFitness = totalFit;

            //The genomes are in order from best to worst,
            //therefore genome at index 0 would be the most fit
            //and the genome at the last index will be the least fit
            Sort(nextGen);
            Best  = nextGen[0];
            Worst = nextGen[PopSize - 1];

            GenCount += 1;



            //Setting the current gen to next gen
            currentGen = nextGen;
        }
Example #7
0
        public virtual Genome Execute()
        {
            if (Selector == null)
            {
                throw new ApplicationException("Impossível executar o algoritimo genético com o Selector nulo!");
            }

            if (Crossover == null)
            {
                throw new ApplicationException("Impossível executar o algoritimo genético com o Crossover nulo!");
            }

            startTime = DateTime.Now;

            int genomeCount = (elitism ? gnomes.Count - 1 : gnomes.Count);

            Genome[] mate = new Genome[genomeCount];

            while (true)
            {
                generations++;

                if (NewGeneration != null)
                {
                    NewGeneration(this, null);
                }

                for (int g = 0; g < genomeCount; g++)
                {
                    Genomes[g].Fitness = Evaluator.Eval(Genomes[g]);
                }

                Genomes.Sort();

                int gnomeIndex = Genomes.Count - 1;

                if (QryBestFitness != null)
                {
                    while (gnomeIndex >= 0 && Genomes[gnomeIndex].Fitness > bestFitness)
                    {
                        GenomeCancelEventArgs args = new GenomeCancelEventArgs();

                        args.Genome = Genomes[Genomes.Count - 1];

                        QryBestFitness(this, args);

                        if (args.Cancel)
                        {
                            Genomes[Genomes.Count - 1].Fitness = 0;
                            gnomeIndex--;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                if (Genomes[Genomes.Count - 1].Fitness > bestFitness)
                {
                    bestFitness = Genomes[Genomes.Count - 1].Fitness;

                    if (NewBestFitness != null)
                    {
                        GenomeEventArgs args = new GenomeEventArgs();

                        args.Genome = Genomes[Genomes.Count - 1];


                        NewBestFitness(this, args);
                    }
                }

                if (!exitConditions.DoesContinue(this))
                {
                    break;
                }

                for (int g = 0; g < genomeCount; g++)
                {
                    mate[g] = Selector.Select();
                }

                for (int g = 0; g < genomeCount; g++)
                {
                    gnomes[g] = Crossover.Crossover(gnomes[g], mate[g], generations);
                }
            }

            if (!elitism)
            {
                Genomes.Sort();
            }

            return(Genomes[Genomes.Count - 1]);
        }