Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/SimpleArithmeticExpressionInterpreter.cs @ 5138

Last change on this file since 5138 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 10.8 KB
RevLine 
[3253]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
[4068]23using System.Collections.Generic;
[4722]24using HeuristicLab.Common;
[3253]25using HeuristicLab.Core;
26using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[4068]27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Compiler;
[3462]28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
[4068]29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[3373]30using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
[3253]31
[3373]32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[3253]33  [StorableClass]
[3462]34  [Item("SimpleArithmeticExpressionInterpreter", "Interpreter for arithmetic symbolic expression trees including function calls.")]
[3491]35  // not thread safe!
[4722]36  public sealed class SimpleArithmeticExpressionInterpreter : NamedItem, ISymbolicExpressionTreeInterpreter {
[3462]37    private class OpCodes {
38      public const byte Add = 1;
39      public const byte Sub = 2;
40      public const byte Mul = 3;
41      public const byte Div = 4;
[3841]42
43      public const byte Sin = 5;
44      public const byte Cos = 6;
45      public const byte Tan = 7;
46
47      public const byte Log = 8;
48      public const byte Exp = 9;
49
50      public const byte IfThenElse = 10;
51
52      public const byte GT = 11;
53      public const byte LT = 12;
54
55      public const byte AND = 13;
56      public const byte OR = 14;
57      public const byte NOT = 15;
58
59
60      public const byte Average = 16;
61
62      public const byte Call = 17;
63
64      public const byte Variable = 18;
65      public const byte LagVariable = 19;
66      public const byte Constant = 20;
67      public const byte Arg = 21;
[3462]68    }
69
[3841]70    private Dictionary<Type, byte> symbolToOpcode = new Dictionary<Type, byte>() {
71      { typeof(Addition), OpCodes.Add },
72      { typeof(Subtraction), OpCodes.Sub },
73      { typeof(Multiplication), OpCodes.Mul },
74      { typeof(Division), OpCodes.Div },
75      { typeof(Sine), OpCodes.Sin },
76      { typeof(Cosine), OpCodes.Cos },
77      { typeof(Tangent), OpCodes.Tan },
78      { typeof(Logarithm), OpCodes.Log },
79      { typeof(Exponential), OpCodes.Exp },
80      { typeof(IfThenElse), OpCodes.IfThenElse },
81      { typeof(GreaterThan), OpCodes.GT },
82      { typeof(LessThan), OpCodes.LT },
83      { typeof(And), OpCodes.AND },
84      { typeof(Or), OpCodes.OR },
85      { typeof(Not), OpCodes.NOT},
86      { typeof(Average), OpCodes.Average},
87      { typeof(InvokeFunction), OpCodes.Call },
88      { typeof(HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable), OpCodes.Variable },
89      { typeof(LaggedVariable), OpCodes.LagVariable },
90      { typeof(Constant), OpCodes.Constant },
91      { typeof(Argument), OpCodes.Arg },
92    };
[3491]93    private const int ARGUMENT_STACK_SIZE = 1024;
[3513]94
[3257]95    private Dataset dataset;
96    private int row;
[3294]97    private Instruction[] code;
98    private int pc;
[4022]99    private double[] argumentStack = new double[ARGUMENT_STACK_SIZE];
100    private int argStackPointer;
[3462]101
[3545]102    public override bool CanChangeName {
103      get { return false; }
104    }
105    public override bool CanChangeDescription {
106      get { return false; }
107    }
108
[4722]109    [StorableConstructor]
110    private SimpleArithmeticExpressionInterpreter(bool deserializing) : base(deserializing) { }
111    private SimpleArithmeticExpressionInterpreter(SimpleArithmeticExpressionInterpreter original, Cloner cloner) : base(original, cloner) { }
112
113    public override IDeepCloneable Clone(Cloner cloner) {
114      return new SimpleArithmeticExpressionInterpreter(this, cloner);
115    }
116
[3513]117    public SimpleArithmeticExpressionInterpreter()
118      : base() {
119    }
120
[3462]121    public IEnumerable<double> GetSymbolicExpressionTreeValues(SymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
[3257]122      this.dataset = dataset;
[3294]123      var compiler = new SymbolicExpressionTreeCompiler();
[3462]124      compiler.AddInstructionPostProcessingHook(PostProcessInstruction);
125      code = compiler.Compile(tree, MapSymbolToOpCode);
[3253]126      foreach (var row in rows) {
[3257]127        this.row = row;
[3294]128        pc = 0;
[3491]129        argStackPointer = 0;
[3513]130        yield return Evaluate();
[3253]131      }
132    }
133
[3462]134    private Instruction PostProcessInstruction(Instruction instr) {
135      if (instr.opCode == OpCodes.Variable) {
136        var variableTreeNode = instr.dynamicNode as VariableTreeNode;
137        instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
[3841]138      } else if (instr.opCode == OpCodes.LagVariable) {
139        var variableTreeNode = instr.dynamicNode as LaggedVariableTreeNode;
140        instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
141      }
[3462]142      return instr;
143    }
144
145    private byte MapSymbolToOpCode(SymbolicExpressionTreeNode treeNode) {
[3841]146      if (symbolToOpcode.ContainsKey(treeNode.Symbol.GetType()))
147        return symbolToOpcode[treeNode.Symbol.GetType()];
148      else
149        throw new NotSupportedException("Symbol: " + treeNode.Symbol);
[3462]150    }
151
[4022]152    private double Evaluate() {
153      Instruction currentInstr = code[pc++];
[3462]154      switch (currentInstr.opCode) {
155        case OpCodes.Add: {
[3996]156            double s = Evaluate();
157            for (int i = 1; i < currentInstr.nArguments; i++) {
[3294]158              s += Evaluate();
159            }
160            return s;
161          }
[3462]162        case OpCodes.Sub: {
[3294]163            double s = Evaluate();
164            for (int i = 1; i < currentInstr.nArguments; i++) {
165              s -= Evaluate();
166            }
[3733]167            if (currentInstr.nArguments == 1) s = -s;
[3294]168            return s;
169          }
[3462]170        case OpCodes.Mul: {
[3294]171            double p = Evaluate();
172            for (int i = 1; i < currentInstr.nArguments; i++) {
173              p *= Evaluate();
174            }
175            return p;
176          }
[3462]177        case OpCodes.Div: {
[3294]178            double p = Evaluate();
179            for (int i = 1; i < currentInstr.nArguments; i++) {
180              p /= Evaluate();
181            }
[3733]182            if (currentInstr.nArguments == 1) p = 1.0 / p;
[3294]183            return p;
184          }
[3841]185        case OpCodes.Average: {
186            double sum = Evaluate();
187            for (int i = 1; i < currentInstr.nArguments; i++) {
188              sum += Evaluate();
189            }
190            return sum / currentInstr.nArguments;
191          }
192        case OpCodes.Cos: {
193            return Math.Cos(Evaluate());
194          }
195        case OpCodes.Sin: {
196            return Math.Sin(Evaluate());
197          }
198        case OpCodes.Tan: {
199            return Math.Tan(Evaluate());
200          }
201        case OpCodes.Exp: {
202            return Math.Exp(Evaluate());
203          }
204        case OpCodes.Log: {
205            return Math.Log(Evaluate());
206          }
207        case OpCodes.IfThenElse: {
208            double condition = Evaluate();
209            double result;
210            if (condition > 0.0) {
211              result = Evaluate(); SkipBakedCode();
212            } else {
213              SkipBakedCode(); result = Evaluate();
214            }
215            return result;
216          }
217        case OpCodes.AND: {
218            double result = Evaluate();
219            for (int i = 1; i < currentInstr.nArguments; i++) {
220              if (result <= 0.0) SkipBakedCode();
221              else {
222                result = Evaluate();
223              }
224            }
225            return result <= 0.0 ? -1.0 : 1.0;
226          }
227        case OpCodes.OR: {
228            double result = Evaluate();
229            for (int i = 1; i < currentInstr.nArguments; i++) {
230              if (result > 0.0) SkipBakedCode();
231              else {
232                result = Evaluate();
233              }
234            }
235            return result > 0.0 ? 1.0 : -1.0;
236          }
237        case OpCodes.NOT: {
238            return -Evaluate();
239          }
240        case OpCodes.GT: {
241            double x = Evaluate();
242            double y = Evaluate();
243            if (x > y) return 1.0;
244            else return -1.0;
245          }
246        case OpCodes.LT: {
247            double x = Evaluate();
248            double y = Evaluate();
249            if (x < y) return 1.0;
250            else return -1.0;
251          }
[3462]252        case OpCodes.Call: {
[3409]253            // evaluate sub-trees
[3491]254            // push on argStack in reverse order
[3409]255            for (int i = 0; i < currentInstr.nArguments; i++) {
[3491]256              argumentStack[argStackPointer + currentInstr.nArguments - i] = Evaluate();
[3409]257            }
[3747]258            argStackPointer += currentInstr.nArguments;
[3491]259
[3409]260            // save the pc
261            int nextPc = pc;
262            // set pc to start of function 
263            pc = currentInstr.iArg0;
264            // evaluate the function
265            double v = Evaluate();
[3491]266
267            // decrease the argument stack pointer by the number of arguments pushed
268            // to set the argStackPointer back to the original location
269            argStackPointer -= currentInstr.nArguments;
270
[3409]271            // restore the pc => evaluation will continue at point after my subtrees 
272            pc = nextPc;
273            return v;
274          }
[3462]275        case OpCodes.Arg: {
[3491]276            return argumentStack[argStackPointer - currentInstr.iArg0];
[3409]277          }
[3462]278        case OpCodes.Variable: {
[3373]279            var variableTreeNode = currentInstr.dynamicNode as VariableTreeNode;
[3462]280            return dataset[row, currentInstr.iArg0] * variableTreeNode.Weight;
281          }
[3841]282        case OpCodes.LagVariable: {
283            var lagVariableTreeNode = currentInstr.dynamicNode as LaggedVariableTreeNode;
284            int actualRow = row + lagVariableTreeNode.Lag;
285            if (actualRow < 0 || actualRow >= dataset.Rows) throw new ArgumentException("Out of range access to dataset row: " + row);
286            return dataset[actualRow, currentInstr.iArg0] * lagVariableTreeNode.Weight;
287          }
[3462]288        case OpCodes.Constant: {
[3373]289            var constTreeNode = currentInstr.dynamicNode as ConstantTreeNode;
[3462]290            return constTreeNode.Value;
[3294]291          }
292        default: throw new NotSupportedException();
[3253]293      }
294    }
[3841]295
296    // skips a whole branch
[4722]297    private void SkipBakedCode() {
[3841]298      int i = 1;
299      while (i > 0) {
300        i += code[pc++].nArguments;
301        i--;
302      }
303    }
[3253]304  }
305}
Note: See TracBrowser for help on using the repository browser.