Esempio n. 1
0
        /// <summary>
        ///     Define a variable.
        /// </summary>
        /// <param name="theName">The name of the variable.</param>
        /// <param name="theVariableType">The type of variable.</param>
        /// <param name="theEnumType">The enum type, not used if not an enum type.</param>
        /// <param name="theEnumValueCount">
        ///     The number of values for the enum, not used if not an enum
        ///     type.
        /// </param>
        public void DefineVariable(String theName,
                                   EPLValueType theVariableType, int theEnumType,
                                   int theEnumValueCount)
        {
            var mapping = new VariableMapping(theName,
                                              theVariableType, theEnumType, theEnumValueCount);

            DefineVariable(mapping);
        }
Esempio n. 2
0
 /// <summary>
 ///     Define a variable, based on a mapping.
 /// </summary>
 /// <param name="mapping">The variable mapping.</param>
 public void DefineVariable(VariableMapping mapping)
 {
     if (_map.ContainsKey(mapping.Name))
     {
         throw new EACompileError("Variable " + mapping.Name
                                  + " already defined.");
     }
     _map[mapping.Name] = mapping;
     _definedVariables.Add(mapping);
 }
 /// <summary>
 ///     Define the specified variable mapping. This is to be used by the context
 ///     to setup the variable definitions. Do not call it directly. You will have
 ///     unexpected results if you have a variable defined in this class, but not
 ///     in the context.
 /// </summary>
 /// <param name="mapping">The variable mapping.</param>
 public void DefineVariable(VariableMapping mapping)
 {
     if (_varMap.ContainsKey(mapping.Name))
     {
         throw new EARuntimeError(
             "Variable "
             + mapping.Name
             + " already defined, simply set its value, do not redefine.");
     }
     _varMap[mapping.Name] = _variables.Count;
     _variables.Add(new ExpressionValue(mapping.VariableType));
 }
Esempio n. 4
0
 /// <summary>
 ///     Define the specified variable mapping. This is to be used by the context
 ///     to setup the variable definitions. Do not call it directly. You will have
 ///     unexpected results if you have a variable defined in this class, but not
 ///     in the context.
 /// </summary>
 /// <param name="mapping">The variable mapping.</param>
 public void DefineVariable(VariableMapping mapping)
 {
     if (_varMap.ContainsKey(mapping.Name))
     {
         throw new EARuntimeError(
                   "Variable "
                   + mapping.Name
                   + " already defined, simply set its value, do not redefine.");
     }
     _varMap[mapping.Name] = _variables.Count;
     _variables.Add(new ExpressionValue(mapping.VariableType));
 }
Esempio n. 5
0
        /// <summary>
        ///     Get the type string for the specified variable mapping.
        /// </summary>
        /// <param name="mapping">The mapping.</param>
        /// <returns>The value.</returns>
        private string GetType(VariableMapping mapping)
        {
            switch (mapping.VariableType)
            {
            case EPLValueType.FloatingType:
                return("f");

            case EPLValueType.StringType:
                return("s");

            case EPLValueType.BooleanType:
                return("b");

            case EPLValueType.IntType:
                return("i");

            case EPLValueType.EnumType:
                return("e");
            }
            throw new EncogError("Unknown type: "
                                 + mapping.VariableType.ToString());
        }
Esempio n. 6
0
        /// <summary>
        ///     Select a random variable from the defined variables.
        /// </summary>
        /// <param name="rnd">A random number generator.</param>
        /// <param name="desiredTypes">The desired types that the variable can be.</param>
        /// <returns>The index of the defined variable, or -1 if unable to define.</returns>
        public int SelectRandomVariable(EncogRandom rnd,
                                        IList <EPLValueType> desiredTypes)
        {
            IList <VariableMapping> selectionSet = _context
                                                   .FindVariablesByTypes(desiredTypes);

            if (selectionSet.Count == 0 &&
                desiredTypes.Contains(EPLValueType.IntType))
            {
                IList <EPLValueType> floatList = new List <EPLValueType>();
                floatList.Add(EPLValueType.FloatingType);
                selectionSet = _context.FindVariablesByTypes(floatList);
            }

            if (selectionSet.Count == 0)
            {
                return(-1);
            }

            VariableMapping selected = selectionSet[rnd.Next(selectionSet.Count)];

            return(Context.DefinedVariables.IndexOf(selected));
        }
 /// <summary>
 ///     Define a variable, based on a mapping.
 /// </summary>
 /// <param name="mapping">The variable mapping.</param>
 public void DefineVariable(VariableMapping mapping)
 {
     if (_map.ContainsKey(mapping.Name))
     {
         throw new EACompileError("Variable " + mapping.Name
                                  + " already defined.");
     }
     _map[mapping.Name] = mapping;
     _definedVariables.Add(mapping);
 }
 /// <summary>
 ///     Define a variable.
 /// </summary>
 /// <param name="theName">The name of the variable.</param>
 /// <param name="theVariableType">The type of variable.</param>
 /// <param name="theEnumType">The enum type, not used if not an enum type.</param>
 /// <param name="theEnumValueCount">
 ///     The number of values for the enum, not used if not an enum
 ///     type.
 /// </param>
 public void DefineVariable(String theName,
                            EPLValueType theVariableType, int theEnumType,
                            int theEnumValueCount)
 {
     var mapping = new VariableMapping(theName,
                                       theVariableType, theEnumType, theEnumValueCount);
     DefineVariable(mapping);
 }
Esempio n. 9
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);
        }
Esempio n. 10
0
        /// <summary>
        ///     Compute the output from the input MLData. The individual values of the
        ///     input will be mapped to the variables defined in the context. The order
        ///     is the same between the input and the defined variables. The input will
        ///     be mapped to the appropriate types. Enums will use their ordinal number.
        ///     The result will be a single number MLData.
        /// </summary>
        /// <param name="input">The input to the program.</param>
        /// <returns>A single numer MLData.</returns>
        public IMLData Compute(IMLData input)
        {
            if (input.Count != InputCount)
            {
                throw new EACompileError("Invalid input count.");
            }

            for (int i = 0; i < input.Count; i++)
            {
                _variables.SetVariable(i, input[i]);
            }

            ExpressionValue v             = RootNode.Evaluate();
            VariableMapping resultMapping = ResultType;

            var  result  = new BasicMLData(1);
            bool success = false;

            switch (resultMapping.VariableType)
            {
            case EPLValueType.FloatingType:
                if (v.IsNumeric)
                {
                    result.Data[0] = v.ToFloatValue();
                    success        = true;
                }
                break;

            case EPLValueType.StringType:
                result.Data[0] = v.ToFloatValue();
                success        = true;
                break;

            case EPLValueType.BooleanType:
                if (v.IsBoolean)
                {
                    result.Data[0] = v.ToBooleanValue() ? 1.0 : 0.0;
                    success        = true;
                }
                break;

            case EPLValueType.IntType:
                if (v.IsNumeric)
                {
                    result[0] = v.ToIntValue();
                    success   = true;
                }
                break;

            case EPLValueType.EnumType:
                if (v.IsEnum)
                {
                    result.Data[0] = v.ToIntValue();
                    success        = true;
                }
                break;
            }

            if (!success)
            {
                throw new EARuntimeError("EncogProgram produced "
                                         + v.ExprType.ToString() + " but "
                                         + resultMapping.VariableType.ToString()
                                         + " was expected.");
            }

            return(result);
        }
        /// <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;
        }
 /// <summary>
 ///     Get the type string for the specified variable mapping.
 /// </summary>
 /// <param name="mapping">The mapping.</param>
 /// <returns>The value.</returns>
 private string GetType(VariableMapping mapping)
 {
     switch (mapping.VariableType)
     {
         case EPLValueType.FloatingType:
             return "f";
         case EPLValueType.StringType:
             return "s";
         case EPLValueType.BooleanType:
             return "b";
         case EPLValueType.IntType:
             return "i";
         case EPLValueType.EnumType:
             return "e";
     }
     throw new EncogError("Unknown type: "
                          + mapping.VariableType.ToString());
 }