コード例 #1
0
        /// <summary>
        /// Find the best neuron, between two parents by the specified neuron id.
        /// </summary>
        /// <param name="nodeId">The neuron id.</param>
        /// <param name="best">The best genome.</param>
        /// <param name="notBest">The non-best (second best) genome. Also the worst, since this
        /// is the 2nd best of 2.</param>
        /// <returns>The best neuron genome by id.</returns>
        private NEATNeuronGene FindBestNeuron(long nodeId,
                                              NEATGenome best, NEATGenome notBest)
        {
            NEATNeuronGene result = best.FindNeuron(nodeId) ?? notBest.FindNeuron(nodeId);

            return(result);
        }
コード例 #2
0
        /// <summary>
        /// Determines if a neuron is still needed. If all links to/from a neuron
        /// have been removed, then the neuron is no longer needed.
        /// </summary>
        /// <param name="target">The target genome.</param>
        /// <param name="neuronID">The neuron id to check for.</param>
        /// <returns>Returns true, if the neuron is still needed.</returns>
        public bool IsNeuronNeeded(NEATGenome target, long neuronID)
        {
            // do not remove bias or input neurons or output
            foreach (NEATNeuronGene gene in target.NeuronsChromosome)
            {
                if (gene.Id == neuronID)
                {
                    NEATNeuronGene neuron = gene;
                    if ((neuron.NeuronType == NEATNeuronType.Input) ||
                        (neuron.NeuronType == NEATNeuronType.Bias) ||
                        (neuron.NeuronType == NEATNeuronType.Output))
                    {
                        return(true);
                    }
                }
            }

            // Now check to see if the neuron is used in any links
            foreach (NEATLinkGene gene in target.LinksChromosome)
            {
                NEATLinkGene linkGene = gene;
                if (linkGene.FromNeuronId == neuronID)
                {
                    return(true);
                }
                if (linkGene.ToNeuronId == neuronID)
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #3
0
        /// <inheritdoc/>
        public override void PerformOperation(EncogRandom rnd, IGenome[] parents, int parentIndex,
                                              IGenome[] offspring, int offspringIndex)
        {
            int countTrysToAddLink = Owner.MaxTries;

            NEATGenome target = ObtainGenome(parents, parentIndex, offspring,
                                             offspringIndex);

            // the link will be between these two neurons
            long neuron1Id = -1;
            long neuron2Id = -1;

            // try to add a link
            while ((countTrysToAddLink--) > 0)
            {
                NEATNeuronGene neuron1 = ChooseRandomNeuron(target, true);
                NEATNeuronGene neuron2 = ChooseRandomNeuron(target, false);

                if (neuron1 == null || neuron2 == null)
                {
                    return;
                }

                // do not duplicate
                // do not go to a bias neuron
                // do not go from an output neuron
                // do not go to an input neuron
                if (!IsDuplicateLink(target, neuron1.Id, neuron2.Id) &&
                    (neuron2.NeuronType != NEATNeuronType.Bias) &&
                    (neuron2.NeuronType != NEATNeuronType.Input))
                {
                    if (((NEATPopulation)Owner.Population).ActivationCycles != 1 ||
                        neuron1.NeuronType != NEATNeuronType.Output)
                    {
                        neuron1Id = neuron1.Id;
                        neuron2Id = neuron2.Id;
                        break;
                    }
                }
            }

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

            double r = ((NEATPopulation)target.Population).WeightRange;

            CreateLink(target, neuron1Id, neuron2Id,
                       RangeRandomizer.Randomize(rnd, -r, r));
            target.SortGenes();
        }
コード例 #4
0
        /// <summary>
        /// Get the specified neuron's index.
        /// </summary>
        /// <param name="target">The neuron id to check for.</param>
        /// <param name="neuronId">The neuron id.</param>
        /// <returns>The index.</returns>
        public int GetElementPos(NEATGenome target, long neuronId)
        {
            for (int i = 0; i < target.NeuronsChromosome.Count; i++)
            {
                NEATNeuronGene neuronGene = target.NeuronsChromosome[i];
                if (neuronGene.Id == neuronId)
                {
                    return(i);
                }
            }

            return(-1);
        }
コード例 #5
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;
 }
コード例 #6
0
        /// <inheritdoc/>
        public IMLMethod Decode(IGenome genome)
        {
            var neatGenome = (NEATGenome)genome;
            var pop        = (NEATPopulation)neatGenome.Population;
            IList <NEATNeuronGene> neuronsChromosome = neatGenome.NeuronsChromosome;
            IList <NEATLinkGene>   linksChromosome   = neatGenome.LinksChromosome;

            if (neuronsChromosome[0].NeuronType != NEATNeuronType.Bias)
            {
                throw new NeuralNetworkError(
                          "The first neuron must be the bias neuron, this genome is invalid.");
            }

            var links = new List <NEATLink>();
            var afs   = new IActivationFunction[neuronsChromosome.Count];

            for (int i = 0; i < afs.Length; i++)
            {
                afs[i] = neuronsChromosome[i].ActivationFunction;
            }

            IDictionary <long, int> lookup = new Dictionary <long, int>();

            for (int i = 0; i < neuronsChromosome.Count; i++)
            {
                NEATNeuronGene neuronGene = neuronsChromosome[i];
                lookup[neuronGene.Id] = i;
            }

            // loop over connections
            for (int i = 0; i < linksChromosome.Count; i++)
            {
                NEATLinkGene linkGene = linksChromosome[i];
                if (linkGene.Enabled)
                {
                    links.Add(new NEATLink(lookup[linkGene.FromNeuronId],
                                           lookup[linkGene.ToNeuronId], linkGene.Weight));
                }
            }

            links.Sort();

            NEATNetwork network = new NEATNetwork(neatGenome.InputCount,
                                                  neatGenome.OutputCount, links, afs);

            network.ActivationCycles = pop.ActivationCycles;
            return(network);
        }
コード例 #7
0
ファイル: NEATInnovation.cs プロジェクト: neismit/emds
 public NEATInnovation(NEATNeuronGene neuronGene, long innovationID, long neuronID_0)
 {
     if (8 != 0)
     {
         this.neuronID = neuronID_0;
         base.InnovationID = innovationID;
         this.splitX = neuronGene.SplitX;
         if (0xff == 0)
         {
             return;
         }
         this.splitY = neuronGene.SplitY;
         this.neuronType = neuronGene.NeuronType;
         this.innovationType = NEATInnovationType.NewNeuron;
     }
     this.fromNeuronID = -1L;
     this.toNeuronID = -1L;
 }
コード例 #8
0
        /// <summary>
        /// Choose a random neuron.
        /// </summary>
        /// <param name="target">The target genome. Should the input and bias neurons be
        /// included.</param>
        /// <param name="choosingFrom">True if we are chosing from all neurons, false if we exclude
        /// the input and bias.</param>
        /// <returns>The random neuron.</returns>
        public NEATNeuronGene ChooseRandomNeuron(NEATGenome target,
                                                 bool choosingFrom)
        {
            int start;

            if (choosingFrom)
            {
                start = 0;
            }
            else
            {
                start = target.InputCount + 1;
            }

            // if this network will not "cycle" then output neurons cannot be source
            // neurons
            if (!choosingFrom)
            {
                int ac = ((NEATPopulation)target.Population)
                         .ActivationCycles;
                if (ac == 1)
                {
                    start += target.OutputCount;
                }
            }

            int end = target.NeuronsChromosome.Count - 1;

            // no neurons to pick!
            if (start > end)
            {
                return(null);
            }

            int            neuronPos  = RangeRandomizer.RandomInt(start, end);
            NEATNeuronGene neuronGene = target.NeuronsChromosome[neuronPos];

            return(neuronGene);
        }
コード例 #9
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);
        }
コード例 #10
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;
        }
コード例 #11
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);
            }
        }
コード例 #12
0
ファイル: NEATGenome.cs プロジェクト: neismit/emds
 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;
 }
コード例 #13
0
        /// <summary>
        /// Create a new neuron gene from an id.
        /// </summary>
        ///
        /// <param name="neuronID">The neuron id.</param>
        /// <returns>The neuron gene.</returns>
        public NEATNeuronGene CreateNeuronFromID(long neuronID)
        {
            var result = new NEATNeuronGene(NEATNeuronType.Hidden,
                                            0, 0, 0);


            foreach (IInnovation i  in  Innovations)
            {
                var innovation = (NEATInnovation) i;
                if (innovation.NeuronID == neuronID)
                {
                    result.NeuronType = innovation.NeuronType;
                    result.Id = innovation.NeuronID;
                    result.SplitY = innovation.SplitY;
                    result.SplitX = innovation.SplitX;

                    return result;
                }
            }

            throw new TrainingError("Failed to find innovation for neuron: "
                                    + neuronID);
        }
コード例 #14
0
        /// <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);
        }
コード例 #15
0
ファイル: NEATInnovationList.cs プロジェクト: neismit/emds
 public NEATNeuronGene CreateNeuronFromID(long neuronID)
 {
     NEATNeuronGene gene = new NEATNeuronGene(NEATNeuronType.Hidden, 0L, 0.0, 0.0);
     using (IEnumerator<IInnovation> enumerator = base.Innovations.GetEnumerator())
     {
         IInnovation innovation;
         NEATInnovation innovation2;
         NEATNeuronGene gene2;
         goto Label_0054;
     Label_002A:
         gene2 = gene;
         if ((((uint) neuronID) - ((uint) neuronID)) > uint.MaxValue)
         {
             goto Label_0088;
         }
         return gene2;
     Label_004B:
         if (innovation2.NeuronID == neuronID)
         {
             goto Label_00B1;
         }
     Label_0054:
         if (enumerator.MoveNext())
         {
             goto Label_0088;
         }
         goto Label_0085;
     Label_005F:
         gene.Id = innovation2.NeuronID;
         gene.SplitY = innovation2.SplitY;
         gene.SplitX = innovation2.SplitX;
         goto Label_002A;
     Label_0085:
         if (0 == 0)
         {
             goto Label_00CE;
         }
     Label_0088:
         innovation = enumerator.Current;
         if ((((uint) neuronID) + ((uint) neuronID)) >= 0)
         {
             innovation2 = (NEATInnovation) innovation;
             goto Label_004B;
         }
     Label_00B1:
         gene.NeuronType = innovation2.NeuronType;
         if (0 == 0)
         {
             goto Label_005F;
         }
     }
     Label_00CE:
     throw new TrainingError("Failed to find innovation for neuron: " + neuronID);
 }
コード例 #16
0
ファイル: PersistNEATPopulation.cs プロジェクト: neismit/emds
        /// <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;
        }
コード例 #17
0
        /// <summary>
        /// Construct an innovation.
        /// </summary>
        ///
        /// <param name="neuronGene">The neuron gene.</param>
        /// <param name="innovationID">The innovation id.</param>
        /// <param name="neuronID_0">The neuron id.</param>
        public NEATInnovation(NEATNeuronGene neuronGene,
            long innovationID, long neuronID_0)
        {
            neuronID = neuronID_0;
            InnovationID = innovationID;
            splitX = neuronGene.SplitX;
            splitY = neuronGene.SplitY;

            neuronType = neuronGene.NeuronType;
            innovationType = NEATInnovationType.NewNeuron;
            fromNeuronID = -1;
            toNeuronID = -1;
        }
コード例 #18
0
ファイル: PersistNEATPopulation.cs プロジェクト: neismit/emds
 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;
 }