상속: Encog.ML.Genetic.Genome.BasicGenome, ICloneable
예제 #1
0
        /// <inheritdoc/>
        public object Clone()
        {
            var result = new NEATGenome();

            result.Copy(this);
            return(result);
        }
        /// <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);
            }
        }
예제 #3
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);
            }
        }
예제 #4
0
파일: NEATGenome.cs 프로젝트: neismit/emds
 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;
 }
예제 #5
0
 public NEATPopulation(int inputCount, int outputCount, int populationSize)
     : base(populationSize)
 {
     int num;
     NEATGenome genome;
     this._neatActivationFunction = new ActivationSigmoid();
     this._outputActivationFunction = new ActivationLinear();
     this.InputCount = inputCount;
     goto Label_00D5;
     Label_0010:
     if (num >= populationSize)
     {
         NEATGenome genome2 = (NEATGenome) base.Genomes[0];
         base.Innovations = new NEATInnovationList(this, genome2.Links, genome2.Neurons);
         if ((((uint) outputCount) & 0) != 0)
         {
             goto Label_00D5;
         }
         if (((uint) num) <= uint.MaxValue)
         {
             return;
         }
         goto Label_009D;
     }
     Label_0086:
     genome = new NEATGenome(base.AssignGenomeID(), inputCount, outputCount);
     base.Add(genome);
     num++;
     goto Label_0010;
     Label_009D:
     throw new NeuralNetworkError("Population must have more than zero genomes.");
     Label_00D5:
     this.OutputCount = outputCount;
     if ((-2147483648 != 0) && (populationSize != 0))
     {
         num = 0;
         if ((((uint) num) - ((uint) populationSize)) <= uint.MaxValue)
         {
             goto Label_0010;
         }
         goto Label_0086;
     }
     goto Label_009D;
 }
예제 #6
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);
            }
        }
예제 #7
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);
            }
        }
예제 #8
0
        /// <summary>
        /// Perform one training iteration.
        /// </summary>
        public override void Iteration()
        {
            iteration++;
            IList<NEATGenome> newPop = new List<NEATGenome>();

            int numSpawnedSoFar = 0;

            foreach (ISpecies s in Population.Species)
            {
                if (numSpawnedSoFar < Population.Size())
                {
                    var numToSpawn = (int) Math.Round(s.NumToSpawn);

                    bool bChosenBestYet = false;

                    while ((numToSpawn--) > 0)
                    {
                        NEATGenome baby = null;

                        if (!bChosenBestYet)
                        {
                            baby = (NEATGenome) s.Leader;

                            bChosenBestYet = true;
                        }

                        else
                        {
                            // if the number of individuals in this species is only
                            // one
                            // then we can only perform mutation
                            if (s.Members.Count == 1)
                            {
                                // spawn a child
                                baby = new NEATGenome((NEATGenome) s.ChooseParent());
                            }
                            else
                            {
                                var g1 = (NEATGenome) s.ChooseParent();

                                if (ThreadSafeRandom.NextDouble() < paramCrossoverRate)
                                {
                                    var g2 = (NEATGenome) s.ChooseParent();

                                    int numAttempts = 5;

                                    while ((g1.GenomeID == g2.GenomeID)
                                           && ((numAttempts--) > 0))
                                    {
                                        g2 = (NEATGenome) s.ChooseParent();
                                    }

                                    if (g1.GenomeID != g2.GenomeID)
                                    {
                                        baby = Crossover(g1, g2);
                                    }
                                }

                                else
                                {
                                    baby = new NEATGenome(g1);
                                }
                            }

                            if (baby != null)
                            {
                                baby.GenomeID = Population.AssignGenomeID();

                                if (baby.Neurons.Size() < paramMaxPermittedNeurons)
                                {
                                    baby.AddNeuron(paramChanceAddNode,
                                                   paramNumTrysToFindOldLink);
                                }

                                // now there's the chance a link may be added
                                baby.AddLink(paramChanceAddLink,
                                             paramChanceAddRecurrentLink,
                                             paramNumTrysToFindLoopedLink,
                                             paramNumAddLinkAttempts);

                                // mutate the weights
                                baby.MutateWeights(paramMutationRate,
                                                   paramProbabilityWeightReplaced,
                                                   paramMaxWeightPerturbation);

                                baby.MutateActivationResponse(
                                    paramActivationMutationRate,
                                    paramMaxActivationPerturbation);
                            }
                        }

                        if (baby != null)
                        {
                            // sort the baby's genes by their innovation numbers
                            baby.SortGenes();

                            // add to new pop
                            // if (newPop.contains(baby)) {
                            // throw new EncogError("readd");
                            // }
                            newPop.Add(baby);

                            ++numSpawnedSoFar;

                            if (numSpawnedSoFar == Population.Size())
                            {
                                numToSpawn = 0;
                            }
                        }
                    }
                }
            }

            while (newPop.Count < Population.Size())
            {
                newPop.Add(TournamentSelection(Population.Size()/5));
            }

            Population.Clear();
            foreach (NEATGenome genome in newPop)
            {
                Population.Add(genome);
            }

            ResetAndKill();
            SortAndRecord();
            SpeciateAndCalculateSpawnLevels();
        }
예제 #9
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;
        }
        /// <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;
        }
예제 #11
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;
        }
예제 #12
0
        /// <summary>
        /// Construct a starting NEAT population.
        /// </summary>
        ///
        /// <param name="inputCount">The input neuron count.</param>
        /// <param name="outputCount">The output neuron count.</param>
        /// <param name="populationSize">The population size.</param>
        public NEATPopulation(int inputCount, int outputCount,
                              int populationSize)
            : base(populationSize)
        {
            _neatActivationFunction = new ActivationSigmoid();
            _outputActivationFunction = new ActivationLinear();
            InputCount = inputCount;
            OutputCount = outputCount;

            if (populationSize == 0)
            {
                throw new NeuralNetworkError(
                    "Population must have more than zero genomes.");
            }

            // create the initial population
            for (int i = 0; i < populationSize; i++)
            {
                var genome = new NEATGenome(AssignGenomeID(), inputCount,
                                            outputCount);
                Add(genome);
            }

            // create initial innovations
            var genome2 = (NEATGenome) Genomes[0];
            Innovations = new NEATInnovationList(this, genome2.Links,
                                                 genome2.Neurons);
        }
예제 #13
0
        /// <summary>
        /// Perform one training iteration.
        /// </summary>
        public override void Iteration()
        {
            iteration++;
            IList <NEATGenome> newPop = new List <NEATGenome>();

            int numSpawnedSoFar = 0;

            foreach (ISpecies s in Population.Species)
            {
                if (numSpawnedSoFar < Population.Size())
                {
                    var numToSpawn = (int)Math.Round(s.NumToSpawn);

                    bool bChosenBestYet = false;

                    while ((numToSpawn--) > 0)
                    {
                        NEATGenome baby = null;

                        if (!bChosenBestYet)
                        {
                            baby = (NEATGenome)s.Leader;

                            bChosenBestYet = true;
                        }

                        else
                        {
                            // if the number of individuals in this species is only
                            // one
                            // then we can only perform mutation
                            if (s.Members.Count == 1)
                            {
                                // spawn a child
                                baby = new NEATGenome((NEATGenome)s.ChooseParent());
                            }
                            else
                            {
                                var g1 = (NEATGenome)s.ChooseParent();

                                if (ThreadSafeRandom.NextDouble() < paramCrossoverRate)
                                {
                                    var g2 = (NEATGenome)s.ChooseParent();

                                    int numAttempts = 5;

                                    while ((g1.GenomeID == g2.GenomeID) &&
                                           ((numAttempts--) > 0))
                                    {
                                        g2 = (NEATGenome)s.ChooseParent();
                                    }

                                    if (g1.GenomeID != g2.GenomeID)
                                    {
                                        baby = Crossover(g1, g2);
                                    }
                                }

                                else
                                {
                                    baby = new NEATGenome(g1);
                                }
                            }

                            if (baby != null)
                            {
                                baby.GenomeID = Population.AssignGenomeID();

                                if (baby.Neurons.Size() < paramMaxPermittedNeurons)
                                {
                                    baby.AddNeuron(paramChanceAddNode,
                                                   paramNumTrysToFindOldLink);
                                }

                                // now there's the chance a link may be added
                                baby.AddLink(paramChanceAddLink,
                                             paramChanceAddRecurrentLink,
                                             paramNumTrysToFindLoopedLink,
                                             paramNumAddLinkAttempts);

                                // mutate the weights
                                baby.MutateWeights(paramMutationRate,
                                                   paramProbabilityWeightReplaced,
                                                   paramMaxWeightPerturbation);

                                baby.MutateActivationResponse(
                                    paramActivationMutationRate,
                                    paramMaxActivationPerturbation);
                            }
                        }

                        if (baby != null)
                        {
                            // sort the baby's genes by their innovation numbers
                            baby.SortGenes();

                            // add to new pop
                            // if (newPop.contains(baby)) {
                            // throw new EncogError("readd");
                            // }
                            newPop.Add(baby);

                            ++numSpawnedSoFar;

                            if (numSpawnedSoFar == Population.Size())
                            {
                                numToSpawn = 0;
                            }
                        }
                    }
                }
            }

            while (newPop.Count < Population.Size())
            {
                newPop.Add(TournamentSelection(Population.Size() / 5));
            }

            Population.Clear();
            foreach (NEATGenome genome in newPop)
            {
                Population.Add(genome);
            }

            ResetAndKill();
            SortAndRecord();
            SpeciateAndCalculateSpawnLevels();
        }
예제 #14
0
        /// <summary>
        /// Get the compatibility score with another genome. Used to determine
        /// species.
        /// </summary>
        ///
        /// <param name="genome">The other genome.</param>
        /// <returns>The score.</returns>
        public double GetCompatibilityScore(NEATGenome genome)
        {
            double numDisjoint      = 0;
            double numExcess        = 0;
            double numMatched       = 0;
            double weightDifference = 0;

            int g1 = 0;
            int g2 = 0;

            while ((g1 < linksChromosome.Size() - 1) ||
                   (g2 < linksChromosome.Size() - 1))
            {
                if (g1 == linksChromosome.Size() - 1)
                {
                    g2++;
                    numExcess++;

                    continue;
                }

                if (g2 == genome.Links.Size() - 1)
                {
                    g1++;
                    numExcess++;

                    continue;
                }

                // get innovation numbers for each gene at this point
                long id1 = ((NEATLinkGene)linksChromosome.Get(g1)).InnovationId;
                long id2 = ((NEATLinkGene)genome.Links.Get(g2)).InnovationId;

                // innovation numbers are identical so increase the matched score
                if (id1 == id2)
                {
                    g1++;
                    g2++;
                    numMatched++;

                    // get the weight difference between these two genes
                    weightDifference += Math.Abs(((NEATLinkGene)linksChromosome.Get(g1)).Weight
                                                 - ((NEATLinkGene)genome.Links.Get(g2)).Weight);
                }

                // innovation numbers are different so increment the disjoint score
                if (id1 < id2)
                {
                    numDisjoint++;
                    g1++;
                }

                if (id1 > id2)
                {
                    ++numDisjoint;
                    ++g2;
                }
            }

            int longest = genome.NumGenes;

            if (NumGenes > longest)
            {
                longest = NumGenes;
            }

            double score = (TWEAK_EXCESS * numExcess / longest)
                           + (TWEAK_DISJOINT * numDisjoint / longest)
                           + (TWEAK_MATCHED * weightDifference / numMatched);

            return(score);
        }
예제 #15
0
파일: NEATGenome.cs 프로젝트: neismit/emds
 public double GetCompatibilityScore(NEATGenome genome)
 {
     double num2;
     double num3;
     double num4;
     int num5;
     int num6;
     long num7;
     long innovationId;
     int numGenes;
     double num10;
     double num = 0.0;
     goto Label_02B8;
     Label_001B:
     return ((((1.0 * num2) / ((double) numGenes)) + ((1.0 * num) / ((double) numGenes))) + ((0.4 * num4) / num3));
     Label_005C:
     if (num7 > innovationId)
     {
         num++;
         goto Label_00BD;
     }
     Label_0062:
     if ((num5 < (this.linksChromosome.Size() - 1)) || (num6 < (this.linksChromosome.Size() - 1)))
     {
         goto Label_0257;
     }
     numGenes = genome.NumGenes;
     if ((((uint) num5) + ((uint) numGenes)) <= uint.MaxValue)
     {
         if (this.NumGenes > numGenes)
         {
             numGenes = this.NumGenes;
         }
         goto Label_001B;
     }
     Label_00BD:
     num6++;
     goto Label_0062;
     Label_00C5:
     num5++;
     if ((((uint) num10) + ((uint) num7)) < 0)
     {
         goto Label_01D0;
     }
     goto Label_005C;
     Label_00EB:
     if (num7 < innovationId)
     {
         num++;
         goto Label_00C5;
     }
     goto Label_005C;
     Label_01D0:
     num7 = ((NEATLinkGene) this.linksChromosome.Get(num5)).InnovationId;
     innovationId = ((NEATLinkGene) genome.Links.Get(num6)).InnovationId;
     if (num7 != innovationId)
     {
         goto Label_00EB;
     }
     if ((((uint) num4) - ((uint) num2)) <= uint.MaxValue)
     {
         if ((((uint) num6) | 2) != 0)
         {
             num5++;
             if ((((uint) num10) + ((uint) innovationId)) > uint.MaxValue)
             {
                 return num10;
             }
             if ((((uint) num2) | 15) != 0)
             {
                 num6++;
                 if (0 != 0)
                 {
                     goto Label_001B;
                 }
                 num3++;
                 if ((((uint) num6) - ((uint) num)) <= uint.MaxValue)
                 {
                     num4 += Math.Abs((double) (((NEATLinkGene) this.linksChromosome.Get(num5)).Weight - ((NEATLinkGene) genome.Links.Get(num6)).Weight));
                     goto Label_00EB;
                 }
                 goto Label_00C5;
             }
         }
         else
         {
             goto Label_02B8;
         }
     }
     Label_0257:
     while (num5 == (this.linksChromosome.Size() - 1))
     {
         num6++;
         num2++;
         goto Label_0062;
     }
     if (num6 == (genome.Links.Size() - 1))
     {
         num5++;
         num2++;
         goto Label_0062;
     }
     goto Label_01D0;
     Label_02B8:
     num2 = 0.0;
     num3 = 0.0;
     num4 = 0.0;
     num5 = 0;
     num6 = 0;
     if ((((uint) innovationId) - ((uint) num3)) > uint.MaxValue)
     {
         goto Label_01D0;
     }
     goto Label_0062;
 }
예제 #16
0
        /// <summary>
        /// Get the compatibility score with another genome. Used to determine
        /// species.
        /// </summary>
        ///
        /// <param name="genome">The other genome.</param>
        /// <returns>The score.</returns>
        public double GetCompatibilityScore(NEATGenome genome)
        {
            double numDisjoint = 0;
            double numExcess = 0;
            double numMatched = 0;
            double weightDifference = 0;

            int g1 = 0;
            int g2 = 0;

            while ((g1 < linksChromosome.Size() - 1)
                   || (g2 < linksChromosome.Size() - 1))
            {
                if (g1 == linksChromosome.Size() - 1)
                {
                    g2++;
                    numExcess++;

                    continue;
                }

                if (g2 == genome.Links.Size() - 1)
                {
                    g1++;
                    numExcess++;

                    continue;
                }

                // get innovation numbers for each gene at this point
                long id1 = ((NEATLinkGene) linksChromosome.Get(g1)).InnovationId;
                long id2 = ((NEATLinkGene) genome.Links.Get(g2)).InnovationId;

                // innovation numbers are identical so increase the matched score
                if (id1 == id2)
                {
                    g1++;
                    g2++;
                    numMatched++;

                    // get the weight difference between these two genes
                    weightDifference += Math.Abs(((NEATLinkGene) linksChromosome.Get(g1)).Weight
                                                 - ((NEATLinkGene) genome.Links.Get(g2)).Weight);
                }

                // innovation numbers are different so increment the disjoint score
                if (id1 < id2)
                {
                    numDisjoint++;
                    g1++;
                }

                if (id1 > id2)
                {
                    ++numDisjoint;
                    ++g2;
                }
            }

            int longest = genome.NumGenes;

            if (NumGenes > longest)
            {
                longest = NumGenes;
            }

            double score = (TWEAK_EXCESS*numExcess/longest)
                           + (TWEAK_DISJOINT*numDisjoint/longest)
                           + (TWEAK_MATCHED*weightDifference/numMatched);

            return score;
        }
예제 #17
0
 public override void Iteration()
 {
     IList<NEATGenome> list;
     int num;
     int num2;
     bool flag;
     int num3;
     this.x47b4ed2c32cb276e++;
     goto Label_00D0;
     Label_0024:
     if (list.Count < base.Population.Size())
     {
         goto Label_04AD;
     }
     if ((((uint) num2) | 1) != 0)
     {
         base.Population.Clear();
     }
     foreach (NEATGenome genome4 in list)
     {
         base.Population.Add(genome4);
     }
     this.ResetAndKill();
     if ((((uint) num) - ((uint) flag)) <= uint.MaxValue)
     {
         this.SortAndRecord();
         this.SpeciateAndCalculateSpawnLevels();
     }
     if ((((uint) num2) - ((uint) num3)) >= 0)
     {
         return;
     }
     Label_00D0:
     list = new List<NEATGenome>();
     num = 0;
     using (IEnumerator<ISpecies> enumerator = base.Population.Species.GetEnumerator())
     {
         ISpecies species;
         NEATGenome genome;
         NEATGenome genome2;
         NEATGenome genome3;
         goto Label_00FD;
     Label_00EC:
         if (num < base.Population.Size())
         {
             goto Label_0485;
         }
     Label_00FD:
         if (enumerator.MoveNext())
         {
             goto Label_0468;
         }
         goto Label_040A;
     Label_010D:
         if (num == base.Population.Size())
         {
             goto Label_0144;
         }
     Label_011B:
         if (num2-- > 0)
         {
             goto Label_0441;
         }
         goto Label_00FD;
     Label_012C:
         if (genome != null)
         {
             goto Label_0182;
         }
         if (((uint) num) >= 0)
         {
             goto Label_011B;
         }
         goto Label_040A;
     Label_0144:
         num2 = 0;
         goto Label_011B;
     Label_014D:
         if (0 == 0)
         {
             goto Label_010D;
         }
         goto Label_01FA;
     Label_0152:
         if (0x7fffffff == 0)
         {
             goto Label_03D9;
         }
         if ((((uint) num2) & 0) != 0)
         {
             goto Label_0266;
         }
         num++;
         goto Label_014D;
     Label_0179:
         if (genome != null)
         {
             goto Label_0246;
         }
         goto Label_012C;
     Label_0182:
         genome.SortGenes();
         list.Add(genome);
         goto Label_0152;
     Label_0197:
         genome.AddNeuron(this.xe6c7b0462e12d2ff, this.x340c2bbd00cd3fa4);
     Label_01AA:
         genome.AddLink(this.x67e8029e782709f0, this.xd3f94467320a5684, this.xe44426390f1f3741, this.xd7944ba63721a56b);
         genome.MutateWeights(this.x68e0847485ce0c21, this.xe5ff50155887c0e7, this.x7a6edccccc229234);
         genome.MutateActivationResponse(this.xd9d3bb742c7a307b, this.xf52a69d338e65c0f);
         goto Label_012C;
     Label_01FA:
         if ((((uint) num3) - ((uint) num2)) >= 0)
         {
             goto Label_0144;
         }
     Label_0212:
         if (genome.Neurons.Size() >= this.x214332e2bd2e8ae1)
         {
             goto Label_01AA;
         }
         goto Label_0197;
     Label_0231:
         if (genome2.GenomeID != genome3.GenomeID)
         {
             goto Label_0266;
         }
         goto Label_0179;
     Label_0246:
         genome.GenomeID = base.Population.AssignGenomeID();
         goto Label_0212;
     Label_0266:
         genome = this.Crossover(genome2, genome3);
         goto Label_0179;
     Label_0277:
         genome = new NEATGenome(genome2);
         goto Label_0179;
     Label_0285:
         if ((((uint) flag) + ((uint) num)) < 0)
         {
             goto Label_0492;
         }
     Label_02A0:
         if (genome2.GenomeID == genome3.GenomeID)
         {
             goto Label_0334;
         }
         if (((uint) num) >= 0)
         {
             goto Label_0231;
         }
         if ((((uint) num) + ((uint) num)) > uint.MaxValue)
         {
             goto Label_0197;
         }
         if ((((uint) num3) | 0xfffffffe) == 0)
         {
             goto Label_02A0;
         }
     Label_02FE:
         if ((((uint) flag) & 0) != 0)
         {
             goto Label_02A0;
         }
         if ((((uint) flag) + ((uint) flag)) >= 0)
         {
             goto Label_0231;
         }
         goto Label_03F5;
     Label_0334:
         if (num3-- <= 0)
         {
             goto Label_02FE;
         }
         genome3 = (NEATGenome) species.ChooseParent();
         if ((((uint) num) - ((uint) num2)) >= 0)
         {
             goto Label_03AA;
         }
     Label_036A:
         if (species.Members.Count == 1)
         {
             goto Label_03D9;
         }
         genome2 = (NEATGenome) species.ChooseParent();
         if (ThreadSafeRandom.NextDouble() >= this.xa4a074c49c97739c)
         {
             goto Label_0277;
         }
         genome3 = (NEATGenome) species.ChooseParent();
         num3 = 5;
         goto Label_02A0;
     Label_03AA:
         if ((((uint) num) - ((uint) flag)) >= 0)
         {
             goto Label_02A0;
         }
     Label_03C4:
         genome = (NEATGenome) species.Leader;
         flag = true;
         goto Label_012C;
     Label_03D9:
         genome = new NEATGenome((NEATGenome) species.ChooseParent());
         goto Label_0179;
     Label_03F5:
         if (((uint) num) >= 0)
         {
             goto Label_0231;
         }
     Label_040A:
         if (((uint) num) >= 0)
         {
             goto Label_0024;
         }
         goto Label_044D;
     Label_0421:
         if ((((uint) num) - ((uint) flag)) > uint.MaxValue)
         {
             goto Label_0144;
         }
         goto Label_011B;
     Label_0441:
         genome = null;
         if (flag)
         {
             goto Label_036A;
         }
         goto Label_03C4;
     Label_044D:
         if ((((uint) num3) - ((uint) flag)) > uint.MaxValue)
         {
             goto Label_0285;
         }
     Label_0468:
         species = enumerator.Current;
         if (((uint) num2) >= 0)
         {
             goto Label_00EC;
         }
     Label_0485:
         num2 = (int) Math.Round(species.NumToSpawn);
     Label_0492:
         flag = false;
         goto Label_0421;
     }
     Label_04AD:
     list.Add(this.TournamentSelection(base.Population.Size() / 5));
     goto Label_0024;
 }
예제 #18
0
 public NEATGenome Crossover(NEATGenome mom, NEATGenome dad)
 {
     x47361738465134f2 xf;
     Chromosome chromosome;
     Chromosome chromosome2;
     List<long> list;
     int num;
     int num2;
     NEATLinkGene gene;
     NEATLinkGene gene2;
     NEATLinkGene gene3;
     int num3;
     NEATGenome genome;
     if (mom.Score != dad.Score)
     {
         while (base.Comparator.IsBetterThan(mom.Score, dad.Score))
         {
             xf = x47361738465134f2.x431cb293a9d996e8;
             if (((uint) num3) >= 0)
             {
                 if ((((uint) num3) & 0) == 0)
                 {
                     goto Label_03BA;
                 }
                 goto Label_0399;
             }
             if ((((uint) num) & 0) == 0)
             {
                 goto Label_0478;
             }
         }
         xf = x47361738465134f2.x86f3d3d96a9a0f93;
         goto Label_03BA;
     }
     goto Label_0478;
     Label_002E:
     genome = new NEATGenome(base.Population.AssignGenomeID(), chromosome, chromosome2, mom.InputCount, mom.OutputCount);
     genome.GA = this;
     if (15 != 0)
     {
         if (0 != 0)
         {
             goto Label_031C;
         }
         genome.Population = base.Population;
         if ((((uint) num3) & 0) == 0)
         {
             return genome;
         }
         goto Label_02C3;
     }
     goto Label_00B2;
     Label_0071:
     num3++;
     Label_0077:
     if (num3 < list.Count)
     {
         chromosome.Add(this.Innovations.CreateNeuronFromID(list[num3]));
         goto Label_0071;
     }
     goto Label_002E;
     Label_00B2:
     this.AddNeuronID((long) gene3.FromNeuronID, list);
     this.AddNeuronID((long) gene3.ToNeuronID, list);
     Label_00D0:
     if ((num < mom.NumGenes) || (num2 < dad.NumGenes))
     {
         if (num >= mom.NumGenes)
         {
             gene = null;
         }
         else
         {
             gene = (NEATLinkGene) mom.Links.Get(num);
         }
         goto Label_034F;
     }
     list.Sort();
     num3 = 0;
     if ((((uint) num2) + ((uint) num)) > uint.MaxValue)
     {
         goto Label_0071;
     }
     if (0 != 0)
     {
         goto Label_034F;
     }
     goto Label_0077;
     Label_0160:
     chromosome2.Add(gene3);
     goto Label_00B2;
     Label_016D:
     if (chromosome2.Size() == 0)
     {
         goto Label_0160;
     }
     if ((0 != 0) || (((NEATLinkGene) chromosome2.Get(chromosome2.Size() - 1)).InnovationId != gene3.InnovationId))
     {
         chromosome2.Add(gene3);
     }
     goto Label_00B2;
     Label_01C8:
     num++;
     if (((uint) num) <= uint.MaxValue)
     {
         if (((uint) num3) > uint.MaxValue)
         {
             goto Label_002E;
         }
         if ((((uint) num2) | 4) == 0)
         {
             goto Label_025D;
         }
         num2++;
         goto Label_016D;
     }
     Label_01E0:
     if ((((uint) num2) | 2) != 0)
     {
         if ((((uint) num3) + ((uint) num3)) <= uint.MaxValue)
         {
             goto Label_016D;
         }
         goto Label_0160;
     }
     if (-2147483648 != 0)
     {
         goto Label_0234;
     }
     if ((((uint) num) + ((uint) num3)) < 0)
     {
         goto Label_024D;
     }
     Label_0222:
     while (ThreadSafeRandom.NextDouble() < 0.5)
     {
         gene3 = gene;
         goto Label_01C8;
     }
     gene3 = gene2;
     goto Label_01C8;
     Label_0234:
     gene3 = gene2;
     Label_0238:
     num2++;
     goto Label_016D;
     Label_024D:
     if (gene.InnovationId < gene2.InnovationId)
     {
         if (xf == x47361738465134f2.x431cb293a9d996e8)
         {
             gene3 = gene;
         }
         num++;
         goto Label_016D;
     }
     Label_025D:
     if (gene2.InnovationId >= gene.InnovationId)
     {
         if (gene2.InnovationId == gene.InnovationId)
         {
             goto Label_0222;
         }
         goto Label_01E0;
     }
     if ((((uint) num2) + ((uint) num)) > uint.MaxValue)
     {
         goto Label_024D;
     }
     if (xf != x47361738465134f2.x86f3d3d96a9a0f93)
     {
         goto Label_0238;
     }
     goto Label_0234;
     Label_02C3:
     if (gene2 == null)
     {
         if (gene != null)
         {
             if (xf == x47361738465134f2.x431cb293a9d996e8)
             {
                 gene3 = gene;
                 if ((((uint) num2) + ((uint) num)) > uint.MaxValue)
                 {
                     goto Label_03BA;
                 }
             }
             num++;
             goto Label_016D;
         }
         if ((((uint) num3) | 0xfffffffe) != 0)
         {
         }
     }
     goto Label_024D;
     Label_031C:
     if (gene2 == null)
     {
         goto Label_02C3;
     }
     if (xf == x47361738465134f2.x86f3d3d96a9a0f93)
     {
         if (1 == 0)
         {
             goto Label_01C8;
         }
         gene3 = gene2;
     }
     num2++;
     goto Label_016D;
     Label_034F:
     if (num2 < dad.NumGenes)
     {
         gene2 = (NEATLinkGene) dad.Links.Get(num2);
     }
     else
     {
         gene2 = null;
     }
     if (gene != null)
     {
         goto Label_02C3;
     }
     goto Label_031C;
     Label_0399:
     if ((((uint) num) & 0) != 0)
     {
         goto Label_00B2;
     }
     gene3 = null;
     goto Label_00D0;
     Label_03BA:
     chromosome = new Chromosome();
     chromosome2 = new Chromosome();
     list = new List<long>();
     num = 0;
     num2 = 0;
     if (0 == 0)
     {
         goto Label_0399;
     }
     Label_0478:
     if (mom.NumGenes != dad.NumGenes)
     {
         if (mom.NumGenes < dad.NumGenes)
         {
             xf = x47361738465134f2.x431cb293a9d996e8;
         }
         else
         {
             xf = x47361738465134f2.x86f3d3d96a9a0f93;
         }
     }
     else if (((((uint) num) - ((uint) num3)) >= 0) && (ThreadSafeRandom.NextDouble() <= 0.0))
     {
         if ((((uint) num3) + ((uint) num2)) <= uint.MaxValue)
         {
             xf = x47361738465134f2.x86f3d3d96a9a0f93;
         }
     }
     else
     {
         xf = x47361738465134f2.x431cb293a9d996e8;
     }
     goto Label_03BA;
 }
예제 #19
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;
 }
예제 #20
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);
        }
 /// <inheritdoc/>
 public object Clone()
 {
     var result = new NEATGenome();
     result.Copy(this);
     return result;
 }