Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/SimpleArithmeticExpressionInterpreter.cs @ 4695

Last change on this file since 4695 was 4193, checked in by gkronber, 14 years ago

Created a feature/exploration branch for new data analysis features #1142

File size: 11.2 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      public const byte Differential = 22;
68    }
69
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      { typeof(DifferentialVariable), OpCodes.Differential},
93    };
94    private const int ARGUMENT_STACK_SIZE = 1024;
95
96    private Dataset dataset;
97    private int row;
98    private Instruction[] code;
99    private int pc;
100    private double[] argumentStack = new double[ARGUMENT_STACK_SIZE];
101    private int argStackPointer;
102
103    public override bool CanChangeName {
104      get { return false; }
105    }
106    public override bool CanChangeDescription {
107      get { return false; }
108    }
109
110    public SimpleArithmeticExpressionInterpreter()
111      : base() {
112    }
113
114    public IEnumerable<double> GetSymbolicExpressionTreeValues(SymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
115      this.dataset = dataset;
116      var compiler = new SymbolicExpressionTreeCompiler();
117      compiler.AddInstructionPostProcessingHook(PostProcessInstruction);
118      code = compiler.Compile(tree, MapSymbolToOpCode);
119      foreach (var row in rows) {
120        this.row = row;
121        pc = 0;
122        argStackPointer = 0;
123        yield return Evaluate();
124      }
125    }
126
127    private Instruction PostProcessInstruction(Instruction instr) {
128      if (instr.opCode == OpCodes.Variable) {
129        var variableTreeNode = instr.dynamicNode as VariableTreeNode;
130        instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
131      } else if (instr.opCode == OpCodes.LagVariable) {
132        var variableTreeNode = instr.dynamicNode as LaggedVariableTreeNode;
133        instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
134      } else if (instr.opCode == OpCodes.Differential) {
135        var variableTreeNode = instr.dynamicNode as DifferentialVariableTreeNode;
136        instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
137      }
138      return instr;
139    }
140
141    private byte MapSymbolToOpCode(SymbolicExpressionTreeNode treeNode) {
142      if (symbolToOpcode.ContainsKey(treeNode.Symbol.GetType()))
143        return symbolToOpcode[treeNode.Symbol.GetType()];
144      else
145        throw new NotSupportedException("Symbol: " + treeNode.Symbol);
146    }
147
148    private double Evaluate() {
149      Instruction currentInstr = code[pc++];
150      switch (currentInstr.opCode) {
151        case OpCodes.Add: {
152            double s = Evaluate();
153            for (int i = 1; i < currentInstr.nArguments; i++) {
154              s += Evaluate();
155            }
156            return s;
157          }
158        case OpCodes.Sub: {
159            double s = Evaluate();
160            for (int i = 1; i < currentInstr.nArguments; i++) {
161              s -= Evaluate();
162            }
163            if (currentInstr.nArguments == 1) s = -s;
164            return s;
165          }
166        case OpCodes.Mul: {
167            double p = Evaluate();
168            for (int i = 1; i < currentInstr.nArguments; i++) {
169              p *= Evaluate();
170            }
171            return p;
172          }
173        case OpCodes.Div: {
174            double p = Evaluate();
175            for (int i = 1; i < currentInstr.nArguments; i++) {
176              p /= Evaluate();
177            }
178            if (currentInstr.nArguments == 1) p = 1.0 / p;
179            return p;
180          }
181        case OpCodes.Average: {
182            double sum = Evaluate();
183            for (int i = 1; i < currentInstr.nArguments; i++) {
184              sum += Evaluate();
185            }
186            return sum / currentInstr.nArguments;
187          }
188        case OpCodes.Cos: {
189            return Math.Cos(Evaluate());
190          }
191        case OpCodes.Sin: {
192            return Math.Sin(Evaluate());
193          }
194        case OpCodes.Tan: {
195            return Math.Tan(Evaluate());
196          }
197        case OpCodes.Exp: {
198            return Math.Exp(Evaluate());
199          }
200        case OpCodes.Log: {
201            return Math.Log(Evaluate());
202          }
203        case OpCodes.IfThenElse: {
204            double condition = Evaluate();
205            double result;
206            if (condition > 0.0) {
207              result = Evaluate(); SkipBakedCode();
208            } else {
209              SkipBakedCode(); result = Evaluate();
210            }
211            return result;
212          }
213        case OpCodes.AND: {
214            double result = Evaluate();
215            for (int i = 1; i < currentInstr.nArguments; i++) {
216              if (result <= 0.0) SkipBakedCode();
217              else {
218                result = Evaluate();
219              }
220            }
221            return result <= 0.0 ? -1.0 : 1.0;
222          }
223        case OpCodes.OR: {
224            double result = Evaluate();
225            for (int i = 1; i < currentInstr.nArguments; i++) {
226              if (result > 0.0) SkipBakedCode();
227              else {
228                result = Evaluate();
229              }
230            }
231            return result > 0.0 ? 1.0 : -1.0;
232          }
233        case OpCodes.NOT: {
234            return -Evaluate();
235          }
236        case OpCodes.GT: {
237            double x = Evaluate();
238            double y = Evaluate();
239            if (x > y) return 1.0;
240            else return -1.0;
241          }
242        case OpCodes.LT: {
243            double x = Evaluate();
244            double y = Evaluate();
245            if (x < y) return 1.0;
246            else return -1.0;
247          }
248        case OpCodes.Call: {
249            // evaluate sub-trees
250            // push on argStack in reverse order
251            for (int i = 0; i < currentInstr.nArguments; i++) {
252              argumentStack[argStackPointer + currentInstr.nArguments - i] = Evaluate();
253            }
254            argStackPointer += currentInstr.nArguments;
255
256            // save the pc
257            int nextPc = pc;
258            // set pc to start of function 
259            pc = currentInstr.iArg0;
260            // evaluate the function
261            double v = Evaluate();
262
263            // decrease the argument stack pointer by the number of arguments pushed
264            // to set the argStackPointer back to the original location
265            argStackPointer -= currentInstr.nArguments;
266
267            // restore the pc => evaluation will continue at point after my subtrees 
268            pc = nextPc;
269            return v;
270          }
271        case OpCodes.Arg: {
272            return argumentStack[argStackPointer - currentInstr.iArg0];
273          }
274        case OpCodes.Variable: {
275            var variableTreeNode = currentInstr.dynamicNode as VariableTreeNode;
276            return dataset[row, currentInstr.iArg0] * variableTreeNode.Weight;
277          }
278        case OpCodes.LagVariable: {
279            var lagVariableTreeNode = currentInstr.dynamicNode as LaggedVariableTreeNode;
280            int actualRow = row + lagVariableTreeNode.Lag;
281            if (actualRow < 0 || actualRow >= dataset.Rows) throw new ArgumentException("Out of range access to dataset row: " + row);
282            return dataset[actualRow, currentInstr.iArg0] * lagVariableTreeNode.Weight;
283          }
284        case OpCodes.Differential: {
285            var diffTreeNode = currentInstr.dynamicNode as DifferentialVariableTreeNode;
286            if (row < 2 || row >= dataset.Rows - 2) throw new ArgumentException("Out of range access to dataset row: " + row);
287            return (-dataset[row + 2, currentInstr.iArg0] + 8 * dataset[row + 1, currentInstr.iArg0] - 8 * dataset[row - 1, currentInstr.iArg0] + dataset[row - 2, currentInstr.iArg0]) * (1.0/12.0) * diffTreeNode.Weight;
288          }
289
290        case OpCodes.Constant: {
291            var constTreeNode = currentInstr.dynamicNode as ConstantTreeNode;
292            return constTreeNode.Value;
293          }
294        default: throw new NotSupportedException();
295      }
296    }
297
298    // skips a whole branch
299    protected void SkipBakedCode() {
300      int i = 1;
301      while (i > 0) {
302        i += code[pc++].nArguments;
303        i--;
304      }
305    }
306  }
307}
Note: See TracBrowser for help on using the repository browser.