Exemple #1
0
    public void Evolve()
    {
        //Evolve pop
        var newPopulation = new List <Genotype>();

        //Breed using routlette wheel selection
        for (int i = 0; i < Population.Count / 2; ++i)
        {
            var parent1 = RouletteWheelSelection(Population);
            var parent2 = RouletteWheelSelection(Population);
            //Crossover
            Genotype offspring1 = parent1, offspring2 = parent2;
            OnePointCrossover(parent1, parent2, ref offspring1, ref offspring2);
            //Mutate offspring
            offspring1.Mutate(mutationRate);
            offspring2.Mutate(mutationRate);

            offspring1.FixEndPoints();
            offspring2.FixEndPoints();

            newPopulation.Add(offspring1);
            newPopulation.Add(offspring2);
        }

        //Maintain fittest from previous population.
        newPopulation[0] = FittestGenotype();

        //Regenerate lower portion of the population to preserve diversity
        for (int i = newPopulation.Count - newPopulation.Count / 6; i < newPopulation.Count; i++)
        {
            newPopulation[i] = new Genotype();
        }

        Population = newPopulation;

        foreach (Genotype g in Population)
        {
            Phenotype.CreatePhenotype(g);
        }

        currentGeneration++;
        generationLabel.text = "Generation " + currentGeneration;
        if (autosaveToggle && currentGeneration % autosaveGenerationInterval == 0)
        {
            string   json = SavePopulation();
            FileInfo file = new FileInfo(Application.persistentDataPath + "/" + sessionNameInputField.text + "/"
                                         + "autosavePopulation" + currentGeneration / autosaveGenerationInterval + ".json");
            file.Directory.Create();
            File.WriteAllText(file.FullName, json);
        }

        results.Clear();
        internalTimer = 0.0f;
    }