Beispiel #1
0
 public Plant(int X, int Y)
 {
     Livelong      = PropertyEndLivelong;
     IndexGenocode = Genomes.AddGenocode();
     AddNewBlockPlant(X, Y);
     AddListNewBlocksPlant();
 }
Beispiel #2
0
        /// <summary>
        /// Запустить генетическую программу
        /// </summary>
        private void GeneticProgram()
        {
            foreach (BlockPlant OneBlockPlant in ListBlocksPlant)
            {
                OneBlockPlant.Activate();
                ///rand = MainWorld.GlobalRand.Next(ActionsOfPlants.LengthActionsOfPlants);
                switch (Genomes.GetGeneCommand(IndexGenocode, 0, OneBlockPlant.GoActiveGene()))
                {
                case (int)TypeActionsOfPlants.GrowUp:
                    AddNewBlockPlant(OneBlockPlant.X, OneBlockPlant.Y + 1, OneBlockPlant);
                    break;

                case (int)TypeActionsOfPlants.GrowLeft:
                    AddNewBlockPlant(OneBlockPlant.X - 1, OneBlockPlant.Y, OneBlockPlant);
                    break;

                case (int)TypeActionsOfPlants.GrowRight:
                    AddNewBlockPlant(OneBlockPlant.X + 1, OneBlockPlant.Y, OneBlockPlant);
                    break;

                case (int)TypeActionsOfPlants.GrowDown:
                    AddNewBlockPlant(OneBlockPlant.X, OneBlockPlant.Y - 1, OneBlockPlant);
                    break;

                default:
                    break;
                }
                OneBlockPlant.NextActiveGene();
            }

            if (StackBlocksPlant.Count > 0)
            {
                AddListNewBlocksPlant();
            }
        }
Beispiel #3
0
 public void Reset(Random r)
 {
     Genome = Genomes[r.Next(Genomes.Count)];
     Genomes.Clear();
     FitnessPop.Clear();
     TotalAdjustedFitness = 0f;
 }
        public void NextGeneration()
        {
            FitnessStats.SaveCurrentToHistory();
            Generation++;

            var newGenomes = new List <Genome>();

            if (_genetics.EliteCount > 0)
            {
                var elites = Genomes.OrderByDescending(x => x.Fitness).Take(_genetics.EliteCount);
                newGenomes.AddRange(elites);
            }

            while (newGenomes.Count < Genomes.Count())
            {
                var mother = getGenomeByRoulette();
                var father = getGenomeByRoulette();

                var children = _genetics.Crossover(mother, father);
                foreach (var child in children)
                {
                    _genetics.Mutate(child);
                    newGenomes.Add(child);
                }
            }
            newGenomes.ForEach(x => x.ResetFitness());
            Genomes = newGenomes.Take(Genomes.Count()).ToList();
        }
Beispiel #5
0
 /// <summary>
 /// Create a population with random genomes.
 /// </summary>
 private void Populate()
 {
     for (int i = 0; i < GenomeCount; i++)
     {
         Genomes.Add(new Genome(InputCount, OutputCount, Config.weightInitRandomValue));
     }
 }
        /// <summary>
        /// Get N genomes from this species.
        /// The best genome is simply copied.
        /// A part of the genomes are soft copied. Soft, means that the mutation
        /// is less than normal.
        /// The rest, are a result of a crossover between weighted random chosen
        /// genomes. The random is weighted, based on the fitness. The parents can't
        /// be the same.
        /// </summary>
        public Genome[] GetNGenomesForNextGeneration(NEATConfig config, int n)
        {
            var result = new Genome[n];

            Genomes = Genomes.OrderByDescending(x => x.Fitness).ToList();

            for (int i = 0; i < n; i++)
            {
                if (i == 0)
                {
                    result[i] = new Genome(Genomes[0]);
                }
                else if (i <= config.partOfGenomesToCopyForNextGenerations * n || Genomes.Count == 1)
                {
                    result[i] = new Genome(FitnessWeightedRandomChoice(Genomes)).Mutate(config, 0.8f);
                }
                else
                {
                    var parent1 = FitnessWeightedRandomChoice(Genomes, config.weightedRandomGradient);
                    var parent2 = FitnessWeightedRandomChoice(Genomes.Where(x => x != parent1), config.weightedRandomGradient);
                    result[i] = Genome.Crossover(config, parent1, parent2).Mutate(config);
                }
            }
            return(result);
        }
Beispiel #7
0
        public void Speciate()
        {
            Genomes.ToList().ForEach(genome => Speciate(genome));

            // Clean up any Species with no Genomes
            Species = Species.Where(s => s.Genomes.Any()).ToList();
        }
Beispiel #8
0
    //Factory en fonction des différent animaux
    public Species ChimeraReproduction(Genomes gene)
    {
        ChimeraAnt child = null;

        switch (gene)
        {
        case Genomes.Tree: {
            child = SpawnChildren();
            int randX = Random.Range(-10, 10);
            int randY = Random.Range(-10, 10);
            print("nAISSANCE mode arbre");
            child.transform.position = transform.position + new Vector3(randX, 0, randY);
        }
        break;

        case Genomes.Wolf:
        {
            if (state != State.Leader && isInReproductionTime == false)
            {
                return(null);
            }

            child = SpawnChildren();
        }
        break;

        default:
        {
            child = SpawnChildren();
        } break;
        }

        return(child);
    }
Beispiel #9
0
        public IList <Genome> GetMostFitGenomes()
        {
            var averageFitness = AverageFitness;
            var sortedGenomes  = Genomes.OrderByDescending(g => g.Fitness).Take((Genomes.Count + 1) / 2).ToList();
            var mostFitGenomeFitnessInSpecie = sortedGenomes[0].Fitness;

            return(sortedGenomes);
        }
Beispiel #10
0
 public Plant(int X, int Y, int ParentsIndex)
 {
     //IndexGenocode = ParentsIndex;
     Livelong      = PropertyEndLivelong;
     IndexGenocode = Genomes.AddGenocode(ParentsIndex);
     AddNewBlockPlant(X, Y);
     AddListNewBlocksPlant();
 }
Beispiel #11
0
    public void createStartPopulation()
    {
        genomes.Clear();

        for (int i = 0; i < populationSize; i++)
        {
            Genomes child = new Genomes(chromosoneLength);
            genomes.Add(child);
        }
    }
Beispiel #12
0
        private void CalculateTotalFitness()
        {
            Genomes.ForEach(g =>
            {
                g.RebuildModelFollowingGenes();
                g.UpdateFitnessScore();
            });

            TotalFitnessScore = Genomes.Max(g => g.Fitness);
        }
        /// <summary>
        ///     Finishes Generation, by ordering Genomes by Fitness descending and
        ///     setting the BestGenome Property.
        /// </summary>
        public void FinishGeneration()
        {
            Genomes = Genomes
                      .OrderByDescending(c => c.Fitness.Value)
                      .ToList();

            // TODO: Write AnalyseData

            BestGenome = Genomes.First();
        }
Beispiel #14
0
        //constructor
        public Population(int size, int inputDims)
        {
            _inputDims       = inputDims;
            AddedConnections = new Dictionary <string, int>();

            for (int i = 0; i < size; i++)
            {
                Genomes.Add(new Genome(inputDims));
            }
        }
        /// <summary>
        /// Calculates the next best generation
        /// </summary>
        public void NextGeneration()
        {
            // increment the generation;
            Generation++;

            // check who can die
            for (int i = 0; i < Genomes.Count; i++)
            {
                if (((Genome)Genomes[i]).CanDie(kDeathFitness))
                {
                    Genomes.RemoveAt(i);
                    i--;
                }
            }


            // determine who can reproduce
            GenomeReproducers.Clear();
            GenomeResults.Clear();
            for (int i = 0; i < Genomes.Count; i++)
            {
                if (((Genome)Genomes[i]).CanReproduce(kReproductionFitness))
                {
                    GenomeReproducers.Add(Genomes[i]);
                }
            }

            // do the crossover of the genes and add them to the population
            DoCrossover(GenomeReproducers);

            Genomes = (ArrayList)GenomeResults.Clone();

            // mutate a few genes in the new population
            for (int i = 0; i < Genomes.Count; i++)
            {
                Mutate((Genome)Genomes[i]);
            }

            // calculate fitness of all the genes
            for (int i = 0; i < Genomes.Count; i++)
            {
                ((Genome)Genomes[i]).CalculateFitness();
            }


            //			Genomes.Sort();

            // kill all the genes above the population limit
            if (Genomes.Count > kPopulationLimit)
            {
                Genomes.RemoveRange(kPopulationLimit, Genomes.Count - kPopulationLimit);
            }

            CurrentPopulation = Genomes.Count;
        }
        /// <summary>
        /// Generates the next generation of the population.
        /// </summary>
        public void NextGeneration()
        {
            var avgDamage       = Genomes.Average(g => g.DamageDealt);
            var avgSurvivalTime = Genomes.Average(g => g.SurvivalTime);

            // make a copy of the genomes and sort by fitness (high to low)
            var orderedGenomes = Genomes.ToList();

            orderedGenomes.Sort((a, b) =>
            {
                var aFitness = a.GetFitness(avgDamage, avgSurvivalTime);
                var bFitness = b.GetFitness(avgDamage, avgSurvivalTime);

                if (aFitness > bFitness)
                {
                    return(1);
                }
                if (aFitness < bFitness)
                {
                    return(-1);
                }

                return(0);
            });

            // trim out the worst genomes
            var toRemove = (int)Math.Floor(ReplacementPercent * Size);

            orderedGenomes.RemoveRange(Size - toRemove, toRemove);

            for (var i = 0; i < Size; i++)
            {
                if (i < NumClones)
                {
                    m_genomes[i]                 = orderedGenomes[i];
                    orderedGenomes[i].Id         = i;
                    orderedGenomes[i].GenomeType = GenomeType.Clone;
                    orderedGenomes[i].ResetStats();
                }
                else
                {
                    var genome = DoCrossover(orderedGenomes);
                    genome.Id = i;

                    if (Random.NextDouble() < MutationRate)
                    {
                        genome.Mutate();
                    }

                    m_genomes[i] = genome;
                }
            }

            Generation++;
        }
 public MasterMindPopulation(int numberOfGenomes)
 {
     Genomes.Clear();
     for (int i = 0; i < numberOfGenomes; i++)
     {
         MastermindGenome aGenome = new MastermindGenome(kLength, 1, 9);
         aGenome.SetCrossoverPoint(kCrossover);
         aGenome.CalculateFitness();
         Genomes.Add(aGenome);
     }
 }
Beispiel #18
0
 /// <summary>
 /// Create a population of a set number of genes, with a crossover type, and the ideal path ends
 /// </summary>
 /// <param name="numberOfGenomes"></param>
 /// <param name="crossOver"></param>
 /// <param name="originPosition"></param>
 /// <param name="destinationPosition"></param>
 public Population(int numberOfGenomes, CrossOver crossOver, Coordinate originPosition, Coordinate destinationPosition, float mutationStrength)
 {
     NumberOfGenomes     = numberOfGenomes;
     CrossOver           = crossOver;
     OriginPosition      = originPosition;
     DestinationPosition = destinationPosition;
     MutationStrength    = (int)(mutationStrength * 100);
     for (int i = 0; i < NumberOfGenomes; i++)
     {
         Genomes.Add(new Genome(OriginPosition));
     }
 }
Beispiel #19
0
        /// <summary>
        /// If the minimum fitness is less than 0, the absolute value of
        /// it is added to every genome, so that they all have positive fitness.
        /// It may be useful in some computations and it doesn't affect anything.
        /// </summary>
        private void MakeGenomesHaveOnlyPositiveFitnesses()
        {
            var minFitness = Genomes.Min(x => x.Fitness);

            if (minFitness > 0)
            {
                return;
            }

            var absMinFitness = Mathf.Abs(minFitness);

            Genomes.ForEach(x => x.Fitness += absMinFitness);
        }
Beispiel #20
0
        private Genome Crossover()
        {
            var mother = Genomes.GetRandomElement();
            var father = Genomes.GetRandomElement();

            while (father == mother)
            {
                father = Genomes.GetRandomElement();
            }

            if (mother.Fitness < father.Fitness)
            {
                var tmp = father;
                father = mother;
                mother = tmp;
            }

            var childGenome = new Genome();

            foreach (var node in mother.NodeGenes.Values)
            {
                childGenome.AddNodeGene(new NodeGene(node));
            }

            foreach (var motherConnectionGene in mother.ConnectionGenes)
            {
                ConnectionGene newChildConnection;
                var            coinToss         = RandomGenerator.GetCoinToss();
                var            connectionGeneId = motherConnectionGene.Key;

                if (father.ConnectionGenes.ContainsKey(connectionGeneId))
                {
                    if (coinToss)
                    {
                        newChildConnection = new ConnectionGene(motherConnectionGene.Value);
                    }
                    else
                    {
                        newChildConnection = new ConnectionGene(father.ConnectionGenes[connectionGeneId]);
                    }
                }
                else
                {
                    newChildConnection = new ConnectionGene(motherConnectionGene.Value);
                }

                childGenome.AddConnectionGene(newChildConnection, connectionGeneId);
            }

            return(childGenome);
        }
Beispiel #21
0
        public void Evolve()
        {
            int prevPoplLen;

            prevPoplLen = Genomes.Count();

            Genomes = GenerationGenerator.Generate(Genomes);
            if (!Genomes.Any())
            {
                Populate(prevPoplLen);
            }

            Generation++;
        }
        /// <summary>
        ///     Ends the generation.
        /// </summary>
        /// <param name="genomesNumber">Genomes number to keep on generation.</param>
        public void End(int genomesNumber)
        {
            Genomes = Genomes
                      .Where(ValidateChromosome)
                      .OrderByDescending(c => c.Fitness.Value)
                      .ToList();

            if (Genomes.Count > genomesNumber)
            {
                Genomes = Genomes.Take(genomesNumber).ToList();
            }

            BestGenome = Genomes.First();
        }
Beispiel #23
0
        private void GrabNBest(int nBest, int numCopies, List <TGenome> newPopulation)
        {
            //sort(m_vecGenomes.begin(), m_vecGenomes.end());
            Genomes = Genomes.OrderByDescending(g => g.Fitness).ToList();

            //now add the required amount of copies of the n most fittest
            //to the supplied vector
            while (nBest-- > 0)
            {
                for (int i = 0; i < numCopies; ++i)
                {
                    newPopulation.Add(Genomes[nBest]);
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// Create a new generation of genomes based on the previous
        /// </summary>
        public void CreateNewGeneration() //when mutate? before, after, new percentage set?
        {
            int topTenPercent = (int)(((double)NumberOfGenomes / 100) * 25);
            IOrderedEnumerable <Genome> genomesByFitness = Genomes.OrderBy(g => GetFitness(g));
            int requiredRemaining = NumberOfGenomes - topTenPercent;

            Genomes = new List <Genome>(genomesByFitness
                                        .Take(topTenPercent)
                                        .ToList());

            List <Genome> offspring = GetCrossOverGenomes(Genomes, requiredRemaining);

            Genomes.AddRange(offspring);
            MutateGenomes(Genomes);
        }
Beispiel #25
0
        private void CreateStartPopulation(int genomes, int numChromosoneBits, int numGeneBits)
        {
            //clear existing population
            Genomes.Clear();

            for (int i = 0; i < genomes; i++)
            {
                var genome = new TGenome();
                genome.Initialize(numChromosoneBits, numGeneBits);
                Genomes.Add(genome);
            }

            //reset all variables
            Generation        = 0;
            TotalFitnessScore = 0;
        }
Beispiel #26
0
        public Genome Breed()
        {
            Genome childGenome;

            if (Genomes.Count > 1 && RandomGenerator.GetRandomResult(Config.CrossoverChance))
            {
                childGenome = Crossover();
            }
            else
            {
                childGenome = new Genome(Genomes.GetRandomElement());
            }

            childGenome.TryMutate();

            return(childGenome);
        }
Beispiel #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="IndexGenome"></param>
        /// <returns></returns>
        public static string GetGenomeProgram(int IndexGenome)
        {
            string str = "";

            //
            IndexGenome = Genomes.GetLastGenocodeIndex();
            //

            foreach (Chromosome Chomo in Genomes.GetGenocode(IndexGenome))
            {
                str += "Chromo:\n";
                foreach (Gene Gen in Chomo)
                {
                    str += (TypeActionsOfPlants)Gen.GetGeneCommand() + "\n";
                }
            }
            return(str);
        }
Beispiel #28
0
        public virtual Genome <T>[] Epoch(Genome <T>[] oldGenomes = null)
        {
            Genomes = oldGenomes ?? Genomes;

            // Sort for the roulette
            Array.Sort(Genomes, Comparer);

            ResetRemarkableValues();
            CalculateRemarkableValues();

            // Copy the genomes
            Genomes = Genomes.Select(g => new Genome <T>(g)).ToArray();

            List <Genome <T> > population;

            if (IsElitist)
            {
                population = GetBests(Math.Min(NbEliteMax, PopulationSize), NbEliteCopies);
            }
            else
            {
                population = new List <Genome <T> >();
            }

            while (population.Count < PopulationSize)
            {
                Genome <T> parent1 = TriggerRoulette();
                Genome <T> parent2 = TriggerRoulette();

                T[] child1, child2;
                Crossover(parent1.Values, parent2.Values, out child1, out child2);

                Mutate(child1, MutationRate);
                Mutate(child2, MutationRate);

                population.Add(new Genome <T>(child1, 0));
                population.Add(new Genome <T>(child2, 0));
            }

            Genomes = population.ToArray();

            return(Genomes);
        }
Beispiel #29
0
        private void CreateStartPopulation(int genomes, Action <TGenome> genomeCreationMethod)
        {
            //clear existing population
            Genomes.Clear();

            for (int i = 0; i < genomes; i++)
            {
                var genome = new TGenome();
                genomeCreationMethod(genome);
                Genomes.Add(genome);
            }

            //reset all variables
            Generation        = 0;
            TotalFitnessScore = 0;

            GeneLength       = -1;
            ChromosoneLength = Genomes.First().Genes.Sum(g => g.Length);
        }
        private Genome getGenomeByRoulette()
        {
            var chosen = default(Genome);

            var slice             = _rand.NextDouble() * FitnessStats.Total;
            var cumulativeFitness = 0.0;

            foreach (var genome in Genomes)
            {
                cumulativeFitness += genome.Fitness;
                if (cumulativeFitness >= slice)
                {
                    chosen = genome;
                    break;
                }
            }
            chosen = chosen ?? Genomes.OrderBy(x => _rand.Next()).First();
            return(chosen);
        }