예제 #1
0
        private SGenome GetChromoRoulette()
        {
            //generate a random number between 0 & total fitness count
            double Slice = (double)(m_Rand.NextDouble() * m_dTotalFitness);

            //this will be set to the chosen chromosome
            SGenome TheChosenOne = m_vecPop[0];

            //go through the chromosones adding up the fitness so far
            double FitnessSoFar = 0;

            for (int i = 0; i < m_iPopSize; ++i)
            {
                FitnessSoFar += m_vecPop[i].Fitness;

                //if the fitness so far > random number return the chromo at
                //this point
                if (FitnessSoFar >= Slice)
                {
                    TheChosenOne = m_vecPop[i];

                    break;
                }
            }

            return(TheChosenOne);
        }
예제 #2
0
        //this runs the GA for one generation.
        public List <SGenome> Epoch(List <SGenome> old_pop)
        {
            //assign the given population to the classes population
            m_vecPop = old_pop;

            //reset the appropriate variables
            Reset();

            //sort the population (for scaling and elitism)
            m_vecPop.Sort();
            //sort(m_vecPop.begin(), m_vecPop.end());

            //calculate best, worst, average and total fitness
            CalculateBestWorstAvTot();

            //create a temporary vector to store new chromosones
            List <SGenome> vecNewPop = new List <SGenome>();

            //Now to add a little elitism we shall add in some copies of the
            //fittest genomes. Make sure we add an EVEN number or the roulette
            //wheel sampling will crash
            if ((m_NumCopiesElite * m_NumElite % 2) == 0)
            {
                GrabNBest(m_NumElite, m_NumCopiesElite, vecNewPop);
            }

            //now we enter the GA loop

            //repeat until a new population is generated
            while (vecNewPop.Count < m_iPopSize)
            {
                //grab two chromosones
                SGenome mum = GetChromoRoulette();
                SGenome dad = GetChromoRoulette();

                //create some offspring via crossover
                List <double> baby1 = new List <double>();
                List <double> baby2 = new List <double>();

                Crossover(mum.Weights, dad.Weights, baby1, baby2);

                //now we mutate
                Mutate(baby1);
                Mutate(baby2);

                //now copy into vecNewPop population
                vecNewPop.Add(new SGenome(baby1, 0));
                vecNewPop.Add(new SGenome(baby2, 0));
            }

            //finished so assign new pop back into m_vecPop
            m_vecPop = vecNewPop;

            return(m_vecPop);
        }