Exemplo n.º 1
0
        private void Test(string input, string expectedX, string expectedY, string expectedZ, string expectedT)
        {
            string expected = string.Empty;
            string actual   = string.Empty;

            try
            {
                FunctionParser parser   = new FunctionParser();
                FunctionTree   function = parser.Parse(input);

                expected = expectedX;
                actual   = function.Expression.Derive(function.Parameters.X).ToString();
                Assert.AreEqual(expected, actual);

                expected = expectedY;
                actual   = function.Expression.Derive(function.Parameters.Y).ToString();
                Assert.AreEqual(expected, actual);

                expected = expectedZ;
                actual   = function.Expression.Derive(function.Parameters.Z).ToString();
                Assert.AreEqual(expected, actual);

                expected = expectedT;
                actual   = function.Expression.Derive(function.Parameters.T).ToString();
                Assert.AreEqual(expected, actual);
            }
            catch (Exception ex)
            {
                Assert.Fail(MessageHandler.GetMessage(ex, input, expected, actual));
            }
        }
Exemplo n.º 2
0
 // Returns NULL if request did not succeeed
 public static FunctionTree ML_FunctionList(int request, String name)
 {
     if (request == MLGUI.GetFunction)
     {
         foreach (FunctionEntry fe in MLGUI.ML_Functions)
         {
             if (fe.Name == name)
             {
                 return(fe.Function);
             }
         }
     }
     else if (request == MLGUI.RemoveItem)
     {
         foreach (FunctionEntry fe in MLGUI.ML_Functions)
         {
             if (fe.Name == name)
             {
                 FunctionTree temp = fe.Function;
                 MLGUI.ML_Functions.Remove(fe);
                 return(temp);
             }
         }
     }
     return(null);
 }
Exemplo n.º 3
0
        private void Test(string input, Type expectedException)
        {
            Exception actualException = null;

            try
            {
                try
                {
                    FunctionParser parser   = new FunctionParser();
                    FunctionTree   function = parser.Parse(input);

                    throw new ArgumentException();
                }
                catch (SyntaxException ex)
                {
                    actualException = ex;
                    Assert.AreEqual(expectedException.FullName, actualException.GetType().FullName);
                }
            }
            catch (Exception ex)
            {
                if (actualException == null)
                {
                    actualException = ex;
                }

                Assert.Fail(MessageHandler.GetMessage(ex, input, expectedException, actualException));
            }
        }
Exemplo n.º 4
0
        private static Node[] GetPartialDerivative(FunctionTree function)
        {
            Node[] result = new Node[4];
            result[0] = function.Expression.Derive(function.Parameters.X);
            result[1] = function.Expression.Derive(function.Parameters.Y);
            result[2] = function.Expression.Derive(function.Parameters.Z);
            result[3] = function.Expression.Derive(function.Parameters.T);

            return(result);
        }
Exemplo n.º 5
0
        public override void Train(IForecastingDataSets datasets)
        {
            OnStartRunning(new ComponentRunEventArgs(datasets));
            NumberOfVariables = datasets.InputVectorLength;
            NumberOfSamples   = datasets.Length;
            EnvolutionStep    = 0;
            if (functionSet == null)
            {
                functionSet = new GPFunctionSet();
            }
            Initialize();
            GenerateFunction();
            double [] gpConstraints = GenerateConstants(mGPModelParameter.ConstantsIntervalFrom, mGPModelParameter.ConstantsIntervalTo, mGPModelParameter.ConstantsNumber);
            GenerateTerminals(datasets, gpConstraints);

            if (population == null)
            {
                EnvolutionStep = 1;
                population     = new GPPopulation(mGPModelParameter.PopulationSize, terminalSet, functionSet, parameters, mGPModelParameter.MultipleCore);
            }
            GPBestHromosome = population.bestChromosome;

            while (ProveEnvolution(EnvolutionStep, mGPModelParameter.EnvolveConditionValue, mGPModelParameter.EnvolveIndicator))
            {
                population.StartEvolution();
                OnRunningEpoch(new ComponentRunEpochEventArgs(EnvolutionStep));
                EnvolutionStep++;
            }

            int        indexOutput = terminalSet.NumConstants + terminalSet.NumVariables - 1;
            List <int> lst         = new List <int>();

            FunctionTree.ToListExpression(lst, GPBestHromosome.Root);
            double y = 0;

            datasets.ForecastedData = new double[datasets.Length][];
            for (int i = 0; i < terminalSet.RowCount; i++)
            {
                // evalue the function
                y = functionSet.Evaluate(lst, terminalSet, i);

                // check for correct numeric value
                if (double.IsNaN(y) || double.IsInfinity(y))
                {
                    y = 0;
                }
                datasets.ForecastedData[i]    = new double[1];
                datasets.ForecastedData[i][0] = y;
            }
            OnFinishRunning(new ComponentRunEventArgs(datasets)
            {
                State = functionSet.DecodeExpression(lst, terminalSet)
            });
        }
Exemplo n.º 6
0
 public override double Forecast(double[] inputVector)
 {
     if (GPBestHromosome != null)
     {
         List <int> lst = new List <int>();
         FunctionTree.ToListExpression(lst, GPBestHromosome.Root);
         return(functionSet.Evaluate(lst, inputVector));
     }
     else
     {
         return(0);
     }
 }
Exemplo n.º 7
0
        private void Test(string input, string expected)
        {
            string actual = string.Empty;

            try
            {
                FunctionParser parser   = new FunctionParser();
                FunctionTree   function = parser.Parse(input);
                actual = function.Expression.ToString();

                Assert.AreEqual(expected, actual);
            }
            catch (Exception ex)
            {
                Assert.Fail(MessageHandler.GetMessage(ex, input, expected, actual));
            }
        }
Exemplo n.º 8
0
        public static FunctionEntry ML_FunctionListSecondary(int request, String funcStr)
        {
            if (request == MLGUI.GetFunctionFromExpression)
            {
                FunctionTree newFunc    = new FunctionTree(funcStr);
                String       newFuncStr = newFunc.ToString();

                // Crude Function Comparison
                foreach (FunctionEntry fe in MLGUI.ML_Functions)
                {
                    if (fe.Function.ToString() == newFuncStr)
                    {
                        return(fe);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Write("> ");
                string line = Console.ReadLine();

                if (line == "quit" || line == "exit")
                {
                    return;
                }

                string[] input = GetInput(line);
                if (input == null)
                {
                    continue;
                }

                FunctionTree function = ParseFunction(input[0]);
                if (function == null)
                {
                    continue;
                }

                double[] values = ParseValues(input, line);
                if (values == null)
                {
                    continue;
                }

                Node[] partialDerivative = GetPartialDerivative(function);

                Console.WriteLine();
                WriteFunction(function.Expression);
                WriteFunctionValue(function.Expression, values);
                WritePartialDerivative(partialDerivative);
                WritePartialDerivativeValue(partialDerivative, values);
                Console.WriteLine();
            }
        }
Exemplo n.º 10
0
        public static bool IsExistingFunctionName(string str)
        {
            // Parse str and check for possible function name match
            // Assign is_existingFunc

            str = str.Trim(notAllowedInFuncName);

            if (str == "")
            {
                return(false);
            }

            foreach (FunctionEntry fe in MLGUI.ML_Functions)
            {
                if (fe.Name == str)
                {
                    is_existingFunc = fe.Function;
                    return(true);
                }
            }


            return(false);
        }
Exemplo n.º 11
0
 public FunctionEntry(string n, FunctionTree f)
 {
     Name     = n;
     Function = f;
 }
Exemplo n.º 12
0
        public static FunctionTree ML_FunctionList(int request, String name, String funcStr)
        {
            if (request == MLGUI.UpdateFunctionExpression)
            {
                foreach (FunctionEntry fe in MLGUI.ML_Functions)
                {
                    if (fe.Name == name)
                    {
                        fe.Function = new FunctionTree(funcStr);
                        if (fe.Function.HasNoVariables())
                        {
                            ML_VariableList(MLGUI.AddItem, name, fe.Function.GetValue());
                            return(null);
                        }
                        else
                        {
                            return(fe.Function);
                        }
                    }
                }
            }
            else if (request == MLGUI.GetFunction)
            {
                foreach (FunctionEntry fe in MLGUI.ML_Functions)
                {
                    if (fe.Name == name)
                    {
                        return(fe.Function);
                    }
                }
            }
            else if (request == MLGUI.AddItem)
            {
                FunctionTree newFunc    = new FunctionTree(funcStr);
                String       newFuncStr = newFunc.ToString();

                //r3.Text += "vars ";
                //foreach (FVar v in newFunc.varList) r3.Text+=v.varName + " ";

                // Crude Function Comparison
                foreach (FunctionEntry fe in MLGUI.ML_Functions)
                {
                    if (fe.Function.ToString() == newFuncStr)
                    {
                        if (name != "")
                        {
                            fe.Name = name;
                        }
                        return(fe.Function);
                    }
                }

                if (name == "")
                {
                    int  x         = 1;
                    bool nameTaken = true;
                    while (nameTaken)
                    {
                        name      = "f" + x;
                        nameTaken = false;

                        foreach (FunctionEntry fe in MLGUI.ML_Functions)
                        {
                            if (fe.Name == name)
                            {
                                nameTaken = true;
                                break;
                            }
                            else
                            {
                                nameTaken = false;
                            }
                        }

                        if (nameTaken)
                        {
                            x++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    MLGUI.lastFunctionEntry = new FunctionEntry(name, newFunc);
                    MLGUI.ML_Functions.Add(MLGUI.lastFunctionEntry);
                    return(newFunc);
                }
                else
                {
                    foreach (FunctionEntry fe in MLGUI.ML_Functions)
                    {
                        if (fe.Name == name)
                        {
                            fe.Function = new FunctionTree(funcStr);
                            return(fe.Function);
                        }
                    }

                    ML_VariableList(MLGUI.RemoveItem, name);

                    MLGUI.lastFunctionEntry = new FunctionEntry(name, newFunc);
                    MLGUI.ML_Functions.Add(MLGUI.lastFunctionEntry);

                    if (MLGUI.lastFunctionEntry.Function.HasNoVariables())
                    {
                        ML_VariableList(MLGUI.AddItem, name, MLGUI.lastFunctionEntry.Function.GetValue());
                    }
                    else
                    {
                        return(newFunc);
                    }
                }
            }
            else if (request == MLGUI.RemoveItem)
            {
                foreach (FunctionEntry fe in MLGUI.ML_Functions)
                {
                    if (fe.Name == name)
                    {
                        FunctionTree temp = fe.Function;
                        MLGUI.ML_Functions.Remove(fe);
                        return(temp);
                    }
                }
            }
            else if (request == MLGUI.RemoveLastItem)
            {
                MLGUI.ML_Functions.Remove(MLGUI.lastFunctionEntry);
                return(MLGUI.lastFunctionEntry.Function);
            }
            return(null);
        }
Exemplo n.º 13
0
        public static void ParseCommand()
        {
            // commands = { "solve", "value", "derivative", "integral", "roots", "plot" , "simplify"};

            switch (comm_inx)
            {
            case 0:         // solve
            case 1:         // value
            {
            }
            break;

            case 2:         // derivative
            {
                int bracket = 0;

                // Parse Function
                while (NotEnd())
                {
                    if (bracket == 0 && p_line[inx] == ',')
                    {
                        break;
                    }
                    if (p_line[inx] == '(')
                    {
                        bracket++;
                    }
                    if (p_line[inx] == ')')
                    {
                        bracket--;
                    }
                    synline[syn_inx] += p_line[inx];
                    inx++;
                }

                if (synline[syn_inx] == "")
                {
                    syntaxError = true;
                    Error();
                    break;
                }

                bool isVariable     = false;
                bool isFunction     = false;
                bool isFunctionName = false;

                int func_fn_inx = 0;
                int var_fn_inx  = 0;

                // Try Parsing Function or Variable
                // All Variables get Added to ML_Variables
                if (isFunctionName = IsExistingFunctionName(synline[syn_inx]))
                {
                    funcs[func_inx] = is_existingFunc;
                    func_inx++;

                    if (End())
                    {
                        output[output_inx] = funcs[func_fn_inx].GetDerivative(funcs[func_fn_inx].VarList[0]).ToString();
                        break;
                    }
                }
                else if (isVariable = IsVariable(synline[syn_inx]))
                {
                    vars[var_inx] = ListHandler.ML_VariableList(MLGUI.AddItem, is_var);
                    var_fn_inx    = var_inx;
                    var_inx++;

                    if (End())
                    {
                        FunctionTree temp = new FunctionTree(vars[var_fn_inx]);
                        output[output_inx] = temp.GetDerivative(vars[var_fn_inx]).ToString();
                        break;
                    }
                }
                else if (isFunction = IsFunction(synline[syn_inx]))
                {
                    funcs[func_inx] = ListHandler.ML_FunctionList(MLGUI.AddItem, "", is_func);
                    func_fn_inx     = func_inx;
                    func_inx++;

                    if (End())
                    {
                        output[output_inx] = funcs[func_fn_inx].GetDerivative(funcs[func_fn_inx].VarList[0]).ToString();
                        break;
                    }
                }
                else
                {
                    syntaxError = true;
                    Error();
                    break;
                }

                // Parse Further
                SkipSpaces();
                inx--;
                if (End())
                {
                    break;
                }

                bool   wrtSet       = false;
                FVar   wrtVar       = null;
                double wrtVarVal    = 0;
                bool   wrtVarValSet = false;
                syn_inx++;
                List <string> varEqList = new List <string>();

                // Next vars[var_inx] Entry will be the w.r.t. variable
                int func_sl_inx = syn_inx;

                // Parse rest of the line
                // Requires addition of "," at end
                p_line = p_line + ",";
                p_len  = p_line.Length;

                inx++;

                while (NotEnd())
                {
                    if (p_line[inx] == ',')
                    {
                        if (!isVariable && IsEquation(synline[syn_inx]) && SplitEquation(synline[syn_inx], VariableAssignment))
                        {
                            if (ListHandler.ML_VariableList(MLGUI.UpdateVariableValue, is_var, is_val) == null)
                            {
                                syntaxError = true;
                                break;
                            }
                            else
                            {
                                varEqList.Add(is_var);
                            }
                        }
                        else if (IsNumber(synline[syn_inx]) && !wrtVarValSet)
                        {
                            wrtVarVal = is_val;
                            if (wrtSet)
                            {
                                ListHandler.ML_VariableList(MLGUI.UpdateVariableValue, wrtVar.varName, is_val);
                                wrtVarVal = is_val;
                            }
                            wrtVarValSet = true;
                        }
                        else if (IsVariable(synline[syn_inx]) && !wrtSet)
                        {
                            wrtVar = ListHandler.ML_VariableList(MLGUI.AddItem, is_var);
                            wrtSet = true;
                        }
                        else
                        {
                            syntaxError = true;
                            break;
                        }
                        syn_inx++;
                    }
                    else
                    {
                        synline[syn_inx] += p_line[inx];
                    }

                    inx++;
                }

                if (Error())
                {
                    break;
                }

                if (isVariable)
                {
                    if (!wrtSet)
                    {
                        wrtVar = vars[var_fn_inx];
                        if (wrtVarValSet)
                        {
                            ListHandler.ML_VariableList(MLGUI.UpdateVariableValue, wrtVar.varName, wrtVarVal);
                        }
                    }

                    output[output_inx] += vars[var_fn_inx].GetDerivative(wrtVar).ToString();
                    break;
                }

                if (!wrtSet)
                {
                    wrtVar = funcs[func_fn_inx].varList[0];
                }

                if (wrtVarValSet)
                {
                    ListHandler.ML_VariableList(MLGUI.UpdateVariableValue, wrtVar.varName, wrtVarVal);
                }

                FunctionTree copy = funcs[func_fn_inx].GetCopy();

                foreach (string varEq in varEqList)
                {
                    if (varEq == wrtVar.varName)
                    {
                        continue;
                    }
                    if (!copy.VariableToSetValue(varEq))
                    {
                        syntaxError = true;
                        break;
                    }
                }

                FunctionTree der = copy.GetDerivative(wrtVar);

                if (Error())
                {
                    break;
                }

                // Store result in output string
                if (der.varList.Count == 0)
                {
                    output[output_inx] = der.GetValue().ToString();

                    // Important to figure out properly
                    comm_isAnsNumVal = true;

                    // Single answer
                    ListHandler.ML_FunctionList(MLGUI.RemoveItem, "ans");
                    ListHandler.ML_VariableList(MLGUI.RemoveItem, "ans");

                    ListHandler.ML_VariableList(MLGUI.AddItem, "ans", der.GetValue());
                }
                else
                {
                    output[output_inx] = der.ToString();

                    if (der.CanHaveValue())
                    {
                        string derVal = der.GetValue().ToString();

                        if (!(derVal == output[output_inx]))
                        {
                            output_inx++;
                            output[output_inx] = derVal;

                            // Important to figure out properly
                            comm_isAnsFunc   = true;
                            comm_isAnsNumVal = true;

                            // Two Answers
                            ListHandler.ML_FunctionList(MLGUI.RemoveItem, "ans0");
                            ListHandler.ML_VariableList(MLGUI.RemoveItem, "ans0");
                            ListHandler.ML_FunctionList(MLGUI.RemoveItem, "ans");
                            ListHandler.ML_VariableList(MLGUI.RemoveItem, "ans");

                            ListHandler.ML_FunctionList(MLGUI.AddItem, "ans0", der.ToString());
                            ListHandler.ML_VariableList(MLGUI.AddItem, "ans", der.GetValue());
                        }
                        else
                        {
                            // Important to figure out properly
                            comm_isAnsNumVal = true;
                            ListHandler.ML_FunctionList(MLGUI.RemoveItem, "ans");
                            ListHandler.ML_VariableList(MLGUI.RemoveItem, "ans");

                            ListHandler.ML_VariableList(MLGUI.AddItem, "ans", der.GetValue());
                        }
                    }
                    else
                    {
                        // Important to figure out properly
                        comm_isAnsFunc = true;

                        // Single answer
                        ListHandler.ML_FunctionList(MLGUI.RemoveItem, "ans");
                        ListHandler.ML_VariableList(MLGUI.RemoveItem, "ans");

                        ListHandler.ML_FunctionList(MLGUI.AddItem, "ans", der.ToString());
                    }
                }
            }
            break;

            case 3:         // integral
            {
            }
            break;

            case 4:         // roots
            {
            }
            break;

            case 5:         // plot
            {
            }
            break;

            case 6:         // simplify
            {
            }
            break;

            case 7:         // cls
            {
                r2.SelectAll(); r2.SelectionProtected = false;
                r2.Clear();
                r3.Clear();
                mlgui.AddLineNumbers(0);
            }
            break;

            default: break;
            }
        }
Exemplo n.º 14
0
        public static void ProcessInput(int startpoint)
        {
            processing = true;

            if (startpoint == 0)
            {
                r3.Text = "";
            }

            noOfLines = r2.Lines.Length - 1;

            int u = startpoint;      // process only last line

            for (; u < noOfLines; u++)
            {
                cuurrentLineNo = u;
                Initialize();
                show_output = true;

                p_line = r2.Lines[u];
                p_line = p_line.Trim(' ');
                if (p_line == "")
                {
                    continue;
                }
                if (p_line[p_line.Length - 1] == ';')
                {
                    show_output = false;
                }
                p_line = p_line.Trim(';');
                p_len  = p_line.Length;
                if (p_len == 0)
                {
                    continue;
                }

                // Skip Initial Spaces
                SkipSpaces();
                inx--;
                if (End())
                {
                    continue;
                }

                // Store This Point;
                beginInx = inx;

                if (IsCommand())
                {
                    // Skip Spaces
                    SkipSpaces();
                    inx--;
                    if (End())
                    {
                        continue;
                    }

                    ParseCommand();
                }
                else if (IsEquation(p_line))
                {
                    if (SplitEquation(p_line, VariableAssignment))
                    {
                        FVar temp = null;
                        if ((temp = ListHandler.ML_VariableList(MLGUI.GetVariable, is_var)) != null)
                        {
                            ListHandler.ML_VariableList(MLGUI.UpdateVariableValue, temp.varName, is_val);
                        }
                        else
                        {
                            ListHandler.ML_VariableList(MLGUI.AddItem, is_var, is_val);
                        }
                    }
                    else if (SplitEquation(p_line, FunctionAssignment))
                    {
                        FunctionTree temp = null;
                        if ((temp = ListHandler.ML_FunctionList(MLGUI.GetFunction, is_var)) != null)
                        {
                            ListHandler.ML_FunctionList(MLGUI.UpdateFunctionExpression, is_var, is_func);
                        }
                        else
                        {
                            ListHandler.ML_FunctionList(MLGUI.AddItem, is_var, is_func);
                        }

                        //foreach (FVar v in temp.varList)
                        //{
                        //if (ListHandler.ML_FunctionList(MLGUI.GetFunction, v.varName))
                        //}
                    }
                    else
                    {
                        syntaxError = true;
                        Error();
                    }
                }
                else if (IsVariable(p_line))
                {
                    ListHandler.ML_VariableList(MLGUI.RemoveItem, is_var);
                    ListHandler.ML_VariableList(MLGUI.AddItem, is_var);
                }
                else if (IsFunction(p_line))
                {
                    FunctionEntry temp = null;
                    if ((temp = ListHandler.ML_FunctionListSecondary(MLGUI.GetFunctionFromExpression, is_func)) != null)
                    {
                        r2.AppendText(temp.Name);
                        r2.SelectionStart = r2.TextLength;
                        r2.ScrollToCaret();
                    }
                    else
                    {
                        ListHandler.ML_FunctionList(MLGUI.AddItem, "", is_func);
                    }
                }
                else
                {
                    parseError = true;
                    Error();
                }

                if (output[0] != "" && show_output)
                {
                    string lu = (u + 1) + "";
                    r3.AppendText("line-" + lu);
                    for (int o = 0; o < (5 - lu.Length); o++)
                    {
                        r3.Text += "  ";
                    }
                    r3.AppendText("\t" + output[0] + "\n");

                    int z = 1;
                    while (output[z] != "" && z < output.Length)
                    {
                        for (int o = 0; o < 10; o++)
                        {
                            r3.Text += "  ";
                        }
                        r3.AppendText("\t" + output[z] + "\n");
                        z++;
                    }
                }
            }
            processing = false;
        }