Inheritance: Encog.ML.Genetic.Genes.BasicGene
Exemplo n.º 1
0
        /// <summary>
        ///  Construct a genome by copying another.
        /// </summary>
        /// <param name="other">The other genome.</param>
        public NEATGenome(NEATGenome other)
        {
            NetworkDepth  = other.NetworkDepth;
            Population    = other.Population;
            Score         = other.Score;
            AdjustedScore = other.AdjustedScore;
            InputCount    = other.InputCount;
            OutputCount   = other.OutputCount;
            Species       = other.Species;

            // copy neurons
            foreach (NEATNeuronGene oldGene in other.NeuronsChromosome)
            {
                var newGene = new NEATNeuronGene(oldGene);
                _neuronsList.Add(newGene);
            }

            // copy links
            foreach (var oldGene in other.LinksChromosome)
            {
                var newGene = new NEATLinkGene(
                    oldGene.FromNeuronId, oldGene.ToNeuronId,
                    oldGene.Enabled, oldGene.InnovationId,
                    oldGene.Weight);
                _linksList.Add(newGene);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Copy from another gene.
        /// </summary>
        /// <param name="gene">The other gene.</param>
        public void Copy(NEATLinkGene gene)
        {
            NEATLinkGene other = gene;

            Enabled      = other.Enabled;
            FromNeuronId = other.FromNeuronId;
            ToNeuronId   = other.ToNeuronId;
            InnovationId = other.InnovationId;
            Weight       = other.Weight;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create a new genome with the specified connection density. This
        /// constructor is typically used to create the initial population.
        /// </summary>
        /// <param name="rnd">Random number generator.</param>
        /// <param name="pop">The population.</param>
        /// <param name="inputCount">The input count.</param>
        /// <param name="outputCount">The output count.</param>
        /// <param name="connectionDensity">The connection density.</param>
        public NEATGenome(EncogRandom rnd, NEATPopulation pop,
                          int inputCount, int outputCount,
                          double connectionDensity)
        {
            AdjustedScore = 0;
            InputCount    = inputCount;
            OutputCount   = outputCount;

            // get the activation function
            IActivationFunction af = pop.ActivationFunctions.PickFirst();

            // first bias
            int innovationId = 0;
            var biasGene     = new NEATNeuronGene(NEATNeuronType.Bias, af,
                                                  inputCount, innovationId++);

            _neuronsList.Add(biasGene);

            // then inputs

            for (var i = 0; i < inputCount; i++)
            {
                var gene = new NEATNeuronGene(NEATNeuronType.Input, af,
                                              i, innovationId++);
                _neuronsList.Add(gene);
            }

            // then outputs

            for (int i = 0; i < outputCount; i++)
            {
                var gene = new NEATNeuronGene(NEATNeuronType.Output, af,
                                              i + inputCount + 1, innovationId++);
                _neuronsList.Add(gene);
            }

            // and now links
            for (var i = 0; i < inputCount + 1; i++)
            {
                for (var j = 0; j < outputCount; j++)
                {
                    // make sure we have at least one connection
                    if (_linksList.Count < 1 ||
                        rnd.NextDouble() < connectionDensity)
                    {
                        long   fromId = this._neuronsList[i].Id;
                        long   toId   = this._neuronsList[inputCount + j + 1].Id;
                        double w      = RangeRandomizer.Randomize(rnd, -pop.WeightRange, pop.WeightRange);
                        var    gene   = new NEATLinkGene(fromId, toId, true,
                                                         innovationId++, w);
                        _linksList.Add(gene);
                    }
                }
            }
        }
Exemplo n.º 4
0
 public NEATGenome(NEATGenome other)
 {
     goto Label_0182;
     Label_0017:
     this.inputCount = other.inputCount;
     this.outputCount = other.outputCount;
     Label_002F:
     this.speciesID = other.speciesID;
     foreach (IGene gene in other.Neurons.Genes)
     {
         NEATNeuronGene gene2 = (NEATNeuronGene) gene;
         if (0xff != 0)
         {
             NEATNeuronGene gene3 = new NEATNeuronGene(gene2.NeuronType, gene2.Id, gene2.SplitY, gene2.SplitX, gene2.Recurrent, gene2.ActivationResponse);
             this.Neurons.Add(gene3);
         }
     }
     foreach (IGene gene4 in other.Links.Genes)
     {
         NEATLinkGene gene5 = (NEATLinkGene) gene4;
         NEATLinkGene gene6 = new NEATLinkGene((long) gene5.FromNeuronID, (long) gene5.ToNeuronID, gene5.Enabled, gene5.InnovationId, gene5.Weight, gene5.Recurrent);
         this.Links.Add(gene6);
     }
     return;
     Label_0182:
     this.neuronsChromosome = new Chromosome();
     this.linksChromosome = new Chromosome();
     base.GA = other.GA;
     base.Chromosomes.Add(this.neuronsChromosome);
     if (0 != 0)
     {
         goto Label_002F;
     }
     base.Chromosomes.Add(this.linksChromosome);
     base.GenomeID = other.GenomeID;
     this.networkDepth = other.networkDepth;
     base.Population = other.Population;
     base.Score = other.Score;
     if (0x7fffffff == 0)
     {
         goto Label_0017;
     }
     base.AdjustedScore = other.AdjustedScore;
     if (0 == 0)
     {
         base.AmountToSpawn = other.AmountToSpawn;
         goto Label_0017;
     }
     goto Label_0182;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Construct a genome by copying another.
        /// </summary>
        ///
        /// <param name="other">The other genome.</param>
        public NEATGenome(NEATGenome other)
        {
            neuronsChromosome = new Chromosome();
            linksChromosome   = new Chromosome();
            GA = other.GA;

            Chromosomes.Add(neuronsChromosome);
            Chromosomes.Add(linksChromosome);

            GenomeID      = other.GenomeID;
            networkDepth  = other.networkDepth;
            Population    = other.Population;
            Score         = other.Score;
            AdjustedScore = other.AdjustedScore;
            AmountToSpawn = other.AmountToSpawn;
            inputCount    = other.inputCount;
            outputCount   = other.outputCount;
            speciesID     = other.speciesID;


            // copy neurons
            foreach (IGene gene  in  other.Neurons.Genes)
            {
                var oldGene = (NEATNeuronGene)gene;
                var newGene = new NEATNeuronGene(
                    oldGene.NeuronType, oldGene.Id,
                    oldGene.SplitY, oldGene.SplitX,
                    oldGene.Recurrent, oldGene.ActivationResponse);
                Neurons.Add(newGene);
            }


            // copy links
            foreach (IGene gene_0  in  other.Links.Genes)
            {
                var oldGene_1 = (NEATLinkGene)gene_0;
                var newGene_2 = new NEATLinkGene(
                    oldGene_1.FromNeuronID, oldGene_1.ToNeuronID,
                    oldGene_1.Enabled, oldGene_1.InnovationId,
                    oldGene_1.Weight, oldGene_1.Recurrent);
                Links.Add(newGene_2);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Copy from another gene.
 /// </summary>
 /// <param name="gene">The other gene.</param>
 public void Copy(NEATLinkGene gene)
 {
     NEATLinkGene other = gene;
     Enabled = other.Enabled;
     FromNeuronId = other.FromNeuronId;
     ToNeuronId = other.ToNeuronId;
     InnovationId = other.InnovationId;
     Weight = other.Weight;
 }
Exemplo n.º 7
0
 internal void AddNeuron(double mutationRate, int numTrysToFindOldLink)
 {
     int num;
     NEATLinkGene gene;
     int num2;
     int num3;
     int num4;
     NEATLinkGene gene2;
     long num5;
     double weight;
     long fromNeuronID;
     long toNeuronID;
     NEATNeuronGene gene3;
     NEATNeuronGene gene4;
     double num9;
     double num10;
     NEATInnovation innovation;
     long num11;
     long num12;
     long num13;
     long num14;
     long neuronID;
     NEATInnovation innovation2;
     NEATInnovation innovation3;
     NEATLinkGene gene7;
     NEATLinkGene gene8;
     NEATNeuronGene gene9;
     if (ThreadSafeRandom.NextDouble() <= mutationRate)
     {
         goto Label_05EE;
     }
     return;
     Label_0043:
     this.linksChromosome.Add(gene7);
     this.linksChromosome.Add(gene8);
     Label_005D:
     gene9 = new NEATNeuronGene(NEATNeuronType.Hidden, neuronID, num9, num10);
     this.neuronsChromosome.Add(gene9);
     if ((((uint) num2) & 0) == 0)
     {
         if ((((uint) num14) + ((uint) num14)) <= uint.MaxValue)
         {
             return;
         }
         if ((((uint) num10) - ((uint) num12)) >= 0)
         {
             goto Label_0131;
         }
         goto Label_00EC;
     }
     Label_008C:
     if ((((uint) num11) & 0) != 0)
     {
         goto Label_0043;
     }
     Label_00A9:
     throw new NeuralNetworkError("NEAT Error");
     Label_00EC:
     innovation3 = ((NEATTraining) base.GA).Innovations.CheckInnovation(neuronID, toNeuronID, NEATInnovationType.NewLink);
     if ((((uint) numTrysToFindOldLink) - ((uint) num4)) < 0)
     {
         goto Label_0332;
     }
     if (innovation2 != null)
     {
         if (innovation3 == null)
         {
             if ((((uint) num) & 0) != 0)
             {
                 return;
             }
             goto Label_008C;
         }
         gene7 = new NEATLinkGene(fromNeuronID, neuronID, true, innovation2.InnovationID, 1.0, false);
         gene8 = new NEATLinkGene(neuronID, toNeuronID, true, innovation3.InnovationID, weight, false);
         goto Label_0043;
     }
     goto Label_00A9;
     Label_0131:
     if (innovation != null)
     {
         neuronID = innovation.NeuronID;
         innovation2 = ((NEATTraining) base.GA).Innovations.CheckInnovation(fromNeuronID, neuronID, NEATInnovationType.NewLink);
         goto Label_00EC;
     }
     do
     {
         num12 = ((NEATTraining) base.GA).Innovations.CreateNewInnovation(fromNeuronID, toNeuronID, NEATInnovationType.NewNeuron, NEATNeuronType.Hidden, num10, num9);
         this.neuronsChromosome.Add(new NEATNeuronGene(NEATNeuronType.Hidden, num12, num9, num10));
         num13 = base.GA.Population.AssignInnovationID();
         if ((((uint) fromNeuronID) | 15) == 0)
         {
             goto Label_0534;
         }
         ((NEATTraining) base.GA).Innovations.CreateNewInnovation(fromNeuronID, num12, NEATInnovationType.NewLink);
         NEATLinkGene gene5 = new NEATLinkGene(fromNeuronID, num12, true, num13, 1.0, false);
         this.linksChromosome.Add(gene5);
         if (((uint) num4) <= uint.MaxValue)
         {
             num14 = base.GA.Population.AssignInnovationID();
             ((NEATTraining) base.GA).Innovations.CreateNewInnovation(num12, toNeuronID, NEATInnovationType.NewLink);
             NEATLinkGene gene6 = new NEATLinkGene(num12, toNeuronID, true, num14, weight, false);
             this.linksChromosome.Add(gene6);
             return;
         }
     }
     while ((((uint) num14) + ((uint) num10)) > uint.MaxValue);
     Label_029B:
     if (((uint) num) > uint.MaxValue)
     {
         goto Label_05EE;
     }
     goto Label_0131;
     Label_0332:
     num10 = (gene3.SplitX + gene4.SplitX) / 2.0;
     innovation = ((NEATTraining) base.GA).Innovations.CheckInnovation(fromNeuronID, toNeuronID, NEATInnovationType.NewNeuron);
     if ((((uint) num9) <= uint.MaxValue) && (innovation == null))
     {
         if (((uint) num5) > uint.MaxValue)
         {
             goto Label_00EC;
         }
         if ((((uint) weight) & 0) != 0)
         {
             goto Label_005D;
         }
         if (((uint) num) >= 0)
         {
             if ((((uint) num) + ((uint) mutationRate)) <= uint.MaxValue)
             {
                 if ((((uint) num9) - ((uint) weight)) < 0)
                 {
                     return;
                 }
                 goto Label_029B;
             }
             goto Label_04BE;
         }
     }
     else
     {
         num11 = innovation.NeuronID;
         if (this.AlreadyHaveThisNeuronID(num11))
         {
             innovation = null;
         }
         goto Label_0131;
     }
     Label_03A3:
     if ((((uint) neuronID) - ((uint) num10)) > uint.MaxValue)
     {
         if (((uint) num5) >= 0)
         {
             goto Label_04BE;
         }
         if ((((uint) num5) & 0) == 0)
         {
             goto Label_04DC;
         }
         goto Label_0534;
     }
     gene4 = (NEATNeuronGene) this.Neurons.Get(this.GetElementPos(toNeuronID));
     num9 = (gene3.SplitY + gene4.SplitY) / 2.0;
     goto Label_0332;
     Label_03FD:
     gene3 = (NEATNeuronGene) this.Neurons.Get(this.GetElementPos(fromNeuronID));
     if ((((uint) num10) - ((uint) num9)) >= 0)
     {
         goto Label_03A3;
     }
     if (((uint) num5) <= uint.MaxValue)
     {
         return;
     }
     Label_0441:
     gene.Enabled = false;
     weight = gene.Weight;
     fromNeuronID = gene.FromNeuronID;
     toNeuronID = gene.ToNeuronID;
     if (((uint) num13) >= 0)
     {
         goto Label_03FD;
     }
     return;
     Label_0475:
     if (gene == null)
     {
         return;
     }
     if ((((uint) num9) - ((uint) weight)) >= 0)
     {
         goto Label_0441;
     }
     goto Label_03FD;
     Label_0497:
     if (num-- > 0)
     {
         goto Label_0534;
     }
     if ((((uint) num10) | 3) != 0)
     {
         goto Label_0475;
     }
     return;
     Label_04BE:
     if (((uint) num12) <= uint.MaxValue)
     {
         goto Label_0497;
     }
     Label_04DC:
     if (((NEATNeuronGene) this.Neurons.Get(this.GetElementPos(num5))).NeuronType == NEATNeuronType.Bias)
     {
         goto Label_0497;
     }
     gene = gene2;
     goto Label_0475;
     Label_0534:
     num4 = RangeRandomizer.RandomInt(0, num3);
     gene2 = (NEATLinkGene) this.linksChromosome.Get(num4);
     num5 = gene2.FromNeuronID;
     if (!gene2.Enabled || gene2.Recurrent)
     {
         goto Label_0497;
     }
     goto Label_04DC;
     Label_0575:
     num3 = this.NumGenes - 1;
     goto Label_0497;
     Label_05EE:
     num = numTrysToFindOldLink;
     if ((((uint) num9) + ((uint) num13)) > uint.MaxValue)
     {
         if ((((uint) num4) - ((uint) num3)) > uint.MaxValue)
         {
             goto Label_00A9;
         }
         goto Label_0575;
     }
     gene = null;
     num2 = (this.inputCount + this.outputCount) + 10;
     if ((((uint) toNeuronID) & 0) != 0)
     {
         goto Label_04DC;
     }
     if (this.linksChromosome.Size() >= num2)
     {
         goto Label_0575;
     }
     num3 = (this.NumGenes - 1) - ((int) Math.Sqrt((double) this.NumGenes));
     goto Label_0497;
 }
Exemplo n.º 8
0
 /// <summary>
 /// Construct from another gene.
 /// </summary>
 /// <param name="other">The other gene.</param>
 public NEATLinkGene(NEATLinkGene other)
 {
     Copy(other);
 }
        /// <inheritdoc/>
        public Object Read(Stream istream)
        {
            long nextInnovationId = 0;
            long nextGeneId = 0;

            var result = new NEATPopulation();
            var innovationList = new NEATInnovationList {Population = result};
            result.Innovations = innovationList;
            var reader = new EncogReadHelper(istream);
            EncogFileSection section;

            while ((section = reader.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("NEAT-POPULATION")
                        && section.SubSectionName.Equals("INNOVATIONS"))
                {
                    foreach (String line in section.Lines)
                    {
                        IList<String> cols = EncogFileSection
                                .SplitColumns(line);
                        var innovation = new NEATInnovation();
                        var innovationId = int.Parse(cols[1]);
                        innovation.InnovationId = innovationId;
                        innovation.NeuronId = int.Parse(cols[2]);
                        result.Innovations.Innovations[cols[0]] = innovation;
                        nextInnovationId = Math.Max(nextInnovationId, innovationId + 1);
                    }
                }
                else if (section.SectionName.Equals("NEAT-POPULATION")
                      && section.SubSectionName.Equals("SPECIES"))
                {
                    NEATGenome lastGenome = null;
                    BasicSpecies lastSpecies = null;

                    foreach (String line in section.Lines)
                    {
                        IList<String> cols = EncogFileSection.SplitColumns(line);

                        if (String.Compare(cols[0], "s", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            lastSpecies = new BasicSpecies
                                {
                                    Population = result,
                                    Age = int.Parse(cols[1]),
                                    BestScore = CSVFormat.EgFormat.Parse(cols[2]),
                                    GensNoImprovement = int.Parse(cols[3])
                                };
                            result.Species.Add(lastSpecies);
                        }
                        else if (String.Compare(cols[0], "g", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            bool isLeader = lastGenome == null;
                            lastGenome = new NEATGenome
                                {
                                    InputCount = result.InputCount,
                                    OutputCount = result.OutputCount,
                                    Species = lastSpecies,
                                    AdjustedScore = CSVFormat.EgFormat.Parse(cols[1]),
                                    Score = CSVFormat.EgFormat.Parse(cols[2]),
                                    BirthGeneration = int.Parse(cols[3])
                                };
                            lastSpecies.Add(lastGenome);
                            if (isLeader)
                            {
                                lastSpecies.Leader = lastGenome;
                            }
                        }
                        else if (String.Compare(cols[0], "n", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            var neuronGene = new NEATNeuronGene();
                            int geneId = int.Parse(cols[1]);
                            neuronGene.Id = geneId;

                            IActivationFunction af = EncogFileSection.ParseActivationFunction(cols[2]);
                            neuronGene.ActivationFunction = af;

                            neuronGene.NeuronType = PersistNEATPopulation.StringToNeuronType(cols[3]);
                            neuronGene.InnovationId = int.Parse(cols[4]);
                            lastGenome.NeuronsChromosome.Add(neuronGene);
                            nextGeneId = Math.Max(geneId + 1, nextGeneId);
                        }
                        else if (String.Compare(cols[0], "l", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            var linkGene = new NEATLinkGene
                                {
                                    Id = int.Parse(cols[1]),
                                    Enabled = (int.Parse(cols[2]) > 0),
                                    FromNeuronId = int.Parse(cols[3]),
                                    ToNeuronId = int.Parse(cols[4]),
                                    Weight = CSVFormat.EgFormat.Parse(cols[5]),
                                    InnovationId = int.Parse(cols[6])
                                };
                            lastGenome.LinksChromosome.Add(linkGene);
                        }
                    }

                }
                else if (section.SectionName.Equals("NEAT-POPULATION")
                      && section.SubSectionName.Equals("CONFIG"))
                {
                    IDictionary<string, string> prm = section.ParseParams();

                    string afStr = prm[NEATPopulation.PropertyNEATActivation];

                    if (String.Compare(afStr, TypeCppn, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        HyperNEATGenome.BuildCPPNActivationFunctions(result.ActivationFunctions);
                    }
                    else
                    {
                        result.NEATActivationFunction = EncogFileSection.ParseActivationFunction(prm,
                                        NEATPopulation.PropertyNEATActivation);
                    }

                    result.ActivationCycles = EncogFileSection.ParseInt(prm,
                            PersistConst.ActivationCycles);
                    result.InputCount = EncogFileSection.ParseInt(prm,
                            PersistConst.InputCount);
                    result.OutputCount = EncogFileSection.ParseInt(prm,
                            PersistConst.OutputCount);
                    result.PopulationSize = EncogFileSection.ParseInt(prm,
                            NEATPopulation.PropertyPopulationSize);
                    result.SurvivalRate = EncogFileSection.ParseDouble(prm,
                            NEATPopulation.PropertySurvivalRate);
                    result.ActivationCycles = EncogFileSection.ParseInt(prm,
                            NEATPopulation.PropertyCycles);
                }
            }

            // set factories
            if (result.IsHyperNEAT)
            {
                result.GenomeFactory = new FactorHyperNEATGenome();
                result.CODEC = new HyperNEATCODEC();
            }
            else
            {
                result.GenomeFactory = new FactorNEATGenome();
                result.CODEC = new NEATCODEC();
            }

            // set the next ID's
            result.InnovationIDGenerate.CurrentID = nextInnovationId;
            result.GeneIdGenerate.CurrentID = nextGeneId;

            // find first genome, which should be the best genome
            if (result.Species.Count > 0)
            {
                ISpecies species = result.Species[0];
                if (species.Members.Count > 0)
                {
                    result.BestGenome = species.Members[0];
                }
            }

            return result;
        }
Exemplo n.º 10
0
 /// <summary>
 /// Construct from another gene.
 /// </summary>
 /// <param name="other">The other gene.</param>
 public NEATLinkGene(NEATLinkGene other)
 {
     Copy(other);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Perform a cross over.
        /// </summary>
        /// <param name="mom">The mother genome.</param>
        /// <param name="dad">The father genome.</param>
        /// <returns></returns>
        public new NEATGenome Crossover(NEATGenome mom, NEATGenome dad)
        {
            NEATParent best;

            // first determine who is more fit, the mother or the father?
            if (mom.Score == dad.Score)
            {
                if (mom.NumGenes == dad.NumGenes)
                {
                    if (ThreadSafeRandom.NextDouble() > 0)
                    {
                        best = NEATParent.Mom;
                    }
                    else
                    {
                        best = NEATParent.Dad;
                    }
                }

                else
                {
                    if (mom.NumGenes < dad.NumGenes)
                    {
                        best = NEATParent.Mom;
                    }
                    else
                    {
                        best = NEATParent.Dad;
                    }
                }
            }
            else
            {
                if (Comparator.IsBetterThan(mom.Score, dad.Score))
                {
                    best = NEATParent.Mom;
                }

                else
                {
                    best = NEATParent.Dad;
                }
            }

            var babyNeurons = new Chromosome();
            var babyGenes   = new Chromosome();

            var vecNeurons = new List <long>();

            int curMom = 0;
            int curDad = 0;

            NEATLinkGene momGene;
            NEATLinkGene dadGene;

            NEATLinkGene selectedGene = null;

            while ((curMom < mom.NumGenes) || (curDad < dad.NumGenes))
            {
                if (curMom < mom.NumGenes)
                {
                    momGene = (NEATLinkGene)mom.Links.Get(curMom);
                }
                else
                {
                    momGene = null;
                }

                if (curDad < dad.NumGenes)
                {
                    dadGene = (NEATLinkGene)dad.Links.Get(curDad);
                }
                else
                {
                    dadGene = null;
                }

                if ((momGene == null) && (dadGene != null))
                {
                    if (best == NEATParent.Dad)
                    {
                        selectedGene = dadGene;
                    }
                    curDad++;
                }
                else if ((dadGene == null) && (momGene != null))
                {
                    if (best == NEATParent.Mom)
                    {
                        selectedGene = momGene;
                    }
                    curMom++;
                }
                else if (momGene.InnovationId < dadGene.InnovationId)
                {
                    if (best == NEATParent.Mom)
                    {
                        selectedGene = momGene;
                    }
                    curMom++;
                }
                else if (dadGene.InnovationId < momGene.InnovationId)
                {
                    if (best == NEATParent.Dad)
                    {
                        selectedGene = dadGene;
                    }
                    curDad++;
                }
                else if (dadGene.InnovationId == momGene.InnovationId)
                {
                    if (ThreadSafeRandom.NextDouble() < 0.5f)
                    {
                        selectedGene = momGene;
                    }

                    else
                    {
                        selectedGene = dadGene;
                    }
                    curMom++;
                    curDad++;
                }

                if (babyGenes.Size() == 0)
                {
                    babyGenes.Add(selectedGene);
                }

                else
                {
                    if (((NEATLinkGene)babyGenes.Get(babyGenes.Size() - 1))
                        .InnovationId != selectedGene.InnovationId)
                    {
                        babyGenes.Add(selectedGene);
                    }
                }

                // Check if we already have the nodes referred to in SelectedGene.
                // If not, they need to be added.
                AddNeuronID(selectedGene.FromNeuronID, vecNeurons);
                AddNeuronID(selectedGene.ToNeuronID, vecNeurons);
            } // end while

            // now create the required nodes. First sort them into order
            vecNeurons.Sort();

            for (int i = 0; i < vecNeurons.Count; i++)
            {
                babyNeurons.Add(Innovations.CreateNeuronFromID(
                                    vecNeurons[i]));
            }

            // finally, create the genome
            var babyGenome = new NEATGenome(Population
                                            .AssignGenomeID(), babyNeurons, babyGenes, mom.InputCount,
                                            mom.OutputCount);

            babyGenome.GA         = this;
            babyGenome.Population = Population;

            return(babyGenome);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Read the object.
        /// </summary>
        /// <param name="mask0">The stream to read the object from.</param>
        /// <returns>The object that was loaded.</returns>
        public virtual Object Read(Stream mask0)
        {
            var result = new NEATPopulation();
            var innovationList = new NEATInnovationList {Population = result};
            result.Innovations = innovationList;
            var ins0 = new EncogReadHelper(mask0);
            IDictionary<Int32, ISpecies> speciesMap = new Dictionary<Int32, ISpecies>();
            IDictionary<ISpecies, Int32> leaderMap = new Dictionary<ISpecies, Int32>();
            IDictionary<Int32, IGenome> genomeMap = new Dictionary<Int32, IGenome>();
            EncogFileSection section;

            while ((section = ins0.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("NEAT-POPULATION")
                    && section.SubSectionName.Equals("INNOVATIONS"))
                {
                    foreach (String line  in  section.Lines)
                    {
                        IList<String> cols = EncogFileSection.SplitColumns(line);
                        var innovation = new NEATInnovation
                                             {
                                                 InnovationID = Int32.Parse(cols[0]),
                                                 InnovationType = StringToInnovationType(cols[1]),
                                                 NeuronType = StringToNeuronType(cols[2]),
                                                 SplitX = CSVFormat.EgFormat.Parse(cols[3]),
                                                 SplitY = CSVFormat.EgFormat.Parse(cols[4]),
                                                 NeuronID = Int32.Parse(cols[5]),
                                                 FromNeuronID = Int32.Parse(cols[6]),
                                                 ToNeuronID = Int32.Parse(cols[7])
                                             };
                        result.Innovations.Add(innovation);
                    }
                }
                else if (section.SectionName.Equals("NEAT-POPULATION")
                         && section.SubSectionName.Equals("SPECIES"))
                {
                    foreach (String line  in  section.Lines)
                    {
                        String[] cols = line.Split(',');
                        var species = new BasicSpecies
                                          {
                                              SpeciesID = Int32.Parse(cols[0]),
                                              Age = Int32.Parse(cols[1]),
                                              BestScore = CSVFormat.EgFormat.Parse(cols[2]),
                                              GensNoImprovement = Int32.Parse(cols[3]),
                                              SpawnsRequired = CSVFormat.EgFormat
                                                  .Parse(cols[4])
                                          };

                        species.SpawnsRequired = CSVFormat.EgFormat
                            .Parse(cols[5]);
                        leaderMap[(species)] = (Int32.Parse(cols[6]));
                        result.Species.Add(species);
                        speciesMap[((int) species.SpeciesID)] = (species);
                    }
                }
                else if (section.SectionName.Equals("NEAT-POPULATION")
                         && section.SubSectionName.Equals("GENOMES"))
                {
                    NEATGenome lastGenome = null;

                    foreach (String line  in  section.Lines)
                    {
                        IList<String> cols = EncogFileSection.SplitColumns(line);
                        if (cols[0].Equals("g", StringComparison.InvariantCultureIgnoreCase))
                        {
                            lastGenome = new NEATGenome
                                             {
                                                 NeuronsChromosome = new Chromosome(),
                                                 LinksChromosome = new Chromosome()
                                             };
                            lastGenome.Chromosomes.Add(lastGenome.NeuronsChromosome);
                            lastGenome.Chromosomes.Add(lastGenome.LinksChromosome);
                            lastGenome.GenomeID = Int32.Parse(cols[1]);
                            lastGenome.SpeciesID = Int32.Parse(cols[2]);
                            lastGenome.AdjustedScore = CSVFormat.EgFormat
                                .Parse(cols[3]);
                            lastGenome.AmountToSpawn = CSVFormat.EgFormat
                                .Parse(cols[4]);
                            lastGenome.NetworkDepth = Int32.Parse(cols[5]);
                            lastGenome.Score = CSVFormat.EgFormat.Parse(cols[6]);
                            result.Add(lastGenome);
                            genomeMap[(int) lastGenome.GenomeID] = lastGenome;
                        }
                        else if (cols[0].Equals("n", StringComparison.InvariantCultureIgnoreCase))
                        {
                            var neuronGene = new NEATNeuronGene
                                                 {
                                                     Id = Int32.Parse(cols[1]),
                                                     NeuronType = StringToNeuronType(cols[2]),
                                                     Enabled = Int32.Parse(cols[3]) > 0,
                                                     InnovationId = Int32.Parse(cols[4]),
                                                     ActivationResponse = CSVFormat.EgFormat
                                                         .Parse(cols[5]),
                                                     SplitX = CSVFormat.EgFormat.Parse(cols[6]),
                                                     SplitY = CSVFormat.EgFormat.Parse(cols[7])
                                                 };
                            lastGenome.Neurons.Add(neuronGene);
                        }
                        else if (cols[0].Equals("l", StringComparison.InvariantCultureIgnoreCase))
                        {
                            var linkGene = new NEATLinkGene();
                            linkGene.Id = Int32.Parse(cols[1]);
                            linkGene.Enabled = Int32.Parse(cols[2]) > 0;
                            linkGene.Recurrent = Int32.Parse(cols[3]) > 0;
                            linkGene.FromNeuronID = Int32.Parse(cols[4]);
                            linkGene.ToNeuronID = Int32.Parse(cols[5]);
                            linkGene.Weight = CSVFormat.EgFormat.Parse(cols[6]);
                            linkGene.InnovationId = Int32.Parse(cols[7]);
                            lastGenome.Links.Add(linkGene);
                        }
                    }
                }
                else if (section.SectionName.Equals("NEAT-POPULATION")
                         && section.SubSectionName.Equals("CONFIG"))
                {
                    IDictionary<String, String> paras = section.ParseParams();

                    result.NeatActivationFunction = EncogFileSection
                        .ParseActivationFunction(paras,
                                                 NEATPopulation.PropertyNEATActivation);
                    result.OutputActivationFunction = EncogFileSection
                        .ParseActivationFunction(paras,
                                                 NEATPopulation.PropertyOutputActivation);
                    result.Snapshot = EncogFileSection.ParseBoolean(paras,
                                                                    PersistConst.Snapshot);
                    result.InputCount = EncogFileSection.ParseInt(paras,
                                                                  PersistConst.InputCount);
                    result.OutputCount = EncogFileSection.ParseInt(paras,
                                                                   PersistConst.OutputCount);
                    result.OldAgePenalty = EncogFileSection.ParseDouble(paras,
                                                                        PopulationConst.PropertyOldAgePenalty);
                    result.OldAgeThreshold = EncogFileSection.ParseInt(paras,
                                                                       PopulationConst.PropertyOldAgeThreshold);
                    result.PopulationSize = EncogFileSection.ParseInt(paras,
                                                                      PopulationConst.PropertyPopulationSize);
                    result.SurvivalRate = EncogFileSection.ParseDouble(paras,
                                                                       PopulationConst.PropertySurvivalRate);
                    result.YoungBonusAgeThreshhold = EncogFileSection.ParseInt(
                        paras, PopulationConst.PropertyYoungAgeThreshold);
                    result.YoungScoreBonus = EncogFileSection.ParseDouble(paras,
                                                                          PopulationConst.PropertyYoungAgeBonus);
                    result.GenomeIDGenerate.CurrentID = EncogFileSection.ParseInt(paras,
                                                                                  PopulationConst.
                                                                                      PropertyNextGenomeID);
                    result.InnovationIDGenerate.CurrentID = EncogFileSection.ParseInt(paras,
                                                                                      PopulationConst.
                                                                                          PropertyNextInnovationID);
                    result.GeneIDGenerate.CurrentID = EncogFileSection.ParseInt(paras,
                                                                                PopulationConst.
                                                                                    PropertyNextGeneID);
                    result.SpeciesIDGenerate.CurrentID = EncogFileSection.ParseInt(paras,
                                                                                   PopulationConst.
                                                                                       PropertyNextSpeciesID);
                }
            }

            // now link everything up

            // first put all the genomes into correct species
            foreach (IGenome genome  in  result.Genomes)
            {
                var neatGenome = (NEATGenome) genome;
                var speciesId = (int) neatGenome.SpeciesID;
                if( speciesMap.ContainsKey(speciesId))
                {
                    ISpecies s = speciesMap[speciesId];
                    s.Members.Add(neatGenome);
                }

                neatGenome.InputCount = result.InputCount;
                neatGenome.OutputCount = result.OutputCount;
            }

            // set the species leader links
            foreach (ISpecies species  in  leaderMap.Keys)
            {
                int leaderID = leaderMap[species];
                IGenome leader = genomeMap[leaderID];
                species.Leader = leader;
                ((BasicSpecies) species).Population = result;
            }

            return result;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Mutate the genome by adding a neuron.
        /// </summary>
        ///
        /// <param name="mutationRate">The mutation rate.</param>
        /// <param name="numTrysToFindOldLink">The number of tries to find a link to split.</param>
        internal void AddNeuron(double mutationRate, int numTrysToFindOldLink)
        {
            // should we add a neuron?
            if (ThreadSafeRandom.NextDouble() > mutationRate)
            {
                return;
            }

            int countTrysToFindOldLink = numTrysToFindOldLink;

            // the link to split
            NEATLinkGene splitLink = null;

            int sizeBias = inputCount + outputCount + 10;

            // if there are not at least
            int upperLimit;

            if (linksChromosome.Size() < sizeBias)
            {
                upperLimit = NumGenes - 1 - (int)Math.Sqrt(NumGenes);
            }
            else
            {
                upperLimit = NumGenes - 1;
            }

            while ((countTrysToFindOldLink--) > 0)
            {
                // choose a link, use the square root to prefer the older links
                int i    = RangeRandomizer.RandomInt(0, upperLimit);
                var link = (NEATLinkGene)linksChromosome
                           .Get(i);

                // get the from neuron
                long fromNeuron = link.FromNeuronID;

                if ((link.Enabled) &&
                    (!link.Recurrent) &&
                    (((NEATNeuronGene)Neurons.Get(
                          GetElementPos(fromNeuron))).NeuronType != NEATNeuronType.Bias))
                {
                    splitLink = link;
                    break;
                }
            }

            if (splitLink == null)
            {
                return;
            }

            splitLink.Enabled = false;

            double originalWeight = splitLink.Weight;

            long from = splitLink.FromNeuronID;
            long to   = splitLink.ToNeuronID;

            var fromGene = (NEATNeuronGene)Neurons.Get(
                GetElementPos(from));
            var toGene = (NEATNeuronGene)Neurons.Get(
                GetElementPos(to));

            double newDepth = (fromGene.SplitY + toGene.SplitY) / 2;
            double newWidth = (fromGene.SplitX + toGene.SplitX) / 2;

            // has this innovation already been tried?
            NEATInnovation innovation = ((NEATTraining)GA).Innovations.CheckInnovation(from, to,
                                                                                       NEATInnovationType
                                                                                       .NewNeuron);

            // prevent chaining
            if (innovation != null)
            {
                long neuronID = innovation.NeuronID;

                if (AlreadyHaveThisNeuronID(neuronID))
                {
                    innovation = null;
                }
            }

            if (innovation == null)
            {
                // this innovation has not been tried, create it
                long newNeuronID = ((NEATTraining)GA).Innovations.CreateNewInnovation(from, to,
                                                                                      NEATInnovationType.
                                                                                      NewNeuron,
                                                                                      NEATNeuronType.
                                                                                      Hidden,
                                                                                      newWidth, newDepth);

                neuronsChromosome.Add(new NEATNeuronGene(
                                          NEATNeuronType.Hidden, newNeuronID, newDepth, newWidth));

                // add the first link
                long link1ID = (GA).Population.AssignInnovationID();

                ((NEATTraining)GA).Innovations
                .CreateNewInnovation(from, newNeuronID,
                                     NEATInnovationType.NewLink);

                var link1 = new NEATLinkGene(from, newNeuronID,
                                             true, link1ID, 1.0d, false);

                linksChromosome.Add(link1);

                // add the second link
                long link2ID = (GA).Population.AssignInnovationID();

                ((NEATTraining)GA).Innovations
                .CreateNewInnovation(newNeuronID, to,
                                     NEATInnovationType.NewLink);

                var link2 = new NEATLinkGene(newNeuronID, to, true,
                                             link2ID, originalWeight, false);

                linksChromosome.Add(link2);
            }

            else
            {
                // existing innovation
                long newNeuronID_0 = innovation.NeuronID;

                NEATInnovation innovationLink1 = ((NEATTraining)GA).Innovations.CheckInnovation(from,
                                                                                                newNeuronID_0,
                                                                                                NEATInnovationType
                                                                                                .
                                                                                                NewLink);
                NEATInnovation innovationLink2 =
                    ((NEATTraining)GA).Innovations.CheckInnovation(newNeuronID_0, to,
                                                                   NEATInnovationType.NewLink);

                if ((innovationLink1 == null) || (innovationLink2 == null))
                {
                    throw new NeuralNetworkError("NEAT Error");
                }

                var link1_1 = new NEATLinkGene(from, newNeuronID_0,
                                               true, innovationLink1.InnovationID, 1.0d, false);
                var link2_2 = new NEATLinkGene(newNeuronID_0, to, true,
                                               innovationLink2.InnovationID, originalWeight, false);

                linksChromosome.Add(link1_1);
                linksChromosome.Add(link2_2);

                var newNeuron = new NEATNeuronGene(
                    NEATNeuronType.Hidden, newNeuronID_0, newDepth, newWidth);

                neuronsChromosome.Add(newNeuron);
            }

            return;
        }
        /// <summary>
        /// Create a new genome with the specified connection density. This
        /// constructor is typically used to create the initial population.
        /// </summary>
        /// <param name="rnd">Random number generator.</param>
        /// <param name="pop">The population.</param>
        /// <param name="inputCount">The input count.</param>
        /// <param name="outputCount">The output count.</param>
        /// <param name="connectionDensity">The connection density.</param>
        public NEATGenome(EncogRandom rnd, NEATPopulation pop,
            int inputCount, int outputCount,
            double connectionDensity)
        {
            AdjustedScore = 0;
            InputCount = inputCount;
            OutputCount = outputCount;

            // get the activation function
            IActivationFunction af = pop.ActivationFunctions.PickFirst();

            // first bias
            int innovationId = 0;
            var biasGene = new NEATNeuronGene(NEATNeuronType.Bias, af,
                    inputCount, innovationId++);
            _neuronsList.Add(biasGene);

            // then inputs

            for (var i = 0; i < inputCount; i++)
            {
                var gene = new NEATNeuronGene(NEATNeuronType.Input, af,
                        i, innovationId++);
                _neuronsList.Add(gene);
            }

            // then outputs

            for (int i = 0; i < outputCount; i++)
            {
                var gene = new NEATNeuronGene(NEATNeuronType.Output, af,
                        i + inputCount + 1, innovationId++);
                _neuronsList.Add(gene);
            }

            // and now links
            for (var i = 0; i < inputCount + 1; i++)
            {
                for (var j = 0; j < outputCount; j++)
                {
                    // make sure we have at least one connection
                    if (_linksList.Count < 1
                            || rnd.NextDouble() < connectionDensity)
                    {
                        long fromId = this._neuronsList[i].Id;
                        long toId = this._neuronsList[inputCount + j + 1].Id;
                        double w = RangeRandomizer.Randomize(rnd, -pop.WeightRange, pop.WeightRange);
                        var gene = new NEATLinkGene(fromId, toId, true,
                                innovationId++, w);
                        _linksList.Add(gene);
                    }
                }
            }
        }
Exemplo n.º 15
0
 internal void AddLink(double mutationRate, double chanceOfLooped, int numTrysToFindLoop, int numTrysToAddLink)
 {
     int num;
     int num2;
     long id;
     long num4;
     bool flag;
     NEATNeuronGene gene;
     NEATNeuronGene gene2;
     NEATNeuronGene gene3;
     NEATInnovation innovation;
     NEATNeuronGene gene4;
     long num5;
     NEATLinkGene gene5;
     if (ThreadSafeRandom.NextDouble() <= mutationRate)
     {
         num = numTrysToFindLoop;
         if ((((uint) num5) - ((uint) chanceOfLooped)) > uint.MaxValue)
         {
             if ((((uint) num4) + ((uint) num2)) < 0)
             {
                 goto Label_01D4;
             }
             if ((((uint) numTrysToAddLink) - ((uint) num2)) < 0)
             {
                 goto Label_0327;
             }
             goto Label_01BA;
         }
         num2 = numTrysToFindLoop;
         id = -1L;
         num4 = -1L;
         flag = false;
         goto Label_01EE;
     }
     return;
     Label_0057:
     if (innovation == null)
     {
         ((NEATTraining) base.GA).Innovations.CreateNewInnovation(id, num4, NEATInnovationType.NewLink);
         num5 = base.GA.Population.AssignInnovationID();
         if (15 != 0)
         {
             gene5 = new NEATLinkGene(id, num4, true, num5, RangeRandomizer.Randomize(-1.0, 1.0), flag);
             if ((((uint) num) + ((uint) num5)) > uint.MaxValue)
             {
                 goto Label_00B2;
             }
         }
     }
     else
     {
         NEATLinkGene gene6 = new NEATLinkGene(id, num4, true, innovation.InnovationID, RangeRandomizer.Randomize(-1.0, 1.0), flag);
         this.linksChromosome.Add(gene6);
         if (3 != 0)
         {
             return;
         }
         goto Label_0123;
     }
     Label_0063:
     this.linksChromosome.Add(gene5);
     return;
     Label_00B2:
     gene4 = (NEATNeuronGene) this.neuronsChromosome.Get(this.GetElementPos(id));
     if (gene4.SplitY > gene4.SplitY)
     {
         flag = true;
     }
     goto Label_0057;
     Label_011E:
     if (id < 0L)
     {
         return;
     }
     Label_0123:
     if (num4 >= 0L)
     {
         innovation = ((NEATTraining) base.GA).Innovations.CheckInnovation(id, id, NEATInnovationType.NewLink);
         if ((((uint) numTrysToAddLink) + ((uint) flag)) <= uint.MaxValue)
         {
             goto Label_00B2;
         }
         goto Label_0063;
     }
     return;
     Label_0198:
     if (num2-- > 0)
     {
         gene2 = this.ChooseRandomNeuron(true);
         gene3 = this.ChooseRandomNeuron(false);
         goto Label_01CA;
     }
     if ((((uint) mutationRate) + ((uint) chanceOfLooped)) < 0)
     {
         if ((((uint) id) | 4) == 0)
         {
             goto Label_0057;
         }
         goto Label_01EE;
     }
     goto Label_011E;
     Label_01BA:
     if (gene3.NeuronType != NEATNeuronType.Bias)
     {
         id = gene2.Id;
         if ((((uint) mutationRate) + ((uint) numTrysToAddLink)) > uint.MaxValue)
         {
             goto Label_01CA;
         }
         num4 = gene3.Id;
         if ((((uint) num5) + ((uint) num4)) > uint.MaxValue)
         {
             goto Label_0311;
         }
         if ((((uint) num) - ((uint) id)) < 0)
         {
             return;
         }
         if (0 == 0)
         {
             goto Label_011E;
         }
         goto Label_02DF;
     }
     goto Label_0198;
     Label_01CA:
     if (this.IsDuplicateLink(id, num4))
     {
         goto Label_0198;
     }
     Label_01D4:
     if (((((uint) num5) - ((uint) chanceOfLooped)) <= uint.MaxValue) && (gene2.Id != gene3.Id))
     {
         goto Label_01BA;
     }
     goto Label_0198;
     Label_01EE:
     if (ThreadSafeRandom.NextDouble() >= chanceOfLooped)
     {
         goto Label_0198;
     }
     Label_02DF:
     if (num-- > 0)
     {
         gene = this.ChooseRandomNeuron(false);
     }
     else
     {
         goto Label_011E;
     }
     Label_0311:
     if ((!gene.Recurrent && (gene.NeuronType != NEATNeuronType.Bias)) && (gene.NeuronType != NEATNeuronType.Input))
     {
         if (-1 == 0)
         {
             goto Label_032F;
         }
         id = gene.Id;
     }
     else
     {
         goto Label_02DF;
     }
     Label_0327:
     num4 = gene.Id;
     Label_032F:
     gene.Recurrent = true;
     flag = true;
     num = 0;
     goto Label_02DF;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Mutate the genome by adding a link to this genome.
        /// </summary>
        ///
        /// <param name="mutationRate">The mutation rate.</param>
        /// <param name="chanceOfLooped">The chance of a self-connected neuron.</param>
        /// <param name="numTrysToFindLoop">The number of tries to find a loop.</param>
        /// <param name="numTrysToAddLink">The number of tries to add a link.</param>
        internal void AddLink(double mutationRate, double chanceOfLooped,
                              int numTrysToFindLoop, int numTrysToAddLink)
        {
            // should we even add the link
            if (ThreadSafeRandom.NextDouble() > mutationRate)
            {
                return;
            }

            int countTrysToFindLoop = numTrysToFindLoop;
            int countTrysToAddLink  = numTrysToFindLoop;

            // the link will be between these two neurons
            long neuron1ID = -1;
            long neuron2ID = -1;

            bool recurrent = false;

            // a self-connected loop?
            if (ThreadSafeRandom.NextDouble() < chanceOfLooped)
            {
                // try to find(randomly) a neuron to add a self-connected link to
                while ((countTrysToFindLoop--) > 0)
                {
                    NEATNeuronGene neuronGene = ChooseRandomNeuron(false);

                    // no self-links on input or bias neurons
                    if (!neuronGene.Recurrent &&
                        (neuronGene.NeuronType != NEATNeuronType.Bias) &&
                        (neuronGene.NeuronType != NEATNeuronType.Input))
                    {
                        neuron1ID = neuronGene.Id;
                        neuron2ID = neuronGene.Id;

                        neuronGene.Recurrent = true;
                        recurrent            = true;

                        countTrysToFindLoop = 0;
                    }
                }
            }
            else
            {
                // try to add a regular link
                while ((countTrysToAddLink--) > 0)
                {
                    NEATNeuronGene neuron1 = ChooseRandomNeuron(true);
                    NEATNeuronGene neuron2 = ChooseRandomNeuron(false);

                    if (!IsDuplicateLink(neuron1ID, neuron2ID) &&
                        (neuron1.Id != neuron2.Id) &&
                        (neuron2.NeuronType != NEATNeuronType.Bias))
                    {
                        neuron1ID = neuron1.Id;
                        neuron2ID = neuron2.Id;
                        break;
                    }
                }
            }

            // did we fail to find a link
            if ((neuron1ID < 0) || (neuron2ID < 0))
            {
                return;
            }

            // check to see if this innovation has already been tried
            NEATInnovation innovation = ((NEATTraining)GA).Innovations.CheckInnovation(neuron1ID,
                                                                                       neuron1ID,
                                                                                       NEATInnovationType
                                                                                       .NewLink);

            // see if this is a recurrent(backwards) link
            var neuronGene_0 = (NEATNeuronGene)neuronsChromosome
                               .Get(GetElementPos(neuron1ID));

            if (neuronGene_0.SplitY > neuronGene_0.SplitY)
            {
                recurrent = true;
            }

            // is this a new innovation?
            if (innovation == null)
            {
                // new innovation
                ((NEATTraining)GA).Innovations
                .CreateNewInnovation(neuron1ID, neuron2ID,
                                     NEATInnovationType.NewLink);

                long id2 = GA.Population.AssignInnovationID();

                var linkGene = new NEATLinkGene(neuron1ID,
                                                neuron2ID, true, id2, RangeRandomizer.Randomize(-1, 1),
                                                recurrent);
                linksChromosome.Add(linkGene);
            }
            else
            {
                // existing innovation
                var linkGene_1 = new NEATLinkGene(neuron1ID,
                                                  neuron2ID, true, innovation.InnovationID,
                                                  RangeRandomizer.Randomize(-1, 1), recurrent);
                linksChromosome.Add(linkGene_1);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Mutate the genome by adding a neuron.
        /// </summary>
        ///
        /// <param name="mutationRate">The mutation rate.</param>
        /// <param name="numTrysToFindOldLink">The number of tries to find a link to split.</param>
        internal void AddNeuron(double mutationRate, int numTrysToFindOldLink)
        {
            // should we add a neuron?
            if (ThreadSafeRandom.NextDouble() > mutationRate)
            {
                return;
            }

            int countTrysToFindOldLink = numTrysToFindOldLink;

            // the link to split
            NEATLinkGene splitLink = null;

            int sizeBias = inputCount + outputCount + 10;

            // if there are not at least
            int upperLimit;
            if (linksChromosome.Size() < sizeBias)
            {
                upperLimit = NumGenes - 1 - (int) Math.Sqrt(NumGenes);
            }
            else
            {
                upperLimit = NumGenes - 1;
            }

            while ((countTrysToFindOldLink--) > 0)
            {
                // choose a link, use the square root to prefer the older links
                int i = RangeRandomizer.RandomInt(0, upperLimit);
                var link = (NEATLinkGene) linksChromosome
                                              .Get(i);

                // get the from neuron
                long fromNeuron = link.FromNeuronID;

                if ((link.Enabled)
                    && (!link.Recurrent)
                    && (((NEATNeuronGene) Neurons.Get(
                        GetElementPos(fromNeuron))).NeuronType != NEATNeuronType.Bias))
                {
                    splitLink = link;
                    break;
                }
            }

            if (splitLink == null)
            {
                return;
            }

            splitLink.Enabled = false;

            double originalWeight = splitLink.Weight;

            long from = splitLink.FromNeuronID;
            long to = splitLink.ToNeuronID;

            var fromGene = (NEATNeuronGene) Neurons.Get(
                GetElementPos(from));
            var toGene = (NEATNeuronGene) Neurons.Get(
                GetElementPos(to));

            double newDepth = (fromGene.SplitY + toGene.SplitY)/2;
            double newWidth = (fromGene.SplitX + toGene.SplitX)/2;

            // has this innovation already been tried?
            NEATInnovation innovation = ((NEATTraining) GA).Innovations.CheckInnovation(from, to,
                                                                                                      NEATInnovationType
                                                                                                          .NewNeuron);

            // prevent chaining
            if (innovation != null)
            {
                long neuronID = innovation.NeuronID;

                if (AlreadyHaveThisNeuronID(neuronID))
                {
                    innovation = null;
                }
            }

            if (innovation == null)
            {
                // this innovation has not been tried, create it
                long newNeuronID = ((NEATTraining) GA).Innovations.CreateNewInnovation(from, to,
                                                                                                     NEATInnovationType.
                                                                                                         NewNeuron,
                                                                                                     NEATNeuronType.
                                                                                                         Hidden,
                                                                                                     newWidth, newDepth);

                neuronsChromosome.Add(new NEATNeuronGene(
                                          NEATNeuronType.Hidden, newNeuronID, newDepth, newWidth));

                // add the first link
                long link1ID = (GA).Population.AssignInnovationID();

                ((NEATTraining) GA).Innovations
                    .CreateNewInnovation(from, newNeuronID,
                                         NEATInnovationType.NewLink);

                var link1 = new NEATLinkGene(from, newNeuronID,
                                             true, link1ID, 1.0d, false);

                linksChromosome.Add(link1);

                // add the second link
                long link2ID = (GA).Population.AssignInnovationID();

                ((NEATTraining) GA).Innovations
                    .CreateNewInnovation(newNeuronID, to,
                                         NEATInnovationType.NewLink);

                var link2 = new NEATLinkGene(newNeuronID, to, true,
                                             link2ID, originalWeight, false);

                linksChromosome.Add(link2);
            }

            else
            {
                // existing innovation
                long newNeuronID_0 = innovation.NeuronID;

                NEATInnovation innovationLink1 = ((NEATTraining) GA).Innovations.CheckInnovation(from,
                                                                                                               newNeuronID_0,
                                                                                                               NEATInnovationType
                                                                                                                   .
                                                                                                                   NewLink);
                NEATInnovation innovationLink2 =
                    ((NEATTraining) GA).Innovations.CheckInnovation(newNeuronID_0, to,
                                                                                  NEATInnovationType.NewLink);

                if ((innovationLink1 == null) || (innovationLink2 == null))
                {
                    throw new NeuralNetworkError("NEAT Error");
                }

                var link1_1 = new NEATLinkGene(from, newNeuronID_0,
                                               true, innovationLink1.InnovationID, 1.0d, false);
                var link2_2 = new NEATLinkGene(newNeuronID_0, to, true,
                                               innovationLink2.InnovationID, originalWeight, false);

                linksChromosome.Add(link1_1);
                linksChromosome.Add(link2_2);

                var newNeuron = new NEATNeuronGene(
                    NEATNeuronType.Hidden, newNeuronID_0, newDepth, newWidth);

                neuronsChromosome.Add(newNeuron);
            }

            return;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Mutate the genome by adding a link to this genome.
        /// </summary>
        ///
        /// <param name="mutationRate">The mutation rate.</param>
        /// <param name="chanceOfLooped">The chance of a self-connected neuron.</param>
        /// <param name="numTrysToFindLoop">The number of tries to find a loop.</param>
        /// <param name="numTrysToAddLink">The number of tries to add a link.</param>
        internal void AddLink(double mutationRate, double chanceOfLooped,
                              int numTrysToFindLoop, int numTrysToAddLink)
        {
            // should we even add the link
            if (ThreadSafeRandom.NextDouble() > mutationRate)
            {
                return;
            }

            int countTrysToFindLoop = numTrysToFindLoop;
            int countTrysToAddLink = numTrysToFindLoop;

            // the link will be between these two neurons
            long neuron1ID = -1;
            long neuron2ID = -1;

            bool recurrent = false;

            // a self-connected loop?
            if (ThreadSafeRandom.NextDouble() < chanceOfLooped)
            {
                // try to find(randomly) a neuron to add a self-connected link to
                while ((countTrysToFindLoop--) > 0)
                {
                    NEATNeuronGene neuronGene = ChooseRandomNeuron(false);

                    // no self-links on input or bias neurons
                    if (!neuronGene.Recurrent
                        && (neuronGene.NeuronType != NEATNeuronType.Bias)
                        && (neuronGene.NeuronType != NEATNeuronType.Input))
                    {
                        neuron1ID = neuronGene.Id;
                        neuron2ID = neuronGene.Id;

                        neuronGene.Recurrent = true;
                        recurrent = true;

                        countTrysToFindLoop = 0;
                    }
                }
            }
            else
            {
                // try to add a regular link
                while ((countTrysToAddLink--) > 0)
                {
                    NEATNeuronGene neuron1 = ChooseRandomNeuron(true);
                    NEATNeuronGene neuron2 = ChooseRandomNeuron(false);

                    if (!IsDuplicateLink(neuron1ID, neuron2ID)
                        && (neuron1.Id != neuron2.Id)
                        && (neuron2.NeuronType != NEATNeuronType.Bias))
                    {
                        neuron1ID = neuron1.Id;
                        neuron2ID = neuron2.Id;
                        break;
                    }
                }
            }

            // did we fail to find a link
            if ((neuron1ID < 0) || (neuron2ID < 0))
            {
                return;
            }

            // check to see if this innovation has already been tried
            NEATInnovation innovation = ((NEATTraining) GA).Innovations.CheckInnovation(neuron1ID,
                                                                                                      neuron1ID,
                                                                                                      NEATInnovationType
                                                                                                          .NewLink);

            // see if this is a recurrent(backwards) link
            var neuronGene_0 = (NEATNeuronGene) neuronsChromosome
                                                    .Get(GetElementPos(neuron1ID));
            if (neuronGene_0.SplitY > neuronGene_0.SplitY)
            {
                recurrent = true;
            }

            // is this a new innovation?
            if (innovation == null)
            {
                // new innovation
                ((NEATTraining) GA).Innovations
                    .CreateNewInnovation(neuron1ID, neuron2ID,
                                         NEATInnovationType.NewLink);

                long id2 = GA.Population.AssignInnovationID();

                var linkGene = new NEATLinkGene(neuron1ID,
                                                neuron2ID, true, id2, RangeRandomizer.Randomize(-1, 1),
                                                recurrent);
                linksChromosome.Add(linkGene);
            }
            else
            {
                // existing innovation
                var linkGene_1 = new NEATLinkGene(neuron1ID,
                                                  neuron2ID, true, innovation.InnovationID,
                                                  RangeRandomizer.Randomize(-1, 1), recurrent);
                linksChromosome.Add(linkGene_1);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Construct a genome by copying another.
        /// </summary>
        ///
        /// <param name="other">The other genome.</param>
        public NEATGenome(NEATGenome other)
        {
            neuronsChromosome = new Chromosome();
            linksChromosome = new Chromosome();
            GA = other.GA;

            Chromosomes.Add(neuronsChromosome);
            Chromosomes.Add(linksChromosome);

            GenomeID = other.GenomeID;
            networkDepth = other.networkDepth;
            Population = other.Population;
            Score = other.Score;
            AdjustedScore = other.AdjustedScore;
            AmountToSpawn = other.AmountToSpawn;
            inputCount = other.inputCount;
            outputCount = other.outputCount;
            speciesID = other.speciesID;


            // copy neurons
            foreach (IGene gene  in  other.Neurons.Genes)
            {
                var oldGene = (NEATNeuronGene) gene;
                var newGene = new NEATNeuronGene(
                    oldGene.NeuronType, oldGene.Id,
                    oldGene.SplitY, oldGene.SplitX,
                    oldGene.Recurrent, oldGene.ActivationResponse);
                Neurons.Add(newGene);
            }


            // copy links
            foreach (IGene gene_0  in  other.Links.Genes)
            {
                var oldGene_1 = (NEATLinkGene) gene_0;
                var newGene_2 = new NEATLinkGene(
                    oldGene_1.FromNeuronID, oldGene_1.ToNeuronID,
                    oldGene_1.Enabled, oldGene_1.InnovationId,
                    oldGene_1.Weight, oldGene_1.Recurrent);
                Links.Add(newGene_2);
            }
        }
Exemplo n.º 20
0
 public virtual object Read(Stream mask0)
 {
     IDictionary<ISpecies, int> dictionary2;
     IDictionary<int, IGenome> dictionary3;
     EncogFileSection section;
     IDictionary<string, string> dictionary4;
     int num;
     int num2;
     NEATPopulation population = new NEATPopulation();
     NEATInnovationList list = new NEATInnovationList {
         Population = population
     };
     population.Innovations = list;
     EncogReadHelper helper = new EncogReadHelper(mask0);
     IDictionary<int, ISpecies> dictionary = new Dictionary<int, ISpecies>();
     goto Label_0BD6;
     Label_0023:
     if ((section = helper.ReadNextSection()) != null)
     {
         if (!section.SectionName.Equals("NEAT-POPULATION"))
         {
             goto Label_085C;
         }
         if (section.SubSectionName.Equals("INNOVATIONS"))
         {
             using (IEnumerator<string> enumerator = section.Lines.GetEnumerator())
             {
                 string str;
                 IList<string> list2;
                 NEATInnovation innovation;
                 NEATInnovation innovation2;
                 goto Label_0A6C;
             Label_0A43:
                 innovation = innovation2;
                 if ((((uint) num2) - ((uint) num)) <= uint.MaxValue)
                 {
                 }
                 population.Innovations.Add(innovation);
             Label_0A6C:
                 if (enumerator.MoveNext())
                 {
                     goto Label_0B54;
                 }
                 goto Label_0AD7;
             Label_0A7A:
                 innovation2.SplitY = CSVFormat.EgFormat.Parse(list2[4]);
                 innovation2.NeuronID = int.Parse(list2[5]);
                 innovation2.FromNeuronID = int.Parse(list2[6]);
                 innovation2.ToNeuronID = int.Parse(list2[7]);
                 goto Label_0A43;
             Label_0AD7:
                 if ((((uint) num2) - ((uint) num)) >= 0)
                 {
                     goto Label_0023;
                 }
             Label_0AEF:
                 innovation2 = new NEATInnovation();
                 innovation2.InnovationID = int.Parse(list2[0]);
                 innovation2.InnovationType = StringToInnovationType(list2[1]);
                 innovation2.NeuronType = StringToNeuronType(list2[2]);
                 innovation2.SplitX = CSVFormat.EgFormat.Parse(list2[3]);
                 if (0 == 0)
                 {
                     goto Label_0A7A;
                 }
                 goto Label_0023;
             Label_0B54:
                 str = enumerator.Current;
                 do
                 {
                     list2 = EncogFileSection.SplitColumns(str);
                 }
                 while (0 != 0);
                 goto Label_0AEF;
             }
         }
         if (((uint) num) <= uint.MaxValue)
         {
             goto Label_085C;
         }
         goto Label_030B;
     }
     using (IEnumerator<IGenome> enumerator4 = population.Genomes.GetEnumerator())
     {
         IGenome genome3;
         NEATGenome genome4;
         ISpecies species3;
     Label_0040:
         if (enumerator4.MoveNext())
         {
             goto Label_00D6;
         }
         goto Label_0102;
     Label_0051:
         genome4.OutputCount = population.OutputCount;
         if ((((uint) num) - ((uint) num2)) >= 0)
         {
             goto Label_0040;
         }
     Label_007D:
         if (dictionary.ContainsKey(num))
         {
             goto Label_00BA;
         }
     Label_0087:
         genome4.InputCount = population.InputCount;
         goto Label_0051;
     Label_0096:
         num = (int) genome4.SpeciesID;
         if ((((uint) num2) + ((uint) num2)) <= uint.MaxValue)
         {
         }
         goto Label_007D;
     Label_00BA:
         species3 = dictionary[num];
         species3.Members.Add(genome4);
         goto Label_0087;
     Label_00D6:
         genome3 = enumerator4.Current;
         genome4 = (NEATGenome) genome3;
         goto Label_0096;
     }
     Label_0102:
     using (IEnumerator<ISpecies> enumerator5 = dictionary2.Keys.GetEnumerator())
     {
         ISpecies current;
         goto Label_011F;
     Label_0112:
         ((BasicSpecies) current).Population = population;
     Label_011F:
         if (enumerator5.MoveNext())
         {
             current = enumerator5.Current;
             num2 = dictionary2[current];
             do
             {
                 IGenome genome5 = dictionary3[num2];
                 current.Leader = genome5;
             }
             while (-1 == 0);
             goto Label_0112;
         }
         return population;
     }
     Label_016E:
     population.YoungScoreBonus = EncogFileSection.ParseDouble(dictionary4, "youngAgeBonus");
     population.GenomeIDGenerate.CurrentID = EncogFileSection.ParseInt(dictionary4, "nextGenomeID");
     population.InnovationIDGenerate.CurrentID = EncogFileSection.ParseInt(dictionary4, "nextInnovationID");
     population.GeneIDGenerate.CurrentID = EncogFileSection.ParseInt(dictionary4, "nextGeneID");
     population.SpeciesIDGenerate.CurrentID = EncogFileSection.ParseInt(dictionary4, "nextSpeciesID");
     goto Label_0023;
     Label_0201:
     population.SurvivalRate = EncogFileSection.ParseDouble(dictionary4, "survivalRate");
     if (0 != 0)
     {
         goto Label_03AA;
     }
     goto Label_02E9;
     Label_0242:
     population.OldAgePenalty = EncogFileSection.ParseDouble(dictionary4, "oldAgePenalty");
     population.OldAgeThreshold = EncogFileSection.ParseInt(dictionary4, "oldAgeThreshold");
     Label_0266:
     population.PopulationSize = EncogFileSection.ParseInt(dictionary4, "populationSize");
     if (((uint) num2) <= uint.MaxValue)
     {
         if ((((uint) num2) - ((uint) num2)) >= 0)
         {
             if ((((uint) num) + ((uint) num2)) > uint.MaxValue)
             {
                 goto Label_0242;
             }
             goto Label_0201;
         }
         goto Label_02E9;
     }
     Label_028A:
     population.OutputActivationFunction = EncogFileSection.ParseActivationFunction(dictionary4, "outAct");
     if ((((uint) num2) + ((uint) num2)) < 0)
     {
         goto Label_0BD6;
     }
     population.Snapshot = EncogFileSection.ParseBoolean(dictionary4, "snapshot");
     population.InputCount = EncogFileSection.ParseInt(dictionary4, "inputCount");
     population.OutputCount = EncogFileSection.ParseInt(dictionary4, "outputCount");
     goto Label_0242;
     Label_02E9:
     if ((((uint) num2) - ((uint) num)) >= 0)
     {
         population.YoungBonusAgeThreshhold = EncogFileSection.ParseInt(dictionary4, "youngAgeThreshold");
     }
     if (0xff != 0)
     {
         goto Label_016E;
     }
     Label_030B:
     population.NeatActivationFunction = EncogFileSection.ParseActivationFunction(dictionary4, "neatAct");
     goto Label_028A;
     Label_03AA:
     if (!section.SectionName.Equals("NEAT-POPULATION") || !section.SubSectionName.Equals("CONFIG"))
     {
         goto Label_0023;
     }
     if ((((uint) num2) + ((uint) num2)) <= uint.MaxValue)
     {
         if ((((uint) num2) + ((uint) num2)) <= uint.MaxValue)
         {
             dictionary4 = section.ParseParams();
         }
         goto Label_030B;
     }
     Label_0821:
     if (section.SectionName.Equals("NEAT-POPULATION"))
     {
         if (section.SubSectionName.Equals("GENOMES"))
         {
             NEATGenome genome = null;
             using (IEnumerator<string> enumerator3 = section.Lines.GetEnumerator())
             {
                 string str3;
                 IList<string> list3;
                 NEATGenome genome2;
                 NEATNeuronGene gene;
                 NEATNeuronGene gene2;
                 NEATLinkGene gene3;
                 goto Label_0402;
             Label_03DA:
                 genome.Links.Add(gene3);
                 goto Label_0402;
             Label_03EA:
                 if (list3[0].Equals("l", StringComparison.InvariantCultureIgnoreCase))
                 {
                     goto Label_04EA;
                 }
             Label_0402:
                 if (enumerator3.MoveNext())
                 {
                     goto Label_0770;
                 }
                 if ((((uint) num2) | 0x80000000) != 0)
                 {
                     goto Label_0023;
                 }
             Label_0429:
                 gene3.Enabled = int.Parse(list3[2]) > 0;
             Label_0440:
                 gene3.Recurrent = int.Parse(list3[3]) > 0;
                 gene3.FromNeuronID = int.Parse(list3[4]);
                 gene3.ToNeuronID = int.Parse(list3[5]);
                 gene3.Weight = CSVFormat.EgFormat.Parse(list3[6]);
                 gene3.InnovationId = int.Parse(list3[7]);
                 goto Label_03DA;
             Label_04B4:
                 if ((((uint) num) & 0) != 0)
                 {
                     goto Label_03DA;
                 }
                 gene3.Id = int.Parse(list3[1]);
                 goto Label_0429;
             Label_04EA:
                 gene3 = new NEATLinkGene();
                 goto Label_04B4;
             Label_04F6:
                 gene2.SplitY = CSVFormat.EgFormat.Parse(list3[7]);
             Label_050F:
                 gene = gene2;
                 genome.Neurons.Add(gene);
                 if ((((uint) num2) & 0) != 0)
                 {
                     goto Label_0782;
                 }
                 goto Label_0402;
             Label_053D:
                 gene2.Enabled = int.Parse(list3[3]) > 0;
                 gene2.InnovationId = int.Parse(list3[4]);
                 if (0xff == 0)
                 {
                     goto Label_050F;
                 }
                 gene2.ActivationResponse = CSVFormat.EgFormat.Parse(list3[5]);
                 gene2.SplitX = CSVFormat.EgFormat.Parse(list3[6]);
                 goto Label_04F6;
             Label_05A7:
                 gene2.Id = int.Parse(list3[1]);
                 gene2.NeuronType = StringToNeuronType(list3[2]);
                 goto Label_053D;
             Label_05DA:
                 if (!list3[0].Equals("n", StringComparison.InvariantCultureIgnoreCase))
                 {
                     goto Label_03EA;
                 }
                 if (3 == 0)
                 {
                     goto Label_0440;
                 }
                 gene2 = new NEATNeuronGene();
                 goto Label_07C8;
             Label_0608:
                 population.Add(genome);
                 dictionary3[(int) genome.GenomeID] = genome;
                 if (((uint) num) >= 0)
                 {
                     goto Label_0402;
                 }
                 goto Label_06B0;
             Label_0638:
                 genome.AmountToSpawn = CSVFormat.EgFormat.Parse(list3[4]);
                 genome.NetworkDepth = int.Parse(list3[5]);
                 if ((((uint) num2) | 0x80000000) == 0)
                 {
                     goto Label_07AD;
                 }
                 if (((uint) num2) < 0)
                 {
                     goto Label_0023;
                 }
                 genome.Score = CSVFormat.EgFormat.Parse(list3[6]);
                 goto Label_06F8;
             Label_06B0:
                 genome.GenomeID = int.Parse(list3[1]);
                 genome.SpeciesID = int.Parse(list3[2]);
                 genome.AdjustedScore = CSVFormat.EgFormat.Parse(list3[3]);
                 goto Label_0638;
             Label_06F8:
                 if (3 != 0)
                 {
                     goto Label_0608;
                 }
                 goto Label_0402;
             Label_0704:
                 genome.Chromosomes.Add(genome.LinksChromosome);
                 if ((((uint) num2) + ((uint) num2)) >= 0)
                 {
                     goto Label_06B0;
                 }
                 goto Label_0402;
             Label_0737:
                 if (8 == 0)
                 {
                     goto Label_050F;
                 }
                 genome = genome2;
                 genome.Chromosomes.Add(genome.NeuronsChromosome);
                 if ((((uint) num) - ((uint) num2)) <= uint.MaxValue)
                 {
                     goto Label_0704;
                 }
             Label_0770:
                 str3 = enumerator3.Current;
                 list3 = EncogFileSection.SplitColumns(str3);
             Label_0782:
                 if (!list3[0].Equals("g", StringComparison.InvariantCultureIgnoreCase))
                 {
                     goto Label_05DA;
                 }
                 genome2 = new NEATGenome {
                     NeuronsChromosome = new Chromosome()
                 };
             Label_07AD:
                 genome2.LinksChromosome = new Chromosome();
                 goto Label_0737;
             Label_07C8:
                 if ((((uint) num2) - ((uint) num)) <= uint.MaxValue)
                 {
                     goto Label_05A7;
                 }
                 if (0 == 0)
                 {
                     goto Label_04EA;
                 }
                 goto Label_04B4;
             }
         }
         if ((((uint) num2) < 0) || ((((uint) num2) - ((uint) num2)) > uint.MaxValue))
         {
             goto Label_030B;
         }
     }
     goto Label_03AA;
     Label_085C:
     if (section.SectionName.Equals("NEAT-POPULATION"))
     {
         if ((((uint) num) | 1) == 0)
         {
             goto Label_0266;
         }
         if (section.SubSectionName.Equals("SPECIES"))
         {
             if ((((uint) num) | 8) == 0)
             {
                 goto Label_0201;
             }
             using (IEnumerator<string> enumerator2 = section.Lines.GetEnumerator())
             {
                 string str2;
                 string[] strArray;
                 BasicSpecies species;
                 BasicSpecies species2;
                 goto Label_0913;
             Label_08CB:
                 species = species2;
                 species.SpawnsRequired = CSVFormat.EgFormat.Parse(strArray[5]);
                 dictionary2[species] = int.Parse(strArray[6]);
                 population.Species.Add(species);
                 dictionary[(int) species.SpeciesID] = species;
             Label_0913:
                 if (enumerator2.MoveNext())
                 {
                     goto Label_09D6;
                 }
                 goto Label_0023;
             Label_0924:
                 if ((((uint) num2) & 0) != 0)
                 {
                     goto Label_0969;
                 }
                 if (2 == 0)
                 {
                     goto Label_0924;
                 }
                 goto Label_09BE;
             Label_0941:
                 species2 = new BasicSpecies();
                 species2.SpeciesID = int.Parse(strArray[0]);
                 species2.Age = int.Parse(strArray[1]);
             Label_0969:
                 species2.BestScore = CSVFormat.EgFormat.Parse(strArray[2]);
                 species2.GensNoImprovement = int.Parse(strArray[3]);
                 species2.SpawnsRequired = CSVFormat.EgFormat.Parse(strArray[4]);
                 if ((((uint) num) + ((uint) num2)) >= 0)
                 {
                     goto Label_0924;
                 }
             Label_09BE:
                 if ((((uint) num2) + ((uint) num)) <= uint.MaxValue)
                 {
                     goto Label_09FD;
                 }
             Label_09D6:
                 str2 = enumerator2.Current;
                 strArray = str2.Split(new char[] { ',' });
                 goto Label_0941;
             Label_09FD:
                 if ((((uint) num) - ((uint) num)) <= uint.MaxValue)
                 {
                     goto Label_08CB;
                 }
                 goto Label_0023;
             }
         }
     }
     goto Label_0821;
     Label_0BD6:
     dictionary2 = new Dictionary<ISpecies, int>();
     dictionary3 = new Dictionary<int, IGenome>();
     goto Label_0023;
 }
        /// <summary>
        ///  Construct a genome by copying another. 
        /// </summary>
        /// <param name="other">The other genome.</param>
        public NEATGenome(NEATGenome other)
        {
            NetworkDepth = other.NetworkDepth;
            Population = other.Population;
            Score = other.Score;
            AdjustedScore = other.AdjustedScore;
            InputCount = other.InputCount;
            OutputCount = other.OutputCount;
            Species = other.Species;

            // copy neurons
            foreach (NEATNeuronGene oldGene in other.NeuronsChromosome)
            {
                var newGene = new NEATNeuronGene(oldGene);
                _neuronsList.Add(newGene);
            }

            // copy links
            foreach (var oldGene in other.LinksChromosome)
            {
                var newGene = new NEATLinkGene(
                        oldGene.FromNeuronId, oldGene.ToNeuronId,
                        oldGene.Enabled, oldGene.InnovationId,
                        oldGene.Weight);
                _linksList.Add(newGene);
            }
        }