public UserDefineFunction(string funcName, IEval f, string[] paramName)
        {
            this.name        = funcName;
            this.formula     = f;
            this.description = "";

            this._paramName = paramName;
            for (int i = 0; i < paramName.Length; i++)
            {
                this.paramType.Add(ExpressionType.Unknown);
            }
        }
Beispiel #2
0
        public EvalTests()
        {
            var factory = new MultEvalFactory();

            _constExpr1 = factory.Const(7);
            _constExpr2 = factory.Const(2);
            _constExpr3 = factory.Const(3);

            _addExpr1 = factory.Add(_constExpr1, _constExpr2);

            _multExpr1 = factory.Mult(_constExpr1, _constExpr2);
            _multExpr2 = factory.Mult(_constExpr2, _constExpr3);

            _addExpr2 = factory.Add(_multExpr1, _multExpr2);
        }
Beispiel #3
0
        public Object Functions(string name, IEval evaluator)
        {
            Object ret = BaseFunctions != null?BaseFunctions(name, evaluator) : new StringParser.ConvertError("() not recognised");

            StringParser.ConvertError ce = ret as StringParser.ConvertError;

            if (ce != null && ce.ErrorValue.Contains("() not recognised"))
            {
                if (functions.ContainsKey(name))
                {
                    FuncDef fd = functions[name];

                    bool hasparas = fd.parameters.Length > 0;

                    if (hasparas)
                    {
                        IEvalParaListType[] plist = new IEvalParaListType[fd.parameters.Length];
                        plist = Enumerable.Repeat(IEvalParaListType.All, fd.parameters.Length).ToArray();

                        List <Object> paras = evaluator.Parameters(name, fd.parameters.Length, plist);
                        if (paras == null)              // if error, stop and return error
                        {
                            return(evaluator.Value);
                        }

                        symbols.Push();
                        for (int i = 0; i < fd.parameters.Length; i++)          // add to symbol list on next level the parameter names and values
                        {
                            System.Diagnostics.Debug.WriteLine(symbols.Levels + " " + name + " Push " + fd.parameters[i] + "=" + paras[i]);
                            symbols.Add(fd.parameters[i], paras[i]);
                        }
                    }

                    Eval   evfunc = (Eval)evaluator.Clone();                    // we need a fresh one just to evaluate this, but with the same configuration
                    Object res    = evfunc.Evaluate(fd.funcdef);                // and evaluate

                    if (hasparas)
                    {
                        symbols.Pop();                                          // clear back stack..
                    }
                    return(res);
                }
            }

            return(ret);
        }
        // *** IOptimizer interface implementation ***

        public ArrayList <double> Optimize(double[] initParamVec, IEval eval)
        {
            Utils.ThrowException(initParamVec == null ? new ArgumentNullException("initParamVec") : null);
            Utils.ThrowException(eval == null ? new ArgumentNullException("eval") : null);
            ArrayList <double> paramVec = new ArrayList <double>(initParamVec);

            Utils.ThrowException(paramVec.Count == 0 ? new ArgumentValueException("initParamVec") : null);
            SetInitPopul(paramVec.Count, paramVec.Count * 10); // *** make this multiplier configurable
            mPopul[0] = new Pair <double, ArrayList <double> >(0, paramVec);
            double             bestGlobalVal = double.MinValue;
            ArrayList <double> bestParamVec  = null;

            // evaluate initial population
            for (int i = 0; i < mPopul.Count; i++)
            {
                Pair <double, ArrayList <double> > indiv = mPopul[i];
                double localVal = eval.Eval(indiv.Second);
                mPopul[i] = new Pair <double, ArrayList <double> >(localVal, indiv.Second);
                if (localVal > bestGlobalVal)
                {
                    bestGlobalVal = localVal; bestParamVec = indiv.Second;
                }
            }
            // optimize
            int    numNoChangeIter = 0;
            double bestVal         = bestGlobalVal;

            while (numNoChangeIter < mMinNoChangeIter)
            {
                SetNextPopul(eval, mWgtFactor, mCrossover, ref bestVal, ref bestParamVec);
                if (bestVal > bestGlobalVal)
                {
                    numNoChangeIter = 0; bestGlobalVal = bestVal;
                }
                else
                {
                    numNoChangeIter++;
                }
                mLogger.Info("Optimize", "Iteration status:\r\n" +
                             "No-change iterations: {0} / {1}\r\n" +
                             "Current best solution vector: {2}\r\n" +
                             "Current best solution score:  {3}", numNoChangeIter, mMinNoChangeIter, bestParamVec, bestGlobalVal);
            }
            return(bestParamVec);
        }
        private void SetNextPopul(IEval eval, double wgtFactor, double crossover, ref double bestVal, ref ArrayList <double> bestParamVec)
        {
            ArrayList <Pair <double, ArrayList <double> > > nextPopul = new ArrayList <Pair <double, ArrayList <double> > >(mPopul.Count);

            // for each individual in the population ...
            foreach (Pair <double, ArrayList <double> > indivInfo in mPopul)
            {
                ArrayList <double> indiv = indivInfo.Second;
                ArrayList <double> rndIndiv1 = null, rndIndiv2 = null, rndIndiv3 = null;
                // randomly select parents
                GetRandomIndiv(indiv, ref rndIndiv1, ref rndIndiv2, ref rndIndiv3);
                // create initial candidate v
                ArrayList <double> v = ComputeInitialCandidate(rndIndiv1, rndIndiv2, rndIndiv3, wgtFactor);
                // create final candidate u
                ArrayList <double> u = indiv.Clone();
                for (int i = 0; i < u.Count; i++)
                {
                    if (mRandom.NextDouble() < crossover)
                    {
                        u[i] = v[i];
                    }
                }
                // accept or reject candidate u
                double newVal = eval.Eval(u);
                if (newVal > indivInfo.First)
                {
                    nextPopul.Add(new Pair <double, ArrayList <double> >(newVal, u));
                    if (newVal > bestVal)
                    {
                        bestVal = newVal; bestParamVec = u;
                    }
                }
                else
                {
                    nextPopul.Add(indivInfo);
                    if (indivInfo.First > bestVal)
                    {
                        bestVal = indivInfo.First; bestParamVec = indivInfo.Second;
                    }
                }
            }
            mPopul = nextPopul;
        }
Beispiel #6
0
        static void OutputFormula(RuntimeData runtime, IFormula f, int level)
        {
            for (int i = 0; i < f.Count; i++)
            {
                if (f.Items[i] is IFormula)
                {
                    Console.WriteLine("{0}{1} [{2}]{3}",
                                      "".PadLeft(level * 2, ' '),
                                      i + 1,
                                      f.Items[i].GetType().Name,
                                      f.Items[i]);
                    OutputFormula(runtime, f.Items[i] as IFormula, level + 1);
                }
                else if (f.Items[i] is Operator)
                {
                    Operator e = (f.Items[i] as Operator);
                    Console.WriteLine("{0}{1}. {2}[{3}] => {4}",
                                      "".PadLeft(level * 2, ' '),
                                      i + 1,
                                      f.Items[i],
                                      f.Items[i].GetType().Name,
                                      e.Evaluator.Name);
                }
                else
                {
                    IEval e  = (f.Items[i] as IEval);
                    var   ee = e != null?e.Eval(runtime) : null;

                    Console.WriteLine("{0}{1}. {2}[{3}] => {4}",
                                      "".PadLeft(level * 2, ' '),
                                      i + 1,
                                      f.Items[i],
                                      f.Items[i].GetType().Name,
                                      e != null ? ee.ToString() + "[" + ee.GetType().Name + "]" : "不明");
                }
            }
        }
 public Add(IEval e1, IEval e2)
 {
     this.e1 = e1;
     this.e2 = e2;
 }
Beispiel #8
0
 public EvalAdd(IEval left, IEval right)
 {
     _left = left;
     _right = right;
 }
        static public Object BaseFunctions(string name, IEval evaluator)
        {
            string[] maths = { "Abs", "Acos",  "Asin", "Atan",  "Ceiling", "Cos",  "Cosh",
                               "Exp", "Floor", "Log",  "Log10", "Sin",     "Sinh", "Sqrt","Tan","Tanh", "Truncate" };

            int mathsindex = Array.IndexOf(maths, name);

            if (mathsindex >= 0)
            {
                List <Object> list = evaluator.Parameters(name, 1, new IEvalParaListType[] { IEvalParaListType.NumberOrInteger });

                if (list != null)
                {
                    return(MathFunc(name, typeof(Math), list[0]));
                }
                else
                {
                    return(evaluator.Value);
                }
            }

            string[] chars = { "IsControl", "IsDigit", "IsLetter", "IsLower", "IsNumber", "IsPunctuation", "IsSeparator", "IsSurrogate", "IsSymbol", "IsUpper", "IsWhiteSpace",
                               "ToLower",   "ToUpper" };
            int      charsindex = Array.IndexOf(chars, name);

            if (charsindex >= 0)
            {
                List <Object> list = evaluator.Parameters(name, 1, new IEvalParaListType[] { (name == "ToLower" || name == "ToUpper") ? IEvalParaListType.IntegerOrString : IEvalParaListType.Integer });

                if (list != null)
                {
                    if (name == "ToLower" && list[0] is string)
                    {
                        return(((string)list[0]).ToLower(evaluator.Culture));
                    }
                    else if (name == "ToUpper" && list[0] is string)
                    {
                        return(((string)list[0]).ToUpper(evaluator.Culture));
                    }
                    else
                    {
                        var methodarray = typeof(Char).GetMember(name);                                                         // get members given name
                        var method      = methodarray.FindMember(new Type[] { list[0] is long?typeof(char) : typeof(string) }); // find all members which have a single para of this type

                        if (method.ReturnType == typeof(bool))
                        {
                            bool value = (bool)method.Invoke(null, new Object[] { (char)(long)list[0] });
                            return(value ? (long)1 : (long)0);
                        }
                        else
                        {
                            char ch = (char)method.Invoke(null, new Object[] { (char)(long)list[0] });
                            return((long)ch);
                        }
                    }
                }
                else
                {
                    return(evaluator.Value);
                }
            }

            if (name == "Max" || name == "Min")
            {
                List <Object> list = evaluator.Parameters(name, 2, new IEvalParaListType[] { IEvalParaListType.NumberOrInteger, IEvalParaListType.NumberOrInteger });

                if (list != null)
                {
                    if (list[0] is long && list[1] is long)
                    {
                        return(name == "Max" ? Math.Max((long)list[0], (long)list[1]) : Math.Min((long)list[0], (long)list[1]));
                    }
                    else
                    {
                        double[] array = ToDouble(list);
                        return(name == "Max" ? Math.Max(array[0], array[1]) : Math.Min(array[0], array[1]));
                    }
                }
            }
            else if (name == "Pow")
            {
                List <Object> list = evaluator.Parameters(name, 2, new IEvalParaListType[] { IEvalParaListType.Number, IEvalParaListType.Number });

                if (list != null)
                {
                    return(Math.Pow((double)list[0], (double)list[1]));
                }
            }
            else if (name == "Round")
            {
                List <Object> list = evaluator.Parameters(name, 1, new IEvalParaListType[] { IEvalParaListType.Number, IEvalParaListType.Integer });

                if (list != null)
                {
                    return((list.Count == 1) ? Math.Round((double)list[0]) : Math.Round((double)list[0], (int)(long)list[1]));
                }
            }
            else if (name == "Sign")
            {
                List <Object> list = evaluator.Parameters(name, 1, new IEvalParaListType[] { IEvalParaListType.NumberOrInteger });

                if (list != null)
                {
                    return((long)(list[0] is long?Math.Sign((long)list[0]) : Math.Sign((double)list[0])));
                }
            }
            else if (name == "Fp" || name == "double" || name == "float")
            {
                List <Object> list = evaluator.Parameters(name, 1, new IEvalParaListType[] { IEvalParaListType.Number });        // gather a single number

                if (list != null)
                {
                    return(list[0]);
                }
            }
            else if (name == "Eval")
            {
                List <Object> list = evaluator.Parameters(name, 1, new IEvalParaListType[] { IEvalParaListType.String });

                if (list != null)
                {
                    Eval ev = new Eval(true, true, true);
                    return(ev.Evaluate((string)list[0]));
                }
            }
            else if (name == "ToString")
            {
                List <Object> list = evaluator.Parameters(name, 2, new IEvalParaListType[] { IEvalParaListType.NumberOrInteger, IEvalParaListType.String });

                if (list != null)
                {
                    string output;

                    bool ok = (list[0] is double) ? ((double)list[0]).SafeToString(list[1] as string, out output) : ((long)list[0]).SafeToString(list[1] as string, out output);

                    if (ok)
                    {
                        return(output);
                    }
                    else
                    {
                        return(new StringParser.ConvertError(name + "() Format is incorrect"));
                    }
                }
            }
            else if (name == "Unicode")
            {
                List <Object> list = evaluator.Parameters(name, 1, new IEvalParaListType[] { IEvalParaListType.Integer });

                if (list != null)
                {
                    return((string)char.ToString((char)(long)list[0]));
                }
            }
            else
            {
                return(new StringParser.ConvertError(name + "() not recognised"));
            }

            return(evaluator.Value);
        }
Beispiel #10
0
        public void LtlDisjunctionTest(string input, string ltl)
        {
            IEval evaluation = Program.BuildAstLTL(_ltlEval, ltl);

            Assert.True(evaluation.Eval(input), $"{input} should be true");
        }
Beispiel #11
0
 // *** IOptimizer interface implementation ***
 public ArrayList<double> Optimize(double[] initParamVec, IEval eval)
 {
     Utils.ThrowException(initParamVec == null ? new ArgumentNullException("initParamVec") : null);
     Utils.ThrowException(eval == null ? new ArgumentNullException("eval") : null);
     ArrayList<double> paramVec = new ArrayList<double>(initParamVec);
     Utils.ThrowException(paramVec.Count == 0 ? new ArgumentValueException("initParamVec") : null);
     SetInitPopul(paramVec.Count, paramVec.Count * 10); // *** make this multiplier configurable
     mPopul[0] = new Pair<double, ArrayList<double>>(0, paramVec);
     double bestGlobalVal = double.MinValue;
     ArrayList<double> bestParamVec = null;
     // evaluate initial population
     for (int i = 0; i < mPopul.Count; i++)
     {
         Pair<double, ArrayList<double>> indiv = mPopul[i];
         double localVal = eval.Eval(indiv.Second);
         mPopul[i] = new Pair<double, ArrayList<double>>(localVal, indiv.Second);
         if (localVal > bestGlobalVal) { bestGlobalVal = localVal; bestParamVec = indiv.Second; }
     }
     // optimize
     int numNoChangeIter = 0;
     double bestVal = bestGlobalVal;
     while (numNoChangeIter < mMinNoChangeIter)
     {
         SetNextPopul(eval, mWgtFactor, mCrossover, ref bestVal, ref bestParamVec);
         if (bestVal > bestGlobalVal) { numNoChangeIter = 0; bestGlobalVal = bestVal; } else { numNoChangeIter++; }
         mLogger.Info("Optimize", "Iteration status:\r\n" +
             "No-change iterations: {0} / {1}\r\n" +
             "Current best solution vector: {2}\r\n" +
             "Current best solution score:  {3}", numNoChangeIter, mMinNoChangeIter, bestParamVec, bestGlobalVal);
     }
     return bestParamVec;
 }
Beispiel #12
0
 private void SetNextPopul(IEval eval, double wgtFactor, double crossover, ref double bestVal, ref ArrayList<double> bestParamVec)
 {
     ArrayList<Pair<double, ArrayList<double>>> nextPopul = new ArrayList<Pair<double, ArrayList<double>>>(mPopul.Count);
     // for each individual in the population ...
     foreach (Pair<double, ArrayList<double>> indivInfo in mPopul)
     {
         ArrayList<double> indiv = indivInfo.Second;
         ArrayList<double> rndIndiv1 = null, rndIndiv2 = null, rndIndiv3 = null;
         // randomly select parents
         GetRandomIndiv(indiv, ref rndIndiv1, ref rndIndiv2, ref rndIndiv3);
         // create initial candidate v
         ArrayList<double> v = ComputeInitialCandidate(rndIndiv1, rndIndiv2, rndIndiv3, wgtFactor);
         // create final candidate u
         ArrayList<double> u = indiv.Clone();
         for (int i = 0; i < u.Count; i++)
         {
             if (mRandom.NextDouble() < crossover)
             {
                 u[i] = v[i];
             }
         }
         // accept or reject candidate u
         double newVal = eval.Eval(u);
         if (newVal > indivInfo.First)
         {
             nextPopul.Add(new Pair<double, ArrayList<double>>(newVal, u));
             if (newVal > bestVal) { bestVal = newVal; bestParamVec = u; }
         }
         else
         {
             nextPopul.Add(indivInfo);
             if (indivInfo.First > bestVal) { bestVal = indivInfo.First; bestParamVec = indivInfo.Second; }
         }
     }
     mPopul = nextPopul;
 }
Beispiel #13
0
        public override INumber Eval(RuntimeData runtime)
        {
            if (this.Count == 0)
            {
                return(null);
            }
            else if (this.Count == 1)
            {
                return((this.Items[0] as IEval).Eval(runtime));
            }
            else if (this.Items.Where(i => i is LineBreak).Count() >= 1)
            {
                // 一番最後がLineBreakじゃなければ追加する
                if (!(this._items.Last() is LineBreak))
                {
                    this._items.Add(new LineBreak(new Token(";", TokenType.Syntax)));
                }


                // LineBreakがあるごとに逆ポーランド記法に変換して実行
                Formula f     = new Expression.Formula();
                IEval   res   = null;
                Array   res_a = null;
                // 配列形式のフォーマットなら配列形式で返す
                if (this.token != null && this.token.Text == "[")
                {
                    res_a = new Array();
                }

                for (int i = 0; i < this._items.Count; i++)
                {
                    if (this._items[i] is LineBreak)
                    {
                        if ((this._items[i] as LineBreak).Token.Text == "," && res_a == null)
                        {
                            throw new SyntaxException(string.Format("不正な文字です。 '{0}' 関数ではないものを関数のように扱っている可能性があります。",
                                                                    this._items[i].Token.Text), this._items[i]);
                        }
                        if (runtime.Setting.IsDebug)
                        {
                            Console.WriteLine("Eval Formula : " + f.ToString());
                        }
                        SyntaxAnalyzer.ConvertToRPEFormula ea = new SyntaxAnalyzer.ConvertToRPEFormula(
                            f, runtime.Setting);
                        res = ea.ConvertToRPE().Eval(runtime);

                        if (res_a != null)
                        {
                            res_a.Items[0].Add(res as INumber);                // '配列' 部の処理
                        }
                        f._items.Clear();
                    }
                    else
                    {
                        f._items.Add(this._items[i]);
                    }
                }

                if (res_a == null)
                {
                    return(res as INumber);
                }
                else // 配列作成でこの式を読んでいる場合は配列として返す
                {
                    return(res_a as INumber);
                }
            }
            else   // This.Items.Countが2以上のときじゃないと逆ポーランド式に変換sれない
            {
                SyntaxAnalyzer.ConvertToRPEFormula ea = new Analyzer.SyntaxAnalyzer.ConvertToRPEFormula(this, runtime.Setting);
                return(ea.ConvertToRPE().Eval(runtime));
            }
        }
Beispiel #14
0
 public AddEval(IEval left, IEval right) =>
 (_left, _right) = (left, right);
Beispiel #15
0
 public MultEval(IEval left, IEval right) =>
 (_left, _right) = (left, right);
Beispiel #16
0
 public EvalSub(IEval left, IEval right)
 {
     _left = left;
     _right = right;
 }