Beispiel #1
0
        /// <summary>
        ///     Handle loading segregation info.
        /// </summary>
        /// <param name="section">The section being loaded.</param>
        private void HandleSegregateFiles(EncogFileSection section)
        {
            IList <AnalystSegregateTarget> nfs = new List <AnalystSegregateTarget>();
            bool first = true;

            foreach (String line in section.Lines)
            {
                if (!first)
                {
                    IList <String> cols     = EncogFileSection.SplitColumns(line);
                    String         filename = cols[0];
                    int            percent  = Int32.Parse(cols[1]);

                    var nf = new AnalystSegregateTarget(
                        filename, percent);
                    nfs.Add(nf);
                }
                else
                {
                    first = false;
                }
            }

            var array = new AnalystSegregateTarget[nfs.Count];

            for (int i = 0; i < array.Length; i++)
            {
                array[i] = nfs[i];
            }

            _script.Segregate.SegregateTargets = array;
        }
Beispiel #2
0
        /// <summary>
        ///     Handle normalization ranges.
        /// </summary>
        /// <param name="section">The section being loaded.</param>
        private void HandleNormalizeRange(EncogFileSection section)
        {
            _script.Normalize.NormalizedFields.Clear();
            bool first = true;

            foreach (String line in section.Lines)
            {
                if (!first)
                {
                    IList <String> cols     = EncogFileSection.SplitColumns(line);
                    String         name     = cols[0];
                    bool           isOutput = cols[1].ToLower()
                                              .Equals("output");
                    int    timeSlice = Int32.Parse(cols[2]);
                    String action    = cols[3];
                    double high      = CSVFormat.EgFormat.Parse(cols[4]);
                    double low       = CSVFormat.EgFormat.Parse(cols[5]);

                    NormalizationAction des;
                    if (action.Equals("range"))
                    {
                        des = NormalizationAction.Normalize;
                    }
                    else if (action.Equals("ignore"))
                    {
                        des = NormalizationAction.Ignore;
                    }
                    else if (action.Equals("pass"))
                    {
                        des = NormalizationAction.PassThrough;
                    }
                    else if (action.Equals("equilateral"))
                    {
                        des = NormalizationAction.Equilateral;
                    }
                    else if (action.Equals("single"))
                    {
                        des = NormalizationAction.SingleField;
                    }
                    else if (action.Equals("oneof"))
                    {
                        des = NormalizationAction.OneOf;
                    }
                    else
                    {
                        throw new AnalystError("Unknown field type:" + action);
                    }

                    var nf = new AnalystField(name, des, high, low)
                    {
                        TimeSlice = timeSlice, Output = isOutput
                    };
                    _script.Normalize.NormalizedFields.Add(nf);
                }
                else
                {
                    first = false;
                }
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Handle loading data stats.
        /// </summary>
        /// <param name="section">The section being loaded.</param>
        private void HandleDataStats(EncogFileSection section)
        {
            IList <DataField> dfs = new List <DataField>();
            bool first            = true;

            foreach (String line in section.Lines)
            {
                if (!first)
                {
                    IList <String> cols       = EncogFileSection.SplitColumns(line);
                    String         name       = cols[0];
                    bool           isclass    = Int32.Parse(cols[1]) > 0;
                    bool           iscomplete = Int32.Parse(cols[2]) > 0;
                    bool           isint      = Int32.Parse(cols[ColumnThree]) > 0;
                    bool           isreal     = Int32.Parse(cols[ColumnFour]) > 0;
                    double         amax       = CSVFormat.EgFormat.Parse(cols[5]);
                    double         amin       = CSVFormat.EgFormat.Parse(cols[6]);
                    double         mean       = CSVFormat.EgFormat.Parse(cols[7]);
                    double         sdev       = CSVFormat.EgFormat.Parse(cols[8]);
                    String         source     = "";

                    // source was added in Encog 3.2, so it might not be there
                    if (cols.Count > 9)
                    {
                        source = cols[9];
                    }

                    var df = new DataField(name)
                    {
                        Class             = isclass,
                        Complete          = iscomplete,
                        Integer           = isint,
                        Real              = isreal,
                        Max               = amax,
                        Min               = amin,
                        Mean              = mean,
                        StandardDeviation = sdev,
                        Source            = source
                    };
                    dfs.Add(df);
                }
                else
                {
                    first = false;
                }
            }

            var array = new DataField[dfs.Count];

            for (int i = 0; i < array.Length; i++)
            {
                array[i] = dfs[i];
            }

            _script.Fields = array;
        }
Beispiel #4
0
        private void LoadOpcodes(EncogFileSection section)
        {
            bool first = true;

            foreach (string line in section.Lines)
            {
                if (!first)
                {
                    IList <string> cols       = EncogFileSection.SplitColumns(line);
                    string         name       = cols[0];
                    int            childCount = int.Parse(cols[1]);
                    var            opcode     = new ScriptOpcode(name, childCount);
                    _script.Opcodes.Add(opcode);
                }
                else
                {
                    first = false;
                }
            }
        }
Beispiel #5
0
        private void HandleProcessFields(EncogFileSection section)
        {
            IList <ProcessField> fields = _script.Process.Fields;
            bool first = true;

            fields.Clear();

            foreach (string line in section.Lines)
            {
                if (!first)
                {
                    IList <string> cols    = EncogFileSection.SplitColumns(line);
                    String         name    = cols[0];
                    String         command = cols[1];
                    var            pf      = new ProcessField(name, command);
                    fields.Add(pf);
                }
                else
                {
                    first = false;
                }
            }
        }
Beispiel #6
0
        /// <inheritdoc/>
        public Object Read(Stream mask0)
        {
            var result = new RBFNetwork();
            var flat   = (FlatNetworkRBF)result.Flat;

            var ins0 = new EncogReadHelper(mask0);
            EncogFileSection section;

            while ((section = ins0.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("RBF-NETWORK") &&
                    section.SubSectionName.Equals("PARAMS"))
                {
                    IDictionary <String, String> paras = section.ParseParams();
                    EngineArray.PutAll(paras, result.Properties);
                }
                if (section.SectionName.Equals("RBF-NETWORK") &&
                    section.SubSectionName.Equals("NETWORK"))
                {
                    IDictionary <String, String> p = section.ParseParams();

                    flat.BeginTraining = EncogFileSection.ParseInt(p,
                                                                   BasicNetwork.TagBeginTraining);
                    flat.ConnectionLimit = EncogFileSection.ParseDouble(p,
                                                                        BasicNetwork.TagConnectionLimit);
                    flat.ContextTargetOffset = EncogFileSection.ParseIntArray(
                        p, BasicNetwork.TagContextTargetOffset);
                    flat.ContextTargetSize = EncogFileSection.ParseIntArray(
                        p, BasicNetwork.TagContextTargetSize);
                    flat.EndTraining = EncogFileSection.ParseInt(p,
                                                                 BasicNetwork.TagEndTraining);
                    flat.HasContext = EncogFileSection.ParseBoolean(p,
                                                                    BasicNetwork.TagHasContext);
                    flat.InputCount = EncogFileSection.ParseInt(p,
                                                                PersistConst.InputCount);
                    flat.LayerCounts = EncogFileSection.ParseIntArray(p,
                                                                      BasicNetwork.TagLayerCounts);
                    flat.LayerFeedCounts = EncogFileSection.ParseIntArray(p,
                                                                          BasicNetwork.TagLayerFeedCounts);
                    flat.LayerContextCount = EncogFileSection.ParseIntArray(p, BasicNetwork.TagLayerContextCount);
                    flat.LayerIndex        = EncogFileSection.ParseIntArray(p,
                                                                            BasicNetwork.TagLayerIndex);
                    flat.LayerOutput = section.ParseDoubleArray(p,
                                                                PersistConst.Output);
                    flat.LayerSums   = new double[flat.LayerOutput.Length];
                    flat.OutputCount = EncogFileSection.ParseInt(p, PersistConst.OutputCount);
                    flat.WeightIndex = EncogFileSection.ParseIntArray(p,
                                                                      BasicNetwork.TagWeightIndex);
                    flat.Weights = section.ParseDoubleArray(p,
                                                            PersistConst.Weights);
                    flat.BiasActivation = section.ParseDoubleArray(p, BasicNetwork.TagBiasActivation);
                }
                else if (section.SectionName.Equals("RBF-NETWORK") &&
                         section.SubSectionName.Equals("ACTIVATION"))
                {
                    int index = 0;

                    flat.ActivationFunctions = new IActivationFunction[flat.LayerCounts.Length];


                    foreach (String line  in  section.Lines)
                    {
                        IActivationFunction af;
                        IList <String>      cols = EncogFileSection
                                                   .SplitColumns(line);
                        String name = ReflectionUtil.AfPath
                                      + cols[0];
                        try
                        {
                            af = (IActivationFunction)ReflectionUtil.LoadObject(name);
                        }
                        catch (Exception e)
                        {
                            throw new PersistError(e);
                        }
                        for (int i = 0; i < af.ParamNames.Length; i++)
                        {
                            af.Params[i] = CSVFormat.EgFormat.Parse(cols[i + 1]);
                        }

                        flat.ActivationFunctions[index++] = af;
                    }
                }
                else if (section.SectionName.Equals("RBF-NETWORK") &&
                         section.SubSectionName.Equals("RBF"))
                {
                    int index = 0;

                    int hiddenCount = flat.LayerCounts[1];
                    int inputCount  = flat.LayerCounts[2];

                    flat.RBF = new IRadialBasisFunction[hiddenCount];


                    foreach (String line  in  section.Lines)
                    {
                        IRadialBasisFunction rbf;
                        IList <String>       cols = EncogFileSection
                                                    .SplitColumns(line);
                        String name = ReflectionUtil.RBFPath + cols[0];
                        try
                        {
                            rbf = (IRadialBasisFunction)ReflectionUtil.LoadObject(name);
                        }
                        catch (TypeLoadException ex)
                        {
                            throw new PersistError(ex);
                        }
                        catch (TargetException ex)
                        {
                            throw new PersistError(ex);
                        }
                        catch (MemberAccessException ex)
                        {
                            throw new PersistError(ex);
                        }

                        rbf.Width   = CSVFormat.EgFormat.Parse(cols[1]);
                        rbf.Peak    = CSVFormat.EgFormat.Parse(cols[2]);
                        rbf.Centers = new double[inputCount];

                        for (int i = 0; i < inputCount; i++)
                        {
                            rbf.Centers[i] = CSVFormat.EgFormat.Parse(cols[i + 3]);
                        }

                        flat.RBF[index++] = rbf;
                    }
                }
            }

            return(result);
        }
Beispiel #7
0
        /// <summary>
        ///     Handle loading the data classes.
        /// </summary>
        /// <param name="section">The section being loaded.</param>
        private void HandleDataClasses(EncogFileSection section)
        {
            var map = new Dictionary <String, List <AnalystClassItem> >();

            bool first = true;

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

                    if (cols.Count < ColumnFour)
                    {
                        throw new AnalystError("Invalid data class: " + line);
                    }

                    String field = cols[0];
                    String code  = cols[1];
                    String name  = cols[2];
                    int    count = Int32.Parse(cols[3]);

                    DataField df = _script.FindDataField(field);

                    if (df == null)
                    {
                        throw new AnalystError(
                                  "Attempting to add class to unknown field: " + name);
                    }

                    List <AnalystClassItem> classItems;

                    if (!map.ContainsKey(field))
                    {
                        classItems = new List <AnalystClassItem>();
                        map[field] = classItems;
                    }
                    else
                    {
                        classItems = map[field];
                    }

                    classItems.Add(new AnalystClassItem(code, name, count));
                }
                else
                {
                    first = false;
                }
            }

            foreach (DataField field in _script.Fields)
            {
                if (field.Class)
                {
                    List <AnalystClassItem> classList = map[field.Name];
                    if (classList != null)
                    {
                        classList.Sort();
                        field.ClassMembers.Clear();
                        foreach (AnalystClassItem item in classList)
                        {
                            field.ClassMembers.Add(item);
                        }
                    }
                }
            }
        }
Beispiel #8
0
        /// <inheritdoc />
        public Object Read(Stream istream)
        {
            var context = new EncogProgramContext();

            var result = new PrgPopulation(context, 0);

            var reader = new EncogReadHelper(istream);
            EncogFileSection section;

            int      count       = 0;
            ISpecies lastSpecies = null;

            while ((section = reader.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("BASIC") &&
                    section.SubSectionName.Equals("PARAMS"))
                {
                    IDictionary <string, string> prms = section.ParseParams();
                    EngineArray.PutAll(prms, result.Properties);
                }
                else if (section.SectionName.Equals("BASIC") &&
                         section.SubSectionName.Equals("EPL-POPULATION"))
                {
                    foreach (string line in section.Lines)
                    {
                        IList <String> cols = EncogFileSection.SplitColumns(line);

                        if (String.Compare(cols[0], "s", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            lastSpecies = new BasicSpecies
                            {
                                Age               = int.Parse(cols[1]),
                                BestScore         = CSVFormat.EgFormat.Parse(cols[2]),
                                Population        = result,
                                GensNoImprovement = int.Parse(cols[3])
                            };
                            result.Species.Add(lastSpecies);
                        }
                        else if (cols[0].Equals("p"))
                        {
                            double score;
                            double adjustedScore;

                            if (String.Compare(cols[1], "nan", StringComparison.OrdinalIgnoreCase) == 0 ||
                                String.Compare(cols[2], "nan", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                score         = Double.NaN;
                                adjustedScore = Double.NaN;
                            }
                            else
                            {
                                score         = CSVFormat.EgFormat.Parse(cols[1]);
                                adjustedScore = CSVFormat.EgFormat.Parse(cols[2]);
                            }

                            String code = cols[3];
                            var    prg  = new EncogProgram(context);
                            prg.CompileEPL(code);
                            prg.Score         = score;
                            prg.Species       = lastSpecies;
                            prg.AdjustedScore = adjustedScore;
                            if (lastSpecies == null)
                            {
                                throw new EncogError(
                                          "Have not defined a species yet");
                            }
                            lastSpecies.Add(prg);
                            count++;
                        }
                    }
                }
                else if (section.SectionName.Equals("BASIC") &&
                         section.SubSectionName.Equals("EPL-OPCODES"))
                {
                    foreach (String line in section.Lines)
                    {
                        IList <string> cols = EncogFileSection.SplitColumns(line);
                        String         name = cols[0];
                        int            args = int.Parse(cols[1]);
                        result.Context.Functions.AddExtension(name, args);
                    }
                }
                else if (section.SectionName.Equals("BASIC") &&
                         section.SubSectionName.Equals("EPL-SYMBOLIC"))
                {
                    bool first = true;
                    foreach (string line in section.Lines)
                    {
                        if (!first)
                        {
                            IList <String> cols = EncogFileSection.SplitColumns(line);
                            String         name = cols[0];
                            String         t    = cols[1];
                            var            vt   = EPLValueType.Unknown;

                            if (string.Compare(t, "f", true) == 0)
                            {
                                vt = EPLValueType.FloatingType;
                            }
                            else if (string.Compare(t, "b", true) == 0)
                            {
                                vt = EPLValueType.BooleanType;
                            }
                            else if (string.Compare(t, "i", true) == 0)
                            {
                                vt = EPLValueType.IntType;
                            }
                            else if (string.Compare(t, "s", true) == 0)
                            {
                                vt = EPLValueType.StringType;
                            }
                            else if (string.Compare(t, "e", true) == 0)
                            {
                                vt = EPLValueType.EnumType;
                            }

                            int enumType  = int.Parse(cols[2]);
                            int enumCount = int.Parse(cols[3]);
                            var mapping   = new VariableMapping(
                                name, vt, enumType, enumCount);
                            if (mapping.Name.Length > 0)
                            {
                                result.Context.DefineVariable(mapping);
                            }
                            else
                            {
                                result.Context.Result = mapping;
                            }
                        }
                        else
                        {
                            first = false;
                        }
                    }
                }
            }
            result.PopulationSize = count;

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

                // set the leaders
                foreach (ISpecies sp in result.Species)
                {
                    if (sp.Members.Count > 0)
                    {
                        sp.Leader = sp.Members[0];
                    }
                }
            }
            return(result);
        }
Beispiel #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);
        }
Beispiel #10
0
        /// <summary>
        /// Read an object.
        /// </summary>
        public Object Read(Stream mask0)
        {
            var ins0 = new EncogReadHelper(mask0);
            EncogFileSection section;
            var samples = new BasicMLDataSet();
            IDictionary <String, String> networkParams = null;
            PNNKernelType kernel      = default(PNNKernelType) /* was: null */;
            PNNOutputMode outmodel    = default(PNNOutputMode) /* was: null */;
            int           inputCount  = 0;
            int           outputCount = 0;
            double        error       = 0;

            double[] sigma = null;

            while ((section = ins0.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("PNN") &&
                    section.SubSectionName.Equals("PARAMS"))
                {
                    networkParams = section.ParseParams();
                }
                if (section.SectionName.Equals("PNN") &&
                    section.SubSectionName.Equals("NETWORK"))
                {
                    IDictionary <String, String> paras = section.ParseParams();
                    inputCount = EncogFileSection.ParseInt(paras,
                                                           PersistConst.InputCount);
                    outputCount = EncogFileSection.ParseInt(paras,
                                                            PersistConst.OutputCount);
                    kernel   = StringToKernel(paras[PersistConst.Kernel]);
                    outmodel = StringToOutputMode(paras[PropertyOutputMode]);
                    error    = EncogFileSection
                               .ParseDouble(paras, PersistConst.Error);
                    sigma = section.ParseDoubleArray(paras, PersistConst.Sigma);
                }
                if (section.SectionName.Equals("PNN") &&
                    section.SubSectionName.Equals("SAMPLES"))
                {
                    foreach (String line in section.Lines)
                    {
                        IList <String> cols = EncogFileSection
                                              .SplitColumns(line);
                        int index     = 0;
                        var inputData = new BasicMLData(inputCount);
                        for (int i = 0; i < inputCount; i++)
                        {
                            inputData[i] =
                                CSVFormat.EgFormat.Parse(cols[index++]);
                        }
                        var idealData = new BasicMLData(inputCount);

                        idealData[0] = CSVFormat.EgFormat.Parse(cols[index++]);

                        IMLDataPair pair = new BasicMLDataPair(inputData,
                                                               idealData);
                        samples.Add(pair);
                    }
                }
            }

            var result = new BasicPNN(kernel, outmodel, inputCount,
                                      outputCount);

            if (networkParams != null)
            {
                EngineArray.PutAll(networkParams, result.Properties);
            }
            result.Samples = samples;
            result.Error   = error;
            if (sigma != null)
            {
                EngineArray.ArrayCopy(sigma, result.Sigma);
            }

            return(result);
        }
Beispiel #11
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);
        }