/// <summary> /// Evolves population /// </summary> /// <param name="population"> population to be evolved (use ref keyword)</param> public static void EvolvePopulation(ref Population population) { if (m_evolving) { return; } if (population == null || population.GetGenome(0) == null) { Debug.LogError("POPULATION IS NULL, WTF ARE YOU DOING?"); return; } m_evolving = true; Population nPop = new Population(population.PopulationSize, population.GenomeSize()); if (m_elite) { nPop.InsertGenome(0, population.BestGenome); } int iVal = 0; //offset for best fitt individual if (m_elite) { iVal = 1; } ///Breeding process for (int i = iVal; i < population.PopulationSize; i = i + 2) { Genome parent1 = SelectionByTournament(population); Genome parent2 = SelectionByTournament(population); Genome[] children = CrossOver(parent1, parent2); nPop.InsertGenome(i, children[0]); if (i + 1 < population.PopulationSize) { nPop.InsertGenome(i + 1, children[1]); } } //mutate after breeding for (int i = iVal; i < nPop.PopulationSize; i++) { Mutate(nPop.GetGenome(i)); } population = nPop; m_generation++; m_evolving = false; }
/// <summary> /// Selects the fittest genome out of a given number of genomes within a population /// </summary> /// <param name="population"></param> /// <returns></returns> private static Genome SelectionByTournament(Population population) { Genome geno = null; Population tournamentCanditates = new Population(m_tournamentSize, population.GenomeSize()); System.Random random = new System.Random(); for (int i = 0; i < m_tournamentSize; i++) { int rgeno = random.Next(0, population.PopulationSize); tournamentCanditates.InsertGenome(i, population.GetGenome(rgeno)); } tournamentCanditates.EvaluatePopulation(); geno = tournamentCanditates.BestGenome; return(geno); }