Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5433 was 5396, checked in by gkronber, 14 years ago

#1400. Refactored interpreter for symbolic expression trees.

File size: 15.9 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.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Compiler;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [StorableClass]
34  [Item("SimpleArithmeticExpressionInterpreter", "Interpreter for arithmetic symbolic expression trees including function calls.")]
35  public sealed class SimpleArithmeticExpressionInterpreter : NamedItem, ISymbolicExpressionTreeInterpreter {
36    private class InterpreterState {
37      private const int ARGUMENT_STACK_SIZE = 1024;
38      private double[] argumentStack;
39      private int argumentStackPointer;
40      private Instruction[] code;
41      private int pc;
42      public int ProgramCounter {
43        get { return pc; }
44        set { pc = value; }
45      }
46      internal InterpreterState(Instruction[] code) {
47        this.code = code;
48        this.pc = 0;
49        this.argumentStack = new double[ARGUMENT_STACK_SIZE];
50        this.argumentStackPointer = 0;
51      }
52
53      internal void Reset() {
54        this.pc = 0;
55        this.argumentStackPointer = 0;
56      }
57
58      internal Instruction NextInstruction() {
59        return code[pc++];
60      }
61      private void Push(double val) {
62        argumentStack[argumentStackPointer++] = val;
63      }
64      private double Pop() {
65        return argumentStack[--argumentStackPointer];
66      }
67
68      internal void CreateStackFrame(double[] argValues) {
69        // push in reverse order to make indexing easier
70        for (int i = argValues.Length - 1; i >= 0; i--) {
71          argumentStack[argumentStackPointer++] = argValues[i];
72        }
73        Push(argValues.Length);
74      }
75
76      internal void RemoveStackFrame() {
77        int size = (int)Pop();
78        argumentStackPointer -= size;
79      }
80
81      internal double GetStackFrameValue(ushort index) {
82        // layout of stack:
83        // [0]   <- argumentStackPointer
84        // [StackFrameSize = N + 1]
85        // [Arg0] <- argumentStackPointer - 2 - 0
86        // [Arg1] <- argumentStackPointer - 2 - 1
87        // [...]
88        // [ArgN] <- argumentStackPointer - 2 - N
89        // <Begin of stack frame>
90        return argumentStack[argumentStackPointer - index - 2];
91      }
92    }
93
94    private class OpCodes {
95      public const byte Add = 1;
96      public const byte Sub = 2;
97      public const byte Mul = 3;
98      public const byte Div = 4;
99
100      public const byte Sin = 5;
101      public const byte Cos = 6;
102      public const byte Tan = 7;
103
104      public const byte Log = 8;
105      public const byte Exp = 9;
106
107      public const byte IfThenElse = 10;
108
109      public const byte GT = 11;
110      public const byte LT = 12;
111
112      public const byte AND = 13;
113      public const byte OR = 14;
114      public const byte NOT = 15;
115
116
117      public const byte Average = 16;
118
119      public const byte Call = 17;
120
121      public const byte Variable = 18;
122      public const byte LagVariable = 19;
123      public const byte Constant = 20;
124      public const byte Arg = 21;
125
126      public const byte Power = 22;
127      public const byte Root = 23;
128      public const byte TimeLag = 24;
129      public const byte Integral = 25;
130      public const byte Derivative = 26;
131    }
132
133    private Dictionary<Type, byte> symbolToOpcode = new Dictionary<Type, byte>() {
134      { typeof(Addition), OpCodes.Add },
135      { typeof(Subtraction), OpCodes.Sub },
136      { typeof(Multiplication), OpCodes.Mul },
137      { typeof(Division), OpCodes.Div },
138      { typeof(Sine), OpCodes.Sin },
139      { typeof(Cosine), OpCodes.Cos },
140      { typeof(Tangent), OpCodes.Tan },
141      { typeof(Logarithm), OpCodes.Log },
142      { typeof(Exponential), OpCodes.Exp },
143      { typeof(IfThenElse), OpCodes.IfThenElse },
144      { typeof(GreaterThan), OpCodes.GT },
145      { typeof(LessThan), OpCodes.LT },
146      { typeof(And), OpCodes.AND },
147      { typeof(Or), OpCodes.OR },
148      { typeof(Not), OpCodes.NOT},
149      { typeof(Average), OpCodes.Average},
150      { typeof(InvokeFunction), OpCodes.Call },
151      { typeof(HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable), OpCodes.Variable },
152      { typeof(LaggedVariable), OpCodes.LagVariable },
153      { typeof(Constant), OpCodes.Constant },
154      { typeof(Argument), OpCodes.Arg },
155      { typeof(Power),OpCodes.Power},
156      { typeof(Root),OpCodes.Root},
157      { typeof(TimeLag), OpCodes.TimeLag},
158      { typeof(Integral), OpCodes.Integral},
159      { typeof(Derivative), OpCodes.Derivative},
160    };
161
162
163    public override bool CanChangeName {
164      get { return false; }
165    }
166    public override bool CanChangeDescription {
167      get { return false; }
168    }
169
170    [StorableConstructor]
171    private SimpleArithmeticExpressionInterpreter(bool deserializing) : base(deserializing) { }
172    private SimpleArithmeticExpressionInterpreter(SimpleArithmeticExpressionInterpreter original, Cloner cloner) : base(original, cloner) { }
173    public override IDeepCloneable Clone(Cloner cloner) {
174      return new SimpleArithmeticExpressionInterpreter(this, cloner);
175    }
176
177    public SimpleArithmeticExpressionInterpreter()
178      : base() {
179    }
180
181    public IEnumerable<double> GetSymbolicExpressionTreeValues(SymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
182      var compiler = new SymbolicExpressionTreeCompiler();
183      Instruction[] code = compiler.Compile(tree, MapSymbolToOpCode);
184
185      for (int i = 0; i < code.Length; i++) {
186        Instruction instr = code[i];
187        if (instr.opCode == OpCodes.Variable) {
188          var variableTreeNode = instr.dynamicNode as VariableTreeNode;
189          instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
190          code[i] = instr;
191        } else if (instr.opCode == OpCodes.LagVariable) {
192          var variableTreeNode = instr.dynamicNode as LaggedVariableTreeNode;
193          instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
194          code[i] = instr;
195        }
196      }
197      var state = new InterpreterState(code);
198
199      foreach (var rowEnum in rows) {
200        int row = rowEnum;
201        state.Reset();
202        yield return Evaluate(dataset, ref row, state);
203      }
204    }
205
206    private double Evaluate(Dataset dataset, ref int row, InterpreterState state) {
207      Instruction currentInstr = state.NextInstruction();
208      switch (currentInstr.opCode) {
209        case OpCodes.Add: {
210            double s = Evaluate(dataset, ref row, state);
211            for (int i = 1; i < currentInstr.nArguments; i++) {
212              s += Evaluate(dataset, ref row, state);
213            }
214            return s;
215          }
216        case OpCodes.Sub: {
217            double s = Evaluate(dataset, ref row, state);
218            for (int i = 1; i < currentInstr.nArguments; i++) {
219              s -= Evaluate(dataset, ref row, state);
220            }
221            if (currentInstr.nArguments == 1) s = -s;
222            return s;
223          }
224        case OpCodes.Mul: {
225            double p = Evaluate(dataset, ref row, state);
226            for (int i = 1; i < currentInstr.nArguments; i++) {
227              p *= Evaluate(dataset, ref row, state);
228            }
229            return p;
230          }
231        case OpCodes.Div: {
232            double p = Evaluate(dataset, ref row, state);
233            for (int i = 1; i < currentInstr.nArguments; i++) {
234              p /= Evaluate(dataset, ref row, state);
235            }
236            if (currentInstr.nArguments == 1) p = 1.0 / p;
237            return p;
238          }
239        case OpCodes.Average: {
240            double sum = Evaluate(dataset, ref row, state);
241            for (int i = 1; i < currentInstr.nArguments; i++) {
242              sum += Evaluate(dataset, ref row, state);
243            }
244            return sum / currentInstr.nArguments;
245          }
246        case OpCodes.Cos: {
247            return Math.Cos(Evaluate(dataset, ref row, state));
248          }
249        case OpCodes.Sin: {
250            return Math.Sin(Evaluate(dataset, ref row, state));
251          }
252        case OpCodes.Tan: {
253            return Math.Tan(Evaluate(dataset, ref row, state));
254          }
255        case OpCodes.Power: {
256            double x = Evaluate(dataset, ref row, state);
257            double y = Math.Round(Evaluate(dataset, ref row, state));
258            return Math.Pow(x, y);
259          }
260        case OpCodes.Root: {
261            double x = Evaluate(dataset, ref row, state);
262            double y = Math.Round(Evaluate(dataset, ref row, state));
263            return Math.Pow(x, 1 / y);
264          }
265        case OpCodes.Exp: {
266            return Math.Exp(Evaluate(dataset, ref row, state));
267          }
268        case OpCodes.Log: {
269            return Math.Log(Evaluate(dataset, ref row, state));
270          }
271        case OpCodes.IfThenElse: {
272            double condition = Evaluate(dataset, ref row, state);
273            double result;
274            if (condition > 0.0) {
275              result = Evaluate(dataset, ref row, state); SkipInstructions(state);
276            } else {
277              SkipInstructions(state); result = Evaluate(dataset, ref row, state);
278            }
279            return result;
280          }
281        case OpCodes.AND: {
282            double result = Evaluate(dataset, ref row, state);
283            for (int i = 1; i < currentInstr.nArguments; i++) {
284              if (result <= 0.0) SkipInstructions(state);
285              else {
286                result = Evaluate(dataset, ref row, state);
287              }
288            }
289            return result <= 0.0 ? -1.0 : 1.0;
290          }
291        case OpCodes.OR: {
292            double result = Evaluate(dataset, ref row, state);
293            for (int i = 1; i < currentInstr.nArguments; i++) {
294              if (result > 0.0) SkipInstructions(state);
295              else {
296                result = Evaluate(dataset, ref row, state);
297              }
298            }
299            return result > 0.0 ? 1.0 : -1.0;
300          }
301        case OpCodes.NOT: {
302            return -Evaluate(dataset, ref row, state);
303          }
304        case OpCodes.GT: {
305            double x = Evaluate(dataset, ref row, state);
306            double y = Evaluate(dataset, ref row, state);
307            if (x > y) return 1.0;
308            else return -1.0;
309          }
310        case OpCodes.LT: {
311            double x = Evaluate(dataset, ref row, state);
312            double y = Evaluate(dataset, ref row, state);
313            if (x < y) return 1.0;
314            else return -1.0;
315          }
316        case OpCodes.TimeLag: {
317            var timeLagTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
318            if (row + timeLagTreeNode.Lag < 0 || row + timeLagTreeNode.Lag >= dataset.Rows)
319              return double.NaN;
320
321            row += timeLagTreeNode.Lag;
322            double result = Evaluate(dataset, ref row, state);
323            row -= timeLagTreeNode.Lag;
324            return result;
325          }
326        case OpCodes.Integral: {
327            int savedPc = state.ProgramCounter;
328            var timeLagTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
329            if (row + timeLagTreeNode.Lag < 0 || row + timeLagTreeNode.Lag >= dataset.Rows)
330              return double.NaN;
331            double sum = 0.0;
332            for (int i = 0; i < Math.Abs(timeLagTreeNode.Lag); i++) {
333              row += Math.Sign(timeLagTreeNode.Lag);
334              sum += Evaluate(dataset, ref row, state);
335              state.ProgramCounter = savedPc;
336            }
337            row -= timeLagTreeNode.Lag;
338            sum += Evaluate(dataset, ref row, state);
339            return sum;
340          }
341
342        //mkommend: derivate calculation taken from:
343        //http://www.holoborodko.com/pavel/numerical-methods/numerical-derivative/smooth-low-noise-differentiators/
344        //one sided smooth differentiatior, N = 4
345        // y' = 1/8h (f_i + 2f_i-1, -2 f_i-3 - f_i-4)
346        case OpCodes.Derivative: {
347            if (row - 4 < 0) return double.NaN;
348            int savedPc = state.ProgramCounter;
349            double f_0 = Evaluate(dataset, ref row, state); ; row--;
350            state.ProgramCounter = savedPc;
351            double f_1 = Evaluate(dataset, ref row, state); ; row -= 2;
352            state.ProgramCounter = savedPc;
353            double f_3 = Evaluate(dataset, ref row, state); ; row--;
354            state.ProgramCounter = savedPc;
355            double f_4 = Evaluate(dataset, ref row, state); ;
356            row += 4;
357
358            return (f_0 + 2 * f_1 - 2 * f_3 - f_4) / 8; // h = 1
359          }
360        case OpCodes.Call: {
361            // evaluate sub-trees
362            double[] argValues = new double[currentInstr.nArguments];
363            for (int i = 0; i < currentInstr.nArguments; i++) {
364              argValues[i] = Evaluate(dataset, ref row, state);
365            }
366            // push on argument values on stack
367            state.CreateStackFrame(argValues);
368
369            // save the pc
370            int savedPc = state.ProgramCounter;
371            // set pc to start of function 
372            state.ProgramCounter = currentInstr.iArg0;
373            // evaluate the function
374            double v = Evaluate(dataset, ref row, state);
375
376            // delete the stack frame
377            state.RemoveStackFrame();
378
379            // restore the pc => evaluation will continue at point after my subtrees 
380            state.ProgramCounter = savedPc;
381            return v;
382          }
383        case OpCodes.Arg: {
384            return state.GetStackFrameValue(currentInstr.iArg0);
385          }
386        case OpCodes.Variable: {
387            var variableTreeNode = currentInstr.dynamicNode as VariableTreeNode;
388            return dataset[row, currentInstr.iArg0] * variableTreeNode.Weight;
389          }
390        case OpCodes.LagVariable: {
391            var laggedVariableTreeNode = currentInstr.dynamicNode as LaggedVariableTreeNode;
392            int actualRow = row + laggedVariableTreeNode.Lag;
393            if (actualRow < 0 || actualRow >= dataset.Rows) throw new ArgumentException("Out of range access to dataset row: " + row);
394            return dataset[actualRow, currentInstr.iArg0] * laggedVariableTreeNode.Weight;
395          }
396        case OpCodes.Constant: {
397            var constTreeNode = currentInstr.dynamicNode as ConstantTreeNode;
398            return constTreeNode.Value;
399          }
400        default: throw new NotSupportedException();
401      }
402    }
403
404    private byte MapSymbolToOpCode(SymbolicExpressionTreeNode treeNode) {
405      if (symbolToOpcode.ContainsKey(treeNode.Symbol.GetType()))
406        return symbolToOpcode[treeNode.Symbol.GetType()];
407      else
408        throw new NotSupportedException("Symbol: " + treeNode.Symbol);
409    }
410
411    // skips a whole branch
412    private void SkipInstructions(InterpreterState state) {
413      int i = 1;
414      while (i > 0) {
415        i += state.NextInstruction().nArguments;
416        i--;
417      }
418    }
419  }
420}
Note: See TracBrowser for help on using the repository browser.