// Construtor public Population( int popSize, int geneLen, RandomGeneSig getRandomGeneFunc ) { // init simple fields this.popSize = popSize; this.geneLen = geneLen; // create creatures with random genes creatures = new Creature[popSize]; for( int i = 0; i < popSize; i++ ) creatures[i] = new Creature( getRandomGeneFunc() ); // create blank supporting lists toMate = new List<int>( popSize ); matingPairs = new List<IntPair>( popSize ); offspring = new List<Creature>( popSize ); toDie = new List<int>( popSize ); // calculate some derived constants elite = (int)( popSize * G.elitism ); // number of creatures that will live on protectFromDeathI = (int)Math.Round( elite * G.protectFromDeath ); // number of best creatures protected from death turnOver = popSize - elite; // number of creatures to kill and recreate numLitters = (int)Math.Ceiling( turnOver / (double)G.litterSize ); // number of reqired litters numAsexual = (int)Math.Round( numLitters * G.asexual ); // number of asexual litters numSexual = numLitters - numAsexual; // number of sexual litters numToMate = numAsexual + 2 * numSexual; // number of creature to select for mating (not all may be used) if( numToMate > popSize ) throw new ArgumentException( "litter size to small to maintain population" ); }
// MAIN FUNCTION public static bool Run( RandomGeneSig getRandomGeneFunc, FitnessSig getPopFitnessFunc ) { // Runs the EA algorythm, returns true if goal is achieved, false if time is exceeded // local variables bool goalAchieved; double bestFitness, avrFitness; double[] popFitness = new double[G.popSize]; double[][] genes; // Create a random population of creatures myPop = new Population( G.popSize, G.geneLen, getRandomGeneFunc ); // MAIN LOOP while( true ) { // Evaluate and sort population genes = myPop.GetGenes(); myPop.GetFitness( ref popFitness ); goalAchieved = getPopFitnessFunc( genes, ref popFitness, out bestFitness, out avrFitness ); myPop.SetFitness( popFitness, bestFitness, avrFitness ); myPop.Sort(); //myPop.Print( "EVALUATED", false ); //Console.ReadKey( true ); // Are we done? if( goalAchieved ) break; // Mate Selection myPop.SelectToMate( showStepsFlag: true ); myPop.MatePairing(); // Create New Creatures myPop.CreateOffspring(); myPop.Mutate(); // Death Selection myPop.SelectToDie( showStepsFlag: false ); // Pause or continue PausePrintContinue(); // Update population (genes) myPop.InsertNewOffspring(); myPop.IncGeneration(); } // success myPop.Print( "(SUCCESS)", false ); FFNN answer = new FFNN( G.netDef, myPop.creatures[0].Gene); Console.WriteLine( answer.ToString() ); return goalAchieved; }