// Check in an individual that has now acquired a fitness value public void CheckIn(uint chr, float fit) { // Make Individual Individual NewDude = new Individual(chr, chromSize, fit, mutProb); newP.AddNewInd(NewDude); // Add to newP nextCIn++; // Count it //Console.WriteLine("In CheckIn chr fit: " + chr + " " + fit); }
// Add a new Individual to the population in the next open spot public int AddNewInd(Individual newDude) { int wherePut = -1; // -1 in case something breaks if (Full) Console.WriteLine ("Panic! Tried to add too many dudes"); else { wherePut = nDudes; dudes[wherePut] = newDude; nDudes++; // Increment for next time } return wherePut; // Return offset in array where it landed }
// Breed a new Individual using crossover and mutation public Individual BreedDude() { // Two selection methods to choose from. Typically use one or the other // but not both. Used both here just to test them. Individual p1 = SelectRoul(); // Get 2 parents Individual p2 = SelectTourn(); uint c1 = p1.Chrom; // Extract their chromosomes uint c2 = p2.Chrom; if (Util.rand.NextDouble () < crossoverProb) // Probably do crossover { uint kidChrom = CrossOver(c1, c2); // Make new chromosome Individual newDude = new Individual (kidChrom, nBits, mutationProb); // Make Individual newDude.Mutate(); // Maybe mutate a bit return newDude; // Send it back } else // No crossover => Pick one of the parents to return unchanged return (Util.rand.NextDouble() < 0.5 ? p1 : p2); }
// Fills population by reading individuals from a file already opened to inStream // Assumes file is correctly formatted with correct number of lines public void ReadPop(StreamReader inStream) { for (int i = 0; i < popSize; i++) { string line = inStream.ReadLine(); // Read a line string [] tokens = line.Split (delim); // Split into "words" uint chr = UInt32.Parse(tokens[0]); // Convert words to numbers int fit = int.Parse(tokens[1]); // Put Individual in population dudes [i] = new Individual (chr, nBits, fit, mutationProb); totFit += fit; // Accumulate total fitness for selection } nDudes = popSize; // Show the population full }
// Fills population with new random chromosomes for generation 0 public void InitPop() { for (int i = 0; i < popSize; i++) { dudes[i] = new Individual ((uint)Util.rand.Next(nChromVals), nBits, mutationProb); } nDudes = popSize; totFit = popSize; // Default fitness for each Individual == 1 }