/// <summary>
        /// Save the object.
        /// </summary>
        /// <param name="os">The output stream.</param>
        /// <param name="obj">The object to save.</param>
        public virtual void Save(Stream os, Object obj)
        {
            var xout = new EncogWriteHelper(os);
            var neat = (NEATNetwork)obj;

            xout.AddSection("NEAT");
            xout.AddSubSection("PARAMS");
            xout.AddProperties(neat.Properties);
            xout.AddSubSection("NETWORK");

            xout.WriteProperty(PersistConst.InputCount, neat.InputCount);
            xout.WriteProperty(PersistConst.OutputCount, neat.OutputCount);
            xout.WriteProperty(PersistConst.ActivationFunction,
                               neat.ActivationFunction);
            xout.WriteProperty(NEATPopulation.PropertyOutputActivation,
                               neat.OutputActivationFunction);
            xout.WriteProperty(PersistConst.Depth, neat.NetworkDepth);
            xout.WriteProperty(PersistConst.Snapshot, neat.Snapshot);

            xout.AddSubSection("NEURONS");

            foreach (NEATNeuron neatNeuron  in  neat.Neurons)
            {
                xout.AddColumn((int)neatNeuron.NeuronID);
                xout.AddColumn(PersistNEATPopulation.NeuronTypeToString(neatNeuron.NeuronType));
                xout.AddColumn(neatNeuron.ActivationResponse);
                xout.AddColumn(neatNeuron.SplitX);
                xout.AddColumn(neatNeuron.SplitY);
                xout.WriteLine();
            }

            xout.AddSubSection("LINKS");

            foreach (NEATNeuron neatNeuron  in  neat.Neurons)
            {
                foreach (NEATLink link  in  neatNeuron.OutputboundLinks)
                {
                    WriteLink(xout, link);
                }
            }

            xout.Flush();
        }
Example #2
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);
        }
        /// <summary>
        /// Read the object.
        /// </summary>
        /// <param name="mask0">The stream to read from.</param>
        /// <returns>The loaded object.</returns>
        public virtual Object Read(Stream mask0)
        {
            var result = new NEATNetwork();
            var ins0   = new EncogReadHelper(mask0);
            EncogFileSection section;
            IDictionary <Int32, NEATNeuron> neuronMap = new Dictionary <Int32, NEATNeuron>();

            while ((section = ins0.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("NEAT") &&
                    section.SubSectionName.Equals("PARAMS"))
                {
                    IDictionary <String, String> paras = section.ParseParams();

                    foreach (String key in paras.Keys)
                    {
                        result.Properties.Add(key, paras[key]);
                    }
                }
                if (section.SectionName.Equals("NEAT") &&
                    section.SubSectionName.Equals("NETWORK"))
                {
                    IDictionary <String, String> p = section.ParseParams();

                    result.InputCount = EncogFileSection.ParseInt(p,
                                                                  PersistConst.InputCount);
                    result.OutputCount = EncogFileSection.ParseInt(p,
                                                                   PersistConst.OutputCount);
                    result.ActivationFunction = EncogFileSection
                                                .ParseActivationFunction(p,
                                                                         PersistConst.ActivationFunction);
                    result.OutputActivationFunction = EncogFileSection
                                                      .ParseActivationFunction(p,
                                                                               NEATPopulation.PropertyOutputActivation);
                    result.NetworkDepth = EncogFileSection.ParseInt(p,
                                                                    PersistConst.Depth);
                    result.Snapshot = EncogFileSection.ParseBoolean(p,
                                                                    PersistConst.Snapshot);
                }
                else if (section.SectionName.Equals("NEAT") &&
                         section.SubSectionName.Equals("NEURONS"))
                {
                    foreach (String line  in  section.Lines)
                    {
                        IList <String> cols = EncogFileSection.SplitColumns(line);

                        long           neuronID   = Int32.Parse(cols[0]);
                        NEATNeuronType neuronType = PersistNEATPopulation
                                                    .StringToNeuronType(cols[1]);
                        double activationResponse = CSVFormat.EgFormat
                                                    .Parse(cols[2]);
                        double splitY = CSVFormat.EgFormat
                                        .Parse(cols[3]);
                        double splitX = CSVFormat.EgFormat
                                        .Parse(cols[4]);

                        var neatNeuron = new NEATNeuron(neuronType,
                                                        neuronID, splitY, splitX, activationResponse);
                        result.Neurons.Add(neatNeuron);
                        neuronMap[((int)neuronID)] = (neatNeuron);
                    }
                }
                else if (section.SectionName.Equals("NEAT") &&
                         section.SubSectionName.Equals("LINKS"))
                {
                    foreach (String line  in  section.Lines)
                    {
                        IList <String> cols       = EncogFileSection.SplitColumns(line);
                        int            fromID     = Int32.Parse(cols[0]);
                        int            toID       = Int32.Parse(cols[1]);
                        bool           recurrent  = Int32.Parse(cols[2]) > 0;
                        double         weight     = CSVFormat.EgFormat.Parse(cols[3]);
                        NEATNeuron     fromNeuron = (neuronMap[fromID]);
                        NEATNeuron     toNeuron   = (neuronMap[toID]);
                        var            neatLink   = new NEATLink(weight, fromNeuron,
                                                                 toNeuron, recurrent);
                        fromNeuron.OutputboundLinks.Add(neatLink);
                        toNeuron.InboundLinks.Add(neatLink);
                    }
                }
            }

            return(result);
        }