Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4249 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

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